sync snapshot from LAN repo (source master-zg @ 40658c74)
This commit is contained in:
1 parent
ea9dcff9c0
commit
754b61572c
179 files changed
+26085
-8788
No files matched your search
@@ -353,6 +353,32 @@ HTML artifacts are single-page by default. Omitted `preferred_page_count` is nor
|
||||
|
||||
Ordinary HTML generation is from scratch by default: do not read `page-template-library`, call catalog/prepare, or select a bundled layout unless the current user explicitly asks to use a template. The agent writes the final path directly under `/mnt/user-data/outputs/`, which lets frontend live preview open on the first `write_file`; it then validates and presents the same file without a bash/cp copy. Single-page HTML means a scrollable responsive document, not a fixed single-screen canvas. Direct validate derives `layout_mode` and page count from `page_brief` / `preferred_page_count`; it rejects `html/body overflow:hidden`, fixed 1920×1080 viewport scaling, undersized G6 containers, and long LR diagrams. Explicit template requests may use the shared `light-document` / `dark-document` profile backed by `report-document-responsive-template.html`; prepare creates its editable `working_copy` directly in outputs and persists the same constraints.
|
||||
|
||||
**Facebook page skill.** `skills/public/facebook-page-generator` is a narrowly routed built-in public skill for explicit Facebook/Facebook-style webpage requests. `_ORDINARY_QA_VISUALIZATION_SECTION` routes that intent to this skill before the generic `page-report-generation` path and explicitly forbids generic template selection or from-scratch HTML for the matched request. The skill uses `assets/default-data.json` as a seven-module schema-complete starting point, validates with the standard-library `scripts/render_facebook_page.py`, and injects the resulting JSON into the single self-contained `assets/facebook-template.html`; the model must not recreate or patch template DOM/CSS. The renderer exposes `init`, `validate`, and `render`, refuses to overwrite existing JSON/HTML, escapes a closing `</script>` sequence before injection, and emits machine-readable status/counts. The output retains the in-page settings modal so users can edit `site/navigation/stories/posts/sidebar/contacts/inbox` and apply changes at runtime. Its browser storage key includes an FNV-1a fingerprint of the embedded initial JSON: manual edits persist on reload for the same artifact, while a newly generated artifact with different JSON cannot be shadowed by stale same-origin sandbox data. The final HTML is still subject to the platform's normal generated-page post-processing and `present_files` delivery boundary. Regression coverage: `tests/test_facebook_page_generator_skill.py`.
|
||||
|
||||
**X page skill.** `skills/public/x-page-generator` is the narrow built-in route for explicit X platform, Twitter/推特, or X-style social timeline webpage requests. It maps source material to six modules (`site/navigation/composer/posts/trends/recommendations`) and uses the standard-library `scripts/render_x_page.py` to validate and inject JSON plus the bundled runtime into a fixed self-contained three-column template. The model must not rewrite the template DOM/CSS. The output retains responsive desktop/mobile layouts, theme switching and timeline interactions, plus a top-right settings modal that edits and applies one JSON module at a time. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_x_page_generator_skill.py`.
|
||||
|
||||
**TikTok page skill.** `skills/public/tiktok-page-generator` is the narrow built-in route for explicit TikTok, international Douyin, or TikTok-style short-video feed webpage requests. It maps source material to six modules (`site/navigation/videos/sidebar/comments/share`) and uses the standard-library `scripts/render_tiktok_page.py` to validate and inject JSON plus the bundled runtime into a fixed self-contained immersive feed template. The output retains scroll snapping, play/pause, double-like, mute, save, follow, comments, sharing, search, keyboard navigation and the mobile full-screen layout, plus a top-right settings modal that edits one JSON module at a time. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_tiktok_page_generator_skill.py`.
|
||||
|
||||
**YouTube page skill.** `skills/public/youtube-page-generator` is the narrow built-in route for explicit YouTube or YouTube-style video portal, home, and channel-page requests. It maps source material to seven modules (`site/navigation/categories/videos/shorts/subscriptions/comments`) and uses the standard-library `scripts/render_youtube_page.py` to validate and inject JSON plus the bundled runtime into a fixed self-contained responsive portal template. The output retains desktop navigation, category filtering, search, a responsive video grid, Shorts, a watch modal, likes, saves, subscriptions and comments, plus a top-right settings modal that edits one JSON module at a time. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_youtube_page_generator_skill.py`.
|
||||
|
||||
**Threads page skill.** `skills/public/threads-page-generator` is the narrow built-in route for explicit Threads or Threads-style conversation-feed webpage requests. It maps source material to six modules (`site/navigation/composer/threads/recommendations/activity`) and uses the standard-library `scripts/render_threads_page.py` to validate and inject JSON plus the bundled runtime into a fixed self-contained responsive thread template. The output retains theme switching, publishing, search, likes, replies, reposts, sharing, following, activity panels and mobile navigation, plus a top-right settings modal that edits one JSON module at a time. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_threads_page_generator_skill.py`.
|
||||
|
||||
**CNN page skill.** `skills/public/cnn-page-generator` is the narrow built-in route for explicit CNN or CNN-style global-news portal and homepage requests. It maps source material to ten modules (`site/navigation/breaking/lead/latest/video/world/markets/newsletter/footer`) and uses the standard-library `scripts/render_cnn_page.py` to validate and inject JSON plus the bundled runtime into a fixed self-contained red-and-black broadcast-news template. The output retains the breaking-news bar, search, live modal, caption toggle, save/share actions, mobile drawer, market snapshot and newsletter form, plus a top-right settings modal that edits one JSON module at a time. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_cnn_page_generator_skill.py`.
|
||||
|
||||
**BBC page skill.** `skills/public/bbc-page-generator` is the narrow built-in route for explicit BBC or BBC-style international public-news portal and homepage requests. It maps source material to ten modules (`site/navigation/breaking/lead/focus/media/moreNews/regions/newsletter/footer`) and uses the standard-library `scripts/render_bbc_page.py` to validate and inject JSON plus the bundled runtime into a fixed self-contained dual-navigation public-news template. The output retains search, the breaking strip, live modal, caption toggle, audio progress, mobile drawer, ranked news, regional weather and newsletter feedback, plus a top-right settings modal that edits one JSON module at a time. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_bbc_page_generator_skill.py`.
|
||||
|
||||
**Xinhua page skill.** `skills/public/xinhua-page-generator` is the narrow built-in route for explicit Xinhua News Agency, Xinhuanet, or Xinhua-style Chinese wire-service portal and homepage requests. It maps source material to ten modules (`site/navigation/specials/headline/focus/features/channels/local/services/footer`) and uses the standard-library `scripts/render_xinhua_page.py` to validate and inject JSON plus the bundled runtime into a fixed self-contained red-and-blue high-density news-agency template. The output retains the multilingual network bar, report series, spotlight gallery, tabbed focus news, named columns, topics, reporter studios, province switching, industry channels, media matrix, live captions and newsletter feedback, plus a top-right settings modal that edits one JSON module at a time. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_xinhua_page_generator_skill.py`.
|
||||
|
||||
**White House page skill.** `skills/public/white-house-page-generator` is the narrow built-in route for explicit White House website, White House-style government homepage, or U.S. executive-institution portal requests. It maps source material to ten modules (`site/navigation/hero/notice/updates/priorities/administration/calendar/participation/footer`): schema keys, ids, anchors, and visual enums remain technical English identifiers, while all reader-facing organization names, headings, summaries, controls, dates, events, and footer copy must be Simplified Chinese, English sources must be translated first, and `site.language` is fixed to `zh-CN`. The standard-library `scripts/render_white_house_page.py` validates and injects that JSON plus the Chinese bundled runtime into a fixed self-contained navy, cream, and gold civic portal template. The output retains the transparent-to-sticky header, architectural hero, public notice, official updates, interactive priorities, administration profile, public calendar, full-screen menu/search, live captions and newsletter feedback, plus a top-right settings modal that edits one JSON module at a time. Default data is explicitly marked as a concept rather than an official government site. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_white_house_page_generator_skill.py`.
|
||||
|
||||
**Manila Times page skill.** `skills/public/manila-times-page-generator` is the narrow built-in route for explicit The Manila Times, Manila Times-style Philippine broadsheet, or matching news-portal requests. It maps source material to ten modules (`site/navigation/ticker/lead/pulse/regions/opinion/sections/media/footer`): schema keys, ids, anchors, visual enums, and direction enums remain technical English identifiers, while all reader-facing masthead, section, story, author, date, control, and footer copy must be Simplified Chinese, English or Filipino sources must be translated first, and `site.language` is fixed to `zh-CN`. The standard-library `scripts/render_manila_times_page.py` validates and injects that JSON plus the Chinese bundled runtime into a fixed self-contained cream-paper, navy, and red broadsheet template. The output retains the Philippine flag stripe, serif masthead, weather rotation, sticky section navigation, breaking ticker, three-column lead, latest/trending and region tabs, opinion, business, sports, video captions, digital-edition paging and newsletter feedback, plus a top-right settings modal that edits one JSON module at a time. Default data is explicitly marked as a concept rather than an official website. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_manila_times_page_generator_skill.py`.
|
||||
|
||||
**GMA News page skill.** `skills/public/gma-news-page-generator` is the narrow built-in route for explicit GMA News, GMA-style Philippine broadcast-news, or matching portal requests. It maps source material to ten modules (`site/navigation/justIn/lead/news/services/broadcast/channels/media/footer`): schema keys, ids, anchors, and visual enums remain technical English identifiers, the GMA brand acronym may remain, while every other reader-facing section, story, author, date, control, and footer string must be Simplified Chinese, English or Filipino sources must be translated first, and `site.language` is fixed to `zh-CN`. The standard-library `scripts/render_gma_news_page.py` validates and injects that JSON plus the Chinese bundled runtime into a fixed self-contained red, blue, and yellow broadcast-news template. The output retains the expandable just-in bar, weather rotation, sticky navigation, broadcast lead, latest/trending/regional feeds, public services, live television captions, channel cards, videos, podcast, lottery switching and newsletter feedback, plus a top-right settings modal that edits one JSON module at a time. Default data is explicitly marked as a concept rather than an official website. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_gma_news_page_generator_skill.py`.
|
||||
|
||||
**Yahoo! JAPAN page skill.** `skills/public/yahoo-japan-page-generator` is the narrow built-in route for explicit Yahoo! JAPAN, Yahoo Japan, or Japanese general-portal requests. It maps source material to ten modules (`site/search/services/news/account/weather/utilities/shopping/pulse/footer`): schema keys, ids, anchors, and visual enums remain technical English identifiers, the `Yahoo! JAPAN` brand may remain, while every other reader-facing section, story, control, weather, transit, market, product, sports, and footer string must be Simplified Chinese, Japanese or English sources must be translated first, and `site.language` is fixed to `zh-CN`. The standard-library `scripts/render_yahoo_japan_page.py` validates and injects that JSON plus the Chinese bundled runtime into a fixed self-contained red-and-blue high-density Japanese portal template. The output retains multi-type search, popular queries, expandable services, categorized news, rotating recommendations, demo login, city weather, route lookup, market switching, product favorites, sports scores, real-time trends, mobile drawer and back-to-top behavior, plus a top-right settings modal that edits one JSON module at a time. Default data is explicitly marked as a concept rather than an official website. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_yahoo_japan_page_generator_skill.py`.
|
||||
|
||||
**Yomiuri News page skill.** `skills/public/yomiuri-news-page-generator` is the narrow built-in route for explicit Yomiuri Shimbun, Yomiuri News, or Japanese national-broadsheet requests. It maps source material to ten modules (`site/navigation/breaking/lead/edition/features/news/opinion/media/footer`): schema keys, ids, anchors, and visual enums remain technical English identifiers, the `YOMIURI ONLINE` romanized brand may remain, while every other reader-facing masthead, section, story, author, control, date, edition, video, and footer string must be Simplified Chinese, Japanese or English sources must be translated first, and `site.language` is fixed to `zh-CN`. The standard-library `scripts/render_yomiuri_news_page.py` validates and injects that JSON plus the Chinese bundled runtime into a fixed self-contained cream-paper, wine-red, and deep-navy broadsheet template. The output retains font-size switching, expandable breaking news, three-column lead, article saving, sticky navigation, full-screen menu, search, demo login, digital-edition paging, feature and category switching, opinion, video captions and newsletter feedback, plus a top-right settings modal that edits one JSON module at a time. Default data is explicitly marked as a concept rather than an official website. Initial-data fingerprinting isolates browser caches, while guarded storage access keeps opaque sandbox previews functional. Regression coverage: `tests/test_yomiuri_news_page_generator_skill.py`.
|
||||
|
||||
For an explicit multi-page HTML request without an explicit template request, `MultiPageHtmlMiddleware` rejects `page_report_template` catalog/prepare calls; the model must make one complete first `write_file`, then one validate. A failed validation returns patch-only repair guidance: retain the artifact and use the smallest `str_replace` edits for all listed CSS/navigation/JSON/DOM errors before one revalidation; do not recreate the page. `html_postprocess.maybe_fix_generated_html` also injects a marker-guarded dark Bootstrap compatibility layer into dark HTML during every write or replacement. It sets Bootstrap body/emphasis/secondary tokens and explicit readable foregrounds for `.card`, `.data-table` cells, `.modal-*`, and common form controls. Validation mirrors this by rejecting dark `.card`, `.data-table`, and modal markup without an explicit matching foreground color, so a preview cannot silently render black text on dark panels.
|
||||
|
||||
### Generated HTML artifact visualization runtimes
|
||||
@@ -367,6 +393,10 @@ Markdown-to-HTML conversion must inventory source Mermaid/flowcharts, charts, an
|
||||
|
||||
G6 nodes use light semantic rounded cards with matching borders, dark high-contrast text, centered type-prefixed labels, subtle shadows, and non-animated initial rendering (avoids a faded first frame). More than seven nodes automatically switch an `LR` request to layered `TB` layout and expand a short container to 720px, preventing long workflows from shrinking into illegible shapes; drag/zoom remain enabled.
|
||||
|
||||
### 系统名称与 Logo
|
||||
|
||||
本系统导航、侧栏和欢迎区的名称与 Logo 存在 `system_settings.json -> app_identity`,和 `generated_page_branding` 分开。管理员通过「设置 → 系统名称」以及 `GET/PUT/DELETE /api/system-settings/app-identity` 修改;上传的图片放在运行目录 `app-identity/`,由 `GET /api/public/app-identity/logo` 提供。名称为空时继续用内置标题,没有上传 Logo 时继续用主题静态图片。它不改生成网页的名称或头像。
|
||||
|
||||
### 问答记忆运行时总开关
|
||||
|
||||
通用/个人问答记忆由 `system_settings.json -> memory.enabled` 控制,默认 `false`,并且是该通用记忆域的权威总开关。关闭时 `lead_agent` 不挂载通用 `MemoryMiddleware`,工具注册不暴露 memory/hindsight 工具,prompt 不读取通用记忆,因此也不会触发 V1 的延迟提取模型调用。普通问答项目的项目级跨会话记忆是独立安全域,只受项目自身 `enabled` 控制,不得被这个通用总开关阻断。`config.yaml -> memory` 仅保留 provider/version/限额等参数,不能自行启用通用记忆。管理员通过 `GET/PUT /api/system-settings/memory` 和「设置 → 问答记忆」修改通用记忆开关;下一次创建的问答立即按新值构建。
|
||||
@@ -712,6 +742,12 @@ from deerflow.config import get_app_config
|
||||
|
||||
**Elasticsearch offline operations built-in agent.** `elasticsearch-offline-ops` (「Elasticsearch 离线运维助手」) and its same-name public skill are seeded from `app/gateway/routers/_elasticsearch_offline_ops_seed_assets/` before `_sync_legacy_agents`. Seeding is missing-directory-only so administrator edits survive restarts. The agent intentionally has `file:read`, `file:write`, and `bash` but no web group: air-gapped guidance comes from the shipped version-parameterized deployment and troubleshooting references. Its SOUL requires the exact ES version/OS/architecture/topology before final commands, keeps Elasticsearch security/TLS enabled, separates the DeerFlow sandbox from the target ES hosts, and makes read-only evidence collection precede changes. `scripts/collect_diagnostics.sh` gathers Linux/service/log and authenticated cluster evidence without mutations or `--insecure`; credentials come from operator-owned netrc/header files rather than command arguments or an unrestricted curl config. `scripts/analyze_diagnostics.py` is a stdlib-only heuristic that emits matched evidence and a next read-only check, or `insufficient_evidence`; it never claims an automatic root cause. Tests: `tests/test_elasticsearch_offline_ops_seed.py`, `tests/test_seed_assets.py`.
|
||||
|
||||
**Chat-history migration built-in agent.** `chat-history-migrator` (「聊天记录迁移助手」) and public skill `chat-history-migration` are seeded from `app/gateway/routers/_chat_history_migration_seed_assets/` before `_sync_legacy_agents`. Seeding is missing-directory-only. The agent has `file:read`, `file:write`, and `bash` only. A visible chat is three layers: application index tables (`threads_meta`, runs, feedback, analysis-project bindings; these may live in GaussDB), LangGraph checkpoints (SQLite, or real PostgreSQL), and `.deer-flow/users/<user_id>/threads/<thread_id>/`. Do not run LangGraph's PostgreSQL checkpointer migrations on GaussDB. `scripts/migrate_chat_history.py` is stdlib-only: it inventories/exports/imports SQLite and thread files, emits read-only Gauss/MySQL export SQL, and emits Gauss `INSERT ... WHERE NOT EXISTS` load SQL. Import is a dry run until `--apply`. Existing thread ids are skipped unless `--on-conflict replace`. The users table and password columns are never copied; `--user-map OLD=NEW` rewrites ownership only. Tests: `tests/test_chat_history_migration_seed.py`, `tests/test_seed_assets.py`.
|
||||
|
||||
**Conversation-list transfer API.** Gated by Settings → 智能体与技能迁移 → 「启用跨服务器迁移」 (`system_settings.json` `agent_skill_migration.enabled`, default off). When off, the chats-page export/import buttons are hidden and the APIs return 403. `/api/chat-history/export` and `/api/chat-history/import` move the current user's ordinary/agent chats between machines from the chats page. Single-thread export accepts one thread id. Account-wide export is a backend job (`POST /export-all`, poll `GET /export-all/{job_id}`, download `GET /export-all/{job_id}/download`) that lists the user's conversations and writes them one-by-one so the browser does not drive the batch. Per-thread cap is 50 MiB of serialized checkpoint plus included `user-data` files; files that would exceed the remaining budget (or the 200-file cap) are omitted and listed in `skipped_files`, while messages still export. A thread is skipped only if it is missing, the checkpoint alone exceeds 50 MiB, or serialization fails. The bundle includes the latest serialized checkpoint (`messages`/`title`/…) plus uploads and outputs under `user-data/`. Import writes `threads_meta` (conversation cards) and the LangGraph checkpointer (message list — often a different database); channel writes must bump `new_versions` or Postgres/SQLite will persist an empty conversation. Import binds rows to the current account, skips existing thread ids, and rolls back a newly created row if state write fails. This is not a substitute for the operator CLI above. Tests: `tests/test_chat_history_transfer.py`.
|
||||
|
||||
**Gauss data-adaptation built-in agent.** `gauss-data-adapter` (「高斯数据适配助手」) and public skill `gauss-data-adaptation` are seeded from `app/gateway/routers/_gauss_data_adaptation_seed_assets/` before `_sync_legacy_agents`. Seeding is missing-directory-only. The agent has `file:read` and `bash` only. Its job is to turn one pasted intranet Gauss error or symptom into one concrete change. `references/adaptation-map.md` is the only diagnosis source: missing `asyncpg`/`opengauss-sqlalchemy` uses the offline `UV_EXTRAS=gauss` image or wheelhouse, Dolphin error 322 requires `DEERFLOW_DATABASE_PRODUCT=gauss_mysql` on the running process, `in-memory fallback` is a checkpointer failure, and an 8-hour clock skew is a backend/product mismatch. A bare `Automatic ORM schema creation failed` is not enough evidence to change configuration. `scripts/print_gauss_adaptation.py` is stdlib-only and only needed when the fix depends on native openGauss versus Dolphin; it never connects or reads URL environment values. Do not run LangGraph's PostgreSQL checkpointer migrations on GaussDB. Ordinary and agent chats share the application tables, so one business-database fix covers both lists. Tests: `tests/test_gauss_data_adaptation_seed.py`, `tests/test_seed_assets.py`.
|
||||
|
||||
**Strategy-selection functional agents.** `app/gateway/routers/_strategy_selection_seed.py` seeds nine stable folder-backed agents from `_strategy_selection_seed_assets/` before `_sync_legacy_agents`: intent, governance/diplomacy/economy/security/public-opinion/law-policy angles, judge, and solution editor. Seeding is missing-directory-only and must never overwrite administrator changes. The global `strategy_agent_roles` registry classifies them independently of projects: intent/judge/solution are fixed, unique roles that may be configured but never added, disabled, reordered, or deleted; angle roles are a shared, ordered catalog that administrators may add, edit, disable (soft delete), restore, and reorder through `/api/strategy-agents`. Public `GET /api/strategy-agents` returns enabled identity/description metadata only; `include_disabled=true` or `include_config=true` is admin-only. Admin writes are `POST /api/strategy-agents/angles`, `PUT /api/strategy-agents/{id}`, and `DELETE /api/strategy-agents/{id}`; DELETE retains the folder-backed agent and role row to preserve historical references. Dynamic angles remain built-in folder-backed agents under the reserved `strategy-selection-angle-` id namespace, with `web` + `file:read`; a blank SOUL on create receives a safe role template. All strategy skill writes validate that names exist, are active, and are globally visible; generic agent CRUD cannot create or hard-delete reserved strategy IDs, and parallel execution rejects disabled roles. Angle configs reuse `policy-knowledge`; intent reuses `intent-clarification-policy`; the judge has no retrieval skill; the solution editor gets only `file:write`. Keep the SOUL contracts neutral and evidence-aware, with explicit de-escalation/civilian-protection framing and hard bans on operational combat guidance and targeted political manipulation. Tests: `tests/test_strategy_selection_seed.py`, `tests/test_strategy_agent_management.py`.
|
||||
|
||||
Only `strategy-selection-intent` has a clarification reply surface in the strategy workbench. `parallel_agents` must exclude `ask_clarification` for every other `strategy-selection-*` role and inject a direct-delivery guard: angle, judge, and solution stages use conservative assumptions, lower confidence/score where needed, list gaps under data limitations, and still finish in one pass. The judge brief repeats this rule at runtime because existing folder-backed agent SOUL files may be administrator-customized and are intentionally never overwritten. If a legacy backend nevertheless emits a judge clarification, the frontend treats it as a bounded repair attempt rather than asking the user to repeat the same manual run. Malformed or incomplete evaluation JSON receives the same bounded repair path; prior attempts are replaced in the live panel, never concatenated into duplicate final content.
|
||||
@@ -983,6 +1019,10 @@ Self-contained product knowledge base. **All knowledge capability lives in this
|
||||
|
||||
Custom agent metadata lives in the `agents` ORM table (`deerflow.persistence.agents`). `agents.id` is the stable runtime id and the filesystem directory name under `.deer-flow/agents/{id}/`; `agents.name` is display-only, can contain Chinese characters, and is not unique. `user_id IS NULL` marks built-in agents, user-owned agents are visible only to their owner unless `published = true`, and update/delete operations require ownership. The runtime accepts `agent_id` in context/configurable, and non-default `assistant_id` values are treated as agent ids after visibility checks.
|
||||
|
||||
**Agent/skill live-folder migration** — `/api/admin/agent-skill-migrations` is the metadata half of an operator-managed offline transfer, deliberately split into two schema-v1 manifests. `POST /export` produces an **agent-only** manifest: agent metadata plus the unchanged skill-name references from each copied `config.yaml`; it never scans or exports skill metadata, so a missing referenced skill cannot block agent export/import. `POST /export-skills` is exposed to administrators in the actual `/page/workspace/skills` list (`SkillSettingsPage`) as well as `AdminSkillsPage.tsx`, and produces the independent skill manifest, including skill metadata and matching `.deerflow-skill-support.json` dependency directories. Operators copy payload directories separately into the target's actual runtime roots (no staging mount and no archive upload). `agent_skill_migration.py` signs each selected tree by relative paths + sizes + bytes, rejects symlinks/path traversal, and preflight requires both hash and embedded identity (`config.yaml.id` or `SKILL.md.name`) to match. Apply repeats preflight server-side, maps owners by normalized email with explicit current-admin fallback, uses privileged migration upserts, and recreates tags. Agent apply rebuilds skill-name/tool/model extras from the copied config and does not require `extensions_config.json`; skill apply alone restores usage metadata, refreshes skill caches, and patches only `skills.<name>.enabled` so unknown extension fields survive. Neither flow writes, moves, deletes, or inspects unlisted payloads. Knowledge-base content, credentials, MCP services, users, and conversations remain outside both manifests; non-empty LLMWiki bindings warn on agent export. Both flows are convergent/idempotent. Frontend entries: `AdminAgentsPage.tsx`, `SkillSettingsPage`, and `AdminSkillsPage.tsx`; client: `core/agent-migrations`; tests: `tests/test_agent_skill_migration.py`.
|
||||
|
||||
Agent/skill migration is controlled by the persisted `system_settings.json -> agent_skill_migration.enabled` switch and is fail-closed: the field defaults to `false`, so missing legacy configuration keeps both UI and migration APIs disabled. Administrators toggle it from the global settings dialog's 「智能体与技能迁移」 section; frontend pages consume the shared `useAgentSkillMigrationSettings` query, and every `/api/admin/agent-skill-migrations` endpoint independently checks the same server setting after administrator authorization. Skill apply supports explicit `skip_invalid_skills`: it removes skills whose own directory fails preflight and every skill depending on a failed support directory, filters skipped-only owner mappings/support entries, applies only the remaining matched skills, and reports `skills_skipped` plus `skipped_skill_names`; strict all-or-nothing remains the default, agent manifests never support skipping, and an all-skipped skill import is rejected.
|
||||
|
||||
Strategy-selection fan-out (`routers/parallel_agents.py`) must keep hidden reasoning separate per agent: provider reasoning blocks/fields and inline `<think>...</think>` text emit `reasoning_delta`, while visible answer text emits `delta` and only visible text may enter `agent_done.content`. Never concatenate `reasoning_delta` into a selectable strategy or generated deliverable. Inspect the final AI message with the shared `is_llm_error_message` detector and require substantive visible text before constructing a success result. A middleware fallback, empty/thinking-only response, or punctuation-only provider degeneration is a failed seat run: raise so the stream emits `agent_error`; never wrap it in `agent_done`. Regression coverage: `tests/test_roundtable_model_fallback.py`.
|
||||
|
||||
**Listing cache + pagination** ? to keep `GET /api/agents` fast, the gallery's per-card extras (skills + tool_groups) are denormalized into two cache tables instead of reading every agent's `config.yaml` on each request: `agent_skills` (relational, one row per (agent, skill) with `position`) and `agent_extras` (one row per agent: `tool_groups` JSON + `model` + `skills_synced_at`). `config.yaml` remains authoritative for the agent runtime; these tables are a read cache, write-through on create/update and backfilled from disk by `_sync_legacy_agents` (mtime-vs-`skills_synced_at` drift check). The list endpoint enriches via `AgentStore.get_extras_for([ids])` (two batched `IN` queries). Both tables are auto-created by `Base.metadata.create_all` (no migration needed). `GET /api/agents` supports **opt-in server-side pagination**: `scope` (`mine` = owned + favorited / `square` = built-in/published public), `page`, `page_size`, returning `{agents, total, page, page_size}`; omitting `scope`/`page` preserves the legacy "return everything" behavior. Name `search` matches the raw OR desensitized name (the frontend's static term?abbrev map is mirrored server-side in `deerflow/config/agent_name_desensitize.py`); `tag_ids` is an SQL OR-filter; `owner` keeps only agents published by that user id (the card's ??? ? built-in agents never match), powering the gallery's click-???-to-filter. `POST /api/agents/private-square/list` takes the same pagination params (incl. `owner`). Repository entry point: `AgentStore.list_paginated(...)`. Tests: `tests/test_agent_listing_cache.py::test_list_paginated_owner_filter_keeps_one_publisher`.
|
||||
@@ -1023,7 +1063,7 @@ The fixed-deep-blue wx full-chat route (`#/page/workspace/wx/chats/new`) hides t
|
||||
|
||||
### Business-mapping authorization
|
||||
|
||||
`/api/business-mapping` remains globally readable. Seeded rows include the main codes (3Q / 6BF / 7BF / 8BF / AFX) plus independent slots `3q-0…3q-6`, `6-1…6-4`, and `7-1…7-4` (empty agent/chain until configured on the 配置管理 page). `3q-1…3q-6` seed as `is_custom=true` / `mapping_type=自定义类型` so `goPath=3q-1` resolves as a custom deep link; the configuration page hides those six rows and defaults the type filter to 自定义类型. Updates to 3Q, 6BF, 7BF, and those independent slots require `system_role == "admin"`; the 8BF public business-chain mapping is intentionally different and can be updated only by the trusted authenticated account whose email prefix is `lqq`. Do not rely on a username supplied in an external login URL. The frontend follows the same email-prefix rule when deciding whether to render the 8BF configuration button, while the router (`app/gateway/routers/business_mapping.py`) remains the enforcement point. Tests: `tests/test_business_mapping.py`.
|
||||
`/api/business-mapping` remains globally readable. Seeded rows include the main codes (3Q / 6BF / 7BF / 8BF / AFX) plus independent slots `3q-0…3q-6`, `6-1…6-4`, and `7-1…7-4` (empty agent/chain until configured on the 配置管理 page). Updates to 3Q, 6BF, 7BF, and those independent slots require `system_role == "admin"`; the 8BF public business-chain mapping is intentionally different and can be updated only by the trusted authenticated account whose email prefix is `lqq`. Do not rely on a username supplied in an external login URL. The frontend follows the same email-prefix rule when deciding whether to render the 8BF configuration button, while the router (`app/gateway/routers/business_mapping.py`) remains the enforcement point. Tests: `tests/test_business_mapping.py`.
|
||||
|
||||
### Position-collaboration foundation
|
||||
|
||||
|
||||
@@ -229,6 +229,32 @@ The single LangGraph agent (`lead_agent`) is the runtime entry point, created vi
|
||||
|
||||
普通问答采用严格的输出载体门禁:只有本次请求明确要求 HTML、网页、页面、看板、大屏或 `.html` 文件时,才允许读取网页生成技能、调用页面模板工具或创建 HTML;“画流程图”“画图表”“画地图”“画思维导图”“做可视化”本身都不构成 HTML 意图。普通流程图直接在消息中输出 Mermaid,普通图表沿用既有消息内方式,普通地图输出 `map-json`。只有本次请求明确要求“思维导图 / 脑图 / 知识导图”或点名 `analysis-mindmap` 时,才会输出专用 `mindmap-json`;普通分析、总结、提纲和结构化 JSON 不会自动生成导图。未闭合的 `mindmap-json`(兼容历史 `mindmap` 围栏)会原样作为代码块流式显示,闭合且本地校验通过后才懒加载横向分析树预览。导图必须是一棵含唯一根节点的受限层级树:目标 12–24 个节点、硬上限 36 个,最多 4 层(含中心主题),中心主题至多 6 个一级维度、每个后续节点至多 3 个子节点;不得把报告的每个数据、段落或引用逐条转成节点。点击父节点本身,或其连线起点处的+/−,即可展开/收起子节点,且连接线明确可见;全量弹窗的右上角含关闭与视图工具、右下角含由实际布局绘制的全图预览,消息预览同样支持拖动、滚轮缩放和视图工具;消息卡片的单个下载图标会打开 PNG、SVG、JSON 选项。明确的 HTML 请求必须进入沙箱生成 `/mnt/user-data/outputs/*.html` 并通过 `present_files` 打开右侧制品预览,禁止用聊天中的完整 HTML 代码块代替文件。前端负责本地校验和渲染,并兼容模型误写成普通 `json` 围栏的合法地图契约;只有包含地图字段且通过完整 schema 校验的 JSON 才会按地图渲染,其他 JSON 保持原代码块。解析前会把常见的 `coords`/`from`/`to`/`lng`/`lat` 写法归一成契约字段;标点可按 `color` 着色(未写则自动配色)。只有用户明确要求连线时才输出 `lines`,此时连线带箭头并沿线循环流动;无法恢复的连线会被丢弃,标点仍可渲染。地图卡片占满消息内容区,与步骤条左右边界对齐;格式错误时显示可读错误与原始数据,不中断整条消息。
|
||||
|
||||
内置公共技能 `facebook-page-generator` 专门处理用户明确提出的 Facebook/Facebook 风格网页请求。技能先把会话材料或经授权检索得到的内容整理为 `site/navigation/stories/posts/sidebar/contacts/inbox` 七模块 JSON,再调用纯标准库脚本把 JSON 确定性注入自包含 Facebook 社交信息流模板;模型不手写 HTML/CSS。生成页保留右上角设置按钮、分模块 JSON 弹窗、实时校验和「应用并渲染」,同时保留移动端全屏编辑、深浅主题、发布、点赞、评论与搜索。浏览器编辑缓存以初始 JSON 指纹为命名空间,因此同一页面刷新可保留手动修改,而新生成页面不会被沙箱同源的旧 JSON 覆盖。源 JSON 和最终 HTML 都保存在 `/mnt/user-data/outputs/` 并一同交付,渲染器默认拒绝覆盖已有文件。
|
||||
|
||||
内置公共技能 `x-page-generator` 专门处理用户明确提出的 X 平台、Twitter/推特或 X 风格社交时间线网页请求。技能把材料或检索结果整理成 `site/navigation/composer/posts/trends/recommendations` 六模块 JSON,再由纯标准库脚本注入固定的自包含三栏 X 风格模板;生成页带右上角设置按钮和模块化 JSON 编辑弹窗,可即时应用数据,并保留主题切换、发布、回复、点赞、转发、收藏、搜索、关注及移动端布局。运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `tiktok-page-generator` 专门处理用户明确提出的 TikTok、抖音国际版或 TikTok 风格短视频信息流网页请求。技能把材料或检索结果整理成 `site/navigation/videos/sidebar/comments/share` 六模块 JSON,再由纯标准库脚本注入固定的自包含沉浸式视频流模板。生成页带右上角设置按钮和模块化 JSON 编辑弹窗,可即时应用数据,并保留滚动吸附、播放/暂停、双击点赞、静音、收藏、关注、评论、分享、搜索及移动端全屏布局。运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `youtube-page-generator` 专门处理用户明确提出的 YouTube 或 YouTube 风格视频门户、视频首页、频道页请求。技能把材料或检索结果整理成 `site/navigation/categories/videos/shorts/subscriptions/comments` 七模块 JSON,再由纯标准库脚本注入固定的自包含响应式视频门户模板。生成页带右上角设置按钮和模块化 JSON 编辑弹窗,并保留桌面导航、分类筛选、搜索、视频网格、Shorts、观看弹窗、点赞、收藏、订阅和评论。运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `threads-page-generator` 专门处理用户明确提出的 Threads 或 Threads 风格串文首页、文本社交信息流请求。技能把材料或检索结果整理成 `site/navigation/composer/threads/recommendations/activity` 六模块 JSON,再由纯标准库脚本注入固定的自包含响应式串文模板。生成页带右上角设置按钮和模块化 JSON 编辑弹窗,并保留深浅主题、发帖、搜索、点赞、回复、转发、分享、关注、动态面板与移动端导航。运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `cnn-page-generator` 专门处理用户明确提出的 CNN 或 CNN 风格全球新闻门户、新闻首页请求。技能把材料或检索结果整理成 `site/navigation/breaking/lead/latest/video/world/markets/newsletter/footer` 十模块 JSON,再由纯标准库脚本注入固定的自包含红黑新闻门户模板。生成页带右上角设置按钮和模块化 JSON 编辑弹窗,并保留突发条、搜索、直播弹窗、字幕切换、收藏、分享、移动菜单、市场快照和订阅表单。运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `bbc-page-generator` 专门处理用户明确提出的 BBC 或 BBC 风格国际公共新闻门户、新闻首页请求。技能把材料或检索结果整理成 `site/navigation/breaking/lead/focus/media/moreNews/regions/newsletter/footer` 十模块 JSON,再由纯标准库脚本注入固定的自包含双层导航公共新闻门户模板。生成页带右上角设置按钮和模块化 JSON 编辑弹窗,并保留搜索、快讯、直播弹窗、字幕切换、音频进度、移动抽屉、新闻排行、地区天气和订阅反馈。运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `xinhua-page-generator` 专门处理用户明确提出的新华社、新华网或新华社风格中文通讯社门户、新闻首页请求。技能把材料或检索结果整理成 `site/navigation/specials/headline/focus/features/channels/local/services/footer` 十模块 JSON,再由纯标准库脚本注入固定的自包含红蓝高密度通讯社门户模板。生成页带右上角设置按钮和模块化 JSON 编辑弹窗,并保留多语种顶栏、报道专集、焦点图、要闻分类、名专栏、专题、记者工作室、地方切换、行业频道、媒体矩阵、直播字幕和订阅反馈。运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `white-house-page-generator` 专门处理用户明确提出的白宫官网、White House 风格政府首页或美国行政机构门户请求。技能把材料或检索结果整理成 `site/navigation/hero/notice/updates/priorities/administration/calendar/participation/footer` 十模块 JSON;JSON 键名、`id`、锚点和视觉枚举保留英文技术值,所有面向读者的机构名、标题、摘要、按钮、日期、活动及页脚文案强制使用简体中文,英文来源必须先翻译,`site.language` 固定为 `zh-CN`。再由纯标准库脚本注入固定的自包含海军蓝、米白和金色行政机构门户模板。生成页带右上角设置按钮和中文模块化 JSON 编辑弹窗,并保留透明转吸顶导航、建筑主视觉、公告、官方动态、优先事项、行政团队、公共日历、全屏菜单搜索、直播字幕和订阅反馈。默认内容明确为概念模板,不冒充政府官网;运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `manila-times-page-generator` 专门处理用户明确提出的马尼拉时报、The Manila Times 或马尼拉时报风格菲律宾大报门户请求。技能把材料或检索结果整理成 `site/navigation/ticker/lead/pulse/regions/opinion/sections/media/footer` 十模块 JSON;JSON 键名、`id`、锚点、视觉和涨跌枚举保留英文技术值,所有面向读者的报头、栏目、新闻、作者、日期、按钮及页脚文案强制使用简体中文,英文或菲律宾语来源必须先翻译,`site.language` 固定为 `zh-CN`。再由纯标准库脚本注入固定的自包含米白纸张、海军蓝和红色报业门户模板。生成页带右上角设置按钮和中文模块化 JSON 编辑弹窗,并保留菲律宾旗色带、衬线报头、天气轮播、滚动吸顶分类栏、三栏头条、最新/热门与地区切换、评论、商业体育、视频字幕、数字报翻页和订阅反馈。默认内容明确为概念模板,不冒充官方网站;运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `gma-news-page-generator` 专门处理用户明确提出的 GMA News、GMA 新闻或菲律宾广播新闻门户风格页面请求。技能把材料或检索结果整理成 `site/navigation/justIn/lead/news/services/broadcast/channels/media/footer` 十模块 JSON;JSON 键名、`id`、锚点和视觉枚举保留英文技术值,品牌缩写 `GMA` 可以保留,其余所有面向读者的栏目、新闻、作者、日期、按钮及页脚文案强制使用简体中文,英文或菲律宾语来源必须先翻译,`site.language` 固定为 `zh-CN`。再由纯标准库脚本注入固定的自包含红蓝黄色广播新闻门户模板。生成页带右上角设置按钮和中文模块化 JSON 编辑弹窗,并保留即时新闻展开、天气轮播、滚动吸顶导航、广播式头条、最新/热门/地方切换、公共服务、电视直播字幕、频道卡片、视频、播客、彩票开奖和订阅反馈。默认内容明确为概念模板,不冒充官方网站;运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `yahoo-japan-page-generator` 专门处理用户明确提出的雅虎日本、Yahoo! JAPAN、Yahoo Japan 或日本综合门户风格页面请求。技能把材料或检索结果整理成 `site/search/services/news/account/weather/utilities/shopping/pulse/footer` 十模块 JSON;JSON 键名、`id`、锚点和视觉枚举保留英文技术值,品牌 `Yahoo! JAPAN` 可以保留,其余所有面向读者的栏目、新闻、按钮、天气、交通、行情、商品、体育及页脚文案强制使用简体中文,日文或英文来源必须先翻译,`site.language` 固定为 `zh-CN`。再由纯标准库脚本注入固定的自包含红蓝高密度日本综合门户模板。生成页带右上角设置按钮和中文模块化 JSON 编辑弹窗,并保留多类型搜索、热门词、服务展开、分类新闻、推荐轮换、演示登录、城市天气、路线查询、市场切换、商品收藏、体育比分、实时热榜、移动抽屉和返回顶部。默认内容明确为概念模板,不冒充官方网站;运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
内置公共技能 `yomiuri-news-page-generator` 专门处理用户明确提出的读卖新闻、读买新闻、Yomiuri、Yomiuri Shimbun 或日本全国大报风格页面请求。技能把材料或检索结果整理成 `site/navigation/breaking/lead/edition/features/news/opinion/media/footer` 十模块 JSON;JSON 键名、`id`、锚点和视觉枚举保留英文技术值,品牌罗马字 `YOMIURI ONLINE` 可以保留,其余所有面向读者的报头、栏目、新闻、作者、按钮、日期、纸面、视频及页脚文案强制使用简体中文,日文或英文来源必须先翻译,`site.language` 固定为 `zh-CN`。再由纯标准库脚本注入固定的自包含米白纸张、酒红和深蓝传统大报门户模板。生成页带右上角设置按钮和中文模块化 JSON 编辑弹窗,并保留字号切换、速报展开、三栏头条、文章收藏、吸顶导航、全屏菜单、搜索、演示登录、数字报翻页、专题与分类新闻切换、社论、视频字幕和邮件订阅。默认内容明确为概念模板,不冒充官方网站;运行时以初始 JSON 指纹隔离缓存,对不允许 localStorage 的沙箱也会回退到内嵌数据正常渲染。
|
||||
|
||||
生成 `.html` 网页、看板或大屏时使用独立的离线绘图契约:流程图使用 `data-df-flow` + AntV G6(不使用 Mermaid),图表使用 `data-df-chart`,地图使用本地 GeoJSON + ECharts Canvas 的 `data-df-geo`。Gateway 从公开路径 `/api/public/html-runtime/` 提供浏览器版 `g6.min.js`、`echarts.min.js`、`bootstrap.min.css`、`bootstrap.bundle.min.js`、`alpine.min.js` 和统一初始化脚本 `deerflow-runtime.js`,以及中国省级、美国州级、日本都道府县、台湾地区县市四份地图资源(`china-provinces` / `us-states` / `japan-prefectures` / `taiwan-counties`)。Bootstrap 负责布局与标准弹窗,Alpine 负责轻量状态和动态列表;生成的 HTML 源码会直接引用这些后台文件,不依赖前端 React 构建产物或公网 CDN。设置里的「HTML 地图」可选 ECharts 本地 GeoJSON,或地图网页(Leaflet);地图网页的瓦片模板在设置 → 外观的「地图瓦片地址」中配置。运行时会等隐藏的逻辑页真实可见后再初始化 ECharts,并通过 `ResizeObserver` 跟随沙箱和页面容器尺寸变化,避免地图或图表首屏以零宽度渲染。区域/标点的 `description` 必须为纯文本,点击后由运行时显示详情浮层;需要筛选或切到明细页时监听 `deerflow:geo-map-click`,不能把链接、HTML 或 `onclick` 写进 `description`。深色 HTML 需声明 `data-df-theme="dark"`,其 ECharts 的全局、标题、图例、坐标轴和可见系列标签都必须显式使用浅色文字,避免 ECharts 默认黑字。这些文件作为 `packages/harness/deerflow/html_runtime/assets/` 的包资源随 harness wheel 一起发布,第三方许可同目录保存。设置 → 外观的「HTML 运行库地址」填写浏览器可访问的 Gateway Runtime 地址(未配置时默认 `http://localhost:8001/api/public/html-runtime`),运行时据此解析本地 GeoJSON 地址;内网部署在设置弹窗里改成用户能够打开的域名即可。用户上传的栅格图片若要作为生成 HTML 的背景图,智能体会使用同一 Gateway 源下的签名地址 `/api/public/html-images/{token}` 写入 `background-image`,不要写沙箱路径或制品接口。该能力不改变普通问答消息列表,普通问答地图仍走原有 `map-json` 前端瓦片渲染与 `frontend-web/public/runtime-config.js` 的 `VITE_MAP_TILE_URL`。地图大屏使用“中间地图舞台”而非整页地图背景:中间地图保持可见和可点击,两侧为窄信息栏、底部为摘要面板;提到的城市和行政区必须分别写入 `markers` 与高亮 `regions`。
|
||||
|
||||
从已有 Markdown 报告生成 HTML 时,必须根据材料盘点 Mermaid/流程图、图表及地图,并在 `page_report_template validate` 的 `required_features` 和 `page_brief` 中如实声明。流程图必须包含 `g6.min.js`、`deerflow-runtime.js`、`.df-flow` 与 `data-df-flow`,并拒绝 Mermaid、手写 HTML/CSS 流程节点以及页面内自行初始化 `G6.Graph`;图表和地图分别检查 ECharts 资源与 `data-df-chart` / `data-df-geo` 声明式数据块。`data-df-chart` 必须是严格 JSON,校验会拒绝函数、箭头函数和其他 JavaScript 回调;颜色使用字面量或数据项 `itemStyle`,提示文本使用字符串模板。地图只能使用上述四个内置 GeoJSON,校验会拒绝 Leaflet、`data-df-map`、瓦片和页面内自行初始化 ECharts。默认页面从零开始直接写入最终 outputs HTML,不读取或预览模板;只有用户明确要求模板时,prepare 才会把要求持久化到同名 brief,validate 会自动恢复并与调用参数合并。校验失败时不得交付,必须修复后重新校验。
|
||||
@@ -350,7 +376,7 @@ FastAPI application providing REST endpoints for frontend integration:
|
||||
| `GET/POST /api/agents` | List visible agents or create a user-owned agent |
|
||||
| `GET/PUT/DELETE /api/agents/{id}` | Read, update, or delete an id-addressed agent |
|
||||
| `GET/POST/PUT/DELETE /api/roundtable-chains` | Manage user-owned roundtable business chains; each seat may optionally carry `position_id` for the separate position-collaboration workspace, plus `human_validation` to mark a Step 2 client-side pause checkpoint after that seat/stage completes (the original roundtable has no extra validation card) |
|
||||
| `GET/PUT /api/business-mapping` | Read global business mappings (seeded 3Q/6BF/7BF/8BF/AFX plus independent slots 3q-0…3q-6, 6-1…6-4, 7-1…7-4). `3q-1…3q-6` seed as custom-type rows and stay off the configuration-page list. Updates to 3Q/6BF/7BF and the independent slots require an administrator; the 8BF public business-chain mapping is maintained exclusively by the trusted `lqq` account (derived from the authenticated email prefix). |
|
||||
| `GET/PUT /api/business-mapping` | Read global business mappings (seeded 3Q/6BF/7BF/8BF/AFX plus independent slots 3q-0…3q-6, 6-1…6-4, 7-1…7-4). Updates to 3Q/6BF/7BF and the independent slots require an administrator; the 8BF public business-chain mapping is maintained exclusively by the trusted `lqq` account (derived from the authenticated email prefix). |
|
||||
| `GET/POST/PUT /api/position-roundtable/sessions` | Standalone position-collaboration sessions: freeze task/intent/chain snapshots, index one direct-agent node per seat, build upstream handoff context (including bounded UTF-8 excerpts of text artifacts), and make archived sessions read-only without invoking the original roundtable coordinator or jobs. Built-in summary/action-plan completion mirrors visible report text into a Markdown artifact when a model omits its final `write_file` call. `POST /sessions/{id}/nodes/{nodeKey}/reject` accepts an optional reason, marks the rejected delivery for rework, and invalidates affected downstream deliveries so they are regenerated in order. The same router is also mounted at `/api/multi-agent/position-roundtable/*` for intranet gateways that only forward the established multi-agent namespace; the compatibility mount is intentionally omitted from OpenAPI. |
|
||||
| `GET /api/memory` | Retrieve memory data |
|
||||
| `POST /api/memory/reload` | Force memory reload |
|
||||
@@ -667,6 +693,20 @@ AI writing supports a sample-imitation mode: the frontend can upload or paste a
|
||||
|
||||
Custom agents are indexed in the `agents` database table. The `id` column is the stable runtime identifier and filesystem directory name (`.deer-flow/agents/{id}/SOUL.md`); `name` is display-only, may be Chinese, and may be duplicated. Rows with `user_id = NULL` are built-in agents, user rows are private unless `published = true`, and users can only update or delete agents they created.
|
||||
|
||||
#### 智能体与技能跨服务器迁移
|
||||
|
||||
迁移拆成两份互不混装的清单。管理员在 `/page/workspace/admin/agents` 点击卡片选择智能体并导出智能体清单;它只包含智能体元数据、标签、创建者邮箱、发布/私有状态、智能体目录 SHA-256,以及 `config.yaml` 中原样保留的技能名称关联,不包含任何技能元数据。引用的技能即使在源机运行目录不存在也不会阻断智能体导出。管理员在实际技能页 `/page/workspace/skills`(管理员技能页 `/page/workspace/admin/skills` 也保留入口)另行选择技能并导出技能清单;该清单才包含技能归属、发布/上下线/精选状态、标签、技能目录 SHA-256 和必要的支持目录。两种清单都不包含目录文件、模型密钥或登录凭据,大批量场景可分别分批导出。
|
||||
|
||||
迁移功能默认关闭。管理员可在全局「设置 → 智能体与技能迁移」中开启;状态持久化到 `system_settings.json -> agent_skill_migration.enabled`,旧部署缺少该配置块时仍按关闭处理。关闭时前端隐藏选择、全选、导出和导入入口(含对话页的聊天记录导出/导入按钮),后端迁移 API 也会拒绝执行;登录用户可读取开关状态,只有管理员可以修改。
|
||||
|
||||
迁移步骤:先保留源机备份,将智能体目录复制到目标机页面显示的实时 `agents_root`,将技能及技能清单列出的支持目录复制到实时 `skills_root`。建议先在目标机「技能管理」导入技能清单,再到「智能体管理」导入智能体清单;智能体清单也允许先导入,暂时不存在的技能名称关联会保留。两处导入都会先按稳定 ID/名称和整目录哈希预检:智能体核对 `config.yaml.id`,技能核对 `SKILL.md.name`。智能体导入保持整批严格校验;技能导入遇到目录缺失、错放、内容不一致、符号链接或支持目录异常时,可由管理员显式勾选「跳过异常技能」继续,被异常支持目录依赖的技能会一并跳过且不写入任何元数据,其余通过预检的技能正常导入;若全部技能都需跳过则仍禁止执行。创建者默认按邮箱映射到目标机已有用户;无法匹配时必须显式选择归属当前管理员。
|
||||
|
||||
预检通过后,智能体导入只同步智能体数据库元数据、标签及从已复制 `config.yaml` 读取的技能名称关联;不要求 `extensions_config.json`,也不检查关联技能是否存在。技能导入才同步技能数据库元数据、标签、使用状态、技能提示缓存,并只补丁 `extensions_config.json` 中清单技能的 `enabled` 字段。两条流程都不会移动、覆盖或删除任何目录,也不会改动未列入清单的资源及扩展配置字段。重复导入同一清单是幂等的,若中途失败可在修复原因后重试。
|
||||
|
||||
建议在停止目标服务或确保目录已完整落盘后复制,再启动服务进行网页预检,避免对正在复制的目录计算到中间态哈希。不要用旧的「同步技能」按钮代替该流程,它只清理智能体中指向不存在技能的引用,不恢复创建者、发布状态和标签。管理员 API 为 `GET /api/admin/agent-skill-migrations/roots`、智能体导出 `POST /export`、技能导出 `POST /export-skills`、`POST /preflight` 和 `POST /apply`。
|
||||
|
||||
这两类清单都不迁移知识库正文、模型供应商凭据、MCP 服务、用户账号或会话记录。智能体绑定了 LLMWiki 知识库时,智能体清单会给出提醒;这些外部依赖必须提前在目标机器部署并核对其 ID。
|
||||
|
||||
The built-in `forced-research-responder` (「强制检索输出助手」) is seeded at Gateway startup. Unlike an ordinary skill-enabled custom agent, it has a runtime-enforced per-turn collection gate: the model cannot finish a response until a retrieval/knowledge/MCP tool or a skill Python script returns usable information. It then answers directly in the user's requested chat format rather than generating an artifact. The agent may create or edit only temporary `.py` files below `/mnt/user-data/workspace/` and may execute `.py` skill scripts through `bash`; writes to `outputs`, Markdown/document creation, `present_files`, general shell commands, and skill mutation are denied. Administrators can edit its model and skill allowlist from agent management; the runtime safety policy remains fixed. Regression coverage: `tests/test_forced_research_agent.py`.
|
||||
|
||||
The built-in `elasticsearch-offline-ops` (「Elasticsearch 离线运维助手」) is also seeded before legacy-agent synchronization, together with the public skill of the same name. It is intended for air-gapped self-managed Elasticsearch deployments: it selects RPM/DEB, archive, or Docker paths only after the exact ES version, target OS/architecture, topology, capacity, TLS, plugins, migration, and recovery objectives are known. The bundled references cover connected-zone artifact manifests and checksums, host/bootstrap preflight, secure first-cluster bootstrapping, acceptance, snapshots, upgrades, and evidence-first troubleshooting. A read-only Linux collector gathers service/log/host/cluster evidence without changing settings or disabling TLS; authentication comes from operator-owned netrc or header files rather than a password argument. A dependency-free analyzer turns known log signatures into evidence plus the next discriminating check and explicitly reports insufficient evidence instead of inventing a cause. `bash` remains the DeerFlow sandbox, so the agent must never treat its local host state as the target ES node unless the user establishes that boundary. Existing agent and skill directories are not overwritten. Regression coverage: `tests/test_elasticsearch_offline_ops_seed.py` and `tests/test_seed_assets.py`.
|
||||
@@ -1063,6 +1103,14 @@ the rest of the visual tokens; the optional `overrides` object only exposes
|
||||
must use the `custom-theme-` prefix. Disabled or removed custom themes cannot
|
||||
remain the system default and automatically fall back to `light`.
|
||||
|
||||
Application chrome name and logo are a separate setting, 「设置 → 系统名称」.
|
||||
They persist in `system_settings.json -> app_identity` and an uploaded logo is
|
||||
stored under `.deer-flow/app-identity/`. `GET/PUT/DELETE /api/system-settings/app-identity`
|
||||
reads and updates it (writes are admin-only); the uploaded image is served from
|
||||
`GET /api/public/app-identity/logo`. An empty name keeps the built-in titles, and
|
||||
a missing logo keeps the static theme logos. This block does not change
|
||||
`generated_page_branding` or generated HTML.
|
||||
|
||||
Compact top-bar shortcuts use the same appearance endpoint. In addition to
|
||||
login and theme query parameters, each shortcut may include ordered keyless
|
||||
`path` parameters. The frontend resolves each selected login field and appends
|
||||
@@ -1758,6 +1806,54 @@ checkpointer:
|
||||
normalized to the openGauss dialect. Do not configure the LangGraph
|
||||
PostgreSQL checkpointer against GaussDB: its migrations are PostgreSQL-specific.
|
||||
For a production image, build with `--build-arg UV_EXTRAS=gauss`.
|
||||
|
||||
openGauss Dolphin (MySQL-protocol) mode keeps `database.backend=mysql` and
|
||||
sets `DEERFLOW_DATABASE_PRODUCT=gauss_mysql`. Only that marker installs
|
||||
`deerflow.persistence.gauss_mysql_compat` and the native-catalog schema
|
||||
repair path. A normal MySQL deployment must leave the marker unset so the
|
||||
stock dialect, Alembic, and `CREATE DATABASE` retry stay unchanged.
|
||||
|
||||
## Chat history migration
|
||||
|
||||
The built-in agent 「聊天记录迁移助手」(`chat-history-migrator`) migrates ordinary
|
||||
DeerFlow conversations onto another server. The skill `chat-history-migration`
|
||||
ships `scripts/migrate_chat_history.py`, which uses only the Python standard
|
||||
library and does not connect to GaussDB.
|
||||
|
||||
A conversation has three layers. `threads_meta`, runs, feedback and analysis
|
||||
project bindings are the index and may live in GaussDB. LangGraph checkpoints
|
||||
hold the messages and stay in SQLite (or a real PostgreSQL checkpointer).
|
||||
Uploads and generated files stay under
|
||||
`.deer-flow/users/<user_id>/threads/<thread_id>/`. Do not run the LangGraph
|
||||
PostgreSQL checkpointer migrations against GaussDB.
|
||||
|
||||
On the source, `emit-export-sql --dialect opengauss` (or `mysql` for Dolphin)
|
||||
prints read-only export SQL. `export` / `pack-jsonl` then builds a bundle from
|
||||
that index, the checkpoint SQLite file and the thread directories. On the
|
||||
target, `import` is a dry run until `--apply`; existing thread ids are left in
|
||||
place unless `--on-conflict replace`. `emit-gauss-sql` writes
|
||||
`INSERT ... WHERE NOT EXISTS` for a Gauss application database. Passwords and
|
||||
the `users` table are not copied. When account ids differ, repeat
|
||||
`--user-map OLD=NEW`. Put database passwords in `~/.pgpass` or the client
|
||||
prompt, not in the command line and not in the agent conversation.
|
||||
|
||||
## Gauss data adaptation
|
||||
|
||||
The built-in agent 「高斯数据适配助手」(`gauss-data-adapter`) tells an operator
|
||||
what to change after an intranet GaussDB error or symptom. The skill
|
||||
`gauss-data-adaptation` does not connect to the database and does not read
|
||||
passwords. Paste the error first. The agent matches one row in
|
||||
`references/adaptation-map.md` and names the config field, environment
|
||||
variable, or offline image to change.
|
||||
|
||||
Native openGauss is `database.backend: gauss`. Dolphin, the MySQL protocol, stays
|
||||
`database.backend: mysql` and requires `DEERFLOW_DATABASE_PRODUCT=gauss_mysql`
|
||||
on the running Gateway process. The two modes must not be enabled together.
|
||||
Keep the LangGraph checkpointer on SQLite or a real PostgreSQL instance; do
|
||||
not run its PostgreSQL migrations against GaussDB. A running process is not
|
||||
proof that schema creation succeeded. Ordinary Q&A and agent chats use the
|
||||
same application tables.
|
||||
|
||||
# 问答记忆开关
|
||||
|
||||
问答记忆默认关闭。关闭时,普通问答不会加载记忆中间件、不会注入历史记忆,也不会在回答结束后调用模型提取或写入记忆。管理员可在「设置 → 问答记忆」中显式开启;开关保存在运行目录的 `system_settings.json`,新部署或没有该字段时始终按关闭处理。
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Publish product-owned public skills into the configured live skill root.
|
||||
|
||||
The Gateway may be launched through the supported shell scripts, an image
|
||||
entrypoint, Compose, or an external release repository. Startup therefore
|
||||
cannot rely on one shell wrapper to populate a persistent ``/app/skills``
|
||||
mount. This module is deliberately standard-library-only so both the launcher
|
||||
CLI and the Gateway lifespan can use the exact same synchronization contract.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
ROUTED_PAGE_SKILLS = (
|
||||
"facebook-page-generator",
|
||||
"x-page-generator",
|
||||
"tiktok-page-generator",
|
||||
"youtube-page-generator",
|
||||
"threads-page-generator",
|
||||
"cnn-page-generator",
|
||||
"bbc-page-generator",
|
||||
"xinhua-page-generator",
|
||||
"white-house-page-generator",
|
||||
"manila-times-page-generator",
|
||||
"gma-news-page-generator",
|
||||
"yahoo-japan-page-generator",
|
||||
"yomiuri-news-page-generator",
|
||||
)
|
||||
|
||||
_BUNDLED_SKILLS_ENV = "DEER_FLOW_BUNDLED_SKILLS_PATH"
|
||||
_SYNC_LOCK_FILE = ".builtin-public-skills.lock"
|
||||
_COPY_IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo")
|
||||
|
||||
|
||||
class SkillSyncError(RuntimeError):
|
||||
"""Raised when bundled skills cannot be published safely."""
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _exclusive_target_lock(target_root: Path) -> Iterator[None]:
|
||||
"""Serialize startup copies across Uvicorn worker processes."""
|
||||
|
||||
target_root.mkdir(parents=True, exist_ok=True)
|
||||
lock_path = target_root / _SYNC_LOCK_FILE
|
||||
with lock_path.open("a+b") as handle:
|
||||
handle.seek(0, os.SEEK_END)
|
||||
if handle.tell() == 0:
|
||||
handle.write(b"\0")
|
||||
handle.flush()
|
||||
handle.seek(0)
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
handle.seek(0)
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def sync_builtin_public_skills(
|
||||
source_root: Path,
|
||||
target_root: Path,
|
||||
*,
|
||||
required: tuple[str, ...] = (),
|
||||
) -> dict[str, object]:
|
||||
"""Overlay bundled ``public`` skills while preserving live custom skills."""
|
||||
|
||||
source_public = source_root.resolve() / "public"
|
||||
target_root = target_root.resolve()
|
||||
target_public = target_root / "public"
|
||||
target_custom = target_root / "custom"
|
||||
if not source_public.is_dir():
|
||||
raise SkillSyncError(f"Bundled public skills directory not found: {source_public}")
|
||||
|
||||
target_public.mkdir(parents=True, exist_ok=True)
|
||||
target_custom.mkdir(parents=True, exist_ok=True)
|
||||
copied: list[str] = []
|
||||
discovered: list[str] = []
|
||||
source_is_live = source_public == target_public.resolve()
|
||||
for source in sorted(source_public.iterdir(), key=lambda path: path.name):
|
||||
if not source.is_dir() or source.name.startswith("."):
|
||||
continue
|
||||
if not source_is_live:
|
||||
destination = target_public / source.name
|
||||
shutil.copytree(
|
||||
source,
|
||||
destination,
|
||||
dirs_exist_ok=True,
|
||||
symlinks=True,
|
||||
ignore=_COPY_IGNORE,
|
||||
)
|
||||
copied.append(source.name)
|
||||
if (source / "SKILL.md").is_file():
|
||||
discovered.append(source.name)
|
||||
|
||||
missing = sorted(name for name in required if not (target_public / name / "SKILL.md").is_file())
|
||||
if missing:
|
||||
raise SkillSyncError("Required built-in skills are unavailable after sync: " + ", ".join(missing))
|
||||
return {
|
||||
"status": "ok",
|
||||
"source": str(source_public),
|
||||
"target": str(target_public),
|
||||
"sourceIsLive": source_is_live,
|
||||
"copiedDirectories": copied,
|
||||
"discoveredSkills": discovered,
|
||||
"requiredSkills": list(required),
|
||||
}
|
||||
|
||||
|
||||
def _required_packages_digest(public_root: Path, required: tuple[str, ...]) -> str | None:
|
||||
"""Hash the required packages, ignoring interpreter cache artifacts."""
|
||||
|
||||
digest = hashlib.sha256()
|
||||
for name in required:
|
||||
skill_root = public_root / name
|
||||
if not (skill_root / "SKILL.md").is_file():
|
||||
return None
|
||||
files = sorted(
|
||||
path
|
||||
for path in skill_root.rglob("*")
|
||||
if path.is_file()
|
||||
and "__pycache__" not in path.parts
|
||||
and path.suffix not in {".pyc", ".pyo"}
|
||||
)
|
||||
for path in files:
|
||||
relative = path.relative_to(public_root).as_posix().encode("utf-8")
|
||||
digest.update(len(relative).to_bytes(4, "big"))
|
||||
digest.update(relative)
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def publish_bundled_public_skills(
|
||||
source_root: Path,
|
||||
target_root: Path,
|
||||
*,
|
||||
required: tuple[str, ...] = ROUTED_PAGE_SKILLS,
|
||||
) -> dict[str, object]:
|
||||
"""Lock, compare and publish the current bundled public skill tree."""
|
||||
|
||||
source_root = source_root.resolve()
|
||||
target_root = target_root.resolve()
|
||||
if source_root == target_root:
|
||||
result = sync_builtin_public_skills(source_root, target_root, required=required)
|
||||
result["skipped"] = True
|
||||
return result
|
||||
with _exclusive_target_lock(target_root):
|
||||
source_digest = _required_packages_digest(source_root / "public", required)
|
||||
if source_digest is None:
|
||||
missing = sorted(
|
||||
name for name in required if not (source_root / "public" / name / "SKILL.md").is_file()
|
||||
)
|
||||
raise SkillSyncError("Required bundled skills are unavailable: " + ", ".join(missing))
|
||||
target_digest = _required_packages_digest(target_root / "public", required)
|
||||
if source_digest == target_digest:
|
||||
return {
|
||||
"status": "ok",
|
||||
"source": str(source_root / "public"),
|
||||
"target": str(target_root / "public"),
|
||||
"sourceIsLive": (source_root / "public") == (target_root / "public"),
|
||||
"copiedDirectories": [],
|
||||
"discoveredSkills": list(required),
|
||||
"requiredSkills": list(required),
|
||||
"skipped": True,
|
||||
}
|
||||
result = sync_builtin_public_skills(source_root, target_root, required=required)
|
||||
result["skipped"] = False
|
||||
return result
|
||||
|
||||
|
||||
def resolve_bundled_skills_root() -> Path:
|
||||
"""Return the authoritative bundled skill root for this deployment."""
|
||||
|
||||
explicit = os.getenv(_BUNDLED_SKILLS_ENV, "").strip()
|
||||
if explicit:
|
||||
candidate = Path(explicit).expanduser().resolve()
|
||||
if not (candidate / "public").is_dir():
|
||||
raise SkillSyncError(f"Configured bundled skills directory not found: {candidate / 'public'}")
|
||||
return candidate
|
||||
|
||||
packaged = Path(__file__).resolve().parents[1] / "skills"
|
||||
candidates = (Path("/app/bundled-skills"), packaged)
|
||||
for candidate in candidates:
|
||||
resolved = candidate.resolve()
|
||||
if (resolved / "public").is_dir():
|
||||
return resolved
|
||||
raise SkillSyncError(
|
||||
"Bundled public skills directory not found; checked: "
|
||||
+ ", ".join(str(candidate.resolve() / "public") for candidate in candidates)
|
||||
)
|
||||
|
||||
|
||||
def ensure_bundled_public_skills(
|
||||
app_config,
|
||||
*,
|
||||
required: tuple[str, ...] = ROUTED_PAGE_SKILLS,
|
||||
) -> dict[str, object]:
|
||||
"""Synchronize bundled skills into the configured root during startup."""
|
||||
|
||||
source_root = resolve_bundled_skills_root()
|
||||
target_root = Path(app_config.skills.get_skills_path()).resolve()
|
||||
return publish_bundled_public_skills(source_root, target_root, required=required)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ROUTED_PAGE_SKILLS",
|
||||
"SkillSyncError",
|
||||
"ensure_bundled_public_skills",
|
||||
"publish_bundled_public_skills",
|
||||
"resolve_bundled_skills_root",
|
||||
"sync_builtin_public_skills",
|
||||
]
|
||||
@@ -0,0 +1,924 @@
|
||||
"""Agent/skill metadata migration manifests for already-copied live folders.
|
||||
|
||||
The manifest deliberately contains no agent or skill payload files. Operators
|
||||
copy those directories with their normal offline transfer process; these
|
||||
helpers only prove that the target runtime folders match the exported inventory
|
||||
before database/configuration metadata is reconciled.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Any, Literal
|
||||
from uuid import uuid4
|
||||
|
||||
import yaml
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
ResourceStatus = Literal["matched", "missing", "hash_mismatch", "identity_mismatch", "invalid_path"]
|
||||
OwnerStatus = Literal["matched", "unresolved"]
|
||||
|
||||
_TREE_HASH_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
_TREE_HASH_MAX_WORKERS = 4
|
||||
|
||||
|
||||
def _safe_relative_path(value: str) -> str:
|
||||
normalized = value.strip()
|
||||
if not normalized or "\\" in normalized or ":" in normalized:
|
||||
raise ValueError("relative_dir must be a non-empty portable relative path")
|
||||
path = PurePosixPath(normalized)
|
||||
if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
|
||||
raise ValueError("relative_dir must stay inside the configured runtime root")
|
||||
return path.as_posix()
|
||||
|
||||
|
||||
def compute_tree_hash(root: Path) -> str:
|
||||
"""Return a deterministic SHA-256 for a directory tree.
|
||||
|
||||
Relative paths and bytes are both signed. Symlinks are rejected so a
|
||||
manifest cannot attest content outside the selected runtime directory.
|
||||
"""
|
||||
|
||||
root = root.resolve()
|
||||
if not root.is_dir():
|
||||
raise FileNotFoundError(root)
|
||||
digest = hashlib.sha256()
|
||||
files = sorted((path for path in root.rglob("*") if path.is_file() or path.is_symlink()), key=lambda p: p.relative_to(root).as_posix())
|
||||
for path in files:
|
||||
if path.is_symlink():
|
||||
raise ValueError(f"Symlinks are not supported in migration trees: {path}")
|
||||
relative = path.relative_to(root).as_posix().encode("utf-8")
|
||||
digest.update(len(relative).to_bytes(4, "big"))
|
||||
digest.update(relative)
|
||||
digest.update(path.stat().st_size.to_bytes(8, "big"))
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
class OwnerReference(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
source_user_id: str | None = None
|
||||
email: str | None = None
|
||||
|
||||
@field_validator("source_user_id", "email")
|
||||
@classmethod
|
||||
def _strip_optional(cls, value: str | None) -> str | None:
|
||||
return value.strip() if value and value.strip() else None
|
||||
|
||||
|
||||
class TagManifestItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
color: str = Field(default="gray", max_length=32)
|
||||
description: str = Field(default="", max_length=1024)
|
||||
|
||||
|
||||
class AgentManifestItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str
|
||||
relative_dir: str
|
||||
tree_hash: str
|
||||
name: str
|
||||
description: str = ""
|
||||
owner: OwnerReference | None = None
|
||||
published: bool = False
|
||||
is_private: bool = False
|
||||
square_id: str = ""
|
||||
featured_order: int | None = None
|
||||
created_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
skills: list[str] = Field(default_factory=list, max_length=5000)
|
||||
tags: list[TagManifestItem] = Field(default_factory=list, max_length=200)
|
||||
|
||||
@field_validator("relative_dir")
|
||||
@classmethod
|
||||
def _relative_dir(cls, value: str) -> str:
|
||||
return _safe_relative_path(value)
|
||||
|
||||
@field_validator("tree_hash")
|
||||
@classmethod
|
||||
def _tree_hash(cls, value: str) -> str:
|
||||
normalized = value.lower()
|
||||
if not _TREE_HASH_RE.fullmatch(normalized):
|
||||
raise ValueError("tree_hash must be a SHA-256 hex digest")
|
||||
return normalized
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _directory_matches_id(self):
|
||||
if self.relative_dir != self.id.lower():
|
||||
raise ValueError("agent relative_dir must equal the stable agent id")
|
||||
return self
|
||||
|
||||
|
||||
class SkillManifestItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str
|
||||
category: Literal["public", "custom"]
|
||||
relative_dir: str
|
||||
tree_hash: str
|
||||
owner: OwnerReference | None = None
|
||||
published: bool = False
|
||||
detail: str | None = None
|
||||
name_zh: str | None = None
|
||||
always_on: bool = False
|
||||
square_id: str = ""
|
||||
enabled: bool = True
|
||||
state: Literal["active", "stale", "archived"] = "active"
|
||||
pinned: bool = False
|
||||
featured: bool = False
|
||||
source: Literal["agent", "upload"] = "upload"
|
||||
created_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
tags: list[TagManifestItem] = Field(default_factory=list, max_length=200)
|
||||
|
||||
@field_validator("relative_dir")
|
||||
@classmethod
|
||||
def _relative_dir(cls, value: str) -> str:
|
||||
normalized = _safe_relative_path(value)
|
||||
if PurePosixPath(normalized).parts[0] not in {"public", "custom"}:
|
||||
raise ValueError("skill relative_dir must begin with public/ or custom/")
|
||||
return normalized
|
||||
|
||||
@field_validator("tree_hash")
|
||||
@classmethod
|
||||
def _tree_hash(cls, value: str) -> str:
|
||||
normalized = value.lower()
|
||||
if not _TREE_HASH_RE.fullmatch(normalized):
|
||||
raise ValueError("tree_hash must be a SHA-256 hex digest")
|
||||
return normalized
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _category_matches_directory(self):
|
||||
if PurePosixPath(self.relative_dir).parts[0] != self.category:
|
||||
raise ValueError("skill category must match relative_dir")
|
||||
return self
|
||||
|
||||
|
||||
class SupportDirectoryManifestItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
relative_dir: str
|
||||
tree_hash: str
|
||||
required_by: list[str] = Field(default_factory=list, max_length=5000)
|
||||
|
||||
@field_validator("relative_dir")
|
||||
@classmethod
|
||||
def _relative_dir(cls, value: str) -> str:
|
||||
normalized = _safe_relative_path(value)
|
||||
if PurePosixPath(normalized).parts[0] not in {"public", "custom"}:
|
||||
raise ValueError("support relative_dir must begin with public/ or custom/")
|
||||
return normalized
|
||||
|
||||
@field_validator("tree_hash")
|
||||
@classmethod
|
||||
def _tree_hash(cls, value: str) -> str:
|
||||
normalized = value.lower()
|
||||
if not _TREE_HASH_RE.fullmatch(normalized):
|
||||
raise ValueError("tree_hash must be a SHA-256 hex digest")
|
||||
return normalized
|
||||
|
||||
|
||||
class MigrationManifest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
schema_version: Literal[1] = 1
|
||||
bundle_id: str = Field(min_length=1, max_length=128)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
agents: list[AgentManifestItem] = Field(default_factory=list, max_length=1000)
|
||||
skills: list[SkillManifestItem] = Field(default_factory=list, max_length=5000)
|
||||
support_directories: list[SupportDirectoryManifestItem] = Field(default_factory=list, max_length=1000)
|
||||
warnings: list[str] = Field(default_factory=list, max_length=1000)
|
||||
|
||||
|
||||
class ResourcePreflightItem(BaseModel):
|
||||
kind: Literal["agent", "skill", "support"]
|
||||
key: str
|
||||
relative_dir: str
|
||||
status: ResourceStatus
|
||||
message: str = ""
|
||||
|
||||
|
||||
class OwnerMappingItem(BaseModel):
|
||||
source_user_id: str | None = None
|
||||
email: str | None = None
|
||||
target_user_id: str | None = None
|
||||
status: OwnerStatus
|
||||
|
||||
|
||||
class MigrationPreflight(BaseModel):
|
||||
ready: bool
|
||||
agents: list[ResourcePreflightItem]
|
||||
skills: list[ResourcePreflightItem]
|
||||
support_directories: list[ResourcePreflightItem]
|
||||
owner_mappings: list[OwnerMappingItem]
|
||||
|
||||
|
||||
class MigrationApplyResult(BaseModel):
|
||||
bundle_id: str
|
||||
agents_applied: int
|
||||
skills_applied: int
|
||||
skills_skipped: int = 0
|
||||
skipped_skill_names: list[str] = Field(default_factory=list)
|
||||
tags_created: int
|
||||
fallback_owner_count: int
|
||||
|
||||
|
||||
def _resolved_child(root: Path, relative_dir: str) -> Path | None:
|
||||
root = root.resolve()
|
||||
child = root
|
||||
for part in PurePosixPath(relative_dir).parts:
|
||||
child /= part
|
||||
if child.is_symlink():
|
||||
return None
|
||||
child = child.resolve()
|
||||
try:
|
||||
child.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
return child
|
||||
|
||||
|
||||
def _agent_identity(directory: Path) -> str | None:
|
||||
config_path = directory / "config.yaml"
|
||||
if not config_path.is_file():
|
||||
return None
|
||||
try:
|
||||
payload = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
|
||||
except (OSError, UnicodeError, yaml.YAMLError):
|
||||
return None
|
||||
return str(payload.get("id") or "").strip() or None if isinstance(payload, dict) else None
|
||||
|
||||
|
||||
def _skill_identity(directory: Path) -> str | None:
|
||||
skill_path = directory / "SKILL.md"
|
||||
if not skill_path.is_file():
|
||||
return None
|
||||
try:
|
||||
text = skill_path.read_text(encoding="utf-8")
|
||||
if not text.startswith("---"):
|
||||
return None
|
||||
parts = text.split("---", 2)
|
||||
payload = yaml.safe_load(parts[1]) or {}
|
||||
except (OSError, UnicodeError, yaml.YAMLError, IndexError):
|
||||
return None
|
||||
return str(payload.get("name") or "").strip() or None if isinstance(payload, dict) else None
|
||||
|
||||
|
||||
def _resource_preflight(
|
||||
*,
|
||||
kind: Literal["agent", "skill", "support"],
|
||||
key: str,
|
||||
root: Path,
|
||||
relative_dir: str,
|
||||
expected_hash: str,
|
||||
expected_identity: str | None = None,
|
||||
) -> ResourcePreflightItem:
|
||||
directory = _resolved_child(root, relative_dir)
|
||||
if directory is None:
|
||||
return ResourcePreflightItem(
|
||||
kind=kind,
|
||||
key=key,
|
||||
relative_dir=relative_dir,
|
||||
status="invalid_path",
|
||||
message="目录路径不安全、包含符号链接或超出运行根目录",
|
||||
)
|
||||
if not directory.is_dir():
|
||||
return ResourcePreflightItem(kind=kind, key=key, relative_dir=relative_dir, status="missing", message="目标运行目录中未找到该目录")
|
||||
if expected_identity is not None:
|
||||
identity_file = directory / ("config.yaml" if kind == "agent" else "SKILL.md")
|
||||
if not identity_file.is_file():
|
||||
return ResourcePreflightItem(
|
||||
kind=kind,
|
||||
key=key,
|
||||
relative_dir=relative_dir,
|
||||
status="missing",
|
||||
message=f"目录中缺少 {identity_file.name}",
|
||||
)
|
||||
try:
|
||||
actual_hash = compute_tree_hash(directory)
|
||||
except (OSError, ValueError) as exc:
|
||||
return ResourcePreflightItem(kind=kind, key=key, relative_dir=relative_dir, status="hash_mismatch", message=str(exc))
|
||||
if actual_hash != expected_hash:
|
||||
return ResourcePreflightItem(kind=kind, key=key, relative_dir=relative_dir, status="hash_mismatch", message="目录内容与导出清单不一致")
|
||||
if expected_identity is not None:
|
||||
actual_identity = _agent_identity(directory) if kind == "agent" else _skill_identity(directory)
|
||||
if actual_identity != expected_identity:
|
||||
return ResourcePreflightItem(
|
||||
kind=kind,
|
||||
key=key,
|
||||
relative_dir=relative_dir,
|
||||
status="identity_mismatch",
|
||||
message=f"目录内标识为 {actual_identity or '空'},清单标识为 {expected_identity}",
|
||||
)
|
||||
return ResourcePreflightItem(kind=kind, key=key, relative_dir=relative_dir, status="matched")
|
||||
|
||||
|
||||
def preflight_manifest(
|
||||
manifest: MigrationManifest,
|
||||
*,
|
||||
agents_root: Path,
|
||||
skills_root: Path,
|
||||
users_by_email: dict[str, str],
|
||||
) -> MigrationPreflight:
|
||||
"""Compare a manifest with target live roots without modifying anything."""
|
||||
|
||||
normalized_users = {email.strip().casefold(): user_id for email, user_id in users_by_email.items()}
|
||||
resource_specs: list[dict[str, Any]] = [
|
||||
{
|
||||
"kind": "agent",
|
||||
"key": item.id,
|
||||
"root": agents_root,
|
||||
"relative_dir": item.relative_dir,
|
||||
"expected_hash": item.tree_hash,
|
||||
"expected_identity": item.id,
|
||||
}
|
||||
for item in manifest.agents
|
||||
]
|
||||
resource_specs.extend(
|
||||
{
|
||||
"kind": "skill",
|
||||
"key": f"{item.category}:{item.name}",
|
||||
"root": skills_root,
|
||||
"relative_dir": item.relative_dir,
|
||||
"expected_hash": item.tree_hash,
|
||||
"expected_identity": item.name,
|
||||
}
|
||||
for item in manifest.skills
|
||||
)
|
||||
resource_specs.extend(
|
||||
{
|
||||
"kind": "support",
|
||||
"key": item.relative_dir,
|
||||
"root": skills_root,
|
||||
"relative_dir": item.relative_dir,
|
||||
"expected_hash": item.tree_hash,
|
||||
}
|
||||
for item in manifest.support_directories
|
||||
)
|
||||
|
||||
def _check_resource(spec: dict[str, Any]) -> ResourcePreflightItem:
|
||||
return _resource_preflight(**spec)
|
||||
|
||||
if len(resource_specs) > 1:
|
||||
with ThreadPoolExecutor(
|
||||
max_workers=min(_TREE_HASH_MAX_WORKERS, len(resource_specs)),
|
||||
thread_name_prefix="skill-migration-hash",
|
||||
) as executor:
|
||||
resources = list(executor.map(_check_resource, resource_specs))
|
||||
else:
|
||||
resources = [_check_resource(spec) for spec in resource_specs]
|
||||
|
||||
agent_count = len(manifest.agents)
|
||||
skill_count = len(manifest.skills)
|
||||
agents = resources[:agent_count]
|
||||
skills = resources[agent_count : agent_count + skill_count]
|
||||
support = resources[agent_count + skill_count :]
|
||||
|
||||
owners: dict[tuple[str | None, str | None], OwnerMappingItem] = {}
|
||||
for resource in [*manifest.agents, *manifest.skills]:
|
||||
owner = resource.owner
|
||||
if owner is None or (owner.source_user_id is None and owner.email is None):
|
||||
continue
|
||||
email = owner.email.strip().casefold() if owner.email else None
|
||||
target_user_id = normalized_users.get(email) if email else None
|
||||
key = (owner.source_user_id, email)
|
||||
owners[key] = OwnerMappingItem(
|
||||
source_user_id=owner.source_user_id,
|
||||
email=email,
|
||||
target_user_id=target_user_id,
|
||||
status="matched" if target_user_id else "unresolved",
|
||||
)
|
||||
|
||||
owner_mappings = list(owners.values())
|
||||
ready = all(item.status == "matched" for item in [*agents, *skills, *support]) and all(item.status == "matched" for item in owner_mappings)
|
||||
return MigrationPreflight(
|
||||
ready=ready,
|
||||
agents=agents,
|
||||
skills=skills,
|
||||
support_directories=support,
|
||||
owner_mappings=owner_mappings,
|
||||
)
|
||||
|
||||
|
||||
def prepare_manifest_for_apply(
|
||||
manifest: MigrationManifest,
|
||||
preflight: MigrationPreflight,
|
||||
*,
|
||||
skip_invalid_skills: bool,
|
||||
) -> tuple[MigrationManifest, MigrationPreflight, list[str]]:
|
||||
"""Optionally remove invalid skills and support-directory dependants.
|
||||
|
||||
Skipping is intentionally limited to skill-only manifests. Agent manifests
|
||||
retain all-or-nothing semantics because their live ``config.yaml`` is the
|
||||
authoritative source for several related database caches.
|
||||
"""
|
||||
|
||||
if not skip_invalid_skills:
|
||||
return manifest, preflight, []
|
||||
if manifest.agents:
|
||||
raise ValueError("跳过异常条目仅支持独立技能清单")
|
||||
|
||||
failed_skill_dirs = {
|
||||
item.relative_dir for item in preflight.skills if item.status != "matched"
|
||||
}
|
||||
skipped_names = {
|
||||
item.name for item in manifest.skills if item.relative_dir in failed_skill_dirs
|
||||
}
|
||||
support_by_dir = {
|
||||
item.relative_dir: item for item in manifest.support_directories
|
||||
}
|
||||
for resource in preflight.support_directories:
|
||||
if resource.status == "matched":
|
||||
continue
|
||||
support = support_by_dir.get(resource.relative_dir)
|
||||
if support is not None:
|
||||
skipped_names.update(support.required_by)
|
||||
|
||||
ordered_skipped = [item.name for item in manifest.skills if item.name in skipped_names]
|
||||
kept_skills = [item for item in manifest.skills if item.name not in skipped_names]
|
||||
kept_names = {item.name for item in kept_skills}
|
||||
kept_support = [
|
||||
item
|
||||
for item in manifest.support_directories
|
||||
if any(name in kept_names for name in item.required_by)
|
||||
]
|
||||
kept_skill_dirs = {item.relative_dir for item in kept_skills}
|
||||
kept_support_dirs = {item.relative_dir for item in kept_support}
|
||||
|
||||
owner_keys = {
|
||||
(
|
||||
item.owner.source_user_id,
|
||||
item.owner.email.strip().casefold() if item.owner and item.owner.email else None,
|
||||
)
|
||||
for item in kept_skills
|
||||
if item.owner is not None
|
||||
and (item.owner.source_user_id is not None or item.owner.email is not None)
|
||||
}
|
||||
owner_mappings = [
|
||||
item
|
||||
for item in preflight.owner_mappings
|
||||
if (
|
||||
item.source_user_id,
|
||||
item.email.strip().casefold() if item.email else None,
|
||||
)
|
||||
in owner_keys
|
||||
]
|
||||
skill_resources = [
|
||||
item for item in preflight.skills if item.relative_dir in kept_skill_dirs
|
||||
]
|
||||
support_resources = [
|
||||
item
|
||||
for item in preflight.support_directories
|
||||
if item.relative_dir in kept_support_dirs
|
||||
]
|
||||
ready = all(
|
||||
item.status == "matched"
|
||||
for item in [*preflight.agents, *skill_resources, *support_resources]
|
||||
) and all(item.status == "matched" for item in owner_mappings)
|
||||
|
||||
effective_manifest = manifest.model_copy(
|
||||
update={
|
||||
"skills": kept_skills,
|
||||
"support_directories": kept_support,
|
||||
}
|
||||
)
|
||||
effective_preflight = preflight.model_copy(
|
||||
update={
|
||||
"ready": ready,
|
||||
"skills": skill_resources,
|
||||
"support_directories": support_resources,
|
||||
"owner_mappings": owner_mappings,
|
||||
}
|
||||
)
|
||||
return effective_manifest, effective_preflight, ordered_skipped
|
||||
|
||||
|
||||
def _owner_reference(user_id: str | None, users_by_id: dict[str, str]) -> OwnerReference | None:
|
||||
if user_id is None:
|
||||
return None
|
||||
return OwnerReference(source_user_id=user_id, email=users_by_id.get(user_id))
|
||||
|
||||
|
||||
def _load_agent_config(directory: Path) -> dict[str, Any]:
|
||||
try:
|
||||
payload = yaml.safe_load((directory / "config.yaml").read_text(encoding="utf-8")) or {}
|
||||
except (OSError, UnicodeError, yaml.YAMLError) as exc:
|
||||
raise ValueError(f"Cannot read agent config: {directory}") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError(f"Agent config must be an object: {directory}")
|
||||
return payload
|
||||
|
||||
|
||||
def _manifest_tags(rows: list[dict[str, Any]]) -> list[TagManifestItem]:
|
||||
return [
|
||||
TagManifestItem(
|
||||
id=str(row.get("id") or ""),
|
||||
name=str(row.get("name") or ""),
|
||||
color=str(row.get("color") or "gray"),
|
||||
description=str(row.get("description") or ""),
|
||||
)
|
||||
for row in rows
|
||||
if row.get("id") and row.get("name")
|
||||
]
|
||||
|
||||
|
||||
async def build_agent_migration_manifest(
|
||||
agent_ids: list[str],
|
||||
*,
|
||||
agent_store: Any,
|
||||
tag_store: Any,
|
||||
agents_root: Path,
|
||||
users_by_id: dict[str, str],
|
||||
) -> MigrationManifest:
|
||||
"""Build an agent manifest without inspecting or exporting skill payloads."""
|
||||
|
||||
selected_ids = list(dict.fromkeys(agent_id.strip() for agent_id in agent_ids if agent_id.strip()))
|
||||
if not selected_ids:
|
||||
raise ValueError("Select at least one agent")
|
||||
rows_by_id = {str(row["id"]): row for row in await agent_store.list_all()}
|
||||
missing_agents = [agent_id for agent_id in selected_ids if agent_id not in rows_by_id]
|
||||
if missing_agents:
|
||||
raise ValueError(f"Unknown agents: {', '.join(missing_agents)}")
|
||||
|
||||
agent_tag_map = await tag_store.list_assignments("agent", selected_ids)
|
||||
agents: list[AgentManifestItem] = []
|
||||
warnings: list[str] = []
|
||||
for agent_id in selected_ids:
|
||||
row = rows_by_id[agent_id]
|
||||
directory = _resolved_child(agents_root, agent_id.lower())
|
||||
if directory is None or not directory.is_dir():
|
||||
raise ValueError(f"Agent directory is missing: {agent_id}")
|
||||
config = _load_agent_config(directory)
|
||||
if str(config.get("id") or "") != agent_id:
|
||||
raise ValueError(f"Agent config id does not match directory: {agent_id}")
|
||||
raw_skills = config.get("skills")
|
||||
selected_skills = list(dict.fromkeys(item.strip() for item in raw_skills if isinstance(item, str) and item.strip())) if isinstance(raw_skills, list) else []
|
||||
knowledge_ids = config.get("llmwiki_knowledge_base_ids")
|
||||
if isinstance(knowledge_ids, list) and any(str(item).strip() for item in knowledge_ids):
|
||||
warnings.append(f"智能体 {agent_id} 绑定了知识库;知识库数据不在本迁移清单范围内,请在目标机器单独确认")
|
||||
agents.append(
|
||||
AgentManifestItem(
|
||||
id=agent_id,
|
||||
relative_dir=directory.relative_to(agents_root.resolve()).as_posix(),
|
||||
tree_hash=await asyncio.to_thread(compute_tree_hash, directory),
|
||||
name=str(row.get("name") or config.get("name") or agent_id),
|
||||
description=str(row.get("description") or ""),
|
||||
owner=_owner_reference(row.get("user_id"), users_by_id),
|
||||
published=bool(row.get("published")),
|
||||
is_private=bool(row.get("is_private")),
|
||||
square_id=str(row.get("square_id") or ""),
|
||||
featured_order=row.get("featured_order"),
|
||||
created_at=row.get("created_at"),
|
||||
updated_at=row.get("updated_at"),
|
||||
skills=selected_skills,
|
||||
tags=_manifest_tags(agent_tag_map.get(agent_id, [])),
|
||||
)
|
||||
)
|
||||
|
||||
return MigrationManifest(
|
||||
bundle_id=uuid4().hex,
|
||||
agents=agents,
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
|
||||
async def build_skill_migration_manifest(
|
||||
skill_names: list[str],
|
||||
*,
|
||||
skill_store: Any,
|
||||
tag_store: Any,
|
||||
skills_root: Path,
|
||||
discovered_skills: list[Any],
|
||||
users_by_id: dict[str, str],
|
||||
usage_entries: dict[str, dict[str, Any]],
|
||||
) -> MigrationManifest:
|
||||
"""Build a metadata-only manifest for explicitly selected live skills."""
|
||||
|
||||
selected_names = list(dict.fromkeys(name.strip() for name in skill_names if name.strip()))
|
||||
if not selected_names:
|
||||
raise ValueError("Select at least one skill")
|
||||
|
||||
skill_rows = {str(row["name"]): row for row in await skill_store.list_all()}
|
||||
discovered = {str(skill.name): skill for skill in discovered_skills}
|
||||
missing_skills = [name for name in selected_names if name not in discovered]
|
||||
if missing_skills:
|
||||
raise ValueError(f"Skills are missing from the live runtime directory: {', '.join(missing_skills)}")
|
||||
|
||||
skill_tag_map = await tag_store.list_assignments("skill", selected_names)
|
||||
skill_directories = [Path(discovered[name].skill_dir).resolve() for name in selected_names]
|
||||
tree_hashes = await _compute_tree_hashes(skill_directories)
|
||||
skills: list[SkillManifestItem] = []
|
||||
for name, tree_hash in zip(selected_names, tree_hashes, strict=True):
|
||||
skill = discovered[name]
|
||||
category = str(skill.category)
|
||||
relative = PurePosixPath(category) / PurePosixPath(Path(skill.relative_path).as_posix())
|
||||
directory = Path(skill.skill_dir).resolve()
|
||||
row = skill_rows.get(name, {})
|
||||
usage = usage_entries.get(name, {})
|
||||
state = str(usage.get("state") or "active")
|
||||
if state not in {"active", "stale", "archived"}:
|
||||
state = "active"
|
||||
source = str(usage.get("source") or "upload")
|
||||
if source not in {"agent", "upload"}:
|
||||
source = "upload"
|
||||
skills.append(
|
||||
SkillManifestItem(
|
||||
name=name,
|
||||
category=category,
|
||||
relative_dir=relative.as_posix(),
|
||||
tree_hash=tree_hash,
|
||||
owner=_owner_reference(row.get("owner_user_id"), users_by_id),
|
||||
published=bool(row.get("published", category == "public")),
|
||||
detail=row.get("detail"),
|
||||
name_zh=row.get("name_zh"),
|
||||
always_on=bool(row.get("always_on", getattr(skill, "always_on", False))),
|
||||
square_id=str(row.get("square_id") or ""),
|
||||
enabled=bool(skill.enabled),
|
||||
state=state,
|
||||
pinned=bool(usage.get("pinned")),
|
||||
featured=bool(usage.get("featured")),
|
||||
source=source,
|
||||
created_at=row.get("created_at") or usage.get("created_at"),
|
||||
updated_at=row.get("updated_at"),
|
||||
tags=_manifest_tags(skill_tag_map.get(name, [])),
|
||||
)
|
||||
)
|
||||
|
||||
selected_set = set(selected_names)
|
||||
warnings: list[str] = []
|
||||
support_directories: list[SupportDirectoryManifestItem] = []
|
||||
support_candidates, support_warnings = await asyncio.to_thread(
|
||||
_find_support_directories,
|
||||
skills_root,
|
||||
selected_set,
|
||||
)
|
||||
warnings.extend(support_warnings)
|
||||
support_hashes = await _compute_tree_hashes(
|
||||
[directory for directory, _required_by in support_candidates]
|
||||
)
|
||||
for (directory, selected_required_by), tree_hash in zip(
|
||||
support_candidates,
|
||||
support_hashes,
|
||||
strict=True,
|
||||
):
|
||||
support_directories.append(
|
||||
SupportDirectoryManifestItem(
|
||||
relative_dir=directory.relative_to(skills_root.resolve()).as_posix(),
|
||||
tree_hash=tree_hash,
|
||||
required_by=selected_required_by,
|
||||
)
|
||||
)
|
||||
|
||||
return MigrationManifest(
|
||||
bundle_id=uuid4().hex,
|
||||
skills=skills,
|
||||
support_directories=support_directories,
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
|
||||
async def _compute_tree_hashes(directories: list[Path]) -> list[str]:
|
||||
if not directories:
|
||||
return []
|
||||
semaphore = asyncio.Semaphore(min(_TREE_HASH_MAX_WORKERS, len(directories)))
|
||||
|
||||
async def _compute(directory: Path) -> str:
|
||||
async with semaphore:
|
||||
return await asyncio.to_thread(compute_tree_hash, directory)
|
||||
|
||||
return list(await asyncio.gather(*(_compute(directory) for directory in directories)))
|
||||
|
||||
|
||||
def _find_support_directories(
|
||||
skills_root: Path,
|
||||
selected_names: set[str],
|
||||
) -> tuple[list[tuple[Path, list[str]]], list[str]]:
|
||||
candidates: list[tuple[Path, list[str]]] = []
|
||||
warnings: list[str] = []
|
||||
for support_manifest in sorted(skills_root.rglob(".deerflow-skill-support.json")):
|
||||
try:
|
||||
payload = json.loads(support_manifest.read_text(encoding="utf-8"))
|
||||
required_by = [str(item).strip() for item in payload.get("required_by", []) if str(item).strip()]
|
||||
except (OSError, UnicodeError, json.JSONDecodeError, AttributeError):
|
||||
warnings.append(f"无法读取技能支持目录清单:{support_manifest}")
|
||||
continue
|
||||
selected_required_by = [name for name in required_by if name in selected_names]
|
||||
if not selected_required_by:
|
||||
continue
|
||||
candidates.append((support_manifest.parent.resolve(), selected_required_by))
|
||||
return candidates, warnings
|
||||
|
||||
|
||||
def _apply_usage_metadata(name: str, metadata: dict[str, Any]) -> None:
|
||||
_apply_usage_metadata_batch({name: metadata})
|
||||
|
||||
|
||||
def _apply_usage_metadata_batch(entries: dict[str, dict[str, Any]]) -> None:
|
||||
from deerflow.skills.usage import set_migration_metadata_batch
|
||||
|
||||
set_migration_metadata_batch(entries)
|
||||
|
||||
|
||||
def _target_owner_id(
|
||||
owner: OwnerReference | None,
|
||||
*,
|
||||
users_by_email: dict[str, str],
|
||||
fallback_owner_user_id: str | None,
|
||||
) -> tuple[str | None, bool]:
|
||||
if owner is None or (owner.source_user_id is None and owner.email is None):
|
||||
return None, False
|
||||
target = users_by_email.get(owner.email.casefold()) if owner.email else None
|
||||
if target:
|
||||
return target, False
|
||||
if fallback_owner_user_id:
|
||||
return fallback_owner_user_id, True
|
||||
raise ValueError(f"Unresolved owner: {owner.email or owner.source_user_id}")
|
||||
|
||||
|
||||
async def _apply_tags(tag_store: Any, target_type: str, target_id: str, tags: list[TagManifestItem]) -> int:
|
||||
return await _apply_tags_bulk(tag_store, target_type, [(target_id, tags)])
|
||||
|
||||
|
||||
async def _apply_tags_bulk(
|
||||
tag_store: Any,
|
||||
target_type: str,
|
||||
targets: list[tuple[str, list[TagManifestItem]]],
|
||||
) -> int:
|
||||
if not targets:
|
||||
return 0
|
||||
existing = await tag_store.list_tags()
|
||||
by_name = {
|
||||
(str(row.get("tag_type")), str(row.get("name"))): row
|
||||
for row in existing
|
||||
}
|
||||
used_ids = {str(row.get("id")) for row in existing}
|
||||
assignments: dict[str, list[str]] = {}
|
||||
created = 0
|
||||
for target_id, tags in targets:
|
||||
tag_ids: list[str] = []
|
||||
for tag in tags:
|
||||
same_name = by_name.get((target_type, tag.name))
|
||||
if same_name is not None:
|
||||
tag_ids.append(str(same_name["id"]))
|
||||
continue
|
||||
tag_id = tag.id if tag.id not in used_ids else uuid4().hex
|
||||
created_tag = await tag_store.create_tag(
|
||||
{
|
||||
"id": tag_id,
|
||||
"name": tag.name,
|
||||
"tag_type": target_type,
|
||||
"color": tag.color,
|
||||
"description": tag.description,
|
||||
}
|
||||
)
|
||||
by_name[(target_type, tag.name)] = created_tag
|
||||
used_ids.add(tag_id)
|
||||
tag_ids.append(tag_id)
|
||||
created += 1
|
||||
assignments[target_id] = tag_ids
|
||||
await tag_store.set_target_tags_bulk(target_type, assignments)
|
||||
return created
|
||||
|
||||
|
||||
async def apply_migration_manifest(
|
||||
manifest: MigrationManifest,
|
||||
*,
|
||||
preflight: MigrationPreflight,
|
||||
agent_store: Any,
|
||||
skill_store: Any,
|
||||
tag_store: Any,
|
||||
agents_root: Path,
|
||||
users_by_email: dict[str, str],
|
||||
fallback_owner_user_id: str | None,
|
||||
extensions_config_path: Path | None,
|
||||
skip_invalid_skills: bool = False,
|
||||
) -> MigrationApplyResult:
|
||||
"""Idempotently reconcile metadata after all live folders passed preflight."""
|
||||
|
||||
manifest, preflight, skipped_skill_names = prepare_manifest_for_apply(
|
||||
manifest,
|
||||
preflight,
|
||||
skip_invalid_skills=skip_invalid_skills,
|
||||
)
|
||||
|
||||
bad_resources = [item for item in [*preflight.agents, *preflight.skills, *preflight.support_directories] if item.status != "matched"]
|
||||
if bad_resources:
|
||||
raise ValueError("Migration preflight contains missing or mismatched directories")
|
||||
if any(item.status == "unresolved" for item in preflight.owner_mappings) and not fallback_owner_user_id:
|
||||
raise ValueError("Migration preflight contains unresolved owners")
|
||||
|
||||
if manifest.skills:
|
||||
if extensions_config_path is None:
|
||||
raise ValueError("目标运行环境未找到 extensions_config.json")
|
||||
from deerflow.config.extensions_config import patch_extensions_config
|
||||
|
||||
enabled_by_name = {item.name: item.enabled for item in manifest.skills}
|
||||
|
||||
def _patch(document: dict[str, Any]) -> None:
|
||||
skills_document = document.setdefault("skills", {})
|
||||
if not isinstance(skills_document, dict):
|
||||
raise ValueError("extensions_config.json skills must be an object")
|
||||
for name, enabled in enabled_by_name.items():
|
||||
current = skills_document.get(name)
|
||||
entry = dict(current) if isinstance(current, dict) else {}
|
||||
entry["enabled"] = enabled
|
||||
skills_document[name] = entry
|
||||
|
||||
patch_extensions_config(extensions_config_path, _patch)
|
||||
|
||||
normalized_users = {email.strip().casefold(): user_id for email, user_id in users_by_email.items()}
|
||||
fallback_count = 0
|
||||
tags_created = 0
|
||||
skill_payloads: list[dict[str, Any]] = []
|
||||
skill_usage_entries: dict[str, dict[str, Any]] = {}
|
||||
for item in manifest.skills:
|
||||
owner_user_id, used_fallback = _target_owner_id(
|
||||
item.owner,
|
||||
users_by_email=normalized_users,
|
||||
fallback_owner_user_id=fallback_owner_user_id,
|
||||
)
|
||||
fallback_count += int(used_fallback)
|
||||
skill_payloads.append(
|
||||
{
|
||||
"name": item.name,
|
||||
"owner_user_id": owner_user_id,
|
||||
"published": item.published,
|
||||
"detail": item.detail,
|
||||
"name_zh": item.name_zh,
|
||||
"always_on": item.always_on,
|
||||
"square_id": item.square_id,
|
||||
"created_at": item.created_at,
|
||||
"updated_at": item.updated_at,
|
||||
}
|
||||
)
|
||||
skill_usage_entries[item.name] = {
|
||||
"state": item.state,
|
||||
"pinned": item.pinned,
|
||||
"featured": item.featured,
|
||||
"source": item.source,
|
||||
}
|
||||
|
||||
if skill_payloads:
|
||||
await skill_store.migration_upsert_many(skill_payloads)
|
||||
tags_created += await _apply_tags_bulk(
|
||||
tag_store,
|
||||
"skill",
|
||||
[(item.name, item.tags) for item in manifest.skills],
|
||||
)
|
||||
_apply_usage_metadata_batch(skill_usage_entries)
|
||||
|
||||
agent_tag_targets: list[tuple[str, list[TagManifestItem]]] = []
|
||||
for item in manifest.agents:
|
||||
owner_user_id, used_fallback = _target_owner_id(
|
||||
item.owner,
|
||||
users_by_email=normalized_users,
|
||||
fallback_owner_user_id=fallback_owner_user_id,
|
||||
)
|
||||
fallback_count += int(used_fallback)
|
||||
await agent_store.migration_upsert(
|
||||
{
|
||||
"id": item.id,
|
||||
"name": item.name,
|
||||
"description": item.description,
|
||||
"user_id": owner_user_id,
|
||||
"published": item.published,
|
||||
"is_private": item.is_private,
|
||||
"square_id": item.square_id,
|
||||
"featured_order": item.featured_order,
|
||||
"created_at": item.created_at,
|
||||
"updated_at": item.updated_at,
|
||||
}
|
||||
)
|
||||
config = _load_agent_config(agents_root / item.relative_dir)
|
||||
await agent_store.replace_skills(item.id, config.get("skills") if isinstance(config.get("skills"), list) else [])
|
||||
await agent_store.set_extras(
|
||||
item.id,
|
||||
tool_groups=config.get("tool_groups") if isinstance(config.get("tool_groups"), list) else None,
|
||||
model=str(config.get("model")) if config.get("model") else None,
|
||||
)
|
||||
agent_tag_targets.append((item.id, item.tags))
|
||||
|
||||
tags_created += await _apply_tags_bulk(tag_store, "agent", agent_tag_targets)
|
||||
|
||||
return MigrationApplyResult(
|
||||
bundle_id=manifest.bundle_id,
|
||||
agents_applied=len(manifest.agents),
|
||||
skills_applied=len(manifest.skills),
|
||||
skills_skipped=len(skipped_skill_names),
|
||||
skipped_skill_names=skipped_skill_names,
|
||||
tags_created=tags_created,
|
||||
fallback_owner_count=fallback_count,
|
||||
)
|
||||
@@ -37,6 +37,7 @@ from app.gateway.routers import (
|
||||
admin_active_runs,
|
||||
admin_audit_retention as admin_audit_retention_routes,
|
||||
admin_users,
|
||||
agent_skill_migrations,
|
||||
agents,
|
||||
ai_writing,
|
||||
app_identity,
|
||||
@@ -48,6 +49,7 @@ from app.gateway.routers import (
|
||||
browser_context,
|
||||
business_mapping,
|
||||
channels,
|
||||
chat_history_transfer,
|
||||
chat_archive,
|
||||
checkpoint_migration,
|
||||
compact_menu_overrides,
|
||||
@@ -1204,6 +1206,30 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
logger.exception(error_msg)
|
||||
raise RuntimeError(error_msg) from e
|
||||
|
||||
# Populate product-owned public skills before any ownership migration,
|
||||
# MySQL catalogue projection, prompt cache, or sandbox view observes the
|
||||
# configured live root. This application-level guard is intentionally in
|
||||
# addition to the supported shell launchers: image entrypoints, Compose,
|
||||
# and external release wrappers must receive the same built-ins.
|
||||
try:
|
||||
from app.builtin_skill_sync import ensure_bundled_public_skills
|
||||
|
||||
sync_result = await asyncio.to_thread(
|
||||
ensure_bundled_public_skills,
|
||||
app.state.config,
|
||||
)
|
||||
logger.info(
|
||||
"Bundled public skills synchronized: source=%s target=%s copied=%d required=%d",
|
||||
sync_result["source"],
|
||||
sync_result["target"],
|
||||
len(sync_result["copiedDirectories"]),
|
||||
len(sync_result["requiredSkills"]),
|
||||
)
|
||||
except Exception as e:
|
||||
error_msg = f"Failed to synchronize required built-in skills during gateway startup: {e}"
|
||||
logger.exception(error_msg)
|
||||
raise RuntimeError(error_msg) from e
|
||||
|
||||
config = get_gateway_config()
|
||||
logger.info(f"Starting API Gateway on {config.host}:{config.port}")
|
||||
|
||||
@@ -1276,6 +1302,20 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
except Exception:
|
||||
logger.exception("Skill MySQL catalog projection sync failed (non-fatal)")
|
||||
|
||||
# Project the compact per-skill catalog metadata into MySQL before the
|
||||
# Gateway accepts requests. List APIs read indexed scalar columns and
|
||||
# never load skill markdown, display samples, or usage sidecars.
|
||||
try:
|
||||
from app.gateway.skill_catalog_cache import refresh_skill_catalog_projection
|
||||
|
||||
catalog_size = await refresh_skill_catalog_projection(
|
||||
app.state.config,
|
||||
skills=catalog_skills,
|
||||
)
|
||||
logger.info("Skill MySQL catalog projection synchronized: skills=%d", catalog_size)
|
||||
except Exception:
|
||||
logger.exception("Skill MySQL catalog projection sync failed (non-fatal)")
|
||||
|
||||
# ????? agent(intent / recommender / coordinator)???????
|
||||
# ??? _sync_legacy_agents **??**??????????????????
|
||||
# ??? upsert ? agents ?,?????? /api/agents ?????,
|
||||
@@ -1462,6 +1502,32 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
logger.exception(
|
||||
"Elasticsearch offline operations agent seeding failed at startup (non-fatal)"
|
||||
)
|
||||
|
||||
# 内置「聊天记录迁移助手」:高斯/SQLite 会话索引、检查点和线程文件分开迁移。
|
||||
# 目录已存在时不覆盖管理员修改。
|
||||
try:
|
||||
from app.gateway.routers._chat_history_migration_seed import (
|
||||
ensure_chat_history_migration_agent,
|
||||
)
|
||||
|
||||
ensure_chat_history_migration_agent()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Chat-history migration agent seeding failed at startup (non-fatal)"
|
||||
)
|
||||
|
||||
# 内置「高斯数据适配助手」:根据报错说明要改的配置。目录已存在时不覆盖。
|
||||
try:
|
||||
from app.gateway.routers._gauss_data_adaptation_seed import (
|
||||
ensure_gauss_data_adaptation_agent,
|
||||
)
|
||||
|
||||
ensure_gauss_data_adaptation_agent()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Gauss data-adaptation agent seeding failed at startup (non-fatal)"
|
||||
)
|
||||
|
||||
# 内置「任务研判报告助手」(agentfx 任务深链固定使用):同样必须在
|
||||
# _sync_legacy_agents 之前补建目录 + 补建配套 task-report-import 技能
|
||||
# (skills/ 被 .gitignore 排除),由后者 upsert 进 agents 表。
|
||||
@@ -1587,6 +1653,13 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
except Exception:
|
||||
logger.exception("Admin audit retention scheduler failed to start (non-fatal)")
|
||||
|
||||
try:
|
||||
app.state.admin_audit_retention_task = asyncio.create_task(
|
||||
_admin_audit_retention_loop(app)
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Admin audit retention scheduler failed to start (non-fatal)")
|
||||
|
||||
# Start IM channel service if any channels are configured
|
||||
try:
|
||||
from app.channels.service import start_channel_service
|
||||
@@ -1765,6 +1838,25 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
await close_api_read_cache()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
from app.gateway.worker_pool.lifecycle import managed_controller
|
||||
from app.gateway.perf_logging import event_loop_watchdog, register_stack_dump_signal
|
||||
|
||||
register_stack_dump_signal()
|
||||
watchdog = asyncio.create_task(event_loop_watchdog(app), name="gateway-event-loop-watchdog")
|
||||
try:
|
||||
async with managed_controller(app):
|
||||
async with _gateway_lifespan(app):
|
||||
yield
|
||||
finally:
|
||||
watchdog.cancel()
|
||||
await asyncio.gather(watchdog, return_exceptions=True)
|
||||
from app.gateway.api_read_cache import close_api_read_cache
|
||||
|
||||
await close_api_read_cache()
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""Create and configure the FastAPI application.
|
||||
|
||||
@@ -2097,11 +2189,14 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
|
||||
app.include_router(analysis_projects.router)
|
||||
app.include_router(threads.router)
|
||||
app.include_router(chat_history_transfer.router)
|
||||
# Dedicated taskId + goPath history lookup for single-agent task deep-link chats.
|
||||
app.include_router(task_deeplink_threads.router)
|
||||
app.include_router(task_deeplink_details.router)
|
||||
# Agents API is mounted at /api/agents
|
||||
app.include_router(agents.router)
|
||||
# Metadata-only migration for agent/skill folders copied into live roots.
|
||||
app.include_router(agent_skill_migrations.router)
|
||||
app.include_router(strategy_agents.router)
|
||||
|
||||
# Recommended Questions API is mounted at /api/recommended-questions
|
||||
|
||||
@@ -1,401 +1,410 @@
|
||||
"""Authorization decorators and context for DeerFlow.
|
||||
|
||||
Inspired by LangGraph Auth system: https://github.com/langchain-ai/langgraph/blob/main/libs/sdk-py/langgraph_sdk/auth/__init__.py
|
||||
|
||||
**Usage:**
|
||||
|
||||
1. Use ``@require_auth`` on routes that need authentication
|
||||
2. Use ``@require_permission("resource", "action", filter_key=...)`` for permission checks
|
||||
3. The decorator chain processes from bottom to top
|
||||
|
||||
**Example:**
|
||||
|
||||
@router.get("/{thread_id}")
|
||||
@require_auth
|
||||
@require_permission("threads", "read", owner_check=True)
|
||||
async def get_thread(thread_id: str, request: Request):
|
||||
# User is authenticated and has threads:read permission
|
||||
...
|
||||
|
||||
**Permission Model:**
|
||||
|
||||
- threads:read - View thread
|
||||
- threads:write - Create/update thread
|
||||
- threads:delete - Delete thread
|
||||
- runs:create - Run agent
|
||||
- runs:read - View run
|
||||
- runs:cancel - Cancel run
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import inspect
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from app.gateway.auth.disabled_mode import get_assumed_user_for_disabled_auth, is_auth_disabled
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.gateway.auth.models import User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
P = ParamSpec("P")
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
async def _project_for_thread(project_store: Any, thread_id: str) -> dict | None:
|
||||
"""Best-effort project binding lookup; a store error must not fail the read."""
|
||||
try:
|
||||
return await project_store.project_for_thread(thread_id)
|
||||
except Exception:
|
||||
logger.debug("project_for_thread failed for %s", thread_id, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def _thread_checkpoint_exists(request: Request, thread_id: str) -> bool:
|
||||
"""Return True if a LangGraph checkpoint exists for ``thread_id``.
|
||||
|
||||
A checkpoint with no matching ``threads_meta`` row is the signature of a
|
||||
DB-switch orphan (sqlite↔mysql/postgres juggling): the conversation state
|
||||
survives in the checkpointer while the business row is gone. Normal thread
|
||||
deletion removes the checkpoint too, so this can never resurrect a
|
||||
deliberately-deleted thread.
|
||||
"""
|
||||
try:
|
||||
from app.gateway.deps import get_checkpointer
|
||||
|
||||
checkpointer = get_checkpointer(request)
|
||||
tup = await checkpointer.aget_tuple({"configurable": {"thread_id": thread_id}})
|
||||
return tup is not None
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# Permission constants
|
||||
class Permissions:
|
||||
"""Permission constants for resource:action format."""
|
||||
|
||||
# Threads
|
||||
THREADS_READ = "threads:read"
|
||||
THREADS_WRITE = "threads:write"
|
||||
THREADS_DELETE = "threads:delete"
|
||||
|
||||
# Runs
|
||||
RUNS_CREATE = "runs:create"
|
||||
RUNS_READ = "runs:read"
|
||||
RUNS_CANCEL = "runs:cancel"
|
||||
|
||||
|
||||
class AuthContext:
|
||||
"""Authentication context for the current request.
|
||||
|
||||
Stored in request.state.auth after require_auth decoration.
|
||||
|
||||
Attributes:
|
||||
user: The authenticated user, or None if anonymous
|
||||
permissions: List of permission strings (e.g., "threads:read")
|
||||
"""
|
||||
|
||||
__slots__ = ("user", "permissions")
|
||||
|
||||
def __init__(self, user: User | None = None, permissions: list[str] | None = None):
|
||||
self.user = user
|
||||
self.permissions = permissions or []
|
||||
|
||||
@property
|
||||
def is_authenticated(self) -> bool:
|
||||
"""Check if user is authenticated."""
|
||||
return self.user is not None
|
||||
|
||||
def has_permission(self, resource: str, action: str) -> bool:
|
||||
"""Check if context has permission for resource:action.
|
||||
|
||||
Args:
|
||||
resource: Resource name (e.g., "threads")
|
||||
action: Action name (e.g., "read")
|
||||
|
||||
Returns:
|
||||
True if user has permission
|
||||
"""
|
||||
permission = f"{resource}:{action}"
|
||||
return permission in self.permissions
|
||||
|
||||
def require_user(self) -> User:
|
||||
"""Get user or raise 401.
|
||||
|
||||
Raises:
|
||||
HTTPException 401 if not authenticated
|
||||
"""
|
||||
if not self.user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
return self.user
|
||||
|
||||
|
||||
def get_auth_context(request: Request) -> AuthContext | None:
|
||||
"""Get AuthContext from request state."""
|
||||
return getattr(request.state, "auth", None)
|
||||
|
||||
|
||||
_ALL_PERMISSIONS: list[str] = [
|
||||
Permissions.THREADS_READ,
|
||||
Permissions.THREADS_WRITE,
|
||||
Permissions.THREADS_DELETE,
|
||||
Permissions.RUNS_CREATE,
|
||||
Permissions.RUNS_READ,
|
||||
Permissions.RUNS_CANCEL,
|
||||
]
|
||||
|
||||
|
||||
def _make_test_request_stub() -> Any:
|
||||
"""Create a minimal request-like object for direct unit calls.
|
||||
|
||||
Used when decorated route handlers are invoked without FastAPI's
|
||||
request injection. Includes fields accessed by auth helpers.
|
||||
"""
|
||||
return SimpleNamespace(state=SimpleNamespace(), cookies={}, _deerflow_test_bypass_auth=True)
|
||||
|
||||
|
||||
async def _authenticate(request: Request) -> AuthContext:
|
||||
"""Authenticate request and return AuthContext.
|
||||
|
||||
Delegates to deps.get_optional_user_from_request() for the JWT→User pipeline.
|
||||
Returns AuthContext with user=None for anonymous requests.
|
||||
"""
|
||||
if is_auth_disabled():
|
||||
user = await get_assumed_user_for_disabled_auth()
|
||||
return AuthContext(user=user, permissions=_ALL_PERMISSIONS)
|
||||
|
||||
from app.gateway.deps import get_optional_user_from_request
|
||||
|
||||
user = await get_optional_user_from_request(request)
|
||||
if user is None:
|
||||
return AuthContext(user=None, permissions=[])
|
||||
|
||||
# In future, permissions could be stored in user record
|
||||
return AuthContext(user=user, permissions=_ALL_PERMISSIONS)
|
||||
|
||||
|
||||
def require_auth[**P, T](func: Callable[P, T]) -> Callable[P, T]:
|
||||
"""Decorator that authenticates the request and enforces authentication.
|
||||
|
||||
Independently raises HTTP 401 for unauthenticated requests, regardless of
|
||||
whether ``AuthMiddleware`` is present in the ASGI stack. Sets the resolved
|
||||
``AuthContext`` on ``request.state.auth`` for downstream handlers.
|
||||
|
||||
Must be placed ABOVE other decorators (executes after them).
|
||||
|
||||
Usage:
|
||||
@router.get("/{thread_id}")
|
||||
@require_auth # Bottom decorator (executes first after permission check)
|
||||
@require_permission("threads", "read")
|
||||
async def get_thread(thread_id: str, request: Request):
|
||||
auth: AuthContext = request.state.auth
|
||||
...
|
||||
|
||||
Raises:
|
||||
HTTPException: 401 if the request is unauthenticated.
|
||||
ValueError: If 'request' parameter is missing.
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
request = kwargs.get("request")
|
||||
if request is None:
|
||||
# Unit tests may call decorated handlers directly without a
|
||||
# FastAPI Request object. Inject a minimal request stub when
|
||||
# the wrapped function declares `request`.
|
||||
if "request" in inspect.signature(func).parameters:
|
||||
kwargs["request"] = _make_test_request_stub()
|
||||
else:
|
||||
raise ValueError("require_auth decorator requires 'request' parameter")
|
||||
request = kwargs["request"]
|
||||
|
||||
if getattr(request, "_deerflow_test_bypass_auth", False):
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
# Authenticate and set context
|
||||
auth_context = await _authenticate(request)
|
||||
request.state.auth = auth_context
|
||||
|
||||
if not auth_context.is_authenticated:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def require_permission(
|
||||
resource: str,
|
||||
action: str,
|
||||
owner_check: bool = False,
|
||||
require_existing: bool = False,
|
||||
claim_orphan: bool = False,
|
||||
) -> Callable[[Callable[P, T]], Callable[P, T]]:
|
||||
"""Decorator that checks permission for resource:action.
|
||||
|
||||
Must be used AFTER @require_auth.
|
||||
|
||||
Args:
|
||||
resource: Resource name (e.g., "threads", "runs")
|
||||
action: Action name (e.g., "read", "write", "delete")
|
||||
owner_check: If True, validates that the current user owns the resource.
|
||||
Requires 'thread_id' path parameter and performs ownership check.
|
||||
require_existing: Only meaningful with ``owner_check=True``. If True, a
|
||||
missing ``threads_meta`` row counts as a denial (404)
|
||||
instead of "untracked legacy thread, allow". Use on
|
||||
**destructive / mutating** routes (DELETE, PATCH,
|
||||
state-update) so a deleted thread can't be re-targeted
|
||||
by another user via the missing-row code path.
|
||||
claim_orphan: Only meaningful with ``owner_check=True`` and
|
||||
``require_existing=True``. When the ``threads_meta``
|
||||
row is missing **and** a LangGraph checkpoint exists
|
||||
for the thread (a DB-switch orphan), adopt it for the
|
||||
current user instead of 404ing. Use on **run-create**
|
||||
routes so a conversation whose business row was lost
|
||||
(sqlite↔mysql swap) stays answerable. Safe: normal
|
||||
deletion removes the checkpoint, so this never revives
|
||||
a deliberately-deleted thread.
|
||||
|
||||
Usage:
|
||||
# Read-style: legacy untracked threads are allowed
|
||||
@require_permission("threads", "read", owner_check=True)
|
||||
async def get_thread(thread_id: str, request: Request):
|
||||
...
|
||||
|
||||
# Destructive: thread row MUST exist and be owned by caller
|
||||
@require_permission("threads", "delete", owner_check=True, require_existing=True)
|
||||
async def delete_thread(thread_id: str, request: Request):
|
||||
...
|
||||
|
||||
Raises:
|
||||
HTTPException 401: If authentication required but user is anonymous
|
||||
HTTPException 403: If user lacks permission
|
||||
HTTPException 404: If owner_check=True but user doesn't own the thread
|
||||
ValueError: If owner_check=True but no ``thread_id`` is supplied,
|
||||
either directly or on the Pydantic request body
|
||||
"""
|
||||
|
||||
def decorator(func: Callable[P, T]) -> Callable[P, T]:
|
||||
@functools.wraps(func)
|
||||
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
request = kwargs.get("request")
|
||||
if request is None:
|
||||
# Unit tests may call decorated route handlers directly without
|
||||
# constructing a FastAPI Request object. Inject a minimal stub
|
||||
# when the wrapped function declares `request`.
|
||||
if "request" in inspect.signature(func).parameters:
|
||||
kwargs["request"] = _make_test_request_stub()
|
||||
else:
|
||||
return await func(*args, **kwargs)
|
||||
request = kwargs["request"]
|
||||
|
||||
if getattr(request, "_deerflow_test_bypass_auth", False):
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
auth: AuthContext = getattr(request.state, "auth", None)
|
||||
if auth is None:
|
||||
auth = await _authenticate(request)
|
||||
request.state.auth = auth
|
||||
|
||||
if not auth.is_authenticated:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Check permission
|
||||
if not auth.has_permission(resource, action):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"Permission denied: {resource}:{action}",
|
||||
)
|
||||
|
||||
# Owner check for thread-specific resources.
|
||||
#
|
||||
# 2.0-rc moved thread metadata into the SQL persistence layer
|
||||
# (``threads_meta`` table). We verify ownership via
|
||||
# ``ThreadMetaStore.check_access``: it returns True for
|
||||
# missing rows (untracked legacy thread) and for rows whose
|
||||
# ``user_id`` is NULL (shared / pre-auth data), so this is
|
||||
# strict-deny rather than strict-allow — only an *existing*
|
||||
# row with a *different* user_id triggers 404.
|
||||
if owner_check:
|
||||
thread_id = kwargs.get("thread_id")
|
||||
# Most thread-scoped routes expose ``thread_id`` in their URL.
|
||||
# A small number of mutation endpoints (for example complete
|
||||
# document rewrite) intentionally keep the target inside a
|
||||
# Pydantic request body so their public URL stays stable. The
|
||||
# FastAPI wrapper passes that body as ``body=...``; accept its
|
||||
# Python field name here while preserving the exact same
|
||||
# ownership verification below.
|
||||
if thread_id is None:
|
||||
body = kwargs.get("body")
|
||||
thread_id = getattr(body, "thread_id", None)
|
||||
if thread_id is None:
|
||||
raise ValueError(
|
||||
"require_permission with owner_check=True requires "
|
||||
"a 'thread_id' parameter or body.thread_id"
|
||||
)
|
||||
|
||||
from app.gateway.deps import get_thread_store
|
||||
|
||||
thread_store = get_thread_store(request)
|
||||
user_id = str(auth.user.id)
|
||||
project_store = getattr(request.app.state, "analysis_project_store", None)
|
||||
allowed_coro = thread_store.check_access(
|
||||
thread_id,
|
||||
user_id,
|
||||
require_existing=require_existing,
|
||||
)
|
||||
if project_store is not None:
|
||||
project, allowed = await asyncio.gather(
|
||||
_project_for_thread(project_store, thread_id),
|
||||
allowed_coro,
|
||||
)
|
||||
if project and project["user_id"] != user_id:
|
||||
raise HTTPException(status_code=404, detail="Project thread not accessible")
|
||||
else:
|
||||
allowed = await allowed_coro
|
||||
if not allowed:
|
||||
# Tell apart three denial causes so the client gets an
|
||||
# accurate message and so DB-switch orphans can be adopted
|
||||
# rather than hard-404'd:
|
||||
# 1. row exists but owned by another user -> not accessible
|
||||
# 2. no row, no checkpoint -> truly missing
|
||||
# 3. no row + checkpoint + claim_orphan -> orphan, claim
|
||||
existing = await thread_store.get(thread_id, user_id=None)
|
||||
if existing is not None:
|
||||
# Distinct detail string lets the frontend show "无权访问"
|
||||
# instead of "不存在" for a cross-user / stale-session hit.
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Thread {thread_id} not accessible",
|
||||
)
|
||||
claimed = False
|
||||
if claim_orphan and await _thread_checkpoint_exists(request, thread_id):
|
||||
try:
|
||||
await thread_store.create(thread_id, user_id=user_id)
|
||||
logger.info(
|
||||
"Claimed orphan thread %s for user %s (checkpoint present, no meta row)",
|
||||
thread_id,
|
||||
user_id,
|
||||
)
|
||||
claimed = True
|
||||
except Exception:
|
||||
logger.warning("Failed to claim orphan thread %s", thread_id, exc_info=True)
|
||||
if not claimed:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Thread {thread_id} not found",
|
||||
)
|
||||
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
"""Authorization decorators and context for DeerFlow.
|
||||
|
||||
Inspired by LangGraph Auth system: https://github.com/langchain-ai/langgraph/blob/main/libs/sdk-py/langgraph_sdk/auth/__init__.py
|
||||
|
||||
**Usage:**
|
||||
|
||||
1. Use ``@require_auth`` on routes that need authentication
|
||||
2. Use ``@require_permission("resource", "action", filter_key=...)`` for permission checks
|
||||
3. The decorator chain processes from bottom to top
|
||||
|
||||
**Example:**
|
||||
|
||||
@router.get("/{thread_id}")
|
||||
@require_auth
|
||||
@require_permission("threads", "read", owner_check=True)
|
||||
async def get_thread(thread_id: str, request: Request):
|
||||
# User is authenticated and has threads:read permission
|
||||
...
|
||||
|
||||
**Permission Model:**
|
||||
|
||||
- threads:read - View thread
|
||||
- threads:write - Create/update thread
|
||||
- threads:delete - Delete thread
|
||||
- runs:create - Run agent
|
||||
- runs:read - View run
|
||||
- runs:cancel - Cancel run
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import inspect
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from app.gateway.auth.disabled_mode import get_assumed_user_for_disabled_auth, is_auth_disabled
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.gateway.auth.models import User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
P = ParamSpec("P")
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
async def _project_for_thread(project_store: Any, thread_id: str) -> dict | None:
|
||||
"""Best-effort project binding lookup; a store error must not fail the read."""
|
||||
try:
|
||||
return await project_store.project_for_thread(thread_id)
|
||||
except Exception:
|
||||
logger.debug("project_for_thread failed for %s", thread_id, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def _project_for_thread(project_store: Any, thread_id: str) -> dict | None:
|
||||
"""Best-effort project binding lookup; a store error must not fail the read."""
|
||||
try:
|
||||
return await project_store.project_for_thread(thread_id)
|
||||
except Exception:
|
||||
logger.debug("project_for_thread failed for %s", thread_id, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def _thread_checkpoint_exists(request: Request, thread_id: str) -> bool:
|
||||
"""Return True if a LangGraph checkpoint exists for ``thread_id``.
|
||||
|
||||
A checkpoint with no matching ``threads_meta`` row is the signature of a
|
||||
DB-switch orphan (sqlite↔mysql/postgres juggling): the conversation state
|
||||
survives in the checkpointer while the business row is gone. Normal thread
|
||||
deletion removes the checkpoint too, so this can never resurrect a
|
||||
deliberately-deleted thread.
|
||||
"""
|
||||
try:
|
||||
from app.gateway.deps import get_checkpointer
|
||||
|
||||
checkpointer = get_checkpointer(request)
|
||||
tup = await checkpointer.aget_tuple({"configurable": {"thread_id": thread_id}})
|
||||
return tup is not None
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# Permission constants
|
||||
class Permissions:
|
||||
"""Permission constants for resource:action format."""
|
||||
|
||||
# Threads
|
||||
THREADS_READ = "threads:read"
|
||||
THREADS_WRITE = "threads:write"
|
||||
THREADS_DELETE = "threads:delete"
|
||||
|
||||
# Runs
|
||||
RUNS_CREATE = "runs:create"
|
||||
RUNS_READ = "runs:read"
|
||||
RUNS_CANCEL = "runs:cancel"
|
||||
|
||||
|
||||
class AuthContext:
|
||||
"""Authentication context for the current request.
|
||||
|
||||
Stored in request.state.auth after require_auth decoration.
|
||||
|
||||
Attributes:
|
||||
user: The authenticated user, or None if anonymous
|
||||
permissions: List of permission strings (e.g., "threads:read")
|
||||
"""
|
||||
|
||||
__slots__ = ("user", "permissions")
|
||||
|
||||
def __init__(self, user: User | None = None, permissions: list[str] | None = None):
|
||||
self.user = user
|
||||
self.permissions = permissions or []
|
||||
|
||||
@property
|
||||
def is_authenticated(self) -> bool:
|
||||
"""Check if user is authenticated."""
|
||||
return self.user is not None
|
||||
|
||||
def has_permission(self, resource: str, action: str) -> bool:
|
||||
"""Check if context has permission for resource:action.
|
||||
|
||||
Args:
|
||||
resource: Resource name (e.g., "threads")
|
||||
action: Action name (e.g., "read")
|
||||
|
||||
Returns:
|
||||
True if user has permission
|
||||
"""
|
||||
permission = f"{resource}:{action}"
|
||||
return permission in self.permissions
|
||||
|
||||
def require_user(self) -> User:
|
||||
"""Get user or raise 401.
|
||||
|
||||
Raises:
|
||||
HTTPException 401 if not authenticated
|
||||
"""
|
||||
if not self.user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
return self.user
|
||||
|
||||
|
||||
def get_auth_context(request: Request) -> AuthContext | None:
|
||||
"""Get AuthContext from request state."""
|
||||
return getattr(request.state, "auth", None)
|
||||
|
||||
|
||||
_ALL_PERMISSIONS: list[str] = [
|
||||
Permissions.THREADS_READ,
|
||||
Permissions.THREADS_WRITE,
|
||||
Permissions.THREADS_DELETE,
|
||||
Permissions.RUNS_CREATE,
|
||||
Permissions.RUNS_READ,
|
||||
Permissions.RUNS_CANCEL,
|
||||
]
|
||||
|
||||
|
||||
def _make_test_request_stub() -> Any:
|
||||
"""Create a minimal request-like object for direct unit calls.
|
||||
|
||||
Used when decorated route handlers are invoked without FastAPI's
|
||||
request injection. Includes fields accessed by auth helpers.
|
||||
"""
|
||||
return SimpleNamespace(state=SimpleNamespace(), cookies={}, _deerflow_test_bypass_auth=True)
|
||||
|
||||
|
||||
async def _authenticate(request: Request) -> AuthContext:
|
||||
"""Authenticate request and return AuthContext.
|
||||
|
||||
Delegates to deps.get_optional_user_from_request() for the JWT→User pipeline.
|
||||
Returns AuthContext with user=None for anonymous requests.
|
||||
"""
|
||||
if is_auth_disabled():
|
||||
user = await get_assumed_user_for_disabled_auth()
|
||||
return AuthContext(user=user, permissions=_ALL_PERMISSIONS)
|
||||
|
||||
from app.gateway.deps import get_optional_user_from_request
|
||||
|
||||
user = await get_optional_user_from_request(request)
|
||||
if user is None:
|
||||
return AuthContext(user=None, permissions=[])
|
||||
|
||||
# In future, permissions could be stored in user record
|
||||
return AuthContext(user=user, permissions=_ALL_PERMISSIONS)
|
||||
|
||||
|
||||
def require_auth[**P, T](func: Callable[P, T]) -> Callable[P, T]:
|
||||
"""Decorator that authenticates the request and enforces authentication.
|
||||
|
||||
Independently raises HTTP 401 for unauthenticated requests, regardless of
|
||||
whether ``AuthMiddleware`` is present in the ASGI stack. Sets the resolved
|
||||
``AuthContext`` on ``request.state.auth`` for downstream handlers.
|
||||
|
||||
Must be placed ABOVE other decorators (executes after them).
|
||||
|
||||
Usage:
|
||||
@router.get("/{thread_id}")
|
||||
@require_auth # Bottom decorator (executes first after permission check)
|
||||
@require_permission("threads", "read")
|
||||
async def get_thread(thread_id: str, request: Request):
|
||||
auth: AuthContext = request.state.auth
|
||||
...
|
||||
|
||||
Raises:
|
||||
HTTPException: 401 if the request is unauthenticated.
|
||||
ValueError: If 'request' parameter is missing.
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
request = kwargs.get("request")
|
||||
if request is None:
|
||||
# Unit tests may call decorated handlers directly without a
|
||||
# FastAPI Request object. Inject a minimal request stub when
|
||||
# the wrapped function declares `request`.
|
||||
if "request" in inspect.signature(func).parameters:
|
||||
kwargs["request"] = _make_test_request_stub()
|
||||
else:
|
||||
raise ValueError("require_auth decorator requires 'request' parameter")
|
||||
request = kwargs["request"]
|
||||
|
||||
if getattr(request, "_deerflow_test_bypass_auth", False):
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
# Authenticate and set context
|
||||
auth_context = await _authenticate(request)
|
||||
request.state.auth = auth_context
|
||||
|
||||
if not auth_context.is_authenticated:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def require_permission(
|
||||
resource: str,
|
||||
action: str,
|
||||
owner_check: bool = False,
|
||||
require_existing: bool = False,
|
||||
claim_orphan: bool = False,
|
||||
) -> Callable[[Callable[P, T]], Callable[P, T]]:
|
||||
"""Decorator that checks permission for resource:action.
|
||||
|
||||
Must be used AFTER @require_auth.
|
||||
|
||||
Args:
|
||||
resource: Resource name (e.g., "threads", "runs")
|
||||
action: Action name (e.g., "read", "write", "delete")
|
||||
owner_check: If True, validates that the current user owns the resource.
|
||||
Requires 'thread_id' path parameter and performs ownership check.
|
||||
require_existing: Only meaningful with ``owner_check=True``. If True, a
|
||||
missing ``threads_meta`` row counts as a denial (404)
|
||||
instead of "untracked legacy thread, allow". Use on
|
||||
**destructive / mutating** routes (DELETE, PATCH,
|
||||
state-update) so a deleted thread can't be re-targeted
|
||||
by another user via the missing-row code path.
|
||||
claim_orphan: Only meaningful with ``owner_check=True`` and
|
||||
``require_existing=True``. When the ``threads_meta``
|
||||
row is missing **and** a LangGraph checkpoint exists
|
||||
for the thread (a DB-switch orphan), adopt it for the
|
||||
current user instead of 404ing. Use on **run-create**
|
||||
routes so a conversation whose business row was lost
|
||||
(sqlite↔mysql swap) stays answerable. Safe: normal
|
||||
deletion removes the checkpoint, so this never revives
|
||||
a deliberately-deleted thread.
|
||||
|
||||
Usage:
|
||||
# Read-style: legacy untracked threads are allowed
|
||||
@require_permission("threads", "read", owner_check=True)
|
||||
async def get_thread(thread_id: str, request: Request):
|
||||
...
|
||||
|
||||
# Destructive: thread row MUST exist and be owned by caller
|
||||
@require_permission("threads", "delete", owner_check=True, require_existing=True)
|
||||
async def delete_thread(thread_id: str, request: Request):
|
||||
...
|
||||
|
||||
Raises:
|
||||
HTTPException 401: If authentication required but user is anonymous
|
||||
HTTPException 403: If user lacks permission
|
||||
HTTPException 404: If owner_check=True but user doesn't own the thread
|
||||
ValueError: If owner_check=True but no ``thread_id`` is supplied,
|
||||
either directly or on the Pydantic request body
|
||||
"""
|
||||
|
||||
def decorator(func: Callable[P, T]) -> Callable[P, T]:
|
||||
@functools.wraps(func)
|
||||
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
request = kwargs.get("request")
|
||||
if request is None:
|
||||
# Unit tests may call decorated route handlers directly without
|
||||
# constructing a FastAPI Request object. Inject a minimal stub
|
||||
# when the wrapped function declares `request`.
|
||||
if "request" in inspect.signature(func).parameters:
|
||||
kwargs["request"] = _make_test_request_stub()
|
||||
else:
|
||||
return await func(*args, **kwargs)
|
||||
request = kwargs["request"]
|
||||
|
||||
if getattr(request, "_deerflow_test_bypass_auth", False):
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
auth: AuthContext = getattr(request.state, "auth", None)
|
||||
if auth is None:
|
||||
auth = await _authenticate(request)
|
||||
request.state.auth = auth
|
||||
|
||||
if not auth.is_authenticated:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Check permission
|
||||
if not auth.has_permission(resource, action):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"Permission denied: {resource}:{action}",
|
||||
)
|
||||
|
||||
# Owner check for thread-specific resources.
|
||||
#
|
||||
# 2.0-rc moved thread metadata into the SQL persistence layer
|
||||
# (``threads_meta`` table). We verify ownership via
|
||||
# ``ThreadMetaStore.check_access``: it returns True for
|
||||
# missing rows (untracked legacy thread) and for rows whose
|
||||
# ``user_id`` is NULL (shared / pre-auth data), so this is
|
||||
# strict-deny rather than strict-allow — only an *existing*
|
||||
# row with a *different* user_id triggers 404.
|
||||
if owner_check:
|
||||
thread_id = kwargs.get("thread_id")
|
||||
# Most thread-scoped routes expose ``thread_id`` in their URL.
|
||||
# A small number of mutation endpoints (for example complete
|
||||
# document rewrite) intentionally keep the target inside a
|
||||
# Pydantic request body so their public URL stays stable. The
|
||||
# FastAPI wrapper passes that body as ``body=...``; accept its
|
||||
# Python field name here while preserving the exact same
|
||||
# ownership verification below.
|
||||
if thread_id is None:
|
||||
body = kwargs.get("body")
|
||||
thread_id = getattr(body, "thread_id", None)
|
||||
if thread_id is None:
|
||||
raise ValueError(
|
||||
"require_permission with owner_check=True requires "
|
||||
"a 'thread_id' parameter or body.thread_id"
|
||||
)
|
||||
|
||||
from app.gateway.deps import get_thread_store
|
||||
|
||||
thread_store = get_thread_store(request)
|
||||
user_id = str(auth.user.id)
|
||||
project_store = getattr(request.app.state, "analysis_project_store", None)
|
||||
allowed_coro = thread_store.check_access(
|
||||
thread_id,
|
||||
user_id,
|
||||
require_existing=require_existing,
|
||||
)
|
||||
if project_store is not None:
|
||||
project, allowed = await asyncio.gather(
|
||||
_project_for_thread(project_store, thread_id),
|
||||
allowed_coro,
|
||||
)
|
||||
if project and project["user_id"] != user_id:
|
||||
raise HTTPException(status_code=404, detail="Project thread not accessible")
|
||||
else:
|
||||
allowed = await allowed_coro
|
||||
if not allowed:
|
||||
# Tell apart three denial causes so the client gets an
|
||||
# accurate message and so DB-switch orphans can be adopted
|
||||
# rather than hard-404'd:
|
||||
# 1. row exists but owned by another user -> not accessible
|
||||
# 2. no row, no checkpoint -> truly missing
|
||||
# 3. no row + checkpoint + claim_orphan -> orphan, claim
|
||||
existing = await thread_store.get(thread_id, user_id=None)
|
||||
if existing is not None:
|
||||
# Distinct detail string lets the frontend show "无权访问"
|
||||
# instead of "不存在" for a cross-user / stale-session hit.
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Thread {thread_id} not accessible",
|
||||
)
|
||||
claimed = False
|
||||
if claim_orphan and await _thread_checkpoint_exists(request, thread_id):
|
||||
try:
|
||||
await thread_store.create(thread_id, user_id=user_id)
|
||||
logger.info(
|
||||
"Claimed orphan thread %s for user %s (checkpoint present, no meta row)",
|
||||
thread_id,
|
||||
user_id,
|
||||
)
|
||||
claimed = True
|
||||
except Exception:
|
||||
logger.warning("Failed to claim orphan thread %s", thread_id, exc_info=True)
|
||||
if not claimed:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Thread {thread_id} not found",
|
||||
)
|
||||
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -204,6 +204,35 @@ class RoundtableJobDispatcher:
|
||||
)
|
||||
return expired
|
||||
|
||||
async def _expire_overdue_step2_rooms(self, now: datetime) -> int:
|
||||
"""Persist hard-timeout cancellation even when no browser is connected."""
|
||||
max_minutes = getattr(
|
||||
get_roundtable_room_limit_settings(),
|
||||
"max_hold_minutes",
|
||||
30,
|
||||
)
|
||||
request_cancel_expired = getattr(
|
||||
self._store,
|
||||
"request_cancel_expired_step2",
|
||||
None,
|
||||
)
|
||||
if request_cancel_expired is None:
|
||||
return 0
|
||||
try:
|
||||
expired = await request_cancel_expired(
|
||||
created_before=now - timedelta(minutes=max_minutes),
|
||||
non_occupying_phases=tuple(NON_OCCUPYING_JOB_PHASES),
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("[roundtable-jobs] hard-timeout scan failed", exc_info=True)
|
||||
return 0
|
||||
if expired:
|
||||
logger.info(
|
||||
"[roundtable-jobs] requested cancellation for %d overdue Step-2 room(s)",
|
||||
expired,
|
||||
)
|
||||
return expired
|
||||
|
||||
async def _reap_cancel_requested(self, now: datetime) -> int:
|
||||
"""收口持租 worker 崩溃后遗留的 ``cancel_requested`` 作业。
|
||||
|
||||
|
||||
@@ -69,6 +69,26 @@ _DRAFT_WRITE_RETRIES = 3
|
||||
ROUNDTABLE_BACKGROUND_REPORT_ENABLED = True
|
||||
|
||||
|
||||
def _background_step2_room_expired(row: dict[str, Any] | None) -> bool:
|
||||
"""Whether a background job exceeded the configurable Step-2 hard limit."""
|
||||
if not row or str(row.get("phase") or "") in NON_OCCUPYING_JOB_PHASES:
|
||||
return False
|
||||
raw_created = row.get("created_at")
|
||||
if isinstance(raw_created, datetime):
|
||||
created_at = raw_created
|
||||
elif isinstance(raw_created, str) and raw_created:
|
||||
try:
|
||||
created_at = datetime.fromisoformat(raw_created)
|
||||
except ValueError:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
if created_at.tzinfo is None:
|
||||
created_at = created_at.replace(tzinfo=UTC)
|
||||
max_minutes = getattr(get_roundtable_room_limit_settings(), "max_hold_minutes", 30)
|
||||
return datetime.now(UTC) >= created_at + timedelta(minutes=max_minutes)
|
||||
|
||||
|
||||
def _background_step2_room_expired(row: dict[str, Any] | None) -> bool:
|
||||
"""Whether a background job exceeded the configurable Step-2 hard limit."""
|
||||
if not row or str(row.get("phase") or "") in NON_OCCUPYING_JOB_PHASES:
|
||||
|
||||
@@ -54,6 +54,8 @@ _AGENT_PURPOSE: dict[str, str] = {
|
||||
# Workflow Studio(候选流程总控,和圆桌总控隔离)
|
||||
"workflow-planner": "工作流编排",
|
||||
"task-analysis-coordinator": "任务分析定时",
|
||||
"chat-history-migrator": "其他内置功能",
|
||||
"gauss-data-adapter": "其他内置功能",
|
||||
}
|
||||
|
||||
_TARGET_TYPE = "agent"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Seed the built-in chat-history migration assistant.
|
||||
|
||||
The agent and its public skill are copied only when their target directories are
|
||||
missing. Existing deployments are never overwritten, so administrator edits made
|
||||
through agent/skill management survive restarts. This seeder must run before
|
||||
``_sync_legacy_agents``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CHAT_HISTORY_MIGRATION_AGENT_ID = "chat-history-migrator"
|
||||
CHAT_HISTORY_MIGRATION_SKILL_NAME = "chat-history-migration"
|
||||
|
||||
_ASSETS_DIR = Path(__file__).parent / "_chat_history_migration_seed_assets"
|
||||
_AGENT_FILES: tuple[str, ...] = ("config.yaml", "SOUL.md")
|
||||
|
||||
|
||||
def _skills_public_dir() -> Path:
|
||||
from deerflow.skills.storage import get_or_new_skill_storage
|
||||
|
||||
return Path(get_or_new_skill_storage().get_skills_root_path()) / "public"
|
||||
|
||||
|
||||
def _ensure_skill() -> bool:
|
||||
try:
|
||||
source = _ASSETS_DIR / "skills" / CHAT_HISTORY_MIGRATION_SKILL_NAME
|
||||
target = _skills_public_dir() / CHAT_HISTORY_MIGRATION_SKILL_NAME
|
||||
if target.exists():
|
||||
return False
|
||||
if not (source / "SKILL.md").is_file():
|
||||
logger.error("Missing chat-history migration skill seed at %s", source)
|
||||
return False
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copytree(source, target)
|
||||
logger.info("Seeded public skill '%s'", CHAT_HISTORY_MIGRATION_SKILL_NAME)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("Failed to seed chat-history migration skill")
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_agent() -> bool:
|
||||
try:
|
||||
target = get_paths().agent_dir(CHAT_HISTORY_MIGRATION_AGENT_ID)
|
||||
if target.exists():
|
||||
return False
|
||||
source = _ASSETS_DIR / CHAT_HISTORY_MIGRATION_AGENT_ID
|
||||
if not source.is_dir():
|
||||
logger.error("Missing chat-history migration agent seed at %s", source)
|
||||
return False
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for filename in _AGENT_FILES:
|
||||
asset = source / filename
|
||||
if asset.is_file():
|
||||
(target / filename).write_bytes(asset.read_bytes())
|
||||
logger.info("Seeded built-in agent '%s'", CHAT_HISTORY_MIGRATION_AGENT_ID)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("Failed to seed chat-history migration agent")
|
||||
return False
|
||||
|
||||
|
||||
def ensure_chat_history_migration_agent() -> bool:
|
||||
"""Install the chat-history migration skill and agent when missing."""
|
||||
_ensure_skill()
|
||||
return _ensure_agent()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CHAT_HISTORY_MIGRATION_AGENT_ID",
|
||||
"CHAT_HISTORY_MIGRATION_SKILL_NAME",
|
||||
"ensure_chat_history_migration_agent",
|
||||
]
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
# 角色
|
||||
|
||||
你是 **聊天记录迁移助手**。你帮助管理员把一台 DeerFlow 服务器上的普通聊天记录迁到另一台服务器。源站的业务库可以是 openGauss/高斯,目标站可以是高斯、SQLite 或 MySQL。
|
||||
|
||||
你面对的操作者可能不熟悉数据库。先用一句通俗的话解释术语,再给可复制的命令。命令里的主机、端口、库名、路径一律用对方提供的值;没有提供时用占位符,禁止猜。
|
||||
|
||||
# 聊天记录实际放在哪
|
||||
|
||||
一次可见的聊天不是高斯库里的一张表。它有三层,缺任何一层都会表现为「列表空」或「有标题但点进去没有内容」:
|
||||
|
||||
1. **会话索引**:`threads_meta` 决定聊天列表里的标题、所属用户和时间。`runs`、`run_events`、`feedback` 是运行记录和评价。项目里的会话还依赖 `analysis_project_threads`。这一层可以在高斯库里。
|
||||
2. **消息正文**:LangGraph 检查点。推荐放在 SQLite 文件,也可以是真正的 PostgreSQL。这里才是问答内容。
|
||||
3. **线程文件**:`.deer-flow/users/<user_id>/threads/<thread_id>/user-data/` 下面的上传文件和生成结果。
|
||||
|
||||
不要把 LangGraph 的 PostgreSQL checkpointer 迁移执行到高斯库上。高斯只承接业务索引。检查点文件原样进入目标的 SQLite 检查点库。
|
||||
|
||||
# 必须遵守的边界
|
||||
|
||||
1. **智能体沙箱不是源服务器,也不是目标服务器。** 除非用户明确说明当前环境就是那台机器,否则不要根据沙箱里的主机名、localhost 或某个 `.db` 文件推断现场。需要现场执行的命令要写明在哪一台机器、哪个目录运行。
|
||||
2. **不要接收密码。** 不要让用户把高斯密码、token、私钥贴进对话。`gsql` / `mysql` 使用 `~/.pgpass` 或客户端自己的密码提示。脚本不会连接高斯,也没有密码参数。
|
||||
3. **先盘点,再导出,再演练,最后才写入。** 导入命令默认是演练。用户明确说过目标库已有可恢复备份之前,不要在命令里加 `--apply`。
|
||||
4. **不导出账号密码。** `users` 表和密码列不进入迁移包。目标站必须已经有对应账号。`user_id` 不同时只用 `--user-map 旧ID=新ID` 改归属,不改 `thread_id`。
|
||||
5. **默认跳过已有会话。** 只有用户明确要求覆盖时才使用 `--on-conflict replace`。替换只影响迁移包里的那些 `thread_id`,不会清空目标库其他会话。已有项目的名称和配置保持目标站原样。
|
||||
6. **系统线程默认不迁。** 调度器和内部工作线程会让列表变脏。用户点名要包含时才加 `--include-system`。
|
||||
7. **源库只读。** 不在源库执行 INSERT、UPDATE、DELETE、DROP。导出 SQL 只有查询和 `\copy TO`。
|
||||
|
||||
# 工作方式
|
||||
|
||||
收到请求后先归入一种模式:
|
||||
|
||||
- **还不清楚数据在哪**:读取技能里的 `references/storage-map.md`,根据用户贴出的 `database.backend` 和 `checkpointer` 判断三层位置。一次只追问会改变命令的几项:业务库类型、检查点文件路径、`.deer-flow` 目录、要迁的用户或时间范围、目标库类型。
|
||||
- **准备搬迁**:读取 `references/runbook.md`。按「停写或接受截止点 → 只读导出 → 打包 → 传到目标 → 演练 → 备份确认 → `--apply` → 验收」推进。每一步都写成功信号和失败时停在哪里。
|
||||
- **迁完对不上**:先区分「列表没有这条会话」「有标题但正文是空的」「附件不见了」「进了别的账号」。分别对应索引、检查点、线程文件和 `user_id`。不要一次改三层。
|
||||
|
||||
脚本在技能目录 `scripts/migrate_chat_history.py`,只用 Python 标准库。用户要在源服务器上跑时,把脚本复制到输出目录并交付:
|
||||
|
||||
```bash
|
||||
cp /mnt/skills/public/chat-history-migration/scripts/migrate_chat_history.py /mnt/user-data/outputs/migrate_chat_history.py
|
||||
```
|
||||
|
||||
沙箱里没有 `bash` 时,用 `read_file` 读取脚本,再用 `write_file` 原样写到该路径。用户已经把 SQLite 或 JSONL 传到当前会话时,可以对 `/mnt/user-data/uploads/` 里的文件运行脚本,把迁移包写到 `/mnt/user-data/outputs/`。
|
||||
|
||||
# 交付格式
|
||||
|
||||
每次给操作步骤时包含这几项;没有的信息写「还不知道」:
|
||||
|
||||
1. **在哪台机器做**:源服务器、目标服务器,或当前会话里的上传文件。
|
||||
2. **这一步会不会改数据**:只读、演练,或写入。写入前重复备份要求。
|
||||
3. **命令**:可复制,占位符用 `<GAUSS_HOST>`、`<GAUSS_DB>`、`<CHECKPOINT_SQLITE>`、`<DEER_FLOW_ROOT>` 这种形式。
|
||||
4. **成功信号**:应该看到的线程数、某个已知会话标题、检查点行数。
|
||||
5. **停机点**:命令失败或数量对不上时不要继续下一步。
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
id: chat-history-migrator
|
||||
name: 聊天记录迁移助手
|
||||
description: 把一台 DeerFlow 服务器上的聊天记录迁到另一台。源站业务库可以是高斯/openGauss。会话索引、LangGraph 检查点和线程文件分开处理,不把 PostgreSQL 检查点迁移直接套到高斯上。
|
||||
tool_groups:
|
||||
- file:read
|
||||
- file:write
|
||||
- bash
|
||||
skills:
|
||||
- chat-history-migration
|
||||
common_questions:
|
||||
- title: 高斯库里的聊天记录怎么迁
|
||||
prompt: >-
|
||||
源服务器的业务库是高斯/openGauss,我要把聊天记录迁到另一台 DeerFlow。
|
||||
请先用通俗的话说明聊天记录分哪几层存放,再给我一份只读盘点步骤。
|
||||
不要让我把数据库密码贴进对话,也不要给出把 LangGraph PostgreSQL 检查点迁移直接执行到高斯库上的命令。
|
||||
- title: 先做只读盘点
|
||||
prompt: >-
|
||||
请根据我提供的 database.backend、checkpointer 类型和目录,判断会话索引、消息正文和线程文件各在哪里。
|
||||
缺哪一项就告诉我该在哪台机器上看哪个文件,不要猜路径,也不要开始拷贝。
|
||||
- title: 导出迁移包
|
||||
prompt: >-
|
||||
请带我从源服务器导出聊天迁移包。业务库如果是高斯或 MySQL 协议的高斯,先生成只读导出 SQL;
|
||||
检查点仍从 SQLite 文件提取。导出前说明会排除系统线程、不会导出用户密码。
|
||||
- title: 导入前先演练
|
||||
prompt: >-
|
||||
迁移包已经放到目标服务器。请先做导入演练,告诉我会新增哪些会话、会跳过哪些已有会话、哪些文件会拷贝。
|
||||
我明确确认已经有可恢复备份之前,不要加上 --apply。
|
||||
- title: 导入后怎么验收
|
||||
prompt: >-
|
||||
导入已经执行。请给我验收步骤:会话列表能看到原标题,点进会话能看到原来的问答,附件还在原线程目录。
|
||||
如果只有标题、打开是空的,请判断是检查点没迁过去,还是 user_id 对不上。
|
||||
- title: 两边的用户 ID 不一样
|
||||
prompt: >-
|
||||
源服务器和目标服务器都有这些账号,但 user_id 不同,聊天记录迁过去后列表是空的。
|
||||
请说明怎样用 --user-map 只改归属、不改 thread_id,以及哪些字段不会自动改写。
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
---
|
||||
name: chat-history-migration
|
||||
description: 把 DeerFlow 聊天记录从一台服务器迁到另一台。源业务库可以是 openGauss/高斯或 MySQL 协议高斯。分别导出会话索引、SQLite 检查点和线程文件,导入前默认只演练,不把 PostgreSQL 检查点迁移执行到高斯上。
|
||||
---
|
||||
|
||||
# 聊天记录迁移
|
||||
|
||||
本技能的脚本和说明都在本地。先确认用户处于「还不知道数据在哪」「准备导出」「准备导入」还是「迁完对不上」,再只读需要的材料:
|
||||
|
||||
- 判断高斯库、检查点和线程目录各存什么:读取 `references/storage-map.md`。
|
||||
- 已经知道路径,需要逐步导出、传输、演练和验收:读取 `references/runbook.md`。
|
||||
- 两件事都还没确定时先读存储说明,不要把两份参考一次读完。
|
||||
|
||||
脚本路径:
|
||||
|
||||
```text
|
||||
/mnt/skills/public/chat-history-migration/scripts/migrate_chat_history.py
|
||||
```
|
||||
|
||||
它只用 Python 标准库,不连接高斯,也不接收密码。`import` 不加 `--apply` 时只演练,不创建、不修改目标文件。
|
||||
|
||||
## 现场和沙箱
|
||||
|
||||
`bash` 跑在 DeerFlow 沙箱里,通常不是要迁移的那台服务器。沙箱里的数据库文件和目录不能当成源站或目标站,除非用户明确说当前环境就是那台机器。
|
||||
|
||||
两种做法:
|
||||
|
||||
1. 把脚本复制到输出目录,让用户在源服务器和目标服务器上执行,再把 JSON 结果贴回来。
|
||||
2. 用户已经把 SQLite、JSONL 或迁移包上传到当前会话时,直接对 `/mnt/user-data/uploads/` 运行脚本,产物写到 `/mnt/user-data/outputs/`。
|
||||
|
||||
交付脚本:
|
||||
|
||||
```bash
|
||||
cp /mnt/skills/public/chat-history-migration/scripts/migrate_chat_history.py /mnt/user-data/outputs/migrate_chat_history.py
|
||||
```
|
||||
|
||||
没有 `bash` 时,读取脚本原文,再用 `write_file` 原样写到上面的路径。
|
||||
|
||||
## 不允许的做法
|
||||
|
||||
- 不要把 LangGraph 的 PostgreSQL checkpointer 迁移执行到高斯库上。
|
||||
- 不要导出或覆盖 `users` 表,不要读写 `password_hash`、`login_password`。
|
||||
- 不要在命令行参数或对话里出现数据库密码。
|
||||
- 不要在用户确认目标库已有可恢复备份之前执行带 `--apply` 的导入。
|
||||
- 不要因为列表能看到标题,就认为消息正文已经迁完。正文在检查点里。
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
# 迁移步骤
|
||||
|
||||
在源服务器导出,在目标服务器导入。迁移包里有对话正文,只通过可信通道拷贝。下面的命令在对应服务器的 shell 里执行,不在智能体沙箱里执行,除非用户确认当前环境就是那台机器。
|
||||
|
||||
开始前向用户要这些值,缺的用占位符,不要猜:
|
||||
|
||||
- 源、目标的 `database.backend`
|
||||
- 高斯是 `opengauss` 还是 Dolphin(`gauss_mysql`)
|
||||
- 检查点 SQLite 的实际路径
|
||||
- `.deer-flow` 根目录
|
||||
- 要迁的 `user_id` 或时间范围
|
||||
- 目标账号 id 是否和源相同
|
||||
|
||||
建议先停止源 Gateway,或接受导出时刻之后的新消息不在包里。脚本不会锁高斯库,热导出不是一致快照。
|
||||
|
||||
## 1. 源站只读盘点
|
||||
|
||||
SQLite 索引或统一的 `deerflow.db`:
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py inventory \
|
||||
--app-sqlite <APP_SQLITE> \
|
||||
--checkpoint-sqlite <CHECKPOINT_SQLITE> \
|
||||
--threads-root <DEER_FLOW_ROOT>
|
||||
```
|
||||
|
||||
只传存在的路径。业务库是高斯、检查点是 SQLite 时,不要传 `--app-sqlite`;索引改用下一步的 SQL 盘点。成功信号是 JSON 里的 `threads_meta`、检查点线程数和文件数。`system_threads` 是默认会排除的内部线程。
|
||||
|
||||
## 2. 从高斯导出索引
|
||||
|
||||
在源服务器上执行。密码放在 `~/.pgpass`(权限 600)或让客户端提示,不要写进命令,也不要贴进对话。
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py emit-export-sql --dialect opengauss --out export_chat_index.sql
|
||||
gsql -h <GAUSS_HOST> -p 26000 -d <GAUSS_DB> -U <GAUSS_USER> -f export_chat_index.sql
|
||||
```
|
||||
|
||||
Dolphin / MySQL 协议把 `--dialect` 换成 `mysql`,然后用 `mysql -h <HOST> -P 3306 -u <USER> -p -D <DB> -N` 逐条执行,每条查询的输出存成对应的 `.jsonl`。`-p` 会提示输入密码。
|
||||
|
||||
这份 SQL 只有查询。它不包含检查点表。不要把 LangGraph 的 PostgreSQL checkpointer 迁移执行到高斯库上。
|
||||
|
||||
## 3. 打迁移包
|
||||
|
||||
索引也在 SQLite 时:
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py export \
|
||||
--out <BUNDLE_DIR> \
|
||||
--app-sqlite <APP_SQLITE> \
|
||||
--checkpoint-sqlite <CHECKPOINT_SQLITE> \
|
||||
--threads-root <DEER_FLOW_ROOT> \
|
||||
--user-id <USER_ID>
|
||||
```
|
||||
|
||||
索引来自刚才的 JSONL 时:
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py pack-jsonl \
|
||||
--out <BUNDLE_DIR> \
|
||||
--threads-meta threads_meta.jsonl \
|
||||
--runs runs.jsonl \
|
||||
--run-events run_events.jsonl \
|
||||
--feedback feedback.jsonl \
|
||||
--project-threads analysis_project_threads.jsonl \
|
||||
--projects analysis_projects.jsonl \
|
||||
--checkpoint-sqlite <CHECKPOINT_SQLITE> \
|
||||
--threads-root <DEER_FLOW_ROOT>
|
||||
```
|
||||
|
||||
`<BUNDLE_DIR>` 必须是空目录,并且不能放在源数据库或 `.deer-flow` 目录里面。成功信号是目录里有 `manifest.json`。`excluded_system_thread_ids` 里的会话是故意不迁的。需要它们时两边都加 `--include-system`。
|
||||
|
||||
只迁某个时间之后的会话时加 `--since 2026-10-01T00:00:00`。
|
||||
|
||||
## 4. 目标站先演练
|
||||
|
||||
先复制备份:目标检查点 SQLite、目标业务库(高斯做库级备份)。没有备份就不加 `--apply`。
|
||||
|
||||
SQLite 业务库:
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py import \
|
||||
--bundle <BUNDLE_DIR> \
|
||||
--app-sqlite <TARGET_APP_SQLITE> \
|
||||
--checkpoint-sqlite <TARGET_CHECKPOINT_SQLITE> \
|
||||
--threads-root <TARGET_DEER_FLOW_ROOT>
|
||||
```
|
||||
|
||||
目标业务库是高斯时,索引和检查点分开:
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py emit-gauss-sql --bundle <BUNDLE_DIR> --out load_chat_index.sql
|
||||
python3 migrate_chat_history.py import \
|
||||
--bundle <BUNDLE_DIR> \
|
||||
--checkpoint-sqlite <TARGET_CHECKPOINT_SQLITE> \
|
||||
--threads-root <TARGET_DEER_FLOW_ROOT>
|
||||
```
|
||||
|
||||
演练的成功信号是 `"dry_run": true`,并且目标文件的修改时间没有变。看 `inserted`、`skipped_threads` 和 `files_copied`。已有的 `thread_id` 默认跳过;如果索引已在而检查点缺失,演练会显示还要补检查点。
|
||||
|
||||
账号 id 不同:
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py import --bundle <BUNDLE_DIR> --user-map <OLD_USER_ID>=<NEW_USER_ID>
|
||||
```
|
||||
|
||||
可以重复写多个 `--user-map`。
|
||||
|
||||
## 5. 确认备份后再写入
|
||||
|
||||
SQLite 目标把同一条 `import` 加上 `--apply`。高斯索引另执行:
|
||||
|
||||
```bash
|
||||
gsql -h <GAUSS_HOST> -p 26000 -d <GAUSS_DB> -U <GAUSS_USER> -f load_chat_index.sql
|
||||
```
|
||||
|
||||
`load_chat_index.sql` 默认 `INSERT ... WHERE NOT EXISTS`,不覆盖已有主键。用户明确要求覆盖这些会话时,生成 SQL 才加 `--on-conflict replace`。替换会删除目标上这些 `thread_id` 的索引行再写入,不会删除同 id 的已有项目定义,也不会动迁移包以外的会话。
|
||||
|
||||
目标 SQLite 文件必须已经存在(先启动一次目标 Gateway,让它建好表)。检查点文件不存在时,`--apply` 可以按迁移包里的表结构创建。
|
||||
|
||||
## 6. 验收
|
||||
|
||||
```bash
|
||||
python3 migrate_chat_history.py verify \
|
||||
--bundle <BUNDLE_DIR> \
|
||||
--app-sqlite <TARGET_APP_SQLITE> \
|
||||
--checkpoint-sqlite <TARGET_CHECKPOINT_SQLITE> \
|
||||
--threads-root <TARGET_DEER_FLOW_ROOT>
|
||||
```
|
||||
|
||||
退出码 0 表示会话、检查点行数和文件都在。高斯索引不经过这个 SQLite 校验;在目标高斯里对一个已知 `thread_id` 查询 `threads_meta`,再在网页上打开该会话,确认能看到迁前的问答和附件。
|
||||
|
||||
数量不对就停。跳过模式下重新执行 `--apply` 只会补缺失的检查点或文件,不会覆盖已有会话。要用备份恢复时,恢复第 4 步复制的目标库和检查点文件,并删掉本次新建的 `users/<user_id>/threads/<thread_id>` 目录。源服务器始终没有被修改。
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
# 聊天记录存在哪
|
||||
|
||||
DeerFlow 的一条聊天要三层都在,打开后才能看到原来的问答。
|
||||
|
||||
## 1. 会话索引(可以在高斯里)
|
||||
|
||||
`config.yaml` 的 `database.backend` 决定这一层:
|
||||
|
||||
| backend | 索引在哪 | 导出方式 |
|
||||
| --- | --- | --- |
|
||||
| `gauss` | `database.gauss_url` 指向的 openGauss/GaussDB | `emit-export-sql --dialect opengauss`,再用 `gsql` 执行 |
|
||||
| `mysql`,且部署设置了 `DEERFLOW_DATABASE_PRODUCT=gauss_mysql` | 高斯的 MySQL 协议(Dolphin) | `emit-export-sql --dialect mysql`,再用 `mysql` 客户端执行 |
|
||||
| `sqlite` | `{sqlite_dir}/deerflow.db`,默认 `.deer-flow/data/deerflow.db` | 脚本直接读这个文件 |
|
||||
| `postgres` | `database.postgres_url` | 先把索引导出成 JSONL,再 `pack-jsonl`。不要改检查点迁移方式 |
|
||||
|
||||
和聊天直接相关的表:
|
||||
|
||||
- `threads_meta`:聊天列表。`thread_id`、`user_id`、`display_name`、`metadata_json`、时间。
|
||||
- `runs` / `run_events`:一轮运行的状态、首句预览和事件。
|
||||
- `feedback`:回答评价。
|
||||
- `analysis_projects` / `analysis_project_threads`:会话属于哪个分析项目。目标上已有的同 id 项目不会被覆盖;项目下的知识库文件不在这个迁移里。
|
||||
|
||||
`users` 表不迁。密码列不迁。目标服务器要先有账号,并且 `threads_meta.user_id` 等于目标账号的 id。两边 id 不同时,导入用 `--user-map 旧ID=新ID`。这个映射只改 `user_id` 以及 `users/<旧ID>/threads/...` 目录,不改 `thread_id`,也不改消息正文里的文字。
|
||||
|
||||
`metadata_json.system = true` 的是调度器或内部工作线程,默认排除。
|
||||
|
||||
## 2. 消息正文(不要放进高斯迁移)
|
||||
|
||||
问答正文在 LangGraph 检查点,不在 `threads_meta`。
|
||||
|
||||
`config.yaml` 的 `checkpointer`:
|
||||
|
||||
- `type: sqlite`:`connection_string` 指向的文件。业务库是 SQLite 且没有单独的 checkpointer 文件时,检查点表和 `threads_meta` 可能在同一个 `deerflow.db` 里。脚本遇到这种文件会把两层拆开。
|
||||
- `type: postgres`:只适用于真正的 PostgreSQL。它的建表迁移不能对高斯执行。
|
||||
- 业务库是 `gauss` 时,检查点应继续用 SQLite。如果现场误把检查点建在了高斯里,先停下来说明这个部署和当前脚本的支持范围不一致,不要自动改跑 PostgreSQL 迁移。
|
||||
|
||||
检查点表通常叫 `checkpoints`、`writes`、`checkpoint_blobs`、`checkpoint_writes`。迁移包里的 `checkpoints.sqlite` 只含选中会话的这些表。
|
||||
|
||||
只迁了 `threads_meta` 时,列表有标题,点进去没有历史消息。
|
||||
|
||||
## 3. 线程文件
|
||||
|
||||
默认在后端运行目录:
|
||||
|
||||
```text
|
||||
<DEER_FLOW_ROOT>/users/<user_id>/threads/<thread_id>/user-data/
|
||||
```
|
||||
|
||||
旧数据可能在 `<DEER_FLOW_ROOT>/threads/<thread_id>/`。`--threads-root` 传 `<DEER_FLOW_ROOT>`,也就是同时能看到 `users/` 或旧 `threads/` 的那一层,不要只传某一个会话目录。
|
||||
|
||||
这里有上传文件和生成的 HTML、Markdown。知识库原文、记忆库和分享链接不在这份迁移里。
|
||||
|
||||
## 迁完后的对照
|
||||
|
||||
| 现象 | 先看 |
|
||||
| --- | --- |
|
||||
| 目标列表完全没有这些会话 | 索引没进目标库,或 `user_id` 对不上 |
|
||||
| 有标题,打开是空的 | 检查点没进目标 SQLite |
|
||||
| 文字在,附件不见 | `--threads-root` 没指到同一个 `.deer-flow` 根 |
|
||||
| 普通聊天在,项目里看不到 | 目标没有同 id 的 `analysis_projects`,或绑定表没导入 |
|
||||
+1591
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,81 @@
|
||||
"""Seed the built-in GaussDB data-adaptation assistant.
|
||||
|
||||
The agent and its public skill are copied only when their target directories are
|
||||
missing. Existing deployments are never overwritten, so administrator edits made
|
||||
through agent/skill management survive restarts. This seeder must run before
|
||||
``_sync_legacy_agents``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
GAUSS_DATA_ADAPTATION_AGENT_ID = "gauss-data-adapter"
|
||||
GAUSS_DATA_ADAPTATION_SKILL_NAME = "gauss-data-adaptation"
|
||||
|
||||
_ASSETS_DIR = Path(__file__).parent / "_gauss_data_adaptation_seed_assets"
|
||||
_AGENT_FILES: tuple[str, ...] = ("config.yaml", "SOUL.md")
|
||||
|
||||
|
||||
def _skills_public_dir() -> Path:
|
||||
from deerflow.skills.storage import get_or_new_skill_storage
|
||||
|
||||
return Path(get_or_new_skill_storage().get_skills_root_path()) / "public"
|
||||
|
||||
|
||||
def _ensure_skill() -> bool:
|
||||
try:
|
||||
source = _ASSETS_DIR / "skills" / GAUSS_DATA_ADAPTATION_SKILL_NAME
|
||||
target = _skills_public_dir() / GAUSS_DATA_ADAPTATION_SKILL_NAME
|
||||
if target.exists():
|
||||
return False
|
||||
if not (source / "SKILL.md").is_file():
|
||||
logger.error("Missing Gauss data-adaptation skill seed at %s", source)
|
||||
return False
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copytree(source, target)
|
||||
logger.info("Seeded public skill '%s'", GAUSS_DATA_ADAPTATION_SKILL_NAME)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("Failed to seed Gauss data-adaptation skill")
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_agent() -> bool:
|
||||
try:
|
||||
target = get_paths().agent_dir(GAUSS_DATA_ADAPTATION_AGENT_ID)
|
||||
if target.exists():
|
||||
return False
|
||||
source = _ASSETS_DIR / GAUSS_DATA_ADAPTATION_AGENT_ID
|
||||
if not source.is_dir():
|
||||
logger.error("Missing Gauss data-adaptation agent seed at %s", source)
|
||||
return False
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for filename in _AGENT_FILES:
|
||||
asset = source / filename
|
||||
if asset.is_file():
|
||||
(target / filename).write_bytes(asset.read_bytes())
|
||||
logger.info("Seeded built-in agent '%s'", GAUSS_DATA_ADAPTATION_AGENT_ID)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("Failed to seed Gauss data-adaptation agent")
|
||||
return False
|
||||
|
||||
|
||||
def ensure_gauss_data_adaptation_agent() -> bool:
|
||||
"""Install the Gauss data-adaptation skill and agent when missing."""
|
||||
_ensure_skill()
|
||||
return _ensure_agent()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GAUSS_DATA_ADAPTATION_AGENT_ID",
|
||||
"GAUSS_DATA_ADAPTATION_SKILL_NAME",
|
||||
"ensure_gauss_data_adaptation_agent",
|
||||
]
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
你是高斯数据适配助手。用户会把内网高斯适配时的报错或现象发给你,你告诉他改哪里。
|
||||
|
||||
不要先给安装教程。不要连接高斯,不要让用户把密码、完整连接串或令牌发到对话里。沙箱里的配置只代表跑脚本的那台机器;用户说的是另一台内网服务器时,不要用沙箱里的 `config.yaml` 给那台机器下改法。
|
||||
|
||||
先读技能里的 `references/adaptation-map.md`,只命中一条。
|
||||
|
||||
1. 报错原文已经能对应地图里唯一一条时,直接写改法。例如缺少 `asyncpg` / `opengauss_sqlalchemy`、错误 322、`in-memory fallback`、`current_schema()` 不一致、`VARCHAR(n)` 被拒绝、`standard_conforming_strings` 冲突。
|
||||
2. 改法取决于「原生 openGauss」还是「Dolphin(MySQL 协议)」时,先确认模式,再给改法。能在出问题的那台 Gateway 上运行技能脚本时就运行;不能运行时,只追问 `database.backend` 和进程环境里有没有 `DEERFLOW_DATABASE_PRODUCT=gauss_mysql`。
|
||||
3. 对不上地图时,要改的地方写「先不要改」。指出下一段必须贴来的日志,不要编造 `ALTER`、不要把检查点迁到高斯、不要让内网机器访问公网安装依赖。
|
||||
4. 用户只贴了 `Automatic ORM schema creation failed` 这一句时,改法还不能确定。向他要这句下面的异常类型和第一条 Gauss/MySQL/openGauss 报错,不要根据这句摘要改配置。
|
||||
5. 通用问答和智能体问答共用同一套业务表。列表不见,改业务库;列表还在、正文没有,改检查点。不要为这两种聊天各做一套适配。
|
||||
|
||||
每次回答用这五段,没有内容就写「无」:
|
||||
|
||||
现象
|
||||
判定模式
|
||||
要改的地方
|
||||
不要改的地方
|
||||
改完如何确认
|
||||
|
||||
要改的地方必须是用户能执行的一项:改哪一个配置字段、哪一个环境变量、换哪一个已在现场的镜像或离线包、或明确「先不要改」。改完如何确认要写出重启后日志里应出现或应消失的那一句。
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
id: gauss-data-adapter
|
||||
name: 高斯数据适配助手
|
||||
description: 内网把业务库适配到高斯后出现报错或异常现象时,根据报错说明要改的配置、环境变量或部署方式。不连接数据库,不收集密码。
|
||||
tool_groups:
|
||||
- file:read
|
||||
- bash
|
||||
skills:
|
||||
- gauss-data-adaptation
|
||||
common_questions:
|
||||
- title: 启动报缺少高斯驱动
|
||||
prompt: Gateway 启动报错,说 database.backend 是 gauss,但没有安装 asyncpg 或 opengauss 的 SQLAlchemy 方言。这是内网,不能访问公网。请告诉我要改哪里。
|
||||
- title: 进程起来了但建表失败
|
||||
prompt: Gateway 进程已经起来,日志里有 Automatic ORM schema creation failed。请根据这个现象告诉我要改什么,不要先给一整套安装步骤。
|
||||
- title: Dolphin 报错 322
|
||||
prompt: 高斯走 MySQL 协议(Dolphin)。启动或建表时报错 322。请告诉我要改哪一项配置或环境变量。
|
||||
- title: 列表还在,重启后正文没了
|
||||
prompt: 通用问答和智能体的会话列表还在,但重启 Gateway 后对话正文没了。日志里有 in-memory fallback。请告诉我该改检查点还是高斯业务库。
|
||||
- title: 时间差了 8 小时
|
||||
prompt: 业务库改到高斯之后,页面上的时间比北京时间差了 8 小时。请告诉我要改配置的哪一处,不要让我在 SQL 里手工加减 8 小时。
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: gauss-data-adaptation
|
||||
description: 根据内网高斯适配报错判断要改的配置或环境变量。区分原生 openGauss 与 Dolphin,不连接数据库,不读取密码。
|
||||
---
|
||||
|
||||
# 高斯数据适配
|
||||
|
||||
用户贴来报错或现象后,先读 `references/adaptation-map.md`,只命中一条,按其中的改法回答。
|
||||
|
||||
报错已经能唯一对应时,直接给改法。只有改法取决于原生 openGauss 还是 Dolphin 时,才在**出问题的那台 Gateway** 上运行:
|
||||
|
||||
```bash
|
||||
python /mnt/skills/public/gauss-data-adaptation/scripts/print_gauss_adaptation.py
|
||||
```
|
||||
|
||||
沙箱里找不到该路径时:
|
||||
|
||||
```bash
|
||||
python scripts/print_gauss_adaptation.py
|
||||
```
|
||||
|
||||
脚本只读本机 `config.yaml` 和当前进程是否设置了 `DEERFLOW_DATABASE_PRODUCT`,并用 `find_spec` 查看驱动是否可导入。它不连接高斯,不读取 `$GAUSS_DATABASE_URL` 或 `$MYSQL_DATABASE_URL` 的值,输出里不保留账号和密码。沙箱不是出问题的那台机器时,把命令交给那台机器,不要把沙箱的判定当成那台机器的改法。
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
# 高斯适配报错对照
|
||||
|
||||
只命中一条。改完都要重启出问题的那个 Gateway 进程。环境变量写在启动该进程的服务配置里;在另一个 shell 里临时 export 不会影响已经启动的进程。
|
||||
|
||||
两种模式不能同时打开:
|
||||
|
||||
- 原生 openGauss:`database.backend: gauss`,`database.gauss_url: $GAUSS_DATABASE_URL`。不要设置 `DEERFLOW_DATABASE_PRODUCT`。
|
||||
- Dolphin(高斯的 MySQL 协议):`database.backend: mysql`,`database.mysql_url: $MYSQL_DATABASE_URL`,并且进程环境为 `DEERFLOW_DATABASE_PRODUCT=gauss_mysql`。不要把 `backend` 改成 `gauss`。
|
||||
|
||||
口令只放在服务器的环境变量或客户端口令文件里。下面的改法都不包含密码。
|
||||
|
||||
固定约束:不要把 LangGraph 的 PostgreSQL checkpointer 迁移执行到高斯库上。
|
||||
|
||||
## 缺驱动
|
||||
|
||||
现象:启动日志含 `asyncpg is not installed` 或 `openGauss SQLAlchemy dialect is not installed`。
|
||||
|
||||
模式:原生 openGauss。不需要再确认。
|
||||
|
||||
要改的地方:不要在内网执行会访问公网的 `uv sync --extra gauss`。换成构建时带 `--build-arg UV_EXTRAS=gauss` 的镜像,或使用现场离线 wheelhouse 里的 `asyncpg` 和 `opengauss-sqlalchemy`。装进当前环境后重启。
|
||||
|
||||
不要改的地方:不要为了绕过缺包把 `backend` 改成 `postgres` 或 `mysql`。
|
||||
|
||||
改完如何确认:这两句 ImportError 消失,日志出现 `Persistence engine initialized` 且 `dialect=opengauss`。
|
||||
|
||||
Dolphin 缺的是 MySQL 驱动。日志含 `MySQL async driver is not installed` 时,用离线 wheelhouse 把 `asyncmy` 装进 `.deer-flow/python-vendor`,不要从公网安装,也不要安装 `opengauss-sqlalchemy`。
|
||||
|
||||
## 误用通用 PostgreSQL 方言
|
||||
|
||||
现象:TCP 能连上高斯,但方言初始化或建表失败;或者脚本显示 `backend` 不是 `gauss`,连接串却指向高斯端口。
|
||||
|
||||
模式:应为原生 openGauss。
|
||||
|
||||
要改的地方:`database.backend` 改为 `gauss`,`gauss_url` 使用 `opengauss://`、`opengauss+asyncpg://`、`gaussdb://` 或 PostgreSQL 风格 URL。启动时会归一化成 `opengauss+asyncpg`。取消 `DEERFLOW_DATABASE_PRODUCT`。
|
||||
|
||||
不要改的地方:不要手改 SQLAlchemy 的 PostgreSQL 方言,不要把这条 URL 同时填进 `checkpointer.connection_string`。
|
||||
|
||||
改完如何确认:`dialect=opengauss`。
|
||||
|
||||
## VARCHAR(n) 被拒绝
|
||||
|
||||
现象:建表报错指向 `VARCHAR(数字)`。
|
||||
|
||||
模式:原生 openGauss。不需要再确认。
|
||||
|
||||
要改的地方:确认进程确实以 `backend: gauss` 启动,从而装上把 `VARCHAR(n)` 编译成不带长度的 `VARCHAR` 的兼容层。驱动按上面的「缺驱动」处理。不要在库里把列改成某种固定长度来迁就这条 SQL。
|
||||
|
||||
不要改的地方:不要改成 Dolphin,也不要删业务列。
|
||||
|
||||
改完如何确认:同一条建表错误消失,`dialect=opengauss`。
|
||||
|
||||
## 错误 322,或 SHOW CREATE TABLE 解析失败
|
||||
|
||||
现象:日志含 `322`,或 MySQL 反射、`SHOW CREATE TABLE`、重复 `ALTER` 导致事务中止。
|
||||
|
||||
模式:Dolphin。不需要再确认。
|
||||
|
||||
要改的地方:保证**正在运行的进程**有 `DEERFLOW_DATABASE_PRODUCT=gauss_mysql`,`database.backend` 保持 `mysql`。设置后重启该进程。不要再执行 MySQL 的 `SHOW CREATE TABLE` 反射、MySQL JSON 回填、MySQL 会话超时变量,也不要让应用执行 `CREATE DATABASE`。
|
||||
|
||||
不要改的地方:不要把 `backend` 改成 `gauss` 来消掉 322。库、用户和 schema 仍由离线部署层创建。
|
||||
|
||||
改完如何确认:日志出现 `GaussDB MySQL compatibility enabled` 和 `Skipping MySQL reflection and JSON backfill for openGauss Dolphin`,不再出现 322。
|
||||
|
||||
## init_command 冲突
|
||||
|
||||
现象:日志含 `gauss_mysql requires init_command` 或 `standard_conforming_strings`。
|
||||
|
||||
模式:Dolphin。
|
||||
|
||||
要改的地方:从 `mysql_url` 里去掉冲突的 `init_command`。兼容层会在连接时设置 `SET standard_conforming_strings TO off`。
|
||||
|
||||
不要改的地方:不要在 URL 里写另一条 `init_command`,不要把口令贴进对话。
|
||||
|
||||
改完如何确认:这句 ValueError 消失,并出现 `GaussDB MySQL compatibility enabled`。
|
||||
|
||||
## current_schema() 对不上
|
||||
|
||||
现象:日志含 `URL schema` 与 `current_schema()` 不一致,或 `current_schema() is empty`。
|
||||
|
||||
模式:Dolphin 的启动补列。
|
||||
|
||||
要改的地方:把 `mysql_url` 里的库名改成 `SELECT current_schema();` 的结果,或让部署层把该登录用户的当前 schema 改成 URL 里的库名。两边必须是同一个名字。
|
||||
|
||||
不要改的地方:不要用 `SHOW CREATE TABLE` 补列,不要由应用 `CREATE DATABASE`。
|
||||
|
||||
改完如何确认:这句 schema integrity check 消失。若随后出现 `openGauss schema is incomplete`,按下一条处理,不要提前改别的配置。
|
||||
|
||||
## 缺列但启动拒绝补列
|
||||
|
||||
现象:日志含 `openGauss schema is incomplete`,以及 `NOT NULL column has no server_default`、主键、identity、computed 或约束需要 explicit migration。
|
||||
|
||||
模式:Dolphin。
|
||||
|
||||
要改的地方:先不要改。把日志里点名的 `schema.表.列` 原样留下。这种列不能靠启动自动补。需要一份针对该列的显式迁移,而不是在对话里手写 `ALTER TABLE`。
|
||||
|
||||
不要改的地方:不要删表、不要把列改成可空来让启动继续。
|
||||
|
||||
改完如何确认:同一句 `schema is incomplete` 消失。只为日志点名的那一列做迁移。
|
||||
|
||||
## 只看到建表失败摘要
|
||||
|
||||
现象:只有 `Automatic ORM schema creation failed; continuing Gateway startup`。
|
||||
|
||||
模式:还不能判定。
|
||||
|
||||
要改的地方:先不要改。把这句下面的异常类型和第一条数据库报错贴出来,再按本表重新命中。
|
||||
|
||||
不要改的地方:不要因为进程还活着就认为适配已经成功。缺表的接口仍会失败。
|
||||
|
||||
改完如何确认:重启后这句消失;若仍在,新贴出的第一条数据库报错必须变了,才能进入下一条。
|
||||
|
||||
## 列表还在,重启后正文没了
|
||||
|
||||
现象:通用问答或智能体的会话列表还在,重启后正文没有;日志含 `LangGraph checkpointer initialization failed` 和 `in-memory fallback`。
|
||||
|
||||
模式:与原生或 Dolphin 无关。列表来自业务库,正文来自检查点。
|
||||
|
||||
要改的地方:修复日志里检查点初始化的那条异常。检查点使用现有 SQLite 文件,或一台真正的 PostgreSQL。不要把 LangGraph 的 PostgreSQL checkpointer 迁移执行到高斯库上。若 `checkpointer.type` 已是 `postgres` 且 `use_postgres: false`,实际文件是 `sqlite_connection_string`,改这个路径的权限或位置,不要改高斯 URL。
|
||||
|
||||
不要改的地方:不要重导 `threads_meta`,不要改 `assistant_id`。两种聊天的正文都在同一套检查点里。
|
||||
|
||||
改完如何确认:`in-memory fallback` 消失。重启后再打开刚才那条通用问答和那条智能体问答,正文仍在。
|
||||
|
||||
## 时间差 8 小时
|
||||
|
||||
现象:库里或页面上的时间比北京时间差 8 小时,业务库刚刚改到高斯。
|
||||
|
||||
先确认模式。
|
||||
|
||||
- 原生 openGauss 却把 `backend` 配成 `mysql` 或 `postgres`:改回上一节的原生配置。`opengauss` 与 `postgresql` 走带时区的时间类型,不在写入时改成北京墙钟。
|
||||
- Dolphin 却没设 `DEERFLOW_DATABASE_PRODUCT=gauss_mysql`,或误设成 `backend: gauss`:改回 Dolphin 配置。Dolphin 按 MySQL 方言把 UTC 存成北京墙钟。
|
||||
- 模式已经配对,只是客户端用另一套时区显示:先不要改 DeerFlow 配置,也不要在 SQL 里加减 8 小时。
|
||||
|
||||
改完如何确认:新写入的一行与页面显示一致。不要批量改历史时间列。
|
||||
|
||||
## JSON 读失败
|
||||
|
||||
现象:日志含 `GaussDB MySQL JSON value is neither valid JSON`,或普通 JSON 解析失败。
|
||||
|
||||
- 这句完整报错只出现在 Dolphin 兼容层已经装上、但库里的值不是严格 JSON、也不是已支持的旧字面量时:先不要改配置。把报错里的预览留给库侧,不要改用另一种解码把坏值读成对象。
|
||||
- 同样的数据在未设置 `DEERFLOW_DATABASE_PRODUCT=gauss_mysql` 时解析失败:按 Dolphin 配置补上该环境变量并重启。普通 MySQL 必须继续拒绝坏 JSON,不要为了读旧数据去设置这个变量。
|
||||
|
||||
改完如何确认:Dolphin 应出现 `GaussDB MySQL compatibility enabled`。坏值那一行仍失败时,失败原因应仍是这句 JSON 报错,而不是驱动或方言报错。
|
||||
|
||||
## 两种模式同时打开
|
||||
|
||||
现象:`backend: gauss`,同时进程环境是 `DEERFLOW_DATABASE_PRODUCT=gauss_mysql`。
|
||||
|
||||
要改的地方:只留一种。原生就删掉该环境变量;Dolphin 就把 `backend` 改回 `mysql` 并保留该环境变量。
|
||||
|
||||
不要改的地方:不要两套 URL 都填上指望自动选择。
|
||||
|
||||
改完如何确认:脚本的「判定模式」只剩一种,启动日志里的 `dialect` 与之相符:原生是 `opengauss`,Dolphin 是 `mysql`。
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
"""Classify the local Gauss adaptation mode without connecting or reading secrets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from importlib.util import find_spec
|
||||
from pathlib import Path
|
||||
|
||||
PROHIBITION = "不要把 LangGraph 的 PostgreSQL checkpointer 迁移执行到高斯库上"
|
||||
DOLPHIN_PRODUCT = "gauss_mysql"
|
||||
GAUSS_URL_PREFIXES = (
|
||||
"opengauss+asyncpg://",
|
||||
"opengauss://",
|
||||
"gaussdb://",
|
||||
"postgres://",
|
||||
"postgresql://",
|
||||
"postgresql+asyncpg://",
|
||||
)
|
||||
|
||||
|
||||
def config_candidates() -> list[Path]:
|
||||
found: list[Path] = []
|
||||
for key in ("DEER_FLOW_CONFIG_PATH", "DEER_FLOW_CONFIG", "DEERFLOW_CONFIG"):
|
||||
value = os.environ.get(key, "").strip()
|
||||
if value:
|
||||
found.append(Path(value))
|
||||
found.extend(
|
||||
[
|
||||
Path("/app/backend/config.yaml"),
|
||||
Path.cwd() / "config.yaml",
|
||||
Path.cwd().parent / "config.yaml",
|
||||
]
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def parse_sections(text: str, names: set[str]) -> dict[str, dict[str, str]]:
|
||||
"""Read one level of scalar keys from the named top-level YAML blocks."""
|
||||
found = {name: {} for name in names}
|
||||
current = ""
|
||||
for raw in text.splitlines():
|
||||
line = raw.split("#", 1)[0].rstrip()
|
||||
if not line.strip():
|
||||
continue
|
||||
if not line.startswith((" ", "\t")):
|
||||
header = line.strip()
|
||||
current = header[:-1] if header.endswith(":") else ""
|
||||
if current not in names:
|
||||
current = ""
|
||||
continue
|
||||
if not current or ":" not in line:
|
||||
continue
|
||||
key, _, value = line.strip().partition(":")
|
||||
value = value.strip().strip("\"'")
|
||||
if value:
|
||||
found[current][key.strip()] = value
|
||||
return found
|
||||
|
||||
|
||||
def describe_value(value: str) -> str:
|
||||
"""Describe a config value without usernames, passwords, or env-var contents."""
|
||||
text = value.strip().strip("\"'")
|
||||
if not text:
|
||||
return "未设置"
|
||||
if text.startswith("$"):
|
||||
return f"环境变量 {text[1:]}(不读取变量值)"
|
||||
if "://" not in text:
|
||||
return text
|
||||
scheme, _, rest = text.partition("://")
|
||||
target = rest.split("@")[-1].split("?")[0]
|
||||
return f"{scheme}://{target}(已去掉账号和密码)"
|
||||
|
||||
|
||||
def driver_status() -> dict[str, bool]:
|
||||
names = ("asyncpg", "opengauss_sqlalchemy", "asyncmy", "aiomysql")
|
||||
return {name: find_spec(name) is not None for name in names}
|
||||
|
||||
|
||||
def _enabled(value: str) -> bool:
|
||||
return value.strip().lower() not in {"", "false", "0", "no", "off"}
|
||||
|
||||
|
||||
def classify(
|
||||
database: dict[str, str],
|
||||
checkpointer: dict[str, str],
|
||||
product: str,
|
||||
drivers: dict[str, bool],
|
||||
) -> list[str]:
|
||||
"""Return the mode and the concrete config change, if one is already known."""
|
||||
backend = database.get("backend", "").strip().lower()
|
||||
product_name = product.strip().lower()
|
||||
checkpoint_type = checkpointer.get("type", "").strip().lower()
|
||||
use_postgres = checkpointer.get("use_postgres", "")
|
||||
lines = [
|
||||
f"database.backend={backend or '未解析'}",
|
||||
f"DEERFLOW_DATABASE_PRODUCT={product_name or '未设置'}",
|
||||
f"checkpointer.type={checkpoint_type or '未解析'}",
|
||||
]
|
||||
if "gauss_url" in database:
|
||||
lines.append(f"database.gauss_url={describe_value(database['gauss_url'])}")
|
||||
if "mysql_url" in database:
|
||||
lines.append(f"database.mysql_url={describe_value(database['mysql_url'])}")
|
||||
if "connection_string" in checkpointer:
|
||||
lines.append(
|
||||
"checkpointer.connection_string="
|
||||
+ describe_value(checkpointer["connection_string"])
|
||||
)
|
||||
if use_postgres:
|
||||
lines.append(f"checkpointer.use_postgres={use_postgres}")
|
||||
for name in ("asyncpg", "opengauss_sqlalchemy", "asyncmy", "aiomysql"):
|
||||
lines.append(f"{name}={'可导入' if drivers.get(name) else '不可导入'}")
|
||||
|
||||
changes: list[str] = []
|
||||
constraints: list[str] = []
|
||||
if backend == "gauss" and product_name == DOLPHIN_PRODUCT:
|
||||
mode = "冲突:原生 openGauss 与 Dolphin 同时打开"
|
||||
changes.append(
|
||||
"只保留一种。原生就取消 DEERFLOW_DATABASE_PRODUCT;"
|
||||
"Dolphin 就把 database.backend 改回 mysql,并保留该环境变量。"
|
||||
)
|
||||
elif backend == "gauss":
|
||||
mode = "原生 openGauss"
|
||||
url = database.get("gauss_url", "")
|
||||
if not url:
|
||||
changes.append("补上 database.gauss_url: $GAUSS_DATABASE_URL。口令只放在该环境变量里。")
|
||||
elif not url.startswith("$") and not url.startswith(GAUSS_URL_PREFIXES):
|
||||
changes.append(
|
||||
"把 gauss_url 改成 opengauss://、opengauss+asyncpg://、gaussdb:// 或 PostgreSQL 风格 URL。"
|
||||
)
|
||||
elif not url.startswith("$") and not url.startswith("opengauss+asyncpg://"):
|
||||
constraints.append("这份 gauss_url 启动时会归一化为 opengauss+asyncpg,不会走通用 PostgreSQL 方言。")
|
||||
if not drivers.get("asyncpg") or not drivers.get("opengauss_sqlalchemy"):
|
||||
changes.append(
|
||||
"当前进程缺少 asyncpg 或 opengauss_sqlalchemy。"
|
||||
"不要在内网访问公网安装。改用带 UV_EXTRAS=gauss 的镜像,或现场离线 wheelhouse。"
|
||||
)
|
||||
constraints.append("不要设置 DEERFLOW_DATABASE_PRODUCT。")
|
||||
elif backend == "mysql" and product_name == DOLPHIN_PRODUCT:
|
||||
mode = "Dolphin(高斯 MySQL 协议)"
|
||||
if not database.get("mysql_url"):
|
||||
changes.append("补上 database.mysql_url: $MYSQL_DATABASE_URL。口令只放在该环境变量里。")
|
||||
if not drivers.get("asyncmy") and not drivers.get("aiomysql"):
|
||||
changes.append(
|
||||
"当前进程缺少 asyncmy 和 aiomysql。用离线 wheelhouse 把 asyncmy 装进 "
|
||||
".deer-flow/python-vendor,不要从公网安装。"
|
||||
)
|
||||
constraints.append(
|
||||
"不要执行 SHOW CREATE TABLE、MySQL JSON 回填或应用侧 CREATE DATABASE。"
|
||||
"URL 里的库名必须等于 SELECT current_schema()。"
|
||||
)
|
||||
elif backend == "mysql":
|
||||
mode = "普通 MySQL"
|
||||
constraints.append(
|
||||
"现在不会安装 Dolphin 补丁。只有报错已经表现为 322、current_schema 或 "
|
||||
"SHOW CREATE TABLE 解析失败时,才给运行中的进程加上 "
|
||||
"DEERFLOW_DATABASE_PRODUCT=gauss_mysql 并重启。普通 MySQL 不要加。"
|
||||
)
|
||||
elif backend == "postgres":
|
||||
mode = "PostgreSQL"
|
||||
changes.append("这不是高斯适配路径。连高斯业务库时不要使用 backend: postgres。")
|
||||
elif backend in {"sqlite", "memory"}:
|
||||
mode = backend
|
||||
constraints.append("当前业务库配置不是高斯。这只代表运行脚本的机器。")
|
||||
else:
|
||||
mode = "未识别"
|
||||
changes.append("先不要改。确认 database.backend 是 gauss、mysql、postgres、sqlite 还是 memory。")
|
||||
|
||||
postgres_checkpoint = checkpoint_type == "postgres" and _enabled(use_postgres or "true")
|
||||
if backend in {"gauss", "mysql"} and postgres_checkpoint and product_name == DOLPHIN_PRODUCT:
|
||||
changes.append(
|
||||
"先确认 checkpointer.connection_string 是不是高斯。"
|
||||
+ PROHIBITION
|
||||
+ " 是高斯就把 checkpointer.type 改为 sqlite,并沿用现有 SQLite 文件;是独立的 PostgreSQL 就不要改。"
|
||||
)
|
||||
elif backend == "gauss" and postgres_checkpoint:
|
||||
changes.append(
|
||||
"先确认 checkpointer.connection_string 是不是高斯。"
|
||||
+ PROHIBITION
|
||||
+ " 是高斯就把 checkpointer.type 改为 sqlite,并沿用现有 SQLite 文件;是独立的 PostgreSQL 就不要改。"
|
||||
)
|
||||
elif checkpoint_type == "memory" and backend in {"gauss", "mysql"}:
|
||||
changes.append("把 checkpointer.type 从 memory 改为 sqlite,否则重启后问答正文不会保留。")
|
||||
|
||||
lines.append(f"判定模式:{mode}")
|
||||
if constraints:
|
||||
lines.append("先不要改:")
|
||||
lines.extend(f"- {item}" for item in constraints)
|
||||
lines.append("要改的地方:")
|
||||
if changes:
|
||||
lines.extend(f"- {item}" for item in changes)
|
||||
else:
|
||||
lines.append("- 配置层面没有必须修改的项。把报错原文发来后再决定。")
|
||||
lines.append(f"固定约束:{PROHIBITION}")
|
||||
return lines
|
||||
|
||||
|
||||
def main() -> None:
|
||||
print("这个结果只代表运行脚本的机器,不连接高斯,也不读取连接串环境变量的值。")
|
||||
chosen = next((item for item in config_candidates() if item.is_file()), None)
|
||||
if chosen is None:
|
||||
database: dict[str, str] = {}
|
||||
checkpointer: dict[str, str] = {}
|
||||
print("配置:未找到 config.yaml。")
|
||||
else:
|
||||
print(f"配置文件:{chosen}")
|
||||
try:
|
||||
parsed = parse_sections(
|
||||
chosen.read_text(encoding="utf-8"),
|
||||
{"database", "checkpointer"},
|
||||
)
|
||||
except OSError as exc:
|
||||
print(f"配置:读取失败:{exc}")
|
||||
parsed = {"database": {}, "checkpointer": {}}
|
||||
database = parsed["database"]
|
||||
checkpointer = parsed["checkpointer"]
|
||||
for line in classify(
|
||||
database,
|
||||
checkpointer,
|
||||
os.environ.get("DEERFLOW_DATABASE_PRODUCT", ""),
|
||||
driver_status(),
|
||||
):
|
||||
print(line)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+2
-2
@@ -21,7 +21,7 @@
|
||||
## 页面生成流程
|
||||
|
||||
1. 先读取 `page-report-generation` 技能,并将材料归为:事实数据、可推导结论、待补充项、图表数据、长文本、表格行、行动/风险项。优先保留用户原文的关键判断和数据口径。
|
||||
2. 默认从零直接创建 `/mnt/user-data/outputs/<主题>.html`,第一项文件操作就是写最终路径。只有用户明确要求使用模板或点名模板时,才读取 `page-template-library` 并调用 `page_report_template(action="prepare")`;主题优先使用界面传入的 `presentation_theme`,其次遵从用户明示。
|
||||
2. 默认从零直接创建 `/mnt/user-data/outputs/<主题>.html`,第一项文件操作就是写最终路径。只有用户明确要求使用模板或点名模板时,才读取 `page-template-library` 并调用 `page_report_template(action="prepare")`;用户明示的页面主题优先,否则只跟随界面传入的 `presentation_theme` 明暗模式。
|
||||
3. 页面文字通常要多于图表:至少包含结论摘要、关键发现、事项/风险说明、数据口径或来源、行动建议中的多个展示样式。默认生成一个可纵向滚动的响应式页面;只有用户明确要求多页或给出页数时才生成多页。
|
||||
4. 使用模板时,工具返回的 outputs 工作副本是唯一成品路径。保留已有图表渲染和本地运行时契约,用真实数据替换占位内容,并删除无数据页面和面板;绝不修改模板源文件。
|
||||
5. 所有可见正文、表头、标签、说明文字最小字号均为 16px;长文本面板要增高、提高行高,不能把段落挤成一团。
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
## 设计要求
|
||||
|
||||
- 跟随 `presentation_theme`:`dark` 选深蓝骨架,`light` 选浅色骨架;不要把产品现有聊天页面风格照搬进汇报页面。
|
||||
- 用户未指定页面主题时跟随 `presentation_theme`:`dark` 选深色骨架,`light` 选浅色骨架;不要复制系统的红、蓝、绿等主题主色,页面自己的强调色根据内容、信息层级和可读性独立设计,也不要把产品现有聊天页面风格照搬进汇报页面。
|
||||
- 深色使用深蓝科技感,选中状态可有细腻的扫描光、描边或流光;浅色使用清晰留白与高对比文字。
|
||||
- 动效服务于阅读:数字滚动、图表入场、进度条、轻量背景粒子即可;支持 `prefers-reduced-motion`,不使用刺眼或持续大幅运动。
|
||||
- 图表必须与材料一致。数据不够时宁可删掉图表或明确标为示意,不伪造事实;避免为了“丰富”而堆满图。
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ allowed-tools:
|
||||
## 使用流程
|
||||
|
||||
1. 先盘点材料和输出约束,确定:
|
||||
- `theme`:优先使用界面传入的 `presentation_theme`,否则遵从用户明示;仍未指定时使用 `auto`。
|
||||
- `theme`:用户明示的页面主题优先;否则使用界面传入的 `presentation_theme`。`auto` 会由工具按当前界面明暗模式解析,界面信息缺失时才回退浅色。
|
||||
- `content_density`:`text-heavy`、`balanced` 或 `data-heavy`。
|
||||
- `required_features`:如 `flowchart`、`chart`、`map`、`table`、`text-panels`;源 Markdown 中的 Mermaid 必须记为 `flowchart`。
|
||||
- `preferred_page_count`:默认 `1`;只有用户明确要求多页或指定页数时才大于 `1`。
|
||||
|
||||
@@ -318,6 +318,20 @@ class AdminLeaderboardResponse(BaseModel):
|
||||
trends: list[AdminLeaderboardTrendPoint] = Field(default_factory=list)
|
||||
|
||||
|
||||
class AdminUserAnalyticsResponse(BaseModel):
|
||||
range_days: int
|
||||
since: str
|
||||
until: str
|
||||
user: AdminLeaderboardUser
|
||||
overview: AdminLeaderboardOverview
|
||||
skills: list[AdminLeaderboardSkill] = Field(default_factory=list)
|
||||
tools: list[AdminLeaderboardSkill] = Field(default_factory=list)
|
||||
models: list[AdminLeaderboardDimension] = Field(default_factory=list)
|
||||
agents: list[AdminLeaderboardDimension] = Field(default_factory=list)
|
||||
run_statuses: list[AdminLeaderboardDimension] = Field(default_factory=list)
|
||||
trends: list[AdminLeaderboardTrendPoint] = Field(default_factory=list)
|
||||
|
||||
|
||||
class AdminLeaderboardReportResponse(BaseModel):
|
||||
report: str
|
||||
generated_at: str
|
||||
@@ -2224,6 +2238,67 @@ async def stream_user_leaderboard_report(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{user_id}/analytics", response_model=AdminUserAnalyticsResponse)
|
||||
async def get_user_analytics(
|
||||
user_id: str,
|
||||
request: Request,
|
||||
days: int = Query(default=30, ge=1, le=ADMIN_QUERY_WINDOW_DAYS),
|
||||
since: str | None = Query(default=None, description="Inclusive range start, ISO datetime"),
|
||||
until: str | None = Query(default=None, description="Inclusive range end, ISO datetime"),
|
||||
limit: int = Query(default=20, ge=5, le=100),
|
||||
) -> AdminUserAnalyticsResponse:
|
||||
"""Return one user's admin analytics profile."""
|
||||
await _require_admin(request)
|
||||
session_factory = get_session_factory()
|
||||
if session_factory is None:
|
||||
raise HTTPException(status_code=503, detail="Analytics requires database persistence")
|
||||
|
||||
settings = load_system_settings().leaderboard
|
||||
common = {
|
||||
"include_scheduled": settings.include_scheduled,
|
||||
"include_admins": settings.include_admins,
|
||||
"include_failed": settings.include_failed,
|
||||
}
|
||||
tool_common = {
|
||||
"include_scheduled": settings.include_scheduled,
|
||||
"include_admins": settings.include_admins,
|
||||
}
|
||||
since_dt, until_dt, range_days = resolve_admin_query_window(
|
||||
days=days,
|
||||
since=since,
|
||||
until=until,
|
||||
)
|
||||
async with session_factory() as session:
|
||||
await _set_analytics_read_timeout(session)
|
||||
users = await _query_user_leaderboard(session, since_dt, until_dt, user_id=user_id, **common)
|
||||
if not users:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
overview = await _query_overview(session, since_dt, until_dt, user_id=user_id, **common)
|
||||
skills = await _query_call_rankings(session, since_dt, until_dt, user_id=user_id, field="skill", limit=limit, **tool_common)
|
||||
tools = await _query_call_rankings(session, since_dt, until_dt, user_id=user_id, field="tool", limit=limit, **tool_common)
|
||||
models = await _query_model_rankings(session, since_dt, until_dt, user_id=user_id, limit=limit, **common)
|
||||
if not models:
|
||||
models = await _query_run_dimensions(session, since_dt, until_dt, user_id=user_id, field="model", limit=limit, **common)
|
||||
agents = await _query_run_dimensions(session, since_dt, until_dt, user_id=user_id, field="agent", limit=limit, **common)
|
||||
run_statuses = await _query_run_dimensions(session, since_dt, until_dt, user_id=user_id, field="status", limit=limit, **common)
|
||||
trends = await _query_trends(session, since_dt, until_dt, user_id=user_id, **common)
|
||||
|
||||
return AdminUserAnalyticsResponse(
|
||||
range_days=range_days,
|
||||
since=_iso(since_dt),
|
||||
until=_iso(until_dt),
|
||||
user=users[0],
|
||||
overview=overview,
|
||||
skills=skills,
|
||||
tools=tools,
|
||||
models=models,
|
||||
agents=agents,
|
||||
run_statuses=run_statuses,
|
||||
trends=trends,
|
||||
)
|
||||
|
||||
|
||||
|
||||
# ── Q&A audit list ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Admin-only metadata migration for agent/skill folders copied in place."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.agent_skill_migration import (
|
||||
MigrationApplyResult,
|
||||
MigrationManifest,
|
||||
MigrationPreflight,
|
||||
apply_migration_manifest,
|
||||
build_agent_migration_manifest,
|
||||
build_skill_migration_manifest,
|
||||
preflight_manifest,
|
||||
prepare_manifest_for_apply,
|
||||
)
|
||||
from app.gateway.deps import (
|
||||
get_agent_store,
|
||||
get_local_provider,
|
||||
get_optional_user_from_request,
|
||||
get_skill_store,
|
||||
get_tag_store,
|
||||
)
|
||||
from deerflow.agents.lead_agent.prompt import refresh_skills_system_prompt_cache_async
|
||||
from deerflow.config.extensions_config import ExtensionsConfig
|
||||
from deerflow.config.paths import get_paths
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
from deerflow.persistence.agents import AgentStore
|
||||
from deerflow.persistence.skills import SkillStore
|
||||
from deerflow.persistence.tags import TagStore
|
||||
from deerflow.runtime.user_context import get_effective_user_id
|
||||
from deerflow.sandbox.skill_view import refresh_skill_sandbox_view
|
||||
from deerflow.skills.storage import get_or_new_skill_storage
|
||||
from deerflow.skills.usage import all_entries as get_skill_usage_entries
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/admin/agent-skill-migrations", tags=["agent-skill-migrations"])
|
||||
|
||||
|
||||
class MigrationExportRequest(BaseModel):
|
||||
agent_ids: list[str] = Field(min_length=1, max_length=1000)
|
||||
|
||||
|
||||
class SkillMigrationExportRequest(BaseModel):
|
||||
skill_names: list[str] = Field(min_length=1, max_length=5000)
|
||||
|
||||
|
||||
class MigrationApplyRequest(BaseModel):
|
||||
manifest: MigrationManifest
|
||||
use_current_admin_for_unresolved_owners: bool = False
|
||||
skip_invalid_skills: bool = False
|
||||
|
||||
|
||||
class MigrationRootsResponse(BaseModel):
|
||||
agents_root: str
|
||||
skills_root: str
|
||||
extensions_config_path: str | None
|
||||
|
||||
|
||||
async def _require_admin(request: Request):
|
||||
user = await get_optional_user_from_request(request)
|
||||
if user is not None and getattr(user, "system_role", None) != "admin":
|
||||
raise HTTPException(status_code=403, detail="智能体与技能迁移仅限管理员")
|
||||
return user
|
||||
|
||||
|
||||
def _require_migration_enabled() -> None:
|
||||
if not load_system_settings().agent_skill_migration.enabled:
|
||||
raise HTTPException(status_code=403, detail="智能体与技能迁移功能未开启")
|
||||
|
||||
|
||||
async def _users() -> tuple[dict[str, str], dict[str, str]]:
|
||||
"""Return ``(id -> email, normalized email -> id)`` without auth secrets."""
|
||||
|
||||
try:
|
||||
users = await get_local_provider().list_users()
|
||||
except Exception: # noqa: BLE001 - metadata migration degrades to manual owner fallback
|
||||
logger.warning("Could not load users for migration owner mapping", exc_info=True)
|
||||
return {}, {}
|
||||
by_id = {str(user.id): str(user.email) for user in users}
|
||||
by_email = {str(user.email).strip().casefold(): str(user.id) for user in users}
|
||||
return by_id, by_email
|
||||
|
||||
|
||||
def _roots() -> tuple[Path, Path]:
|
||||
storage = get_or_new_skill_storage()
|
||||
return get_paths().agents_dir.resolve(), Path(storage.get_skills_root_path()).resolve()
|
||||
|
||||
|
||||
@router.get("/roots", response_model=MigrationRootsResponse)
|
||||
async def migration_roots(request: Request) -> MigrationRootsResponse:
|
||||
await _require_admin(request)
|
||||
_require_migration_enabled()
|
||||
agents_root, skills_root = _roots()
|
||||
extensions_path = ExtensionsConfig.resolve_config_path()
|
||||
return MigrationRootsResponse(
|
||||
agents_root=str(agents_root),
|
||||
skills_root=str(skills_root),
|
||||
extensions_config_path=str(extensions_path.resolve()) if extensions_path else None,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/export", response_model=MigrationManifest)
|
||||
async def export_migration_manifest(
|
||||
body: MigrationExportRequest,
|
||||
request: Request,
|
||||
agent_store: AgentStore = Depends(get_agent_store),
|
||||
tag_store: TagStore = Depends(get_tag_store),
|
||||
) -> MigrationManifest:
|
||||
await _require_admin(request)
|
||||
_require_migration_enabled()
|
||||
agents_root, _ = _roots()
|
||||
users_by_id, _ = await _users()
|
||||
try:
|
||||
return await build_agent_migration_manifest(
|
||||
body.agent_ids,
|
||||
agent_store=agent_store,
|
||||
tag_store=tag_store,
|
||||
agents_root=agents_root,
|
||||
users_by_id=users_by_id,
|
||||
)
|
||||
except (FileNotFoundError, ValueError) as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/export-skills", response_model=MigrationManifest)
|
||||
async def export_skill_migration_manifest(
|
||||
body: SkillMigrationExportRequest,
|
||||
request: Request,
|
||||
skill_store: SkillStore = Depends(get_skill_store),
|
||||
tag_store: TagStore = Depends(get_tag_store),
|
||||
) -> MigrationManifest:
|
||||
await _require_admin(request)
|
||||
_require_migration_enabled()
|
||||
_, skills_root = _roots()
|
||||
storage = get_or_new_skill_storage()
|
||||
users_by_id, _ = await _users()
|
||||
discovered_skills = await asyncio.to_thread(storage.load_skills, enabled_only=False)
|
||||
try:
|
||||
return await build_skill_migration_manifest(
|
||||
body.skill_names,
|
||||
skill_store=skill_store,
|
||||
tag_store=tag_store,
|
||||
skills_root=skills_root,
|
||||
discovered_skills=discovered_skills,
|
||||
users_by_id=users_by_id,
|
||||
usage_entries=get_skill_usage_entries(),
|
||||
)
|
||||
except (FileNotFoundError, ValueError) as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/preflight", response_model=MigrationPreflight)
|
||||
async def preflight_migration_manifest(
|
||||
manifest: MigrationManifest,
|
||||
request: Request,
|
||||
) -> MigrationPreflight:
|
||||
await _require_admin(request)
|
||||
_require_migration_enabled()
|
||||
agents_root, skills_root = _roots()
|
||||
_, users_by_email = await _users()
|
||||
return await asyncio.to_thread(
|
||||
preflight_manifest,
|
||||
manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email=users_by_email,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/apply", response_model=MigrationApplyResult)
|
||||
async def apply_migration(
|
||||
body: MigrationApplyRequest,
|
||||
request: Request,
|
||||
agent_store: AgentStore = Depends(get_agent_store),
|
||||
skill_store: SkillStore = Depends(get_skill_store),
|
||||
tag_store: TagStore = Depends(get_tag_store),
|
||||
) -> MigrationApplyResult:
|
||||
user = await _require_admin(request)
|
||||
_require_migration_enabled()
|
||||
agents_root, skills_root = _roots()
|
||||
_, users_by_email = await _users()
|
||||
# Re-scan at apply time. The browser's earlier preflight is informative,
|
||||
# never an authorization or integrity token.
|
||||
preflight = await asyncio.to_thread(
|
||||
preflight_manifest,
|
||||
body.manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email=users_by_email,
|
||||
)
|
||||
try:
|
||||
effective_manifest, effective_preflight, _ = prepare_manifest_for_apply(
|
||||
body.manifest,
|
||||
preflight,
|
||||
skip_invalid_skills=body.skip_invalid_skills,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
if body.manifest.skills and not effective_manifest.skills:
|
||||
raise HTTPException(status_code=409, detail="所有技能均未通过预检,没有可导入的技能")
|
||||
resource_failures = [item.model_dump(mode="json") for item in [*effective_preflight.agents, *effective_preflight.skills, *effective_preflight.support_directories] if item.status != "matched"]
|
||||
unresolved = [item for item in effective_preflight.owner_mappings if item.status == "unresolved"]
|
||||
if resource_failures or (unresolved and not body.use_current_admin_for_unresolved_owners):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={
|
||||
"message": "迁移预检未通过,未写入任何元数据",
|
||||
"preflight": effective_preflight.model_dump(mode="json"),
|
||||
},
|
||||
)
|
||||
|
||||
extensions_path = ExtensionsConfig.resolve_config_path() if effective_manifest.skills else None
|
||||
if effective_manifest.skills and extensions_path is None:
|
||||
raise HTTPException(status_code=503, detail="目标运行环境未找到 extensions_config.json")
|
||||
fallback_owner_user_id = None
|
||||
if unresolved and body.use_current_admin_for_unresolved_owners:
|
||||
fallback_owner_user_id = str(user.id) if user is not None else get_effective_user_id()
|
||||
|
||||
try:
|
||||
result = await apply_migration_manifest(
|
||||
body.manifest,
|
||||
preflight=preflight,
|
||||
agent_store=agent_store,
|
||||
skill_store=skill_store,
|
||||
tag_store=tag_store,
|
||||
agents_root=agents_root,
|
||||
users_by_email=users_by_email,
|
||||
fallback_owner_user_id=fallback_owner_user_id,
|
||||
extensions_config_path=extensions_path,
|
||||
skip_invalid_skills=body.skip_invalid_skills,
|
||||
)
|
||||
if result.skills_applied:
|
||||
await refresh_skills_system_prompt_cache_async()
|
||||
storage = get_or_new_skill_storage()
|
||||
await asyncio.to_thread(refresh_skill_sandbox_view, storage=storage, force=True)
|
||||
return result
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,700 @@
|
||||
"""Account-scoped chat history transfer for the conversation list page.
|
||||
|
||||
Exports and imports ordinary / agent chats as a JSON bundle that includes
|
||||
the latest checkpoint (messages) and the thread ``user-data`` files
|
||||
(uploads + outputs). One oversized or broken thread is skipped so the
|
||||
rest of the batch can still succeed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import FileResponse
|
||||
from langgraph.checkpoint.base import empty_checkpoint
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.authz import require_permission
|
||||
from app.gateway.deps import get_checkpointer, get_thread_store
|
||||
from app.gateway.routers.threads import _strip_reserved_metadata
|
||||
from app.gateway.utils import sanitize_log_param
|
||||
from deerflow.config.paths import get_paths
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
from deerflow.persistence.thread_meta.base import is_excluded_system_thread
|
||||
from deerflow.runtime import serialize_channel_values
|
||||
from deerflow.runtime.user_context import get_effective_user_id
|
||||
from deerflow.utils.time import coerce_iso, now_iso
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/chat-history", tags=["chat-history-transfer"])
|
||||
|
||||
FORMAT = "deerflow-chat-history-ui"
|
||||
FORMAT_VERSION = 1
|
||||
BATCH_LIMIT = 1
|
||||
MAX_THREAD_BYTES = 50 * 1024 * 1024
|
||||
MAX_FILES_PER_THREAD = 200
|
||||
SAFE_REL_PATH = re.compile(r"^(?:[A-Za-z0-9._-]+/)*[A-Za-z0-9._-]+$")
|
||||
_FILE_JSON_OVERHEAD = 64
|
||||
_DROP_META_KEYS = frozenset(
|
||||
{
|
||||
"owner_id",
|
||||
"user_id",
|
||||
"analysis_project_id",
|
||||
"analysis_project_mode",
|
||||
"analysis_project_name",
|
||||
"shared_from_code",
|
||||
"shared_origin",
|
||||
"shared_by",
|
||||
"taskId",
|
||||
"actionId",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class SkippedThread(BaseModel):
|
||||
thread_id: str
|
||||
title: str = ""
|
||||
reason: str
|
||||
|
||||
|
||||
class TransferFile(BaseModel):
|
||||
path: str
|
||||
content_b64: str
|
||||
size: int = 0
|
||||
|
||||
|
||||
class TransferThread(BaseModel):
|
||||
thread_id: str
|
||||
title: str = ""
|
||||
assistant_id: str | None = None
|
||||
metadata: dict[str, Any] = Field(default_factory=dict)
|
||||
created_at: str = ""
|
||||
updated_at: str = ""
|
||||
values: dict[str, Any] = Field(default_factory=dict)
|
||||
files: list[TransferFile] = Field(default_factory=list)
|
||||
skipped_files: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ExportRequest(BaseModel):
|
||||
thread_ids: list[str] = Field(..., min_length=1, max_length=BATCH_LIMIT)
|
||||
|
||||
|
||||
class ExportResponse(BaseModel):
|
||||
format: str = FORMAT
|
||||
version: int = FORMAT_VERSION
|
||||
threads: list[TransferThread] = Field(default_factory=list)
|
||||
skipped: list[SkippedThread] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ImportRequest(BaseModel):
|
||||
threads: list[TransferThread] = Field(..., min_length=1, max_length=BATCH_LIMIT)
|
||||
|
||||
|
||||
class ImportResponse(BaseModel):
|
||||
imported: int = 0
|
||||
skipped: list[SkippedThread] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ExportAllStartResponse(BaseModel):
|
||||
job_id: str
|
||||
|
||||
|
||||
class ExportAllStatusResponse(BaseModel):
|
||||
job_id: str
|
||||
status: str
|
||||
total: int = 0
|
||||
processed: int = 0
|
||||
succeeded: int = 0
|
||||
skipped: list[SkippedThread] = Field(default_factory=list)
|
||||
skipped_files: int = 0
|
||||
error: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportAllJob:
|
||||
job_id: str
|
||||
user_id: str
|
||||
status: str = "running"
|
||||
total: int = 0
|
||||
processed: int = 0
|
||||
succeeded: int = 0
|
||||
skipped: list[SkippedThread] = field(default_factory=list)
|
||||
skipped_files: int = 0
|
||||
error: str | None = None
|
||||
path: Path | None = None
|
||||
task: asyncio.Task[None] | None = None
|
||||
|
||||
|
||||
_EXPORT_JOBS: dict[str, ExportAllJob] = {}
|
||||
_SAFE_USER_DIR = re.compile(r"[^A-Za-z0-9._-]+")
|
||||
|
||||
|
||||
def require_transfer_enabled() -> None:
|
||||
if not load_system_settings().agent_skill_migration.enabled:
|
||||
raise HTTPException(status_code=403, detail="跨服务器迁移功能未开启")
|
||||
|
||||
|
||||
def current_user_id(request: Request) -> str:
|
||||
user = getattr(request.state, "user", None)
|
||||
if user is not None and getattr(user, "id", None):
|
||||
return str(user.id)
|
||||
auth = getattr(request.state, "auth", None)
|
||||
auth_user = getattr(auth, "user", None) if auth is not None else None
|
||||
if auth_user is not None and getattr(auth_user, "id", None):
|
||||
return str(auth_user.id)
|
||||
return get_effective_user_id()
|
||||
|
||||
|
||||
def payload_size(value: Any) -> int:
|
||||
return len(json.dumps(value, ensure_ascii=False, default=str).encode("utf-8"))
|
||||
|
||||
|
||||
def clean_export_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
|
||||
return {
|
||||
key: item
|
||||
for key, item in _strip_reserved_metadata(metadata).items()
|
||||
if key not in _DROP_META_KEYS
|
||||
}
|
||||
|
||||
|
||||
def safe_relpath(root: Path, path: Path) -> str | None:
|
||||
try:
|
||||
resolved = path.resolve()
|
||||
relative = resolved.relative_to(root.resolve())
|
||||
except ValueError:
|
||||
return None
|
||||
text = relative.as_posix()
|
||||
if not SAFE_REL_PATH.fullmatch(text):
|
||||
return None
|
||||
return text
|
||||
|
||||
|
||||
def encoded_file_cost(size: int, path: str) -> int:
|
||||
return (size * 4 + 3) // 3 + len(path) + _FILE_JSON_OVERHEAD
|
||||
|
||||
|
||||
def list_thread_file_candidates(root: Path) -> list[tuple[int, str, Path]]:
|
||||
if not root.is_dir():
|
||||
return []
|
||||
candidates: list[tuple[int, str, Path]] = []
|
||||
for path in sorted(root.rglob("*")):
|
||||
if not path.is_file() or path.is_symlink():
|
||||
continue
|
||||
rel = safe_relpath(root, path)
|
||||
if rel is None:
|
||||
continue
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
except OSError:
|
||||
continue
|
||||
if size < 0:
|
||||
continue
|
||||
candidates.append((size, rel, path))
|
||||
candidates.sort(key=lambda item: (item[0], item[1]))
|
||||
return candidates
|
||||
|
||||
|
||||
def collect_thread_files(root: Path, *, budget: int) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
candidates = list_thread_file_candidates(root)
|
||||
if not candidates:
|
||||
return [], []
|
||||
files: list[dict[str, Any]] = []
|
||||
skipped: list[str] = []
|
||||
used = 0
|
||||
for size, rel, path in candidates:
|
||||
cost = encoded_file_cost(size, rel)
|
||||
if budget <= 0 or len(files) >= MAX_FILES_PER_THREAD or used + cost > budget:
|
||||
skipped.append(rel)
|
||||
continue
|
||||
try:
|
||||
data = path.read_bytes()
|
||||
except OSError:
|
||||
skipped.append(rel)
|
||||
continue
|
||||
files.append(
|
||||
{
|
||||
"path": rel,
|
||||
"content_b64": base64.b64encode(data).decode("ascii"),
|
||||
"size": size,
|
||||
}
|
||||
)
|
||||
used += cost
|
||||
return files, skipped
|
||||
|
||||
|
||||
def write_thread_files(
|
||||
root: Path,
|
||||
files: list[TransferFile],
|
||||
*,
|
||||
budget: int = MAX_THREAD_BYTES,
|
||||
) -> list[str]:
|
||||
failed: list[str] = []
|
||||
used = 0
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
root_resolved = root.resolve()
|
||||
for item in files[:MAX_FILES_PER_THREAD]:
|
||||
rel = safe_relpath(root, root / item.path) if SAFE_REL_PATH.fullmatch(item.path) else None
|
||||
if rel is None:
|
||||
failed.append(item.path)
|
||||
continue
|
||||
dest = (root / rel).resolve()
|
||||
if dest != root_resolved and root_resolved not in dest.parents:
|
||||
failed.append(item.path)
|
||||
continue
|
||||
try:
|
||||
data = base64.b64decode(item.content_b64, validate=True)
|
||||
if used + len(data) > budget:
|
||||
failed.append(item.path)
|
||||
continue
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(data)
|
||||
used += len(data)
|
||||
except Exception:
|
||||
failed.append(item.path)
|
||||
return failed
|
||||
|
||||
|
||||
def _title_of(record: dict[str, Any], values: dict[str, Any] | None = None) -> str:
|
||||
title = record.get("display_name") or (values or {}).get("title") or ""
|
||||
return str(title).strip()
|
||||
|
||||
|
||||
def bump_channel_versions(checkpointer: Any, checkpoint: dict[str, Any], keys: list[str]) -> dict[str, Any]:
|
||||
"""LangGraph stores each channel as a versioned blob.
|
||||
|
||||
``aput(..., new_versions={})`` only keeps the in-memory dict on some
|
||||
savers. Postgres/SQLite ignore unversioned channels, so imported
|
||||
messages would not survive ``aget`` / ``GET /threads/{id}/state``.
|
||||
"""
|
||||
versions = dict(checkpoint.get("channel_versions") or {})
|
||||
new_versions: dict[str, Any] = {}
|
||||
get_next_version = getattr(checkpointer, "get_next_version", None)
|
||||
if not callable(get_next_version):
|
||||
return dict(versions)
|
||||
for key in keys:
|
||||
next_version = get_next_version(versions.get(key), None)
|
||||
versions[key] = next_version
|
||||
new_versions[key] = next_version
|
||||
checkpoint["channel_versions"] = versions
|
||||
return new_versions
|
||||
|
||||
|
||||
async def write_imported_checkpoint(
|
||||
checkpointer: Any,
|
||||
*,
|
||||
thread_id: str,
|
||||
values: dict[str, Any],
|
||||
metadata: dict[str, Any],
|
||||
) -> None:
|
||||
config = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
||||
now = now_iso()
|
||||
checkpoint = dict(empty_checkpoint())
|
||||
checkpoint["channel_values"] = dict(values)
|
||||
new_versions = bump_channel_versions(checkpointer, checkpoint, list(values.keys()))
|
||||
await checkpointer.aput(
|
||||
config,
|
||||
checkpoint,
|
||||
{
|
||||
"step": 1,
|
||||
"source": "update",
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
**metadata,
|
||||
},
|
||||
new_versions,
|
||||
)
|
||||
written = await checkpointer.aget_tuple(config)
|
||||
if written is None:
|
||||
raise RuntimeError("missing checkpoint after import")
|
||||
restored = serialize_channel_values(
|
||||
(getattr(written, "checkpoint", {}) or {}).get("channel_values", {}) or {}
|
||||
)
|
||||
if values.get("messages") and not restored.get("messages"):
|
||||
raise RuntimeError("checkpoint messages were not persisted")
|
||||
|
||||
|
||||
def export_job_dir(user_id: str) -> Path:
|
||||
safe = _SAFE_USER_DIR.sub("_", user_id).strip("._") or "user"
|
||||
path = get_paths().base_dir / "chat-history-exports" / safe
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def get_export_job(job_id: str, user_id: str) -> ExportAllJob:
|
||||
job = _EXPORT_JOBS.get(job_id)
|
||||
if job is None or job.user_id != user_id:
|
||||
raise HTTPException(status_code=404, detail="导出任务不存在")
|
||||
return job
|
||||
|
||||
|
||||
def find_running_export_job(user_id: str) -> ExportAllJob | None:
|
||||
for job in _EXPORT_JOBS.values():
|
||||
if job.user_id == user_id and job.status == "running":
|
||||
return job
|
||||
return None
|
||||
|
||||
|
||||
def purge_finished_export_jobs(user_id: str) -> None:
|
||||
stale = [
|
||||
job_id
|
||||
for job_id, job in _EXPORT_JOBS.items()
|
||||
if job.user_id == user_id and job.status != "running"
|
||||
]
|
||||
for job_id in stale:
|
||||
job = _EXPORT_JOBS.pop(job_id, None)
|
||||
if job is None or job.path is None:
|
||||
continue
|
||||
try:
|
||||
job.path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
logger.debug("Failed to remove export file %s", job.path)
|
||||
|
||||
|
||||
def job_status(job: ExportAllJob) -> ExportAllStatusResponse:
|
||||
return ExportAllStatusResponse(
|
||||
job_id=job.job_id,
|
||||
status=job.status,
|
||||
total=job.total,
|
||||
processed=job.processed,
|
||||
succeeded=job.succeeded,
|
||||
skipped=list(job.skipped),
|
||||
skipped_files=job.skipped_files,
|
||||
error=job.error,
|
||||
)
|
||||
|
||||
|
||||
class BundleWriter:
|
||||
def __init__(self, path: Path) -> None:
|
||||
self.path = path
|
||||
self._fh = path.open("w", encoding="utf-8")
|
||||
self._first = True
|
||||
self._fh.write(
|
||||
'{"format":%s,"version":%s,"exported_at":%s,"threads":['
|
||||
% (
|
||||
json.dumps(FORMAT, ensure_ascii=False),
|
||||
FORMAT_VERSION,
|
||||
json.dumps(now_iso()),
|
||||
)
|
||||
)
|
||||
|
||||
def add_thread(self, thread: TransferThread) -> None:
|
||||
if not self._first:
|
||||
self._fh.write(",")
|
||||
self._first = False
|
||||
self._fh.write(thread.model_dump_json())
|
||||
self._fh.flush()
|
||||
|
||||
def finish(self, skipped: list[SkippedThread]) -> None:
|
||||
self._fh.write('],"skipped":')
|
||||
self._fh.write(json.dumps([item.model_dump() for item in skipped], ensure_ascii=False))
|
||||
self._fh.write("}")
|
||||
self._fh.close()
|
||||
|
||||
def abort(self) -> None:
|
||||
try:
|
||||
self._fh.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
async def list_exportable_thread_ids(thread_store: Any, user_id: str) -> list[str]:
|
||||
ids: list[str] = []
|
||||
offset = 0
|
||||
page_size = 100
|
||||
while True:
|
||||
rows = await thread_store.search(
|
||||
user_id=user_id,
|
||||
exclude_system=True,
|
||||
limit=page_size,
|
||||
offset=offset,
|
||||
)
|
||||
ids.extend(str(row["thread_id"]) for row in rows if row.get("thread_id"))
|
||||
if len(rows) < page_size:
|
||||
break
|
||||
offset += len(rows)
|
||||
return ids
|
||||
|
||||
|
||||
async def run_export_all_job(
|
||||
job: ExportAllJob,
|
||||
*,
|
||||
thread_store: Any,
|
||||
checkpointer: Any,
|
||||
) -> None:
|
||||
writer: BundleWriter | None = None
|
||||
try:
|
||||
thread_ids = await list_exportable_thread_ids(thread_store, job.user_id)
|
||||
job.total = len(thread_ids)
|
||||
if not thread_ids:
|
||||
job.status = "done"
|
||||
return
|
||||
dest = export_job_dir(job.user_id) / f"{job.job_id}.json"
|
||||
writer = BundleWriter(dest)
|
||||
for thread_id in thread_ids:
|
||||
try:
|
||||
payload, skip = await export_one_thread(
|
||||
thread_id=thread_id,
|
||||
user_id=job.user_id,
|
||||
thread_store=thread_store,
|
||||
checkpointer=checkpointer,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Unexpected export failure for %s", sanitize_log_param(thread_id))
|
||||
payload, skip = None, SkippedThread(thread_id=thread_id, reason="export_failed")
|
||||
if payload is not None:
|
||||
await asyncio.to_thread(writer.add_thread, payload)
|
||||
job.succeeded += 1
|
||||
job.skipped_files += len(payload.skipped_files)
|
||||
if skip is not None:
|
||||
job.skipped.append(skip)
|
||||
job.processed += 1
|
||||
await asyncio.to_thread(writer.finish, list(job.skipped))
|
||||
job.path = dest
|
||||
job.status = "done"
|
||||
except Exception:
|
||||
logger.exception("Background chat-history export failed for %s", sanitize_log_param(job.user_id))
|
||||
if writer is not None:
|
||||
writer.abort()
|
||||
job.status = "error"
|
||||
job.error = "导出失败"
|
||||
|
||||
|
||||
async def export_one_thread(
|
||||
*,
|
||||
thread_id: str,
|
||||
user_id: str,
|
||||
thread_store: Any,
|
||||
checkpointer: Any,
|
||||
max_bytes: int = MAX_THREAD_BYTES,
|
||||
) -> tuple[TransferThread | None, SkippedThread | None]:
|
||||
record = await thread_store.get(thread_id, user_id=user_id)
|
||||
if record is None:
|
||||
return None, SkippedThread(thread_id=thread_id, reason="not_found")
|
||||
if is_excluded_system_thread(record.get("metadata")):
|
||||
return None, SkippedThread(
|
||||
thread_id=thread_id,
|
||||
title=_title_of(record),
|
||||
reason="system_thread",
|
||||
)
|
||||
|
||||
try:
|
||||
checkpoint_tuple = await checkpointer.aget_tuple(
|
||||
{"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to read checkpoint for export %s", sanitize_log_param(thread_id))
|
||||
return None, SkippedThread(thread_id=thread_id, title=_title_of(record), reason="export_failed")
|
||||
|
||||
values: dict[str, Any] = {}
|
||||
if checkpoint_tuple is not None:
|
||||
checkpoint = getattr(checkpoint_tuple, "checkpoint", {}) or {}
|
||||
try:
|
||||
values = serialize_channel_values(checkpoint.get("channel_values", {}) or {})
|
||||
except Exception:
|
||||
logger.exception("Failed to serialize state for export %s", sanitize_log_param(thread_id))
|
||||
return None, SkippedThread(thread_id=thread_id, title=_title_of(record), reason="export_failed")
|
||||
|
||||
title = _title_of(record, values)
|
||||
if title and not values.get("title"):
|
||||
values["title"] = title
|
||||
|
||||
used = payload_size(values)
|
||||
if used > max_bytes:
|
||||
return None, SkippedThread(thread_id=thread_id, title=title, reason="too_large")
|
||||
|
||||
user_data = get_paths().sandbox_user_data_dir(thread_id, user_id=user_id)
|
||||
files, skipped_files = await asyncio.to_thread(
|
||||
collect_thread_files, user_data, budget=max_bytes - used
|
||||
)
|
||||
payload = TransferThread(
|
||||
thread_id=thread_id,
|
||||
title=title,
|
||||
assistant_id=record.get("assistant_id"),
|
||||
metadata=clean_export_metadata(record.get("metadata") or {}),
|
||||
created_at=coerce_iso(record.get("created_at", "")),
|
||||
updated_at=coerce_iso(record.get("updated_at", "")),
|
||||
values=values,
|
||||
files=[TransferFile.model_validate(item) for item in files],
|
||||
skipped_files=list(skipped_files),
|
||||
)
|
||||
while payload.files and payload_size(payload.model_dump()) > max_bytes:
|
||||
largest = max(payload.files, key=lambda item: (item.size, item.path))
|
||||
payload.files.remove(largest)
|
||||
payload.skipped_files.append(largest.path)
|
||||
if payload_size(payload.model_dump()) > max_bytes:
|
||||
return None, SkippedThread(thread_id=thread_id, title=title, reason="too_large")
|
||||
return payload, None
|
||||
|
||||
|
||||
async def import_one_thread(
|
||||
*,
|
||||
item: TransferThread,
|
||||
user_id: str,
|
||||
thread_store: Any,
|
||||
checkpointer: Any,
|
||||
) -> SkippedThread | None:
|
||||
thread_id = item.thread_id.strip()
|
||||
if not thread_id or not re.fullmatch(r"[A-Za-z0-9_-]+", thread_id):
|
||||
return SkippedThread(thread_id=item.thread_id or "unknown", title=item.title, reason="invalid_id")
|
||||
|
||||
existing = await thread_store.get(thread_id, user_id=user_id)
|
||||
if existing is not None:
|
||||
return SkippedThread(thread_id=thread_id, title=item.title or _title_of(existing), reason="exists")
|
||||
|
||||
metadata = clean_export_metadata(item.metadata)
|
||||
title = (item.title or str(item.values.get("title") or "")).strip()
|
||||
values = dict(item.values or {})
|
||||
if title:
|
||||
values["title"] = title
|
||||
|
||||
created = False
|
||||
try:
|
||||
await thread_store.create(
|
||||
thread_id,
|
||||
assistant_id=item.assistant_id,
|
||||
user_id=user_id,
|
||||
display_name=title or None,
|
||||
metadata=metadata,
|
||||
)
|
||||
created = True
|
||||
await write_imported_checkpoint(
|
||||
checkpointer,
|
||||
thread_id=thread_id,
|
||||
values=values,
|
||||
metadata=metadata,
|
||||
)
|
||||
if title:
|
||||
try:
|
||||
await thread_store.update_display_name(thread_id, title, user_id=user_id)
|
||||
except Exception:
|
||||
logger.debug("Failed to sync imported title for %s", sanitize_log_param(thread_id))
|
||||
if item.files:
|
||||
dest = get_paths().sandbox_user_data_dir(thread_id, user_id=user_id)
|
||||
failed_files = await asyncio.to_thread(write_thread_files, dest, item.files)
|
||||
if failed_files:
|
||||
logger.warning(
|
||||
"Imported thread %s with %d skipped files",
|
||||
sanitize_log_param(thread_id),
|
||||
len(failed_files),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to import thread %s", sanitize_log_param(thread_id))
|
||||
if created:
|
||||
try:
|
||||
await thread_store.delete(thread_id, user_id=user_id)
|
||||
except Exception:
|
||||
logger.debug("Failed to roll back imported thread %s", sanitize_log_param(thread_id))
|
||||
return SkippedThread(thread_id=thread_id, title=title, reason="import_failed")
|
||||
return None
|
||||
|
||||
|
||||
@router.post("/export", response_model=ExportResponse, summary="Export a batch of conversations")
|
||||
@require_permission("threads", "read")
|
||||
async def export_chat_history(body: ExportRequest, request: Request) -> ExportResponse:
|
||||
require_transfer_enabled()
|
||||
user_id = current_user_id(request)
|
||||
thread_store = get_thread_store(request)
|
||||
checkpointer = get_checkpointer(request)
|
||||
exported: list[TransferThread] = []
|
||||
skipped: list[SkippedThread] = []
|
||||
for thread_id in body.thread_ids:
|
||||
try:
|
||||
payload, skip = await export_one_thread(
|
||||
thread_id=thread_id,
|
||||
user_id=user_id,
|
||||
thread_store=thread_store,
|
||||
checkpointer=checkpointer,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Unexpected export failure for %s", sanitize_log_param(thread_id))
|
||||
skipped.append(SkippedThread(thread_id=thread_id, reason="export_failed"))
|
||||
continue
|
||||
if payload is not None:
|
||||
exported.append(payload)
|
||||
if skip is not None:
|
||||
skipped.append(skip)
|
||||
return ExportResponse(threads=exported, skipped=skipped)
|
||||
|
||||
|
||||
@router.post("/import", response_model=ImportResponse, summary="Import a batch of conversations")
|
||||
@require_permission("threads", "write")
|
||||
async def import_chat_history(body: ImportRequest, request: Request) -> ImportResponse:
|
||||
require_transfer_enabled()
|
||||
user_id = current_user_id(request)
|
||||
thread_store = get_thread_store(request)
|
||||
checkpointer = get_checkpointer(request)
|
||||
imported = 0
|
||||
skipped: list[SkippedThread] = []
|
||||
for item in body.threads:
|
||||
try:
|
||||
skip = await import_one_thread(
|
||||
item=item,
|
||||
user_id=user_id,
|
||||
thread_store=thread_store,
|
||||
checkpointer=checkpointer,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Unexpected import failure for %s", sanitize_log_param(item.thread_id))
|
||||
skipped.append(SkippedThread(thread_id=item.thread_id, title=item.title, reason="import_failed"))
|
||||
continue
|
||||
if skip is None:
|
||||
imported += 1
|
||||
else:
|
||||
skipped.append(skip)
|
||||
return ImportResponse(imported=imported, skipped=skipped)
|
||||
|
||||
|
||||
@router.post("/export-all", response_model=ExportAllStartResponse, summary="Start a backend export of all conversations")
|
||||
@require_permission("threads", "read")
|
||||
async def start_export_all(request: Request) -> ExportAllStartResponse:
|
||||
require_transfer_enabled()
|
||||
user_id = current_user_id(request)
|
||||
running = find_running_export_job(user_id)
|
||||
if running is not None:
|
||||
return ExportAllStartResponse(job_id=running.job_id)
|
||||
purge_finished_export_jobs(user_id)
|
||||
job = ExportAllJob(job_id=uuid.uuid4().hex, user_id=user_id)
|
||||
_EXPORT_JOBS[job.job_id] = job
|
||||
job.task = asyncio.create_task(
|
||||
run_export_all_job(
|
||||
job,
|
||||
thread_store=get_thread_store(request),
|
||||
checkpointer=get_checkpointer(request),
|
||||
)
|
||||
)
|
||||
return ExportAllStartResponse(job_id=job.job_id)
|
||||
|
||||
|
||||
@router.get("/export-all/{job_id}", response_model=ExportAllStatusResponse, summary="Poll a backend export job")
|
||||
@require_permission("threads", "read")
|
||||
async def get_export_all_status(job_id: str, request: Request) -> ExportAllStatusResponse:
|
||||
require_transfer_enabled()
|
||||
return job_status(get_export_job(job_id, current_user_id(request)))
|
||||
|
||||
|
||||
@router.get("/export-all/{job_id}/download", summary="Download a finished backend export")
|
||||
@require_permission("threads", "read")
|
||||
async def download_export_all(job_id: str, request: Request) -> FileResponse:
|
||||
require_transfer_enabled()
|
||||
job = get_export_job(job_id, current_user_id(request))
|
||||
if job.status != "done" or job.path is None or not job.path.is_file():
|
||||
raise HTTPException(status_code=409, detail="导出文件还没准备好")
|
||||
return FileResponse(
|
||||
job.path,
|
||||
media_type="application/json",
|
||||
filename="deerflow-chats.json",
|
||||
)
|
||||
@@ -10,6 +10,7 @@ from pathlib import Path
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi.responses import FileResponse, Response
|
||||
|
||||
from deerflow.config.system_settings import generated_page_logo_path, load_system_settings
|
||||
from deerflow.html_runtime.addresses import html_map_tile_url, html_runtime_base_url
|
||||
|
||||
router = APIRouter(prefix="/api/public/html-runtime", tags=["html-runtime"])
|
||||
@@ -28,6 +29,12 @@ _STATIC_ASSETS = {
|
||||
"g6.min.js": "application/javascript",
|
||||
"leaflet.js": "application/javascript",
|
||||
"leaflet.css": "text/css",
|
||||
# 生成页品牌页头背景设计图(浅色红调 / 深色深蓝),随明暗 tone 由页头样式切换。
|
||||
"topbar-light.svg": "image/svg+xml",
|
||||
"topbar-dark.svg": "image/svg+xml",
|
||||
# Packaged fallback used when an administrator-uploaded generated-page
|
||||
# logo cannot be fetched through a deployment's reverse-proxy path.
|
||||
"brand-logo-dark.png": "image/png",
|
||||
}
|
||||
_GEO_MAP_ASSETS = {
|
||||
"china-provinces.geojson": "application/geo+json",
|
||||
@@ -94,6 +101,26 @@ async def get_html_runtime_geo_map(filename: str) -> FileResponse:
|
||||
)
|
||||
|
||||
|
||||
@router.get("/generated-page-logo")
|
||||
async def get_generated_page_logo() -> FileResponse:
|
||||
"""Serve the configured logo, falling back to the packaged default."""
|
||||
|
||||
branding = load_system_settings().generated_page_branding
|
||||
path = generated_page_logo_path(branding)
|
||||
if path is None:
|
||||
path = _RUNTIME_DIR / "brand-logo-dark.png"
|
||||
media_type = "image/png"
|
||||
else:
|
||||
media_type = branding.logo_media_type or "application/octet-stream"
|
||||
if not path.is_file():
|
||||
raise HTTPException(status_code=503, detail="Generated-page fallback logo is not installed")
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=media_type,
|
||||
headers={**_PUBLIC_HEADERS, "Cache-Control": "public, max-age=3600"},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{filename}")
|
||||
async def get_html_runtime_asset(filename: str) -> FileResponse:
|
||||
"""Serve a whitelisted, vendored browser distribution file."""
|
||||
|
||||
@@ -76,6 +76,17 @@ class LightAppResponse(BaseModel):
|
||||
|
||||
class LightAppListResponse(BaseModel):
|
||||
apps: list[LightAppResponse]
|
||||
|
||||
|
||||
class LightAppSidebarItem(BaseModel):
|
||||
app_id: str
|
||||
name: str
|
||||
mount_location: str | None = None
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class LightAppSidebarResponse(BaseModel):
|
||||
apps: list[LightAppSidebarItem]
|
||||
|
||||
|
||||
class LightAppSidebarItem(BaseModel):
|
||||
@@ -209,6 +220,13 @@ async def list_sidebar_light_apps(request: Request) -> LightAppSidebarResponse:
|
||||
return await cached_catalog(request, "light_apps", "sidebar", load, LightAppSidebarResponse)
|
||||
|
||||
|
||||
@router.get("/sidebar", response_model=LightAppSidebarResponse)
|
||||
async def list_sidebar_light_apps(request: Request) -> LightAppSidebarResponse:
|
||||
"""Return the small set of fields required to build the shared sidebar."""
|
||||
rows = await _get_store(request).list_sidebar_apps()
|
||||
return LightAppSidebarResponse(apps=[LightAppSidebarItem(**row) for row in rows])
|
||||
|
||||
|
||||
@router.post("", response_model=LightAppResponse)
|
||||
async def create_light_app(request: Request, body: LightAppCreateRequest) -> LightAppResponse:
|
||||
await _require_admin(request)
|
||||
|
||||
@@ -93,6 +93,14 @@ _STEP3_AGENT_IDS = frozenset({
|
||||
SUMMARY_AGENT_ID,
|
||||
})
|
||||
|
||||
_STEP3_AGENT_IDS = frozenset({
|
||||
ACTION_PLAN_AGENT_ID,
|
||||
DASHBOARD_AGENT_ID,
|
||||
REPORT_AGENT_ID,
|
||||
STRUCTURE_AGENT_ID,
|
||||
SUMMARY_AGENT_ID,
|
||||
})
|
||||
|
||||
|
||||
def _stage_for_agent(agent_type: str, agent_name: str) -> str:
|
||||
"""把一次 /run/stream 的 (agent_type, agent_name) 映射成诊断日志的 stage。
|
||||
@@ -131,12 +139,45 @@ def _is_step2_room_limited(
|
||||
return agent_type == "leader" or agent_name not in _STEP3_AGENT_IDS
|
||||
|
||||
|
||||
|
||||
# 圆桌(intent / recommend / 席位 / 协调)创建的 thread 都是功能型内部线程,
|
||||
# 不是用户的普通对话。打上这个 metadata,前端「最近的对话」列表(recent-chat-list.tsx)
|
||||
# 据 `metadata.thread_type` 过滤掉,与 scheduler / bootstrap 系统会话同一套机制。
|
||||
_ROUNDTABLE_THREAD_METADATA: dict[str, Any] = {"thread_type": "roundtable", "system": True}
|
||||
|
||||
|
||||
def _room_thread_metadata(
|
||||
*,
|
||||
draft_id: str | None,
|
||||
user_id: str | None,
|
||||
task_id: str | None,
|
||||
room_session_id: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""Step-2 threads carry a stable room key so later occupancy can see live runs."""
|
||||
from deerflow.persistence.roundtable_jobs.sql import compute_active_dedupe_key
|
||||
from deerflow.persistence.roundtable_rooms.sql import compute_room_session_key
|
||||
|
||||
meta = dict(_ROUNDTABLE_THREAD_METADATA)
|
||||
clean_session_id = (room_session_id or "").strip() or None
|
||||
key = compute_room_session_key(clean_session_id) or compute_active_dedupe_key(
|
||||
draft_id, user_id, task_id
|
||||
)
|
||||
if key:
|
||||
meta["roundtable_room_key"] = key
|
||||
if clean_session_id:
|
||||
meta["roundtable_room_session_id"] = clean_session_id
|
||||
if draft_id:
|
||||
meta["draft_id"] = draft_id
|
||||
if task_id:
|
||||
meta["task_id"] = task_id
|
||||
return meta
|
||||
|
||||
|
||||
def _step3_thread_metadata() -> dict[str, Any]:
|
||||
"""Step-3 threads are internal threads, but never Step-2 room occupants."""
|
||||
return dict(_ROUNDTABLE_THREAD_METADATA)
|
||||
|
||||
|
||||
def _room_thread_metadata(
|
||||
*,
|
||||
draft_id: str | None,
|
||||
@@ -905,6 +946,26 @@ async def init_multi_agent(request: Request, payload: dict = Body(...)) -> Strea
|
||||
room_session_id=room_session_id,
|
||||
)
|
||||
|
||||
# The browser already acquired the room before entering Step 2. Init only
|
||||
# renews that lease; it cannot create a second room or bypass admission.
|
||||
from app.gateway.roundtable_room_gate import enforce_existing_roundtable_room
|
||||
|
||||
room_draft_id = str(payload.get("draft_id") or "").strip() or None
|
||||
room_task_id = str(payload.get("task_id") or "").strip() or None
|
||||
room_session_id = str(payload.get("room_session_id") or "").strip() or None
|
||||
await enforce_existing_roundtable_room(
|
||||
request,
|
||||
draft_id=room_draft_id,
|
||||
task_id=room_task_id,
|
||||
room_session_id=room_session_id,
|
||||
)
|
||||
room_thread_meta = _room_thread_metadata(
|
||||
draft_id=room_draft_id,
|
||||
user_id=_resolve_user_id(request),
|
||||
task_id=room_task_id,
|
||||
room_session_id=room_session_id,
|
||||
)
|
||||
|
||||
def _frame(payload: dict[str, Any]) -> str:
|
||||
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
@@ -153,6 +153,16 @@ async def _refresh_catalog_snapshot(config: AppConfig) -> None:
|
||||
logger.exception("Skill catalog projection refresh failed after a mutation")
|
||||
|
||||
|
||||
async def _refresh_catalog_snapshot(config: AppConfig) -> None:
|
||||
"""Keep normalized MySQL skill rows current after a skill edit."""
|
||||
try:
|
||||
await refresh_skill_catalog_projection(config)
|
||||
except Exception:
|
||||
# A failed projection refresh must not turn a successful skill write
|
||||
# into an API failure. Startup or the next edit can recover it.
|
||||
logger.exception("Skill catalog projection refresh failed after a mutation")
|
||||
|
||||
|
||||
def _can_view_skill_source(
|
||||
category: SkillCategory,
|
||||
owner_user_id: str | None,
|
||||
@@ -513,6 +523,69 @@ _SKILL_DISPLAY_TABLE_LOCK = asyncio.Lock()
|
||||
_skill_display_table_engine: object | None = None
|
||||
|
||||
|
||||
def _skill_display_table_already_exists(exc: BaseException) -> bool:
|
||||
message = str(exc).lower()
|
||||
return any(
|
||||
token in message
|
||||
for token in (
|
||||
"already exists",
|
||||
"duplicate table",
|
||||
"42p07",
|
||||
"error 1050",
|
||||
"(1050",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _catalog_item_to_response(
|
||||
item: dict[str, Any],
|
||||
ownership: dict[str, Any] | None,
|
||||
*,
|
||||
adapter: dict[str, Any] | None,
|
||||
favorited: bool,
|
||||
) -> SkillResponse:
|
||||
"""Build a list response from the MySQL snapshot and MySQL metadata rows."""
|
||||
|
||||
try:
|
||||
category = SkillCategory(str(item.get("category") or SkillCategory.PUBLIC.value))
|
||||
except ValueError:
|
||||
category = SkillCategory.PUBLIC
|
||||
owner_user_id = ownership.get("owner_user_id") if ownership else None
|
||||
return SkillResponse(
|
||||
name=str(item.get("name") or ""),
|
||||
name_zh=ownership.get("name_zh") if ownership else None,
|
||||
description=str(item.get("description") or ""),
|
||||
license=item.get("license"),
|
||||
category=category,
|
||||
enabled=bool(item.get("enabled", True)),
|
||||
always_on=bool(ownership.get("always_on", item.get("always_on", False)) if ownership else item.get("always_on", False)),
|
||||
use_count=int(item.get("use_count") or 0),
|
||||
view_count=int(item.get("view_count") or 0),
|
||||
patch_count=int(item.get("patch_count") or 0),
|
||||
last_activity_at=item.get("last_activity_at"),
|
||||
created_at=item.get("created_at"),
|
||||
state=str(item.get("state") or "active"),
|
||||
pinned=bool(item.get("pinned")),
|
||||
featured=bool(item.get("featured")),
|
||||
source=str(item.get("source") or "upload"),
|
||||
owner_user_id=owner_user_id,
|
||||
published=bool(ownership.get("published", False)) if ownership else False,
|
||||
square_id=str(ownership.get("square_id") or "") if ownership else "",
|
||||
builtin=bool(ownership.get("builtin", owner_user_id is None)) if ownership else category != SkillCategory.CUSTOM,
|
||||
favorited=favorited,
|
||||
detail=(ownership.get("detail_preview") or ownership.get("detail")) if ownership else None,
|
||||
display=adapter.get("display") if adapter else None,
|
||||
displaySample=adapter.get("sample") if adapter else None,
|
||||
)
|
||||
|
||||
|
||||
# ``checkfirst=True`` is a check-then-create operation. The in-process lock
|
||||
# serializes concurrent requests in one worker; the duplicate-table fallback
|
||||
# covers two Gateway workers racing during first access.
|
||||
_SKILL_DISPLAY_TABLE_LOCK = asyncio.Lock()
|
||||
_skill_display_table_engine: object | None = None
|
||||
|
||||
|
||||
def _skill_display_table_already_exists(exc: BaseException) -> bool:
|
||||
message = str(exc).lower()
|
||||
return any(
|
||||
|
||||
@@ -8,19 +8,22 @@ from typing import Literal
|
||||
from urllib.parse import urlparse
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.auth.password import hash_password_async
|
||||
from app.gateway.deps import get_current_user_from_request, get_optional_user_from_request
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.config.runtime_paths import runtime_home
|
||||
from deerflow.config.system_settings import (
|
||||
BUILTIN_THEME_IDS,
|
||||
AgentSkillMigrationSettings,
|
||||
AppearanceRouteParam,
|
||||
AuthenticationSettings,
|
||||
CompactShortcutButton,
|
||||
ConversationContextSettings,
|
||||
CustomThemePreset,
|
||||
GeneratedPageBrandingSettings,
|
||||
HtmlMapSettings,
|
||||
LeaderboardSettings,
|
||||
ModelConcurrencySettings,
|
||||
@@ -36,6 +39,8 @@ from deerflow.config.system_settings import (
|
||||
StrategyProjectSettings,
|
||||
WordHeadingNumberingStyle,
|
||||
WriteFileCompatibilitySettings,
|
||||
generated_page_logo_path,
|
||||
generated_page_logo_public_url,
|
||||
get_module_tag_ids,
|
||||
list_publish_squares,
|
||||
load_system_settings,
|
||||
@@ -313,11 +318,15 @@ class HtmlMapSettingsUpdateRequest(BaseModel):
|
||||
class HtmlRuntimeSettingsResponse(BaseModel):
|
||||
base_url: str
|
||||
map_tile_url: str
|
||||
message_map_tile_min_zoom: int
|
||||
message_map_tile_max_zoom: int
|
||||
|
||||
|
||||
class HtmlRuntimeSettingsUpdateRequest(BaseModel):
|
||||
base_url: str
|
||||
map_tile_url: str
|
||||
message_map_tile_min_zoom: int | None = Field(default=None, ge=0, le=20)
|
||||
message_map_tile_max_zoom: int | None = Field(default=None, ge=0, le=20)
|
||||
|
||||
|
||||
class LeaderboardSettingsResponse(BaseModel):
|
||||
@@ -518,6 +527,17 @@ class MemoryRuntimeUpdateRequest(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
class AgentSkillMigrationResponse(BaseModel):
|
||||
enabled: bool = Field(
|
||||
default=False,
|
||||
description="Whether administrator agent/skill migration is enabled deployment-wide",
|
||||
)
|
||||
|
||||
|
||||
class AgentSkillMigrationUpdateRequest(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
class WriteFileCompatibilityResponse(BaseModel):
|
||||
enabled: bool = Field(
|
||||
default=False,
|
||||
@@ -617,6 +637,7 @@ def _knowledge_retrieval_settings_store(request: Request):
|
||||
return store
|
||||
|
||||
|
||||
|
||||
@router.get("/memory", response_model=MemoryRuntimeResponse)
|
||||
async def get_memory_runtime_setting() -> MemoryRuntimeResponse:
|
||||
return MemoryRuntimeResponse(enabled=load_system_settings().memory.enabled)
|
||||
@@ -635,6 +656,28 @@ async def update_memory_runtime_setting(
|
||||
return MemoryRuntimeResponse(enabled=saved.memory.enabled)
|
||||
|
||||
|
||||
@router.get("/agent-skill-migration", response_model=AgentSkillMigrationResponse)
|
||||
async def get_agent_skill_migration_setting() -> AgentSkillMigrationResponse:
|
||||
return AgentSkillMigrationResponse(
|
||||
enabled=load_system_settings().agent_skill_migration.enabled,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/agent-skill-migration", response_model=AgentSkillMigrationResponse)
|
||||
async def update_agent_skill_migration_setting(
|
||||
body: AgentSkillMigrationUpdateRequest,
|
||||
request: Request,
|
||||
) -> AgentSkillMigrationResponse:
|
||||
await _require_admin(request)
|
||||
current = load_system_settings()
|
||||
updated = AgentSkillMigrationSettings(enabled=body.enabled)
|
||||
saved = save_system_settings(
|
||||
current.model_copy(update={"agent_skill_migration": updated})
|
||||
)
|
||||
logger.info("Agent/skill migration switch changed: enabled=%s", saved.agent_skill_migration.enabled)
|
||||
return AgentSkillMigrationResponse(enabled=saved.agent_skill_migration.enabled)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/write-file-compatibility",
|
||||
response_model=WriteFileCompatibilityResponse,
|
||||
@@ -837,6 +880,7 @@ async def update_ordinary_knowledge_retrieval_setting(
|
||||
)
|
||||
|
||||
|
||||
|
||||
def _skill_compression_to_response(settings: SkillCompressionSettings) -> SkillCompressionResponse:
|
||||
return SkillCompressionResponse(
|
||||
enabled=settings.enabled,
|
||||
@@ -1073,10 +1117,13 @@ async def update_html_map_settings(
|
||||
|
||||
@router.get("/html-runtime", response_model=HtmlRuntimeSettingsResponse)
|
||||
async def get_html_runtime_settings() -> HtmlRuntimeSettingsResponse:
|
||||
"""Return the addresses newly generated HTML pages will use."""
|
||||
"""Return generated-page addresses and message-map native tile limits."""
|
||||
settings = load_system_settings().html_runtime
|
||||
return HtmlRuntimeSettingsResponse(
|
||||
base_url=html_runtime_base_url(),
|
||||
map_tile_url=html_map_tile_url(),
|
||||
message_map_tile_min_zoom=settings.message_map_tile_min_zoom,
|
||||
message_map_tile_max_zoom=settings.message_map_tile_max_zoom,
|
||||
)
|
||||
|
||||
|
||||
@@ -1085,7 +1132,7 @@ async def update_html_runtime_settings(
|
||||
body: HtmlRuntimeSettingsUpdateRequest,
|
||||
request: Request,
|
||||
) -> HtmlRuntimeSettingsResponse:
|
||||
"""Save the browser-reachable runtime and map-tile addresses. Admin only."""
|
||||
"""Save generated-page addresses and message-map native tile limits. Admin only."""
|
||||
await _require_admin(request)
|
||||
try:
|
||||
base_url = normalize_html_runtime_base_url(body.base_url)
|
||||
@@ -1093,13 +1140,32 @@ async def update_html_runtime_settings(
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
current = load_system_settings()
|
||||
min_zoom = (
|
||||
body.message_map_tile_min_zoom
|
||||
if body.message_map_tile_min_zoom is not None
|
||||
else current.html_runtime.message_map_tile_min_zoom
|
||||
)
|
||||
max_zoom = (
|
||||
body.message_map_tile_max_zoom
|
||||
if body.message_map_tile_max_zoom is not None
|
||||
else current.html_runtime.message_map_tile_max_zoom
|
||||
)
|
||||
if min_zoom > max_zoom:
|
||||
raise HTTPException(status_code=400, detail="消息列表瓦片最小层级不能大于最大层级")
|
||||
updated = current.html_runtime.model_copy(
|
||||
update={"base_url": base_url, "map_tile_url": map_tile_url}
|
||||
update={
|
||||
"base_url": base_url,
|
||||
"map_tile_url": map_tile_url,
|
||||
"message_map_tile_min_zoom": min_zoom,
|
||||
"message_map_tile_max_zoom": max_zoom,
|
||||
}
|
||||
)
|
||||
saved = save_system_settings(current.model_copy(update={"html_runtime": updated}))
|
||||
return HtmlRuntimeSettingsResponse(
|
||||
base_url=saved.html_runtime.base_url,
|
||||
map_tile_url=saved.html_runtime.map_tile_url,
|
||||
message_map_tile_min_zoom=saved.html_runtime.message_map_tile_min_zoom,
|
||||
message_map_tile_max_zoom=saved.html_runtime.message_map_tile_max_zoom,
|
||||
)
|
||||
|
||||
|
||||
@@ -1422,6 +1488,230 @@ async def update_appearance_settings(body: AppearanceUpdateRequest, request: Req
|
||||
return _appearance_response(saved.appearance)
|
||||
|
||||
|
||||
class GeneratedPageBrandingResponse(BaseModel):
|
||||
"""Generated-page identity: name, logo display mode and optional custom logo."""
|
||||
|
||||
chrome_enabled: bool = True
|
||||
header_layout: str = "center"
|
||||
system_name: str | None = None
|
||||
footer_text: str | None = None
|
||||
logo_mode: Literal["custom", "default", "none"] = "custom"
|
||||
logo_url: str | None = None
|
||||
logo_version: str | None = None
|
||||
customized: bool = False
|
||||
active: bool = False
|
||||
|
||||
|
||||
_MAX_BRAND_LOGO_BYTES = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def _detect_brand_logo(data: bytes) -> tuple[str, str]:
|
||||
"""Return a safe extension/media type from file signatures, never the filename."""
|
||||
|
||||
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return ".png", "image/png"
|
||||
if data.startswith(b"\xff\xd8\xff"):
|
||||
return ".jpg", "image/jpeg"
|
||||
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return ".webp", "image/webp"
|
||||
raise HTTPException(status_code=422, detail="Logo 仅支持 PNG、JPG 或 WebP 图片")
|
||||
|
||||
|
||||
def _normalize_system_name(value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = " ".join(value.split())
|
||||
if len(normalized) > 80:
|
||||
raise HTTPException(status_code=422, detail="系统名称不能超过 80 个字符")
|
||||
return normalized or None
|
||||
|
||||
|
||||
def _normalize_footer_text(value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = " ".join(value.split())
|
||||
if len(normalized) > 160:
|
||||
raise HTTPException(status_code=422, detail="网页页脚文字不能超过 160 个字符")
|
||||
return normalized or None
|
||||
|
||||
|
||||
def _generated_page_branding_response(
|
||||
settings: GeneratedPageBrandingSettings,
|
||||
) -> GeneratedPageBrandingResponse:
|
||||
defaults = GeneratedPageBrandingSettings()
|
||||
logo_url = generated_page_logo_public_url("/api/public/html-runtime", settings)
|
||||
return GeneratedPageBrandingResponse(
|
||||
chrome_enabled=settings.chrome_enabled,
|
||||
header_layout=settings.header_layout,
|
||||
system_name=settings.system_name,
|
||||
footer_text=settings.footer_text,
|
||||
logo_mode=settings.logo_mode,
|
||||
logo_url=logo_url,
|
||||
logo_version=settings.logo_version if logo_url else None,
|
||||
customized=bool(
|
||||
settings.system_name
|
||||
or settings.footer_text
|
||||
or logo_url
|
||||
or settings.logo_mode != defaults.logo_mode
|
||||
or settings.chrome_enabled != defaults.chrome_enabled
|
||||
or settings.header_layout != defaults.header_layout
|
||||
),
|
||||
active=bool(
|
||||
settings.system_name
|
||||
and settings.chrome_enabled
|
||||
and (settings.logo_mode == "none" or logo_url)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _write_generated_page_logo(data: bytes, suffix: str) -> str:
|
||||
directory = runtime_home() / "generated-page-branding"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"logo-{uuid4().hex}{suffix}"
|
||||
destination = directory / filename
|
||||
temporary = directory / f".{filename}.tmp"
|
||||
try:
|
||||
temporary.write_bytes(data)
|
||||
temporary.replace(destination)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return filename
|
||||
|
||||
|
||||
@router.get("/generated-page-branding", response_model=GeneratedPageBrandingResponse)
|
||||
async def get_generated_page_branding_settings() -> GeneratedPageBrandingResponse:
|
||||
"""Return the optional generated-page identity. Any logged-in user may read it."""
|
||||
|
||||
return _generated_page_branding_response(load_system_settings().generated_page_branding)
|
||||
|
||||
|
||||
@router.put("/generated-page-branding", response_model=GeneratedPageBrandingResponse)
|
||||
async def update_generated_page_branding_settings(
|
||||
request: Request,
|
||||
chrome_enabled: bool | None = Form(default=None),
|
||||
header_layout: str | None = Form(default=None),
|
||||
system_name: str | None = Form(default=None),
|
||||
logo_mode: Literal["custom", "default", "none"] | None = Form(default=None),
|
||||
# Plain str (not Optional): FastAPI coerces an empty Optional form value to
|
||||
# None, which would make "clear the footer text" indistinguishable from
|
||||
# "field omitted". The settings UI always sends this field, so an empty
|
||||
# value here means the admin cleared the input and wants the default footer.
|
||||
footer_text: str = Form(default=""),
|
||||
remove_logo: bool = Form(default=False),
|
||||
logo: UploadFile | None = File(default=None),
|
||||
) -> GeneratedPageBrandingResponse:
|
||||
"""Update the identity used in generated pages and the auto-injection switch. Admin only."""
|
||||
|
||||
await _require_admin(request)
|
||||
if logo is not None and (remove_logo or logo_mode in {"default", "none"}):
|
||||
raise HTTPException(status_code=422, detail="上传 Logo 时不能同时选择默认头像或不显示头像")
|
||||
if remove_logo and logo_mode not in {None, "none"}:
|
||||
raise HTTPException(status_code=422, detail="移除 Logo 时只能选择不显示头像")
|
||||
|
||||
current = load_system_settings()
|
||||
previous_logo = generated_page_logo_path(current.generated_page_branding)
|
||||
update: dict[str, object] = {}
|
||||
if chrome_enabled is not None:
|
||||
update["chrome_enabled"] = bool(chrome_enabled)
|
||||
if header_layout is not None:
|
||||
normalized_layout = str(header_layout).strip().lower()
|
||||
if normalized_layout not in {"left", "center"}:
|
||||
raise HTTPException(status_code=422, detail="header_layout 仅支持 left 或 center")
|
||||
update["header_layout"] = normalized_layout
|
||||
if system_name is not None:
|
||||
update["system_name"] = _normalize_system_name(system_name)
|
||||
update["footer_text"] = _normalize_footer_text(footer_text)
|
||||
|
||||
new_logo_path = None
|
||||
if logo is not None:
|
||||
data = await logo.read(_MAX_BRAND_LOGO_BYTES + 1)
|
||||
await logo.close()
|
||||
if not data:
|
||||
raise HTTPException(status_code=422, detail="Logo 文件不能为空")
|
||||
if len(data) > _MAX_BRAND_LOGO_BYTES:
|
||||
raise HTTPException(status_code=413, detail="Logo 文件不能超过 10MB")
|
||||
suffix, media_type = _detect_brand_logo(data)
|
||||
filename = await asyncio.to_thread(_write_generated_page_logo, data, suffix)
|
||||
new_logo_path = runtime_home() / "generated-page-branding" / filename
|
||||
update.update(
|
||||
{
|
||||
"logo_mode": "custom",
|
||||
"logo_filename": filename,
|
||||
"logo_media_type": media_type,
|
||||
"logo_version": uuid4().hex,
|
||||
}
|
||||
)
|
||||
elif logo_mode == "none":
|
||||
update.update(
|
||||
{
|
||||
"logo_mode": "none",
|
||||
"logo_filename": None,
|
||||
"logo_media_type": None,
|
||||
"logo_version": None,
|
||||
}
|
||||
)
|
||||
elif remove_logo:
|
||||
# Preserve the legacy API behavior: an older client that only sends
|
||||
# remove_logo leaves branding as an incomplete custom-logo draft.
|
||||
# The new text-only header is an explicit logo_mode="none" choice.
|
||||
update.update(
|
||||
{
|
||||
"logo_mode": "custom",
|
||||
"logo_filename": None,
|
||||
"logo_media_type": None,
|
||||
"logo_version": None,
|
||||
}
|
||||
)
|
||||
elif logo_mode == "default":
|
||||
update.update(
|
||||
{
|
||||
"logo_mode": "default",
|
||||
"logo_filename": None,
|
||||
"logo_media_type": None,
|
||||
"logo_version": "default",
|
||||
}
|
||||
)
|
||||
elif logo_mode == "custom":
|
||||
update["logo_mode"] = "custom"
|
||||
if current.generated_page_branding.logo_mode != "custom":
|
||||
update.update(
|
||||
{
|
||||
"logo_filename": None,
|
||||
"logo_media_type": None,
|
||||
"logo_version": None,
|
||||
}
|
||||
)
|
||||
|
||||
if not update:
|
||||
return _generated_page_branding_response(current.generated_page_branding)
|
||||
|
||||
updated = current.generated_page_branding.model_copy(update=update)
|
||||
try:
|
||||
saved = save_system_settings(current.model_copy(update={"generated_page_branding": updated}))
|
||||
except Exception:
|
||||
if new_logo_path is not None:
|
||||
await asyncio.to_thread(new_logo_path.unlink, missing_ok=True)
|
||||
raise
|
||||
if previous_logo is not None and previous_logo != generated_page_logo_path(saved.generated_page_branding):
|
||||
await asyncio.to_thread(previous_logo.unlink, missing_ok=True)
|
||||
return _generated_page_branding_response(saved.generated_page_branding)
|
||||
|
||||
|
||||
@router.delete("/generated-page-branding", response_model=GeneratedPageBrandingResponse)
|
||||
async def delete_generated_page_branding_settings(
|
||||
request: Request,
|
||||
) -> GeneratedPageBrandingResponse:
|
||||
"""Remove generated-page identity requirements; the app UI is unaffected."""
|
||||
|
||||
await _require_admin(request)
|
||||
current = load_system_settings()
|
||||
previous_logo = generated_page_logo_path(current.generated_page_branding)
|
||||
saved = save_system_settings(current.model_copy(update={"generated_page_branding": GeneratedPageBrandingSettings()}))
|
||||
if previous_logo is not None:
|
||||
await asyncio.to_thread(previous_logo.unlink, missing_ok=True)
|
||||
return _generated_page_branding_response(saved.generated_page_branding)
|
||||
|
||||
|
||||
class LogSystemResponse(BaseModel):
|
||||
"""External log-system entry shown in the admin settings menu.
|
||||
|
||||
@@ -1575,3 +1865,4 @@ async def update_wx_common_agents(
|
||||
updated = current.wx_common_agents.model_copy(update={"agent_type": agent_type})
|
||||
saved = save_system_settings(current.model_copy(update={"wx_common_agents": updated}))
|
||||
return WxCommonAgentsResponse(agent_type=saved.wx_common_agents.agent_type)
|
||||
|
||||
@@ -546,8 +546,8 @@ _CONTEXT_CONFIGURABLE_KEYS: frozenset[str] = frozenset(
|
||||
"subagent_enabled",
|
||||
"max_concurrent_subagents",
|
||||
"agent_name",
|
||||
# 页面研报设计师由前端随消息带入当前界面明暗模式;需要进入 agent
|
||||
# 提示词及 ToolRuntime.context,才能选择同色系模板。
|
||||
# 前端随消息只带入当前界面的明暗模式;需要进入 agent 提示词及
|
||||
# ToolRuntime.context,才能选择对应的浅色或深色页面模板。
|
||||
"presentation_theme",
|
||||
"is_bootstrap",
|
||||
"is_writing_setup",
|
||||
|
||||
@@ -526,17 +526,17 @@ auth_login:
|
||||
# 点击后在新标签页打开下面的 url。enabled 关掉则不显示该入口。
|
||||
|
||||
database:
|
||||
# 本地开发使用 SQLite;切回远程 MySQL 时改 backend: mysql 并配置 .env.local。
|
||||
# LangGraph 对话检查点仍由下方 checkpointer 保存到本机 SQLite。
|
||||
# 单节点本地部署:业务表与 LangGraph 检查点均使用 SQLite。
|
||||
backend: sqlite
|
||||
# mysql_url: $MYSQL_DATABASE_URL
|
||||
sqlite_dir: .deer-flow/data
|
||||
# mysql_url: $MYSQL_DATABASE_URL
|
||||
# 高斯/OpenGauss 业务库示例(启用前先执行 uv sync --extra gauss):
|
||||
# backend: gauss
|
||||
# gauss_url: $GAUSS_DATABASE_URL # opengauss+asyncpg://user:pass@host:26000/deerflow
|
||||
# checkpointer 请继续使用下方 sqlite;不要把 PostgreSQL 专用 checkpointer 迁移直接用于高斯。
|
||||
pool_size: 20 # 基础连接池(postgres/gauss/mysql 生效;sqlite 忽略)
|
||||
max_overflow: 20 # 高峰期可临时超出 pool_size 的额外连接数,真实上限 = pool_size + max_overflow
|
||||
# Dolphin(MySQL 协议)模式保持 backend: mysql,并由部署层设置 DEERFLOW_DATABASE_PRODUCT=gauss_mysql。
|
||||
pool_size: 5 # 本地测试降低连接池规模,减少资源占用
|
||||
max_overflow: 2 # 本地测试只允许少量突发连接
|
||||
pool_timeout: 30 # 池满时等待空闲连接的秒数,超时报错
|
||||
pool_recycle: 1800 # 连接回收周期(秒);防火墙/pgbouncer/MySQL wait_timeout 静默断连兜底。多 worker 部署:每 worker 上限 = pool_size + max_overflow,总数 × worker 数 < DB max_connections
|
||||
echo_sql: false
|
||||
@@ -544,6 +544,7 @@ database:
|
||||
checkpointer:
|
||||
type: sqlite
|
||||
connection_string: .deer-flow/data/deerflow.db
|
||||
use_postgres: false
|
||||
|
||||
# 记忆子系统参数。真正的问答总开关由管理员「设置 → 问答记忆」控制,
|
||||
# system_settings.json 没有显式开启时始终关闭;这里的 enabled 不会绕过管理员总开关。
|
||||
|
||||
+44
-9
@@ -20,6 +20,7 @@ from deerflow.agents.middlewares.markdown_file_deliverable_middleware import (
|
||||
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
|
||||
from deerflow.agents.middlewares.multi_page_html_middleware import MultiPageHtmlMiddleware
|
||||
from deerflow.agents.middlewares.prompt_prefix_middleware import PromptPrefixMiddleware
|
||||
from deerflow.agents.middlewares.recent_turns_middleware import RecentTurnsMiddleware
|
||||
from deerflow.agents.middlewares.rag_citation_middleware import RagCitationMiddleware
|
||||
from deerflow.agents.middlewares.recent_turns_middleware import RecentTurnsMiddleware
|
||||
from deerflow.agents.middlewares.setup_agent_approval_middleware import SetupAgentApprovalMiddleware
|
||||
@@ -48,6 +49,24 @@ from deerflow.tools.builtins.llmwiki_reasoning_tools import (
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def _build_presentation_theme_prompt(cfg: dict) -> str:
|
||||
"""Describe only the current light/dark mode to generated-page agents."""
|
||||
mode = str(cfg.get("presentation_theme") or "").strip().lower()
|
||||
if mode not in {"dark", "light"}:
|
||||
return ""
|
||||
|
||||
mode_label = "浅色" if mode == "light" else "深色"
|
||||
|
||||
return (
|
||||
"\n\n【当前界面主题】\n"
|
||||
f"当前系统界面为 `{mode_label} ({mode})` 模式。"
|
||||
f"若本轮生成 HTML 网页且用户没有明确指定页面主题,必须生成{mode_label}页面。"
|
||||
"用户明确指定的浅色、深色或其他配色优先。"
|
||||
"只跟随明暗模式,不得根据系统的红、蓝、绿等主题色或自定义主色改变网页配色;"
|
||||
"页面自身的强调色应根据内容、信息层级与可读性独立设计。"
|
||||
"不得仅因页面属于科技、数据、看板、驾驶舱或地图类型就擅自改成深色。"
|
||||
)
|
||||
|
||||
# 写作配置 Q&A:意图澄清最多几轮(一条用户消息 = 一轮),到顶强制提交配置卡。
|
||||
# 写作配置 Q&A 现在「先生成大纲并与用户多轮确认 → 再提交配置」,需要更多来回,故上限放宽。
|
||||
# 仍是兜底安全阀:到顶才用 tool_choice 强制提交,正常流程由用户确认大纲后自然提交。
|
||||
@@ -1223,15 +1242,9 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
|
||||
# applies to the WeKnora-style smart knowledge loop.
|
||||
system_prompt = _without_classic_citation_contracts(system_prompt)
|
||||
|
||||
# 前端可提供当前视觉明暗模式给页面生成类任务。把值放入系统提示而不是
|
||||
# 指望模型从 ToolRuntime.context 猜测,确保自定义 SOUL 也能稳定使用。
|
||||
presentation_theme = str(cfg.get("presentation_theme") or "").strip().lower()
|
||||
if presentation_theme in {"dark", "light"}:
|
||||
system_prompt += (
|
||||
"\n\n【当前界面主题】\n"
|
||||
f"当前页面呈现主题为 `{presentation_theme}`。若本轮生成汇报页面,请优先选择同色系 HTML 模板;"
|
||||
"除非用户明确要求覆盖该主题。"
|
||||
)
|
||||
# 前端提供当前系统主题。把值放入系统提示而不是指望模型从
|
||||
# ToolRuntime.context 猜测,确保普通问答与自定义 SOUL 都能稳定使用。
|
||||
system_prompt += _build_presentation_theme_prompt(cfg)
|
||||
|
||||
system_prompt = _append_orchestration_capability_boundary(system_prompt, agent_id)
|
||||
|
||||
@@ -1287,3 +1300,25 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
|
||||
system_prompt=system_prompt,
|
||||
state_schema=ThreadState,
|
||||
)
|
||||
|
||||
|
||||
def _create_context_reduction_middleware(
|
||||
*,
|
||||
app_config: AppConfig | None = None,
|
||||
summarization_requested: bool = False,
|
||||
) -> AgentMiddleware | None:
|
||||
"""Resolve the active context-reduction strategy for this model run.
|
||||
|
||||
The administrator-managed recent-turn window has priority over summary
|
||||
compression and is global once enabled. Its request-only trimming avoids
|
||||
the summarization LLM call while leaving checkpoint history untouched.
|
||||
With the setting off, the existing per-request/config summarization
|
||||
behavior is preserved exactly.
|
||||
"""
|
||||
context_settings = get_conversation_context_settings()
|
||||
if context_settings.recent_turn_window_enabled:
|
||||
return RecentTurnsMiddleware()
|
||||
return _create_summarization_middleware(
|
||||
app_config=app_config,
|
||||
force_enabled=summarization_requested,
|
||||
)
|
||||
+71
-45
@@ -617,44 +617,44 @@ task(description="Oracle Cloud analysis", prompt="...", subagent_type="general-p
|
||||
</subagent_system>"""
|
||||
|
||||
|
||||
_ORDINARY_QA_HEADING_RULES = {
|
||||
"hybrid_decimal": """- 一级章节使用 `## 一、标题`,二级章节使用 `### 1.1 标题`,三级章节使用 `#### 1.1.1 标题`。
|
||||
- 二级章节按 `1.1`、`1.2`、`2.1` 的形式编号,三级及更深层级继续使用完整多级阿拉伯数字。
|
||||
- 确需更深层级时,四级章节使用 `##### 1.1.1.1 标题`,五级章节使用 `###### 1.1.1.1.1 标题`。""",
|
||||
"official_chinese": """- 一级章节使用 `## 一、标题`,二级章节使用 `### (一) 标题`,三级章节使用 `#### 1. 标题`。
|
||||
- 确需更深层级时,四级章节使用 `##### (1) 标题`,五级章节使用 `###### 1) 标题`。""",
|
||||
"decimal": """- 一级章节使用 `## 1 标题`,二级章节使用 `### 1.1 标题`,三级章节使用 `#### 1.1.1 标题`。
|
||||
- 确需更深层级时,继续使用 `##### 1.1.1.1 标题`、`###### 1.1.1.1.1 标题`。""",
|
||||
"chapter_section": """- 一级章节使用 `## 第一章 标题`,二级章节使用 `### 第一节 标题`,三级章节使用 `#### 一、标题`。
|
||||
- 确需更深层级时,四级章节使用 `##### (一) 标题`,五级章节使用 `###### 1. 标题`。""",
|
||||
"none": """- 各级章节只写标题文字,不手写编号:`## 一级标题`、`### 二级标题`、`#### 三级标题`。
|
||||
- 确需更深层级时使用 `##### 四级标题`、`###### 五级标题`,仍不添加编号。""",
|
||||
}
|
||||
|
||||
|
||||
def _word_heading_numbering_style() -> str:
|
||||
"""Return the configured Word heading-numbering preset with a safe default."""
|
||||
try:
|
||||
return load_system_settings().prompt_prefix.word_heading_numbering_style
|
||||
except Exception:
|
||||
logger.debug("Failed to read the Word heading-numbering style; using default", exc_info=True)
|
||||
return "hybrid_decimal"
|
||||
|
||||
|
||||
def _build_ordinary_qa_markdown_format_section() -> str:
|
||||
rules = _ORDINARY_QA_HEADING_RULES.get(
|
||||
_word_heading_numbering_style(),
|
||||
_ORDINARY_QA_HEADING_RULES["hybrid_decimal"],
|
||||
)
|
||||
return f"""
|
||||
<ordinary_qa_markdown_format>
|
||||
当普通问答需要输出带章节结构的较长内容时,必须采用以下 Markdown 规范,以便下载为 Word 后得到正确的自动编号和公文标题格式:
|
||||
- 文档主标题使用 `# 主标题`;主标题只写标题文字,不添加章节编号。
|
||||
{rules}
|
||||
- 默认禁止使用以 `-`、`*`、`+` 或 `•` 开头的无序圆点列表;并列内容优先改写为完整自然段,确需逐项表达时使用有序列表。只有用户明确要求无序列表时才使用。
|
||||
- 简短问答不必为了套用格式而强行添加标题;本规范只约束实际使用的标题和列表。
|
||||
</ordinary_qa_markdown_format>
|
||||
"""
|
||||
_ORDINARY_QA_HEADING_RULES = {
|
||||
"hybrid_decimal": """- 一级章节使用 `## 一、标题`,二级章节使用 `### 1.1 标题`,三级章节使用 `#### 1.1.1 标题`。
|
||||
- 二级章节按 `1.1`、`1.2`、`2.1` 的形式编号,三级及更深层级继续使用完整多级阿拉伯数字。
|
||||
- 确需更深层级时,四级章节使用 `##### 1.1.1.1 标题`,五级章节使用 `###### 1.1.1.1.1 标题`。""",
|
||||
"official_chinese": """- 一级章节使用 `## 一、标题`,二级章节使用 `### (一) 标题`,三级章节使用 `#### 1. 标题`。
|
||||
- 确需更深层级时,四级章节使用 `##### (1) 标题`,五级章节使用 `###### 1) 标题`。""",
|
||||
"decimal": """- 一级章节使用 `## 1 标题`,二级章节使用 `### 1.1 标题`,三级章节使用 `#### 1.1.1 标题`。
|
||||
- 确需更深层级时,继续使用 `##### 1.1.1.1 标题`、`###### 1.1.1.1.1 标题`。""",
|
||||
"chapter_section": """- 一级章节使用 `## 第一章 标题`,二级章节使用 `### 第一节 标题`,三级章节使用 `#### 一、标题`。
|
||||
- 确需更深层级时,四级章节使用 `##### (一) 标题`,五级章节使用 `###### 1. 标题`。""",
|
||||
"none": """- 各级章节只写标题文字,不手写编号:`## 一级标题`、`### 二级标题`、`#### 三级标题`。
|
||||
- 确需更深层级时使用 `##### 四级标题`、`###### 五级标题`,仍不添加编号。""",
|
||||
}
|
||||
|
||||
|
||||
def _word_heading_numbering_style() -> str:
|
||||
"""Return the configured Word heading-numbering preset with a safe default."""
|
||||
try:
|
||||
return load_system_settings().prompt_prefix.word_heading_numbering_style
|
||||
except Exception:
|
||||
logger.debug("Failed to read the Word heading-numbering style; using default", exc_info=True)
|
||||
return "hybrid_decimal"
|
||||
|
||||
|
||||
def _build_ordinary_qa_markdown_format_section() -> str:
|
||||
rules = _ORDINARY_QA_HEADING_RULES.get(
|
||||
_word_heading_numbering_style(),
|
||||
_ORDINARY_QA_HEADING_RULES["hybrid_decimal"],
|
||||
)
|
||||
return f"""
|
||||
<ordinary_qa_markdown_format>
|
||||
当普通问答需要输出带章节结构的较长内容时,必须采用以下 Markdown 规范,以便下载为 Word 后得到正确的自动编号和公文标题格式:
|
||||
- 文档主标题使用 `# 主标题`;主标题只写标题文字,不添加章节编号。
|
||||
{rules}
|
||||
- 默认禁止使用以 `-`、`*`、`+` 或 `•` 开头的无序圆点列表;并列内容优先改写为完整自然段,确需逐项表达时使用有序列表。只有用户明确要求无序列表时才使用。
|
||||
- 简短问答不必为了套用格式而强行添加标题;本规范只约束实际使用的标题和列表。
|
||||
</ordinary_qa_markdown_format>
|
||||
"""
|
||||
|
||||
|
||||
_ORDINARY_QA_VISUALIZATION_SECTION = """
|
||||
@@ -771,12 +771,14 @@ _HTML_ARTIFACT_VISUALIZATION_SECTION = """
|
||||
只有通过 `<ordinary_qa_visualization>` 中的 HTML 页面意图门禁后,才允许阅读和执行本节;否则必须完全忽略本节的绘图契约。
|
||||
触发本节的前提是:用户在本次请求中明确要求生成 HTML、网页、看板、大屏页面或 `.html` 文件。
|
||||
不得仅因为用户要求画地图、标注地点或显示坐标,就推断用户需要 HTML;这类普通地图请求必须在消息列表中使用 `map-json`。
|
||||
__DF_GENERATED_PAGE_BRANDING__
|
||||
通过门禁后,必须在沙箱中生成并通过 `present_files` 交付实际 `.html` 文件,以便右侧制品面板打开预览;不得只在聊天消息中粘贴 HTML 代码。
|
||||
除非用户直接明确要求多页面或指定多个页面,生成的 HTML 必须是单页面,且质量校验时 `preferred_page_count` 必须传 `1`。不得因为报告较长、章节较多或模板自带导航而擅自生成多页面。
|
||||
“单页面”表示一个可以自然纵向滚动的 HTML 文档,不等于把所有内容压进一个固定尺寸的单屏。
|
||||
除非用户本次明确要求“大屏、驾驶舱、单屏或 1920×1080 固定画布”,普通 HTML 页面必须使用响应式文档布局:`body` 允许纵向滚动,主体使用 `width:min(100% - 32px, 1200px)` 一类的最大宽度,区块高度随内容增长,移动端改为单列。
|
||||
普通报告页面禁止固定 1920×1080 舞台、禁止 `html/body { overflow:hidden }`、禁止用 JavaScript 按 1920×1080 对整个页面做 `scale()`。不要把长报告做成 KPI 驾驶舱,不要为了装饰虚构指标;优先保留原报告的标题、摘要、章节、结论和来源层级。
|
||||
页面视觉应克制清晰:默认使用浅色低饱和配色、充足留白和稳定卡片层级;除非用户明确要求,禁止粒子背景、跑马灯、持续漂浮光斑、数字翻牌等循环动画,也不要用 emoji 充当功能图标。
|
||||
页面视觉应克制清晰:用户未明确指定页面主题时,必须跟随系统提示中的【当前界面主题】明暗模式——浅色系统生成浅色页面,深色系统生成深色页面;如果本轮没有收到界面主题,才以浅色低饱和配色兜底。不要复制系统的红、蓝、绿等主题主色,页面具体配色应根据内容、信息层级与可读性独立设计。
|
||||
背景、卡片与正文使用可读的中性色并保证正文对比度至少 4.5:1。不得仅因科技、数据、看板、驾驶舱或地图题材自行改成深色;除非用户明确要求,禁止粒子背景、跑马灯、持续漂浮光斑、数字翻牌等循环动画,也不要用 emoji 充当功能图标。
|
||||
满足 HTML 触发条件后,才使用下列平台内置绘图契约。生成的 HTML 源码必须直接引用 Gateway 提供的浏览器版 AntV G6、ECharts 和当前 HTML 地图引擎对应的地图资源,内网部署不依赖 CDN,也不依赖前端 React 构建产物。
|
||||
|
||||
- 用户上传了图片并要求把它作为页面背景时,必须把 `<uploaded_files>` 里该图片的 Public URL(`/api/public/html-images/...` 绝对地址)直接写成背景:单页面写成 `html, body` 的唯一背景;多页面只写到用户指定的 `.page` 选择器,未指定时写到首页 `.page`。两种情况均使用 `background-image: url('Public URL'); background-size: cover; background-position: center; background-repeat: no-repeat;`。禁止再叠 `linear-gradient`、`.overlay` 全屏蒙层、半透明遮罩或任何 rgba 滤镜;图片背景不得意外扩展到其他逻辑页面。禁止写 `/mnt/user-data/uploads/...`、相对路径、制品 API 路径,也禁止把图片转成 base64。理解图片内容仍只调用 `view_image`。没有 Public URL 时不要编造链接。禁止把 HTML 源码、Public URL 或 CSS 原文粘贴进聊天消息。
|
||||
@@ -847,9 +849,9 @@ _HTML_ECHARTS_MAP_BODY = """- HTML 网页中的地图一律使用本地 GeoJSON
|
||||
内置地图目录如下,坐标统一为 `[经度,纬度]`:中国省级 `china-provinces`、美国州级 `us-states`、日本都道府县 `japan-prefectures`、台湾地区县市 `taiwan-counties`。根据用户指定国家或城市自动选择对应地图;若没有给出国家,默认使用 `china-provinces`。不要猜测或引用未内置的国家、行政区或在线地图。
|
||||
平台自动加载本地 GeoJSON、注册地图、绘制区域/标记/连线,并支持拖拽缩放与点击。多页面中地图所在 `.page` 初始隐藏时,运行时会等容器可见后再初始化,并跟随容器尺寸变化自动 resize;不要调用不存在的 `deerflowMapReady`,也不要为切页手写延迟初始化、`echarts.init` 或 `chart.resize()`。`regions` 与 `markers` 中的 `description` 会在用户点击区域或标点时自动显示为可关闭的详情浮层;`description` 必须是纯文本,不能包含 `<a>`、`<span>`、`onclick` 或其他 HTML/事件属性,因为运行时会转义它。不要自己写地图弹窗。`us-states`、`japan-prefectures` 和 `taiwan-counties` 的区域名应使用地图中的标准英文名称(例如 `California`、`Osaka Prefecture`、`Taipei City`)。
|
||||
如需把点击结果联动到页面内已有的信息卡、筛选站点或切换明细页,只能监听 `window` 的 `deerflow:geo-map-click` 事件,并读取 `event.detail.name`、`event.detail.description` 或 `event.detail.data` 更新文字;需要切页时在事件回调内设置一个真实导航锚点,例如 `window.location.hash="#page-stations"`,再执行筛选。禁止在地图 `description` 中伪造“查看全部”链接,也禁止为此自行初始化 ECharts。
|
||||
用户明确要求“地图网页、地图看板或地图大屏”时,默认采用“深蓝三栏态势数据大屏”风格,而不是通用报告卡片或整页背景地图。桌面宽度(至少 1180px)使用 `min-height:100dvh` 的三栏网格:左列约 24%–27%,中列约 46%–52%,右列约 24%–27%,间距 12px–16px;窄屏时改为单列纵向布局,地图优先显示,禁止通过 `min-width` 强行产生横向滚动。
|
||||
用户明确要求“地图网页、地图看板或地图大屏”时,采用“三栏态势数据大屏”结构,而不是通用报告卡片或整页背景地图;配色仍按【当前界面主题】自动选择浅色或深色,只有用户明确要求深蓝/夜间/深色时才使用深蓝风格。桌面宽度(至少 1180px)使用 `min-height:100dvh` 的三栏网格:左列约 24%–27%,中列约 46%–52%,右列约 24%–27%,间距 12px–16px;窄屏时改为单列纵向布局,地图优先显示,禁止通过 `min-width` 强行产生横向滚动。
|
||||
顶部使用 72px–84px 的细标题带:左侧放日期、资料范围或状态,中央放中文主标题和一行大写英文副标题,右侧只放数据更新时间等已知信息;可用低透明斜线和一条青色发光分隔线增强层次,但没有真实时间数据时不要虚构实时时钟。主内容左列优先放 2 个紧凑 KPI 和一张趋势图;中列放一张占满列高的 `.df-geo-map`;右列放横向排名图和占比环图或与用户任务同等重要的两张分析图。所有图表必须对应用户给出的主题,缺少真实数据时清晰标注“示意数据”。
|
||||
面板使用深蓝半透明渐变、细蓝色边框、青色标题竖条、左上/右下的小角标和克制内发光;主色为深蓝和青色,金色只用于用户关注的枢纽、告警或最高优先级数据。标题可以有中英双层信息,但正文和交互控件最小字号为 16px;不要使用 emoji、厚重不透明白卡、夸张霓虹、无意义动画或外部字体/CDN。所有可点击控件须保留悬停、按下和键盘焦点状态,并尊重 `prefers-reduced-motion`。
|
||||
浅色主题使用浅灰/白色中性表面、细边框和克制的业务强调色;深色主题可使用深色半透明渐变、协调的强调色描边、标题竖条、小角标和克制内发光。告警色只用于真实告警或最高优先级数据。标题可以有中英双层信息,但正文和交互控件最小字号为 16px;不要使用 emoji、夸张霓虹、无意义动画或外部字体/CDN。所有可点击控件须保留悬停、按下和键盘焦点状态,并尊重 `prefers-reduced-motion`。
|
||||
中列地图必须始终是视觉主角,作为面板主体背景而非 `body` 背景。这种三栏结构中的中列就是“中间地图舞台”,中间至少 65% 的地图画面保持无遮挡。地图容器高度至少 560px,使用 `mode:"background"`、`showLabels:false`,地图头部另放标题和小图例;用户提到的城市必须写入 `markers`,提到的行政区必须同时写入 `regions` 并高亮,每个标点/区域提供 `description`,由运行时弹出详情浮层。需要联动页面内摘要时只监听 `deerflow:geo-map-click`;不要手写地图弹窗、`echarts.init`、`echarts.registerMap`、视觉映射或函数式 ECharts 配置。
|
||||
地图面板层级必须保持可点击:地图容器在最底层,装饰网格、角标和渐变遮罩都使用 `pointer-events:none`,信息卡仅存在于左右列,不得覆盖中列地图的主体画面;卡片之外的透明区域不得拦截鼠标事件,使地图标点和区域始终可点击。"""
|
||||
|
||||
@@ -862,22 +864,46 @@ _HTML_LEAFLET_MAP_BODY = """- HTML 网页中的地图一律使用「地图网页
|
||||
`"markers":[{"name":"北京","coordinate":[116.4,39.9],"description":"华北服务中心"}],`
|
||||
`"lines":[{"name":"联络","coordinates":[[116.4,39.9],[121.47,31.23]]}],"polygons":[]}</script>`
|
||||
坐标统一为 `[经度,纬度]`。平台自动加载配置的地图瓦片,并绘制标点、连线和多边形,支持拖拽缩放。多页面中地图所在 `.page` 初始隐藏时,运行时会等容器可见后再初始化;不要手写 `L.map` 或延迟初始化。`description` 必须是纯文本,不能包含 `<a>`、`<span>`、`onclick` 或其他 HTML/事件属性。不要自己写地图弹窗。
|
||||
用户明确要求“地图网页、地图看板或地图大屏”时,默认采用“深蓝三栏态势数据大屏”风格,而不是通用报告卡片或整页背景地图。桌面宽度(至少 1180px)使用 `min-height:100dvh` 的三栏网格:左列约 24%–27%,中列约 46%–52%,右列约 24%–27%,间距 12px–16px;窄屏时改为单列纵向布局,地图优先显示,禁止通过 `min-width` 强行产生横向滚动。
|
||||
用户明确要求“地图网页、地图看板或地图大屏”时,采用“三栏态势数据大屏”结构,而不是通用报告卡片或整页背景地图;配色仍按【当前界面主题】自动选择浅色或深色,只有用户明确要求深蓝/夜间/深色时才使用深蓝风格。桌面宽度(至少 1180px)使用 `min-height:100dvh` 的三栏网格:左列约 24%–27%,中列约 46%–52%,右列约 24%–27%,间距 12px–16px;窄屏时改为单列纵向布局,地图优先显示,禁止通过 `min-width` 强行产生横向滚动。
|
||||
顶部使用 72px–84px 的细标题带:左侧放日期、资料范围或状态,中央放中文主标题和一行大写英文副标题,右侧只放数据更新时间等已知信息;可用低透明斜线和一条青色发光分隔线增强层次,但没有真实时间数据时不要虚构实时时钟。主内容左列优先放 2 个紧凑 KPI 和一张趋势图;中列放一张占满列高的 `.df-map`;右列放横向排名图和占比环图或与用户任务同等重要的两张分析图。所有图表必须对应用户给出的主题,缺少真实数据时清晰标注“示意数据”。
|
||||
面板使用深蓝半透明渐变、细蓝色边框、青色标题竖条、左上/右下的小角标和克制内发光;主色为深蓝和青色,金色只用于用户关注的枢纽、告警或最高优先级数据。标题可以有中英双层信息,但正文和交互控件最小字号为 16px;不要使用 emoji、厚重不透明白卡、夸张霓虹、无意义动画或外部字体/CDN。所有可点击控件须保留悬停、按下和键盘焦点状态,并尊重 `prefers-reduced-motion`。
|
||||
浅色主题使用浅灰/白色中性表面、细边框和克制的业务强调色;深色主题可使用深色半透明渐变、协调的强调色描边、标题竖条、小角标和克制内发光。告警色只用于真实告警或最高优先级数据。标题可以有中英双层信息,但正文和交互控件最小字号为 16px;不要使用 emoji、夸张霓虹、无意义动画或外部字体/CDN。所有可点击控件须保留悬停、按下和键盘焦点状态,并尊重 `prefers-reduced-motion`。
|
||||
中列地图必须始终是视觉主角,作为面板主体背景而非 `body` 背景。这种三栏结构中的中列就是“中间地图舞台”,中间至少 65% 的地图画面保持无遮挡。地图容器高度至少 560px;用户提到的城市必须写入 `markers`,需要画出的范围写入 `polygons`,每个标点提供 `description`,由运行时弹出说明。不要手写 `L.map`、`L.tileLayer` 或瓦片地址。
|
||||
地图面板层级必须保持可点击:地图容器在最底层,装饰网格、角标和渐变遮罩都使用 `pointer-events:none`,信息卡仅存在于左右列,不得覆盖中列地图的主体画面;卡片之外的透明区域不得拦截鼠标事件,使地图标点和区域始终可点击。"""
|
||||
|
||||
|
||||
def _build_html_artifact_visualization_section(app_config: AppConfig) -> str:
|
||||
"""Render browser-reachable backend runtime URLs into the HTML contract."""
|
||||
from deerflow.config.system_settings import generated_page_logo_public_url
|
||||
from deerflow.html_runtime.addresses import html_runtime_base_url
|
||||
from deerflow.html_runtime.map_engine import html_map_engine
|
||||
|
||||
base_url = html_runtime_base_url(fallback=app_config.html_runtime.base_url)
|
||||
branding = load_system_settings().generated_page_branding
|
||||
logo_url = generated_page_logo_public_url(base_url, branding)
|
||||
branding_section = ""
|
||||
text_only_branding = getattr(branding, "logo_mode", "custom") == "none"
|
||||
if (
|
||||
branding.system_name
|
||||
and getattr(branding, "chrome_enabled", True)
|
||||
and (logo_url or text_only_branding)
|
||||
):
|
||||
branding_section = (
|
||||
"<generated_page_branding>\n"
|
||||
"管理员已配置生成网页标识。平台会在 HTML 写入与校验时自动注入通栏品牌页头"
|
||||
"(品牌居左、页面导航居中),不注入页脚;多页面并确保首个逻辑页初始可见。\n"
|
||||
"- 你只负责页面正文,禁止在主视觉、内容卡片、标题区或自定义导航里再次书写系统名称、引用系统 Logo,"
|
||||
"也不要创建 `data-df-brand`、品牌横条、品牌卡片、版权行或落款,避免重复。\n"
|
||||
"- 单页面直接从正文主标题开始;多页面只需提供 `.pages` 与 `.page[data-page]` 逻辑页,"
|
||||
"每页保留唯一 `id=\"page-...\"`、简短的 `data-page-title`(建议 2–8 个字)和清晰的 h1/h2 标题。"
|
||||
"此处由平台导航替代通用的模型自写导航要求;不要另写顶部 nav,平台会从逻辑页生成。\n"
|
||||
"</generated_page_branding>"
|
||||
)
|
||||
leaflet = html_map_engine() == "leaflet"
|
||||
section = (
|
||||
_HTML_ARTIFACT_VISUALIZATION_SECTION.replace(
|
||||
"__DF_GENERATED_PAGE_BRANDING__",
|
||||
branding_section,
|
||||
).replace(
|
||||
"__DF_HTML_MAP_CONTRACT__",
|
||||
_HTML_LEAFLET_MAP_SCRIPT if leaflet else _HTML_ECHARTS_MAP_SCRIPT,
|
||||
).replace(
|
||||
@@ -2004,8 +2030,8 @@ When a search, knowledge, skill, or MCP tool returns a result list:
|
||||
if rag_mode_enabled
|
||||
else ""
|
||||
)
|
||||
ordinary_qa_format_section = (
|
||||
_build_ordinary_qa_markdown_format_section()
|
||||
ordinary_qa_format_section = (
|
||||
_build_ordinary_qa_markdown_format_section()
|
||||
if _ordinary_qa_markdown_format_enabled()
|
||||
and not is_bootstrap
|
||||
and not writing_mode
|
||||
|
||||
+3
-1
@@ -47,7 +47,9 @@ _CONTRACT_REMINDER = (
|
||||
"<system_reminder>\n"
|
||||
"用户本次明确要求多页面 HTML。此类文件在 present_files 前会由服务器检查:"
|
||||
"必须引用本地 Bootstrap、Alpine 和 Bootstrap bundle;使用 `.pages`、"
|
||||
'至少两个 `.page[data-page]` 逻辑页,以及与页面 id 真实匹配的 `href="#page-..."` 锚点导航。'
|
||||
"至少两个带唯一 `id=\"page-...\"` 和简短 `data-page-title` 的 `.page[data-page]` 逻辑页。"
|
||||
"已配置生成网页标识时,平台后处理会统一生成真实锚点导航,正文禁止再写顶部导航;"
|
||||
'未配置时仍须自行提供与页面 id 真实匹配的 `href="#page-..."` 锚点导航。'
|
||||
"深色 ECharts 必须显式配置浅色文字;地图 description 只能写纯文本,点击联动监听 deerflow:geo-map-click。"
|
||||
"没有明确要求模板时,禁止 catalog/prepare 或读取模板:首个 write_file 直接写完整 outputs/*.html。"
|
||||
"请在同一个文件上完成一次 page_report_template validate 后再交付;"
|
||||
|
||||
+174
-174
@@ -1,141 +1,141 @@
|
||||
"""Tool error handling middleware and shared runtime middleware builders."""
|
||||
|
||||
import logging
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import override
|
||||
|
||||
from langchain.agents import AgentState
|
||||
from langchain.agents.middleware import AgentMiddleware
|
||||
from langchain_core.messages import ToolMessage
|
||||
from langgraph.errors import GraphBubbleUp
|
||||
from langgraph.prebuilt.tool_node import ToolCallRequest
|
||||
from langgraph.types import Command
|
||||
|
||||
from deerflow.config.app_config import AppConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MISSING_TOOL_CALL_ID = "missing_tool_call_id"
|
||||
|
||||
|
||||
class ToolErrorHandlingMiddleware(AgentMiddleware[AgentState]):
|
||||
"""Convert tool exceptions into error ToolMessages so the run can continue."""
|
||||
|
||||
def _build_error_message(self, request: ToolCallRequest, exc: Exception) -> ToolMessage:
|
||||
tool_name = str(request.tool_call.get("name") or "unknown_tool")
|
||||
tool_call_id = str(request.tool_call.get("id") or _MISSING_TOOL_CALL_ID)
|
||||
detail = str(exc).strip() or exc.__class__.__name__
|
||||
if len(detail) > 500:
|
||||
detail = detail[:497] + "..."
|
||||
|
||||
content = f"Error: Tool '{tool_name}' failed with {exc.__class__.__name__}: {detail}. Continue with available context, or choose an alternative tool."
|
||||
return ToolMessage(
|
||||
content=content,
|
||||
tool_call_id=tool_call_id,
|
||||
name=tool_name,
|
||||
status="error",
|
||||
)
|
||||
|
||||
@override
|
||||
def wrap_tool_call(
|
||||
self,
|
||||
request: ToolCallRequest,
|
||||
handler: Callable[[ToolCallRequest], ToolMessage | Command],
|
||||
) -> ToolMessage | Command:
|
||||
try:
|
||||
return handler(request)
|
||||
except GraphBubbleUp:
|
||||
# Preserve LangGraph control-flow signals (interrupt/pause/resume).
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.exception("Tool execution failed (sync): name=%s id=%s", request.tool_call.get("name"), request.tool_call.get("id"))
|
||||
return self._build_error_message(request, exc)
|
||||
|
||||
@override
|
||||
async def awrap_tool_call(
|
||||
self,
|
||||
request: ToolCallRequest,
|
||||
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
|
||||
) -> ToolMessage | Command:
|
||||
try:
|
||||
return await handler(request)
|
||||
except GraphBubbleUp:
|
||||
# Preserve LangGraph control-flow signals (interrupt/pause/resume).
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.exception("Tool execution failed (async): name=%s id=%s", request.tool_call.get("name"), request.tool_call.get("id"))
|
||||
return self._build_error_message(request, exc)
|
||||
|
||||
|
||||
def _build_runtime_middlewares(
|
||||
*,
|
||||
app_config: AppConfig,
|
||||
include_uploads: bool,
|
||||
include_dangling_tool_call_patch: bool,
|
||||
lazy_init: bool = True,
|
||||
) -> list[AgentMiddleware]:
|
||||
"""Build shared base middlewares for agent execution."""
|
||||
from deerflow.agents.middlewares.llm_error_handling_middleware import LLMErrorHandlingMiddleware
|
||||
from deerflow.agents.middlewares.thread_data_middleware import ThreadDataMiddleware
|
||||
from deerflow.sandbox.middleware import SandboxMiddleware
|
||||
|
||||
middlewares: list[AgentMiddleware] = [
|
||||
ThreadDataMiddleware(lazy_init=lazy_init),
|
||||
SandboxMiddleware(lazy_init=lazy_init),
|
||||
]
|
||||
|
||||
if include_uploads:
|
||||
from deerflow.agents.middlewares.uploads_middleware import UploadsMiddleware
|
||||
|
||||
middlewares.insert(1, UploadsMiddleware())
|
||||
|
||||
if include_dangling_tool_call_patch:
|
||||
from deerflow.agents.middlewares.dangling_tool_call_middleware import DanglingToolCallMiddleware
|
||||
|
||||
middlewares.append(DanglingToolCallMiddleware())
|
||||
|
||||
middlewares.append(LLMErrorHandlingMiddleware(app_config=app_config))
|
||||
|
||||
# LLM call metrics — always on, even when the user-facing speed indicator
|
||||
# is disabled. We append *after* the retry middleware so the metrics
|
||||
# middleware sits deeper in the wrap chain and observes individual provider
|
||||
# attempts (including the failed ones).
|
||||
from deerflow.agents.middlewares.llm_metrics_middleware import LlmMetricsMiddleware
|
||||
|
||||
middlewares.append(LlmMetricsMiddleware())
|
||||
|
||||
# Guardrail middleware (if configured)
|
||||
guardrails_config = app_config.guardrails
|
||||
if guardrails_config.enabled and guardrails_config.provider:
|
||||
import inspect
|
||||
|
||||
from deerflow.guardrails.middleware import GuardrailMiddleware
|
||||
from deerflow.reflection import resolve_variable
|
||||
|
||||
provider_cls = resolve_variable(guardrails_config.provider.use)
|
||||
provider_kwargs = dict(guardrails_config.provider.config) if guardrails_config.provider.config else {}
|
||||
# Pass framework hint if the provider accepts it (e.g. for config discovery).
|
||||
# Built-in providers like AllowlistProvider don't need it, so only inject
|
||||
# when the constructor accepts 'framework' or '**kwargs'.
|
||||
if "framework" not in provider_kwargs:
|
||||
try:
|
||||
sig = inspect.signature(provider_cls.__init__)
|
||||
if "framework" in sig.parameters or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()):
|
||||
provider_kwargs["framework"] = "deerflow"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
provider = provider_cls(**provider_kwargs)
|
||||
middlewares.append(GuardrailMiddleware(provider, fail_closed=guardrails_config.fail_closed, passport=guardrails_config.passport))
|
||||
|
||||
from deerflow.agents.middlewares.sandbox_audit_middleware import SandboxAuditMiddleware
|
||||
|
||||
middlewares.append(SandboxAuditMiddleware())
|
||||
middlewares.append(ToolErrorHandlingMiddleware())
|
||||
|
||||
# Tool / skill call metrics — appended last so it sits *deepest* in the
|
||||
# wrap_tool_call chain: its handler is the raw tool, so it observes the
|
||||
# unconverted exception (before ToolErrorHandlingMiddleware turns it into
|
||||
# an error ToolMessage) and the raw return value.
|
||||
"""Tool error handling middleware and shared runtime middleware builders."""
|
||||
|
||||
import logging
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import override
|
||||
|
||||
from langchain.agents import AgentState
|
||||
from langchain.agents.middleware import AgentMiddleware
|
||||
from langchain_core.messages import ToolMessage
|
||||
from langgraph.errors import GraphBubbleUp
|
||||
from langgraph.prebuilt.tool_node import ToolCallRequest
|
||||
from langgraph.types import Command
|
||||
|
||||
from deerflow.config.app_config import AppConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MISSING_TOOL_CALL_ID = "missing_tool_call_id"
|
||||
|
||||
|
||||
class ToolErrorHandlingMiddleware(AgentMiddleware[AgentState]):
|
||||
"""Convert tool exceptions into error ToolMessages so the run can continue."""
|
||||
|
||||
def _build_error_message(self, request: ToolCallRequest, exc: Exception) -> ToolMessage:
|
||||
tool_name = str(request.tool_call.get("name") or "unknown_tool")
|
||||
tool_call_id = str(request.tool_call.get("id") or _MISSING_TOOL_CALL_ID)
|
||||
detail = str(exc).strip() or exc.__class__.__name__
|
||||
if len(detail) > 500:
|
||||
detail = detail[:497] + "..."
|
||||
|
||||
content = f"Error: Tool '{tool_name}' failed with {exc.__class__.__name__}: {detail}. Continue with available context, or choose an alternative tool."
|
||||
return ToolMessage(
|
||||
content=content,
|
||||
tool_call_id=tool_call_id,
|
||||
name=tool_name,
|
||||
status="error",
|
||||
)
|
||||
|
||||
@override
|
||||
def wrap_tool_call(
|
||||
self,
|
||||
request: ToolCallRequest,
|
||||
handler: Callable[[ToolCallRequest], ToolMessage | Command],
|
||||
) -> ToolMessage | Command:
|
||||
try:
|
||||
return handler(request)
|
||||
except GraphBubbleUp:
|
||||
# Preserve LangGraph control-flow signals (interrupt/pause/resume).
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.exception("Tool execution failed (sync): name=%s id=%s", request.tool_call.get("name"), request.tool_call.get("id"))
|
||||
return self._build_error_message(request, exc)
|
||||
|
||||
@override
|
||||
async def awrap_tool_call(
|
||||
self,
|
||||
request: ToolCallRequest,
|
||||
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
|
||||
) -> ToolMessage | Command:
|
||||
try:
|
||||
return await handler(request)
|
||||
except GraphBubbleUp:
|
||||
# Preserve LangGraph control-flow signals (interrupt/pause/resume).
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.exception("Tool execution failed (async): name=%s id=%s", request.tool_call.get("name"), request.tool_call.get("id"))
|
||||
return self._build_error_message(request, exc)
|
||||
|
||||
|
||||
def _build_runtime_middlewares(
|
||||
*,
|
||||
app_config: AppConfig,
|
||||
include_uploads: bool,
|
||||
include_dangling_tool_call_patch: bool,
|
||||
lazy_init: bool = True,
|
||||
) -> list[AgentMiddleware]:
|
||||
"""Build shared base middlewares for agent execution."""
|
||||
from deerflow.agents.middlewares.llm_error_handling_middleware import LLMErrorHandlingMiddleware
|
||||
from deerflow.agents.middlewares.thread_data_middleware import ThreadDataMiddleware
|
||||
from deerflow.sandbox.middleware import SandboxMiddleware
|
||||
|
||||
middlewares: list[AgentMiddleware] = [
|
||||
ThreadDataMiddleware(lazy_init=lazy_init),
|
||||
SandboxMiddleware(lazy_init=lazy_init),
|
||||
]
|
||||
|
||||
if include_uploads:
|
||||
from deerflow.agents.middlewares.uploads_middleware import UploadsMiddleware
|
||||
|
||||
middlewares.insert(1, UploadsMiddleware())
|
||||
|
||||
if include_dangling_tool_call_patch:
|
||||
from deerflow.agents.middlewares.dangling_tool_call_middleware import DanglingToolCallMiddleware
|
||||
|
||||
middlewares.append(DanglingToolCallMiddleware())
|
||||
|
||||
middlewares.append(LLMErrorHandlingMiddleware(app_config=app_config))
|
||||
|
||||
# LLM call metrics — always on, even when the user-facing speed indicator
|
||||
# is disabled. We append *after* the retry middleware so the metrics
|
||||
# middleware sits deeper in the wrap chain and observes individual provider
|
||||
# attempts (including the failed ones).
|
||||
from deerflow.agents.middlewares.llm_metrics_middleware import LlmMetricsMiddleware
|
||||
|
||||
middlewares.append(LlmMetricsMiddleware())
|
||||
|
||||
# Guardrail middleware (if configured)
|
||||
guardrails_config = app_config.guardrails
|
||||
if guardrails_config.enabled and guardrails_config.provider:
|
||||
import inspect
|
||||
|
||||
from deerflow.guardrails.middleware import GuardrailMiddleware
|
||||
from deerflow.reflection import resolve_variable
|
||||
|
||||
provider_cls = resolve_variable(guardrails_config.provider.use)
|
||||
provider_kwargs = dict(guardrails_config.provider.config) if guardrails_config.provider.config else {}
|
||||
# Pass framework hint if the provider accepts it (e.g. for config discovery).
|
||||
# Built-in providers like AllowlistProvider don't need it, so only inject
|
||||
# when the constructor accepts 'framework' or '**kwargs'.
|
||||
if "framework" not in provider_kwargs:
|
||||
try:
|
||||
sig = inspect.signature(provider_cls.__init__)
|
||||
if "framework" in sig.parameters or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()):
|
||||
provider_kwargs["framework"] = "deerflow"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
provider = provider_cls(**provider_kwargs)
|
||||
middlewares.append(GuardrailMiddleware(provider, fail_closed=guardrails_config.fail_closed, passport=guardrails_config.passport))
|
||||
|
||||
from deerflow.agents.middlewares.sandbox_audit_middleware import SandboxAuditMiddleware
|
||||
|
||||
middlewares.append(SandboxAuditMiddleware())
|
||||
middlewares.append(ToolErrorHandlingMiddleware())
|
||||
|
||||
# Tool / skill call metrics — appended last so it sits *deepest* in the
|
||||
# wrap_tool_call chain: its handler is the raw tool, so it observes the
|
||||
# unconverted exception (before ToolErrorHandlingMiddleware turns it into
|
||||
# an error ToolMessage) and the raw return value.
|
||||
# Omit the recorder entirely while paused: no record allocation, skill-merge
|
||||
# lookup, or fire-and-forget DB task is created by any tool invocation.
|
||||
# Keep tool execution/error handling and LLM metrics independent of this flag.
|
||||
@@ -143,42 +143,42 @@ def _build_runtime_middlewares(
|
||||
from deerflow.agents.middlewares.tool_metrics_middleware import ToolMetricsMiddleware
|
||||
|
||||
middlewares.append(ToolMetricsMiddleware())
|
||||
return middlewares
|
||||
|
||||
|
||||
def build_lead_runtime_middlewares(*, app_config: AppConfig, lazy_init: bool = True) -> list[AgentMiddleware]:
|
||||
"""Middlewares shared by lead agent runtime before lead-only middlewares."""
|
||||
return _build_runtime_middlewares(
|
||||
app_config=app_config,
|
||||
include_uploads=True,
|
||||
include_dangling_tool_call_patch=True,
|
||||
lazy_init=lazy_init,
|
||||
)
|
||||
|
||||
|
||||
def build_subagent_runtime_middlewares(
|
||||
*,
|
||||
app_config: AppConfig | None = None,
|
||||
model_name: str | None = None,
|
||||
lazy_init: bool = True,
|
||||
) -> list[AgentMiddleware]:
|
||||
"""Middlewares shared by subagent runtime before subagent-only middlewares."""
|
||||
if app_config is None:
|
||||
from deerflow.config import get_app_config
|
||||
|
||||
app_config = get_app_config()
|
||||
|
||||
middlewares = _build_runtime_middlewares(
|
||||
app_config=app_config,
|
||||
include_uploads=False,
|
||||
include_dangling_tool_call_patch=True,
|
||||
lazy_init=lazy_init,
|
||||
)
|
||||
|
||||
if model_name is None and app_config.models:
|
||||
model_name = app_config.models[0].name
|
||||
|
||||
model_config = app_config.get_model_config(model_name) if model_name else None
|
||||
return middlewares
|
||||
|
||||
|
||||
def build_lead_runtime_middlewares(*, app_config: AppConfig, lazy_init: bool = True) -> list[AgentMiddleware]:
|
||||
"""Middlewares shared by lead agent runtime before lead-only middlewares."""
|
||||
return _build_runtime_middlewares(
|
||||
app_config=app_config,
|
||||
include_uploads=True,
|
||||
include_dangling_tool_call_patch=True,
|
||||
lazy_init=lazy_init,
|
||||
)
|
||||
|
||||
|
||||
def build_subagent_runtime_middlewares(
|
||||
*,
|
||||
app_config: AppConfig | None = None,
|
||||
model_name: str | None = None,
|
||||
lazy_init: bool = True,
|
||||
) -> list[AgentMiddleware]:
|
||||
"""Middlewares shared by subagent runtime before subagent-only middlewares."""
|
||||
if app_config is None:
|
||||
from deerflow.config import get_app_config
|
||||
|
||||
app_config = get_app_config()
|
||||
|
||||
middlewares = _build_runtime_middlewares(
|
||||
app_config=app_config,
|
||||
include_uploads=False,
|
||||
include_dangling_tool_call_patch=True,
|
||||
lazy_init=lazy_init,
|
||||
)
|
||||
|
||||
if model_name is None and app_config.models:
|
||||
model_name = app_config.models[0].name
|
||||
|
||||
model_config = app_config.get_model_config(model_name) if model_name else None
|
||||
if model_config is not None and model_config.supports_vision:
|
||||
from deerflow.agents.middlewares.view_image_middleware import ViewImageMiddleware
|
||||
|
||||
|
||||
+195
-55
@@ -345,6 +345,167 @@ class AppearanceSettings(BaseModel):
|
||||
raise ValueError("Unknown theme id")
|
||||
|
||||
|
||||
_GENERATED_PAGE_LOGO_FILE_RE = re.compile(r"^logo-[a-f0-9]{32}\.(?:png|jpg|webp)$")
|
||||
|
||||
|
||||
class GeneratedPageBrandingSettings(BaseModel):
|
||||
"""Optional name and logo mode used only inside newly generated HTML pages.
|
||||
|
||||
A configured name enables the generated-page shell when the logo mode is
|
||||
``default`` or ``none``; ``custom`` additionally needs an uploaded image.
|
||||
The custom image lives beside ``system_settings.json`` so the JSON document
|
||||
stays small and ordinary runtime backups keep the two together.
|
||||
"""
|
||||
|
||||
chrome_enabled: bool = Field(
|
||||
default=True,
|
||||
description="Master switch for the platform-injected brand header/footer/nav. "
|
||||
"On by default: once an administrator configures a name and logo display mode, generated HTML "
|
||||
"receives the platform header. The configured name/logo stay available to template skills "
|
||||
"when injection is explicitly turned off.",
|
||||
)
|
||||
header_layout: Literal["left", "center"] = Field(
|
||||
default="center",
|
||||
description="Brand lockup position in the injected page header: "
|
||||
"left = brand left + nav right on one row; center = centered brand row above a centered nav row.",
|
||||
)
|
||||
system_name: str | None = Field(
|
||||
default=None,
|
||||
max_length=80,
|
||||
description="Administrator-provided name rendered inside generated pages",
|
||||
)
|
||||
footer_text: str | None = Field(
|
||||
default=None,
|
||||
max_length=160,
|
||||
description="Optional footer line rendered at the bottom of generated pages; empty keeps the default brand footer",
|
||||
)
|
||||
logo_filename: str | None = Field(
|
||||
default=None,
|
||||
description="Opaque runtime-owned logo filename used by generated pages",
|
||||
)
|
||||
logo_mode: Literal["custom", "default", "none"] = Field(
|
||||
default="custom",
|
||||
description="How generated-page branding renders the logo: uploaded custom file, packaged default, or no logo",
|
||||
)
|
||||
logo_media_type: Literal["image/png", "image/jpeg", "image/webp"] | None = None
|
||||
logo_version: str | None = Field(default=None, max_length=64)
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
@field_validator("header_layout")
|
||||
@classmethod
|
||||
def _normalize_header_layout(cls, value: str | None) -> str:
|
||||
normalized = str(value or "").strip().lower()
|
||||
return normalized if normalized in {"left", "center"} else "center"
|
||||
|
||||
@field_validator("system_name")
|
||||
@classmethod
|
||||
def _normalize_system_name(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = " ".join(str(value).split())
|
||||
return normalized or None
|
||||
|
||||
@field_validator("footer_text")
|
||||
@classmethod
|
||||
def _normalize_footer_text(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = " ".join(str(value).split())
|
||||
return normalized or None
|
||||
|
||||
@field_validator("logo_filename")
|
||||
@classmethod
|
||||
def _validate_logo_filename(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = str(value).strip().lower()
|
||||
if not _GENERATED_PAGE_LOGO_FILE_RE.fullmatch(normalized):
|
||||
raise ValueError("Invalid generated-page logo filename")
|
||||
return normalized
|
||||
|
||||
@field_validator("logo_mode", mode="before")
|
||||
@classmethod
|
||||
def _normalize_logo_mode(cls, value: str | None) -> str:
|
||||
normalized = str(value or "custom").strip().lower()
|
||||
return normalized if normalized in {"custom", "default", "none"} else "custom"
|
||||
|
||||
|
||||
_APP_IDENTITY_LOGO_FILE_RE = re.compile(r"^logo-[a-f0-9]{32}\.(?:png|jpg|webp)$")
|
||||
|
||||
|
||||
class AppIdentitySettings(BaseModel):
|
||||
"""Name and logo shown in this application's own chrome.
|
||||
|
||||
Empty ``system_name`` and a missing logo keep the built-in title and the
|
||||
static theme logos. This block is independent of generated-page branding.
|
||||
"""
|
||||
|
||||
system_name: str = Field(default="", max_length=80)
|
||||
logo_filename: str | None = None
|
||||
logo_media_type: Literal["image/png", "image/jpeg", "image/webp"] | None = None
|
||||
logo_version: str | None = None
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
@field_validator("system_name")
|
||||
@classmethod
|
||||
def _normalize_app_system_name(cls, value: str | None) -> str:
|
||||
normalized = " ".join(str(value or "").split())
|
||||
return normalized
|
||||
|
||||
@field_validator("logo_filename")
|
||||
@classmethod
|
||||
def _validate_app_logo_filename(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = str(value).strip().lower()
|
||||
if not _APP_IDENTITY_LOGO_FILE_RE.fullmatch(normalized):
|
||||
raise ValueError("Invalid application logo filename")
|
||||
return normalized
|
||||
|
||||
|
||||
def app_identity_logo_path(
|
||||
settings: AppIdentitySettings | None = None,
|
||||
) -> Path | None:
|
||||
"""Resolve the uploaded application logo without accepting an arbitrary path."""
|
||||
|
||||
current = settings or load_system_settings().app_identity
|
||||
if not current.logo_filename:
|
||||
return None
|
||||
path = runtime_home() / "app-identity" / current.logo_filename
|
||||
return path if path.is_file() else None
|
||||
|
||||
|
||||
def generated_page_logo_path(
|
||||
settings: GeneratedPageBrandingSettings | None = None,
|
||||
) -> Path | None:
|
||||
"""Resolve the generated-page logo without accepting an arbitrary disk path."""
|
||||
|
||||
current = settings or load_system_settings().generated_page_branding
|
||||
if current.logo_mode != "custom":
|
||||
return None
|
||||
if not current.logo_filename:
|
||||
return None
|
||||
path = runtime_home() / "generated-page-branding" / current.logo_filename
|
||||
return path if path.is_file() else None
|
||||
|
||||
|
||||
def generated_page_logo_public_url(
|
||||
html_runtime_base_url: str,
|
||||
settings: GeneratedPageBrandingSettings | None = None,
|
||||
) -> str | None:
|
||||
"""Return the browser URL used only inside generated HTML pages."""
|
||||
|
||||
current = settings or load_system_settings().generated_page_branding
|
||||
if current.logo_mode == "none":
|
||||
return None
|
||||
if current.logo_mode == "default":
|
||||
return f"{html_runtime_base_url.rstrip('/')}/brand-logo-dark.png"
|
||||
if generated_page_logo_path(current) is None:
|
||||
return None
|
||||
version = current.logo_version or "current"
|
||||
return f"{html_runtime_base_url.rstrip('/')}/generated-page-logo?v={version}"
|
||||
|
||||
|
||||
class CitationDisplaySettings(BaseModel):
|
||||
"""System-wide controls for citation mode entry and display cleanup."""
|
||||
|
||||
@@ -624,6 +785,21 @@ class MemoryRuntimeSettings(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
|
||||
class AgentSkillMigrationSettings(BaseModel):
|
||||
"""Deployment-wide gate for administrator agent/skill migration tools.
|
||||
|
||||
The feature is deliberately opt-in because it reconciles persisted metadata
|
||||
against folders copied directly into the live runtime. Missing legacy
|
||||
configuration therefore fails closed.
|
||||
"""
|
||||
|
||||
enabled: bool = Field(
|
||||
default=False,
|
||||
description="Whether administrator agent/skill migration APIs and UI are enabled.",
|
||||
)
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
|
||||
class ConversationContextSettings(BaseModel):
|
||||
"""Deployment-wide short-context policy for chat model requests.
|
||||
|
||||
@@ -741,10 +917,7 @@ class LocalWikiEncoderSettings(BaseModel):
|
||||
|
||||
mode: Literal["configured", "local"] = Field(
|
||||
default="configured",
|
||||
description=(
|
||||
"Use the embedding provider from config.yaml, or explicitly override it "
|
||||
"with the administrator-managed offline BGE-M3 encoder."
|
||||
),
|
||||
description=("Use the embedding provider from config.yaml, or explicitly override it with the administrator-managed offline BGE-M3 encoder."),
|
||||
)
|
||||
model_path: str = Field(
|
||||
default="",
|
||||
@@ -769,53 +942,8 @@ class HtmlMapSettings(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
|
||||
_APP_IDENTITY_LOGO_FILE_RE = re.compile(r"^logo-[a-f0-9]{32}\.(?:png|jpg|webp)$")
|
||||
|
||||
|
||||
class AppIdentitySettings(BaseModel):
|
||||
"""Name and logo shown in this application's own chrome.
|
||||
|
||||
Empty ``system_name`` and a missing logo keep the built-in title and the
|
||||
static theme logos. This block is independent of generated-page branding.
|
||||
"""
|
||||
|
||||
system_name: str = Field(default="", max_length=80)
|
||||
logo_filename: str | None = None
|
||||
logo_media_type: Literal["image/png", "image/jpeg", "image/webp"] | None = None
|
||||
logo_version: str | None = None
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
@field_validator("system_name")
|
||||
@classmethod
|
||||
def _normalize_app_system_name(cls, value: str | None) -> str:
|
||||
normalized = " ".join(str(value or "").split())
|
||||
return normalized
|
||||
|
||||
@field_validator("logo_filename")
|
||||
@classmethod
|
||||
def _validate_app_logo_filename(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = str(value).strip().lower()
|
||||
if not _APP_IDENTITY_LOGO_FILE_RE.fullmatch(normalized):
|
||||
raise ValueError("Invalid application logo filename")
|
||||
return normalized
|
||||
|
||||
|
||||
def app_identity_logo_path(
|
||||
settings: AppIdentitySettings | None = None,
|
||||
) -> Path | None:
|
||||
"""Resolve the uploaded application logo without accepting an arbitrary path."""
|
||||
|
||||
current = settings or load_system_settings().app_identity
|
||||
if not current.logo_filename:
|
||||
return None
|
||||
path = runtime_home() / "app-identity" / current.logo_filename
|
||||
return path if path.is_file() else None
|
||||
|
||||
|
||||
class HtmlRuntimeSettings(BaseModel):
|
||||
"""Addresses written into newly generated HTML pages.
|
||||
"""Generated-page addresses and ordinary-Q&A message-map tile limits.
|
||||
|
||||
Empty strings mean the settings dialog has not saved this block. Readers
|
||||
then keep an older config.yaml value, and finally the built-in default.
|
||||
@@ -831,6 +959,18 @@ class HtmlRuntimeSettings(BaseModel):
|
||||
max_length=2048,
|
||||
description="Leaflet tile template containing {z}, {x} and {y}",
|
||||
)
|
||||
message_map_tile_min_zoom: int = Field(
|
||||
default=0,
|
||||
ge=0,
|
||||
le=20,
|
||||
description="Lowest native raster-tile zoom used by ordinary-Q&A message maps",
|
||||
)
|
||||
message_map_tile_max_zoom: int = Field(
|
||||
default=8,
|
||||
ge=0,
|
||||
le=20,
|
||||
description="Highest native raster-tile zoom used by ordinary-Q&A message maps",
|
||||
)
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
|
||||
@@ -862,6 +1002,8 @@ class SystemSettings(BaseModel):
|
||||
private_square: PrivateSquareSettings = Field(default_factory=PrivateSquareSettings)
|
||||
publish_squares: PublishSquaresSettings = Field(default_factory=PublishSquaresSettings)
|
||||
appearance: AppearanceSettings = Field(default_factory=AppearanceSettings)
|
||||
generated_page_branding: GeneratedPageBrandingSettings = Field(default_factory=GeneratedPageBrandingSettings)
|
||||
app_identity: AppIdentitySettings = Field(default_factory=AppIdentitySettings)
|
||||
citation_display: CitationDisplaySettings = Field(default_factory=CitationDisplaySettings)
|
||||
leaderboard: LeaderboardSettings = Field(default_factory=LeaderboardSettings)
|
||||
skill_compression: SkillCompressionSettings = Field(default_factory=SkillCompressionSettings)
|
||||
@@ -879,19 +1021,16 @@ class SystemSettings(BaseModel):
|
||||
default_factory=RetryKeepPartialSettings
|
||||
)
|
||||
roundtable_room_limit: RoundtableRoomLimitSettings = Field(default_factory=RoundtableRoomLimitSettings)
|
||||
agent_skill_migration: AgentSkillMigrationSettings = Field(default_factory=AgentSkillMigrationSettings)
|
||||
local_wiki_encoder: LocalWikiEncoderSettings = Field(default_factory=LocalWikiEncoderSettings)
|
||||
strategy_projects: StrategyProjectSettings = Field(default_factory=StrategyProjectSettings)
|
||||
html_map: HtmlMapSettings = Field(default_factory=HtmlMapSettings)
|
||||
html_runtime: HtmlRuntimeSettings = Field(default_factory=HtmlRuntimeSettings)
|
||||
app_identity: AppIdentitySettings = Field(default_factory=AppIdentitySettings)
|
||||
llmwiki: LlmWikiRuntimeOverride = Field(default_factory=LlmWikiRuntimeOverride)
|
||||
skill_knowledge_auto_sync: SkillKnowledgeAutoSyncSettings = Field(default_factory=SkillKnowledgeAutoSyncSettings)
|
||||
knowledge_base_product_version: Literal["v1", "v2"] = Field(
|
||||
default="v1",
|
||||
description=(
|
||||
"v1 keeps assistant-knowledge day-to-day surfaces admin-only; "
|
||||
"v2 releases them to ordinary users while ordinary knowledge remains the default landing."
|
||||
),
|
||||
description=("v1 keeps assistant-knowledge day-to-day surfaces admin-only; v2 releases them to ordinary users while ordinary knowledge remains the default landing."),
|
||||
)
|
||||
ordinary_knowledge_landing: Literal["wiki", "weknora"] = "wiki"
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
@@ -1035,3 +1174,4 @@ def save_system_settings(settings: SystemSettings) -> SystemSettings:
|
||||
_settings_cache_key = None
|
||||
_settings_cache_value = None
|
||||
return settings
|
||||
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 5.6 MiB |
+1
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1920" height="64" viewBox="0 0 1920 64"><defs><style>.a{fill:url(#a);}.b{fill:url(#b);}.c{clip-path:url(#c);}.d{fill:url(#d);}</style><linearGradient id="a" x1="0.5" x2="0.5" y2="1" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#131f3d"/><stop offset="1" stop-color="#094593"/></linearGradient><linearGradient id="b" x1="0.473" x2="0.473" y2="0.95" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#131f3d"/><stop offset="1" stop-color="#094593" stop-opacity="0"/></linearGradient><clipPath id="c"><rect class="a" width="1920" height="64" transform="translate(-2 5)"/></clipPath><pattern id="d" preserveAspectRatio="xMidYMid slice" width="100%" height="100%" viewBox="0 0 1917 104"><image width="1917" height="104" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB30AAABoCAYAAAD1oOqOAAAABHNCSVQICAgIfAhkiAAAIABJREFUeF7svQnUbMdRJli3qv717U+bpSdZsi1LtiUbtVdsQ7Nz2LpZvNADPdimWYfumW4Yz4Dpw+FwGs2hB4YZppsxDeOF5TCNMYYeNwM+mIPBm7zbki3JkmxL1tPytLz1X6vq3onIyMiMjBt5q/7//ZL+/ylL+l/VzZtL5BdLZkbkzVt986eaqlc+BYGCQEGgIFAQKAgUBAoCBYGCQEGgIFAQKAgUBAoCBYGCQEGgIFAQKAgUBAoCBYGCQEGgILAnEahK0HdP8q0QXRAoCBQECgIFgYJAQaAgUBAoCBQECgIFgYJAQaAgUBAoCBQECgIFgYJAQaAgUBAoCBQEHAIl6FsEoSBQECgIFAQKAgWBgkBBoCBQECgIFAQKAgWBgkBBoCBQECgIFAQKAgWBgkBBoCBQECgI7GEEStB3DzOvkF4QKAgUBAoCBYGCQEGgIFAQKAgUBAoCBYGCQEGgIFAQKAgUBAoCBYGCQEGgIFAQKAgUBErQt8hAQaAgUBAoCBQECgIFgYJAQaAgUBAoCBQECgIFgYJAQaAgUBAoCBQECgIFgYJAQaAgUBDYwwiUoO8eZl4hvSBQECgIFAQKAgWBgkBBoCBQECgIFAQKAgWBgkBBoCBQECgIFAQKAgWBgkBBoCBQECgIlKBvkYGCQEGgIFAQKAgUBAoCBYGCQEGgIFAQKAgUBAoCBYGCQEGgIFAQKAgUBAoCBYGCQEGgILCHEShB3z3MvEL6U4pA9ZS2bjfe7EKaCkkFgYJAQaAgUBAoCBQECgIFgYJAQaAgUBAoCBQECgIFgYJAQaAgsDsRKH7u3cmXQlVBYFsIlKDvtmArhQoCDoHdMiCWYG8RyIJAQaAgUBAoCBQECgIFgYJAQaAgUBAoCBQECgIFgYJAQaAgUBDYDgLFz70d1EqZgsAuRKAEfXchUwpJewqB3TAglqDvnhKZQmxBoCBQECgIFAQKAgWBgkBBoCBQECgIFAQKAgWBgkBBoCBQENhVCBQ/965iRyGmILA9BErQd3u4lVJ7G4HdMIDtVgRLAHm3cqbQVRAoCBQECgIFgYJAQaAgUBAoCBQECgIFgYJAQaAgUBAoCBQEIgLFz52XhuLnLprytESgBH2flmx/2ne6DIZlMHzaK0EBoCBQECgIFAQKAgWBgkBBoCBQECgIFAQKAgWBgkBBoCBQENjTCBQ/d/Fz72kBLsTvPAIY9O3vfLWlxoJAQaAgUBAoCBQECgK7GoGy43NXs6cQVxAoCBQECgIFgYJAQaAgUBDYNgIlCLJt6ErBgkBBoCBQECgIFAT2MgIl6LuXuVdoLwgUBAoCBYGCQEFgJxEogeCdRLPUVRAoCBQECgIFgYJAQaAgUBB44hEoAd4nHuPSQkGgIFAQKAgUBAoCewSBEvTdI4wqZO4qBGZdUGDwYNa8XR3U9XRdl4DFrhKVQkxBoCBwgSGwE3a92OkLTChKdwoCBYGCQEGgIFAQKAgUBEwELH/IrPPpWfMV6AsCBYGCQEFg+whsx2/9RNtnWX/xn2yft6Xk0xiBEvR9GjO/dH1LCGxnENxSA09A5jIwPgGglioLAgWBgsAOIFDs8w6AWKooCBQECgIFgYJAQaAgUBDY1QjsRT/Krga0EFcQKAgUBHYIgb1on4sfZYeYX6q58BGobvqPHxwcfeWrm8c+9KGq8m/3xevH4bqH13UE4eirp6djWS6BdbgyH4FvrBO+sb5QD2bkNwpjO/C7gW9ndbht/91A4kWvinXo+4FKyB/akvzz9Ye+wT2ss8LGNE3cPt7zveFyeHmR7xNXL+8xhlgn16/pcX0U2CZ4+EoZN3fpaeffrl5t5sSbmRu4F+5LHI26knb4PnfM4IHDiz8ZXubkJ9Cde4u0qi+Li5fNRNZQtuDDbVtyJ+UZ70N2V+bsbbdWJAjIbw8sXuvfPu3AjS9ssIz7/vxt1YEbbgzcCOlYJ3wwj2sD8rlryIt5HI8EliGfpMXTw+0wfQ0UPOjrcZVIOgV7Qn98Q9w2lpE0n/G0jk+fcbQGmfC6H3TP6zPmcfYBP17fXJrXb66DSXnswx+qpO5i/TpN1hXsBbQRdBQzeHpMO6RlSuhMS+c9t1rb0ry8a52Q5YO98vQktGTSWN81z009Ufoq87AdYRvZ0l0PuLQ3rCPBvmtcgGdsL6S+ef1wNTq+Mv4GzhYGQQzVGMLpWsaS/Hwhxp4ue8/20cIqjF+SDm0TNd+kDsnxyac78eGxA/VFjG0sx5Imrk6Of0GHrDHW65EcnzQ+SZtCByXpgW8STzk+qnGF9VaO/S3eajngOoTtTngrxm83Jmk+qPqkjPM4G8ZLySdh7wOWyAs/R5G6zbLM8xGNvewjt896E7CQdHJfUXf8WJ7kF0zQY5g1prnsYkA/+qqvQ/Kb43/27urYD7ymOf7ud5sLsWOviffwN1Zz/5++uyJzLyYIrEdaF0WbjBd+X/na1/m63uXma/i58vU+7U8gzX8w7X5xbaVznlxertuqR8ryLG1JOmXZvfq7mUx6zXjcw+8av/FvNMLfVTMaw/cIrq1vyof5XTlRz3axYP5vt/xeLCdlUsqx0zND7qUsS3mV2HXJ+Sw6YtExTTem3Z+FN5b+W7qby3e+eafRqPs4zV7NypNZbNA02vR9i9YuWcvJm8XXLvy77PY0mnJlu2TW6rfuS64PjMesdE0bk7bKo5K/ILATuq/nP9a1bEfL/Sz6pccariP4omQDuKjQn2RNl96Xc0xdjO+5bz9XxTyPf/iDsUZoz5p/u3zsH/S+BL0eb/kJ9fpfEJRdK4n1icsu1/jKhyF9Gi4v+z/wt/AVJmtRkU+ue1prCuFP5XvW2kquP+R6xeGlfFzsi0j8i3KuL2jTflbpJ2NeJPV5bALvlA8g8YlABdx3XA8hVs7fI/BNZEfQmPjrpL9HrE0Tf+YUs8S+JfbrYvYgV9baU9aX8zdwHuU7QR+W5T/WfhS5Dmdfe/AhC/mUdOZ4mkuXGGm/EPLEtaf0jX13vMZl/5TVhpbZRC6kH8HLnKkLjGPOJ235psT6WvoFuX7te0l8zJKfks+WDRC2QdsJ9lU6H5qQdeZliFfgPY6d6PaU3OqYQLA3yucubUTwH2qfi9BN5gvSPHfwYDDm7of0FXt62JeNl+G3dExDo4lvmvvBdUm/uUiTvmbnn5Y+aPSFC591yOtp4Cacz5zzyXb9bzleBL+6b8c5NRWtmHLwxhfWLO/a9rCtcLYeMksZb/l35Jjp/UFYXvuLEhsv5LHlX9W+OIyFQX0XSd+ib7MVI5N6JfWP7a+/nx2TfBmuJrEfYsx1/RM+frzW/iwZ8+L6ZBxQxhOt8YbLI/uSeB9UJmNvLb1H8ZY4aFuOtPrYpPaLmv59gx8hTsjxTBUjlfMcppXHCEmvNT6YsQDsD/tr1Rwp6LmP23LfJI8sPyzed0HfhBFRVZLAayuQyIJiOMWTwIgSKFd9LkAjGOUUGgVfBjCR8XryZdWv29BOT1YeVXdCG5SRAadE0TJttiYXVsBD4mUFIgwFZrwCDWiRkuirZBr8tgRW0txFF1dlDOStwItBPwVECIng5Jfk6XotupR8uH5jZcgQvgeC0cD13KE4sCkUOi+9Z7w3OnNajA693twBqM8PXhhcJf+5xxvb5DSrdj3Q6Dz+vquu3w7WNnWTstUKRCt6zE4ag3sY8HNyg33bCoAi7/gsBIvl4sqyCZZcs55aQQnUfeS7L8f2wHXfTwRlEFXqp95UoQO1VgDRrYWRL9yeH/hde06a1SfXR5EuaTbxsXQtg0UreNllR1intJ3VfRCL2rAJxehXa7PGlMl0blGsF56JnWI1k0Io7H/CA22/jEWEmV/3LTcOSfy0LZXyoHmgy0mZl/oh5V7TnrOHurxVt2rfXOxKGVAT1xZ/JC1WOSmrmb63+KD7Z2FtjRE+n9bF7CJvlrFX9smYJEqdNbHU+DFfc7hJW6Z1ka9bu7liobWHHu400Sk2Pqulq76NUFlOn6VBZPoyFCS22Jie6A0vVvdnyZODraQXBJ4MBLr21z0Z7W+nDUuvcrq21XRNzzQ7gPl3Ws/PtLine truncated
|
||||
|
After Width: | Height: | Size: 98 KiB |
+1
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1920" height="64" viewBox="0 0 1920 64"><image width="1920" height="64" preserveAspectRatio="none" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAABACAIAAAB0j/2rAADncElEQVR42uz9aZctSXYdBp59zG/Em3POrEKhJoAkKE4tCmyBk4ZufQDYf1X9mb2WunuxRUlscqnJJZKCCBQKqEJVzpmV05si4l4/uz/Y7G7mw414WZCIt0hUpF+/fn0wNztnn332xi9/+cs3X3tNWv9IAiApIgDSFv/HZGP6qHmQ3n+GjSKQff/8V+b/N30qrWNOfogi4k8+bkHx3cnBJzsIKcWFhO31D0yOJrOzahy2/rv5b74D6qNtP+b8DFf3nGxBfWO5eNqTZ7d6sZNP58+Xi1+Z33YuXtHGf2d/8S/Uv7/IV7Fwbs2XevUgWNt//qb3fnr7UOfaYOZs5+3v/sK3Ns4P513almd39ov2v9M36/8YE8Jf/vvLf3/57z+2medbnrvu6udwR7Hc9vWRfwFuI9aCir9c9b61s/3LWOXst+z2r5t863kc9gf8f/lK/uW7+Rf/lfy1LCi3XE8X8uuN578dHMDmjb3Dso8EkpSIh/bwxjme2QM/d+GozZ23oLVNyLdEhicQce8gIvLF118PIvJ//2//2/kvTP5evTCaVb9Cto9ZHo0EYGb5P8vb7RFe0m+nCCgSAfFwKH9tpN+ab0Y8uAhBCinwhwwbxZhGQPMGi3A+xGC2dIF+hzx80rCx4lAMaHe6uuJQqI5JoQiAkZ27z+5p9G5+/8yn322fUjUE0/CKr0r+CuNQ6H19eg7l3Sg2pq/78b4yodg4jifnBhGQpsyDrTVVxbO1+NPozzakoHiEJqrNC4KEEQoRi+9hH46jgKQD/HCbvKW5wjGN2WAULS6iMZFAUMxUJuJEKEKIUvwoVpmM/XQXFutC9fTov+GvPT7zVNAJbx4EaM3XFP/SYvIzTQhz8kUgHjO844T2akxCCQ8sDSHEk58/6uo/EZ63P7hxUnhhus9QCMVMoKLo1sF6z6v3ckNAHG5eutO1QUFCzE9OIn54QEBRGCBKNQkLmr+0cI/Sq+q/ZUJM1ls0Hn8cJWkUAUKj4ObeExsuyVFElILxNJxuRDi6S4MTMYmzbX0/4yuc3/R4CcWDQPpo/uzD1+MywcY9BUVg1W1k+WwZtoAIU3N4gIxzux++KF9AxpmfDA+XIloNE44EBSoki/c1hxMQChGXsfR6hDNDXkH8mIr7LcyfVaQg+fEWxVUIKMUCCr/khRNEnMjhLyqticXkQTK+wgh/CyHpzWUzoUS+z2GEpjU9zrPlwwvLvOSSLiQvtcU9CrNNsTQDpKGu+oJxefJ3T0EzoSG+uWC8HeFp+btNkGBYbGJ4GMMS0igA/V3It86/S/T32uJt95+G+wkyPHv/mIyI9wRCf2R/M/31QcTS1My02IYb6wethvNL0ZRfiONt9qdDIoyBMJn44Q5heAUZZgjkmdQ/WX+qoL8hiA+Ms7pXMd2ymCziWfFEUcSNFEthjcgYT36kDIAJR8oBAGQkLxSkjKSJOEBERtIoFLnQ8CRPFoaCA3S2YlwZy8XEf2shGB+ZZ0K/8cbYiOuZ3itRkaGgL8ThLC4uTlyMekTk2lgeeFAMOabPu43kkTwAAnGCATiRfjsACtO3TqQK/N07kiZ0gjGu0APkGBctkbxSqcjC7ZnMplosjgyzRVzLBTFwz2txfLdzAE+gnEolLTDIo0jS/AwRwiQMJE0PA3m2S3/H40DytIv0TAFlNWv72R7xT//qgxAIADFBXg4AA5AmkfDGxnsJFPcEfkYlNazFPsRTpPHFFJCE44NChI15SQi/7gOeHIbG4CfF3+GMqnOIt6EaSOHFR1w9KExfXBurMgmN8jqOvJrHuKV+lyrGTxlclVF/kYsXr5yWkXcxao15+JahQrylVSwZH1s+LuYkorjy+fHnoyTEX2SMFVD/4ceYAhaXQh+mpUNPIQS/5ORpxS/KRqqq/yON2PQWicVAqbwoY76E+C6Vt5xW7j3lS/nLJOcfhZUF0HrtATgOp6OQJ3UcDmEMjKfDzQsXwg/GjDxHGMKc3iEMvBiVxvUKBBimB/HLofoFM3wZYbGMyzIJ+onBH58CVQUppm4cLgiNj6fImzJEEC86XrcZ2/NfmeCIQBgeBYrkghAtolj/Fatj3nLK9MPe0lodxxIhGl8QFbE0jzLPhsXIbpxwGuWSblgjwQPEwh8gLQFEYek3AQQKmt9LQ4LqkQwSmqd8pDc9PLUQV4jfLX7ElC8p5vklTcr8Ok25aSDR/KgqIqQivJQ0J1ZzF32c5E8bABRmhhAEh8dh/sjIaIof1MZiorCwpNACYijFTVi6LfF9Cue/QKeC0NITteIGqUAINZJChY52UndQUU5TVUgBvIjUA26VxjXJeeerwGp4gDwiubwdRYQIzGbhGglJk3nr0ppfSeBo3qc8h7RGJ9AHYFrOyt3Kr6efCFNnXjEmRxYJaAOrr1cZSgAr4ltH55q3y78wxXYpog4/WwZIk/FG+ZWDYW1NURhZPpQCvSrZt5TZe1Q/iOWhsjKEWjv/X//JPxlE5NiMNeqNXIlHhGnBy0gC6xGf1iUJcDE9FIzJiZuU6EnMPMMBUi4TIlMROQET7JvFjEewfM99LikqiIlfea3MMEb6ueKfCxULs1HqQkGONkqAMYIpZilcNCkTDJ+ejj6y9Ykzi9xXRAQamdoFSmoxd00hfjmfMn7EnANYcWb+o/RpXZthBS+mOykUyXc1rJU252VmuD+HnNKgbaKAaor/LR5vREDidGGUIpUtfyK8fuPJ5KjDwUdmbjTRAiFFHj25JmOUoXg1/QgOS59KChTzU64DmZCrCBNITcRHRoiyjDYzFptw2eLJiU8uXIhwIDHO1cYKkrAYWBlW5dAYrL6okq9LKOrTOvi0Tnzyns8wBlpCSWEc3EplkUUSmV5mWpxDQ8Aen51FYKS+wHSEHMMyRN9MZ6IxhYrjgyLqI1FUGAnqs0JVXUCJJswvZEbvj+sOpMDvp5GfiwAYBKILN6rOs1DkN8oMD4MkHO6P/O6LZw/t+ht3eS16AA5wHrgCjKJ6gjiMjDc84WITQDD/nX8hpMPF6CmzM+FJcshHg97nzTcvv/zFa+/e3Huofng7gZ7uH68Pxit3ODmdYujpJRUNS6MP5SAB2RcjPehH88/Kv/aoJhbzCYr5XSOyZ6xmF0SYSzRm1xbLOxhDXKEWsCw/cZgIqeJRrPSao0gZ4yJS1EYn2Z5LS5RFENKfZDmfwsQyZMsapg2lrYQqUFE+txDZ+rJRhIEoVCsg3dEYAOIAVurJjBnVmQ5uxEQ7JA8z2CHXF1MFt5i2y5WqWiv9a4V4jUhV8knQqCF+igtkCgKMozaCTgmJRUq3Gf728yZzAFBUtY0jNWTaAph5LOhkogHZEjFzoIr4nMsYIXGaxvJDeG38mDfzEQ/8e0gK/SREJY0UMyWFJhz9awKKGUnzv3IhPJFO/OlFEMwfSsTIwa8nNA81+GhpDHilqUAZF2ihgTAZSYiMwiFGQQDGWH4IqDZ9xixKMYRtoHj812dbTiiAExl9rh8HoRMZKfRImsiRIbj1mZeTACKHpSguimnd1TrWMhbAXQhW6CAKHP28klZLkUGQIgV/M4FcMU4Luoo4VAW09EPhJAHUU7OGegQdSmzKr4SYIhcSYgpFWYTKQFJ606qfQD6TAfCouoo4wA+RA0I92cUEHQF3ThMAFXARmLKYaap4TJRjXEscRCAR1uYFlBIGhqWpJXw35OYD8lqncX5QVE9HQok15mgUP0KAkOafKPH0JN5hX0uIKwsEMYxQFVp8gCpjxqegIfoC4hxiAkvziQAKmihgEAAmft4Wgfjyb6iXACoY/dGgEBDifKQDp+qJBzABFQYMgEBJ8f9XnZpAnTP1yxGgMIBQAUQB0VEFUKV6lEagAgKOQlHnXw6NyZ7RT80qhCjgB6xipKk6hEwTJCxUsv29cEU5KQScqioAeYJf6qB+QTKBms93/OMDVSUhOIRBQUsvPxGBo4QDECM8VyHXURmj8VidUhELZT7xQFVRzQoDDGWlGUSsQBgFowa4SikGn4lYCEYBesAqothKpFLnWCQQ/nCkouIFBBCc4mLcmILFMHj9tKp+4IiOpI9LfdAUMhuQDgmdFQOEooBCCD0ICYqJSgb0nJB+t1ha8EMcSDSFcDcdGNCxgGR5GlZiWOVLEYTg3PkLsVRcVAhdyn00FZxT1BLqzQzLFgvwGpLBW1EwhPoOvjDkZ3wtcVe/so73xhtHfXZxOLoLX6M53Lz8wbPnl3b6lWAg7iucMx9kSfhRJCQwzQMxWkFdqhcRMWCMCwWgQIhQ6AO6kUKqc2o5AguVpPF0nzcv3PDRxcOX7v40tW0F4enxxvmaOYZknWOiTYsJ76RWcWPr/2LG25mCEilHi4GKTHeQelFpXhXKDIjLiOc0MfDvsieVNOlHVVEhxbdzilTKIuO6rqm4XeFDBa6yRnbV2RVj8U6gvl0ubgxrWHFJaQuK+jNnFYjJ5ZeDgbPhgRoXzuefaj75jpeBiMwKBv62jarplTYenTtAXeYIQgPLBIGWgEhewWTgzUHCDjtv/kUPd2KJFYYQixQwkXqEVBUoq1CB9pBZJT44YIm05kqyv550SsT0V8N9RpXXh5w/1nFlwlIpCiEx0SguL8zi/vdRFbKBirKMFK8kzNdnaZJ/WkpUBDXliOo0BpCYILVh7CBjwfBVDhSwvGr5JUQmASp6mWZoHtWbrcQUemZV0ui+ZD7ya4yrBtmwzoOrV2MIV4XZhBMTGFZcMJb8xkQ0yGLine truncated
|
||||
|
After Width: | Height: | Size: 155 KiB |
+568
@@ -0,0 +1,568 @@
|
||||
"""Inject deterministic branding chrome into generated HTML artifacts.
|
||||
|
||||
Generated page content is intentionally kept separate from this platform-owned
|
||||
header/footer. The post-processor supplies one compact single-page shell or a
|
||||
multi-page shell with reliable navigation, so model-authored layout choices do
|
||||
not decide whether the configured identity is visible or whether the first
|
||||
logical page renders.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html as html_lib
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CHROME_MARKER = "data-df-generated-chrome"
|
||||
HEADER_MARKER = "data-df-generated-header"
|
||||
FOOTER_MARKER = "data-df-generated-footer"
|
||||
NAV_MARKER = "data-df-generated-nav"
|
||||
DEFAULT_BRAND_LOGO_ASSET = "brand-logo-dark.png"
|
||||
|
||||
_OPEN_ELEMENT_RE = re.compile(r"<(?:section|article|div)\b[^>]*>", re.IGNORECASE)
|
||||
_NAV_BLOCK_RE = re.compile(r"<nav\b(?P<attrs>[^>]*)>(?P<body>[\s\S]*?)</nav>", re.IGNORECASE)
|
||||
_HEADING_RE = re.compile(r"<h[1-3]\b[^>]*>([\s\S]*?)</h[1-3]>", re.IGNORECASE)
|
||||
_TAG_RE = re.compile(r"<[^>]+>")
|
||||
_NON_CONTENT_RE = re.compile(
|
||||
r"<script\b[^>]*>[\s\S]*?</script>|<style\b[^>]*>[\s\S]*?</style>|<!--[\s\S]*?-->",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_BRAND_GROUP_RE = re.compile(
|
||||
r"<(?P<tag>[a-z][\w:-]*)\b(?=[^>]*\bdata-df-brand(?:\s|=|>))[^>]*>"
|
||||
r"[\s\S]*?</(?P=tag)\s*>",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_BRAND_SINGLE_RE = re.compile(
|
||||
r"<[a-z][\w:-]*\b(?=[^>]*\bdata-df-brand(?:\s|=|>))[^>]*/\s*>",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _LogicalPage:
|
||||
start: int
|
||||
end: int
|
||||
opening_tag: str
|
||||
page_id: str
|
||||
page_key: str
|
||||
label: str
|
||||
|
||||
|
||||
def _attribute(tag: str, name: str) -> str | None:
|
||||
match = re.search(
|
||||
rf"(?<![-\w]){re.escape(name)}\s*=\s*([\"'])(.*?)\1",
|
||||
tag,
|
||||
flags=re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
return html_lib.unescape(match.group(2).strip()) if match else None
|
||||
|
||||
|
||||
def _classes(tag: str) -> list[str]:
|
||||
return (_attribute(tag, "class") or "").split()
|
||||
|
||||
|
||||
def _set_attribute(tag: str, name: str, value: str) -> str:
|
||||
escaped = html_lib.escape(value, quote=True)
|
||||
pattern = re.compile(
|
||||
rf"(?<![-\w]){re.escape(name)}\s*=\s*([\"']).*?\1",
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
replacement = f'{name}="{escaped}"'
|
||||
if pattern.search(tag):
|
||||
return pattern.sub(replacement, tag, count=1)
|
||||
return tag[:-1].rstrip() + f" {replacement}>"
|
||||
|
||||
|
||||
def _remove_attribute(tag: str, name: str) -> str:
|
||||
return re.sub(
|
||||
rf"\s+(?<![-\w]){re.escape(name)}(?:\s*=\s*(?:[\"'][^\"']*[\"']|[^\s>]+))?",
|
||||
"",
|
||||
tag,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _safe_page_suffix(value: str, index: int) -> str:
|
||||
suffix = re.sub(r"[^a-z0-9_-]+", "-", value.strip().lower()).strip("-_")
|
||||
return suffix or str(index + 1)
|
||||
|
||||
|
||||
def _plain_text(markup: str) -> str:
|
||||
clean = _NON_CONTENT_RE.sub(" ", markup)
|
||||
clean = _TAG_RE.sub(" ", clean)
|
||||
return re.sub(r"\s+", " ", html_lib.unescape(clean)).strip()
|
||||
|
||||
|
||||
def _short_label(value: str, index: int) -> str:
|
||||
normalized = re.sub(r"\s+", " ", value).strip() or f"第 {index + 1} 页"
|
||||
return normalized if len(normalized) <= 18 else normalized[:17].rstrip() + "…"
|
||||
|
||||
|
||||
def _logical_pages(html: str) -> list[_LogicalPage]:
|
||||
candidates: list[re.Match[str]] = []
|
||||
for match in _OPEN_ELEMENT_RE.finditer(html):
|
||||
tag = match.group(0)
|
||||
if "page" not in _classes(tag) or _attribute(tag, "data-page") is None:
|
||||
continue
|
||||
candidates.append(match)
|
||||
|
||||
used_ids: set[str] = set()
|
||||
pages: list[_LogicalPage] = []
|
||||
for index, match in enumerate(candidates):
|
||||
tag = match.group(0)
|
||||
page_key = _attribute(tag, "data-page") or str(index + 1)
|
||||
requested_id = _attribute(tag, "id") or ""
|
||||
page_id = requested_id if requested_id.startswith("page-") else f"page-{_safe_page_suffix(page_key, index)}"
|
||||
base_id = page_id
|
||||
serial = 2
|
||||
while page_id in used_ids:
|
||||
page_id = f"{base_id}-{serial}"
|
||||
serial += 1
|
||||
used_ids.add(page_id)
|
||||
|
||||
next_start = candidates[index + 1].start() if index + 1 < len(candidates) else len(html)
|
||||
chunk = html[match.end() : next_start]
|
||||
explicit_label = _attribute(tag, "data-page-title") or _attribute(tag, "aria-label")
|
||||
heading = _HEADING_RE.search(chunk)
|
||||
inferred_label = _plain_text(heading.group(1)) if heading else page_key.replace("-", " ")
|
||||
label = _short_label(explicit_label or inferred_label, index)
|
||||
pages.append(
|
||||
_LogicalPage(
|
||||
start=match.start(),
|
||||
end=match.end(),
|
||||
opening_tag=tag,
|
||||
page_id=page_id,
|
||||
page_key=page_key,
|
||||
label=label,
|
||||
)
|
||||
)
|
||||
return pages
|
||||
|
||||
|
||||
def _prepare_logical_pages(html: str, pages: list[_LogicalPage]) -> str:
|
||||
replacements: list[tuple[int, int, str]] = []
|
||||
for index, page in enumerate(pages):
|
||||
tag = _set_attribute(page.opening_tag, "id", page.page_id)
|
||||
tag = _set_attribute(tag, "data-df-page-title", page.label)
|
||||
classes = [item for item in _classes(tag) if item not in {"active", "is-active", "df-page-active"}]
|
||||
if index == 0:
|
||||
classes.extend(["active", "is-active", "df-page-active"])
|
||||
tag = _remove_attribute(tag, "hidden")
|
||||
tag = _set_attribute(tag, "aria-hidden", "false")
|
||||
else:
|
||||
tag = _remove_attribute(tag, "hidden")
|
||||
tag = tag[:-1].rstrip() + " hidden>"
|
||||
tag = _set_attribute(tag, "aria-hidden", "true")
|
||||
tag = _set_attribute(tag, "class", " ".join(dict.fromkeys(classes)))
|
||||
replacements.append((page.start, page.end, tag))
|
||||
|
||||
for start, end, replacement in reversed(replacements):
|
||||
html = html[:start] + replacement + html[end:]
|
||||
return html
|
||||
|
||||
|
||||
def _hide_replaced_page_navigation(html: str, page_ids: set[str]) -> str:
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
attrs = match.group("attrs")
|
||||
if NAV_MARKER in attrs or "data-df-replaced-page-nav" in attrs:
|
||||
return match.group(0)
|
||||
targets = set(
|
||||
re.findall(r"\bhref\s*=\s*[\"']#(page-[^\"']+)[\"']", match.group("body"), flags=re.IGNORECASE)
|
||||
)
|
||||
if len(targets & page_ids) < 2:
|
||||
return match.group(0)
|
||||
opening = f'<nav{attrs} data-df-replaced-page-nav hidden aria-hidden="true">'
|
||||
return opening + match.group("body") + "</nav>"
|
||||
|
||||
return _NAV_BLOCK_RE.sub(replace, html)
|
||||
|
||||
|
||||
def _strip_authored_brand_groups(html: str) -> str:
|
||||
return _BRAND_SINGLE_RE.sub("", _BRAND_GROUP_RE.sub("", html))
|
||||
|
||||
|
||||
def _html_runtime_asset_url(filename: str) -> str:
|
||||
"""Return a browser URL for one packaged HTML runtime asset."""
|
||||
|
||||
from deerflow.html_runtime.addresses import html_runtime_base_url
|
||||
|
||||
runtime_base = html_runtime_base_url().rstrip("/")
|
||||
return f"{runtime_base}/{filename}" if runtime_base else f"/api/public/html-runtime/{filename}"
|
||||
|
||||
|
||||
def _brand_markup(system_name: str | None, logo_url: str | None, *, footer: bool = False) -> str:
|
||||
label = html_lib.escape(system_name or "网页标识")
|
||||
logo = ""
|
||||
if logo_url:
|
||||
fallback_url = html_lib.escape(_html_runtime_asset_url(DEFAULT_BRAND_LOGO_ASSET), quote=True)
|
||||
logo = (
|
||||
f'<img class="df-generated-brand__logo" src="{html_lib.escape(logo_url, quote=True)}" '
|
||||
f'data-df-fallback-src="{fallback_url}" alt="{label} Logo" '
|
||||
"onerror=\"if(this.dataset.dfLogoFallback!=='1'){this.dataset.dfLogoFallback='1';"
|
||||
"this.src=this.dataset.dfFallbackSrc;}else{this.hidden=true;}\">"
|
||||
)
|
||||
divider = '<i class="df-generated-brand__divider" aria-hidden="true"></i>' if system_name and logo_url else ""
|
||||
name = f'<span class="df-generated-brand__name">{label}</span>' if system_name else ""
|
||||
marker = "data-df-brand-footer" if footer else "data-df-brand"
|
||||
return f'<div class="df-generated-brand" {marker}>{logo}{divider}{name}</div>'
|
||||
|
||||
|
||||
def _navigation_markup(pages: list[_LogicalPage], *, extra_class: str = "", mark_first: bool = True) -> str:
|
||||
links = []
|
||||
for index, page in enumerate(pages):
|
||||
current = ' aria-current="page"' if (index == 0 and mark_first) else ""
|
||||
links.append(
|
||||
f'<a class="df-generated-nav__link" href="#{html_lib.escape(page.page_id, quote=True)}"'
|
||||
f'{current}>{html_lib.escape(page.label)}</a>'
|
||||
)
|
||||
return (
|
||||
f'<nav class="df-generated-nav{extra_class}" {NAV_MARKER} aria-label="页面导航">'
|
||||
+ "".join(links)
|
||||
+ "</nav>"
|
||||
)
|
||||
|
||||
|
||||
def _style_markup() -> str:
|
||||
runtime_base = _html_runtime_asset_url("").rstrip("/")
|
||||
return f"""<style {CHROME_MARKER}>
|
||||
:root{{--df-generated-header-height:64px}}
|
||||
/* 顶栏背景:跟随明暗 tone 切换全量模式导航栏设计图(浅色红调 / 深色深蓝),
|
||||
设计图自带中央发光基座,品牌锁孔居中落在基座上,文字恒白。 */
|
||||
.df-generated-header{{--df-chrome-bg:rgba(255,255,255,.8);--df-chrome-fg:#fff;--df-chrome-muted:rgba(255,255,255,.78);--df-chrome-dim:rgba(255,255,255,.55);--df-chrome-border:rgba(154,174,210,.35);--df-chrome-accent:#fff;--df-chrome-accent-2:rgba(255,255,255,.55);--df-chrome-topbar:url("{runtime_base}/topbar-light.svg");--df-chrome-glow:rgba(161,32,24,.38);box-sizing:border-box;color:var(--df-chrome-fg);font-family:inherit}}
|
||||
.df-generated-header[data-df-tone="dark"]{{--df-chrome-bg:rgba(7,19,45,.86);--df-chrome-muted:rgba(255,255,255,.78);--df-chrome-dim:rgba(255,255,255,.55);--df-chrome-border:rgba(38,100,200,.4);--df-chrome-topbar:url("{runtime_base}/topbar-dark.svg");--df-chrome-glow:rgba(120,200,255,.4)}}
|
||||
.df-generated-header{{position:sticky;top:0;z-index:1000;width:100%;margin:0;
|
||||
background:var(--df-chrome-topbar) center/cover no-repeat var(--df-chrome-bg);
|
||||
border-bottom:1px solid var(--df-chrome-border)}}
|
||||
.df-generated-header__inner{{width:100%;min-height:64px;margin:0 auto;padding:0 clamp(20px,3vw,44px);
|
||||
display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:12px}}
|
||||
/* —— 品牌锁孔:Logo + 系统名称(白色金属渐变字,落在中央基座上) —— */
|
||||
.df-generated-brand{{display:inline-flex;align-items:center;gap:10px;min-width:0;white-space:nowrap;justify-self:start}}
|
||||
.df-generated-brand__logo{{display:block;width:auto;height:35px;max-width:168px;object-fit:contain;flex:none;position:relative;top:-1px}}
|
||||
.df-generated-brand__divider{{display:none}}
|
||||
.df-generated-brand__name{{overflow:hidden;text-overflow:ellipsis;
|
||||
font-family:"Source Han Sans SC","Noto Sans SC","Noto Sans S Chinese","Microsoft YaHei",sans-serif;
|
||||
font-size:26px;font-weight:700;letter-spacing:4px;line-height:1;
|
||||
background:linear-gradient(180deg,#fff 0%,#f3f7ff 49%,#fff 89%);-webkit-background-clip:text;background-clip:text;
|
||||
-webkit-text-fill-color:transparent;color:transparent;
|
||||
filter:drop-shadow(0 0 12px var(--df-chrome-glow))}}
|
||||
/* 单页(无导航):品牌落到中央基座 */
|
||||
.df-generated-header--single .df-generated-header__inner{{display:flex;justify-content:center}}
|
||||
.df-generated-header--single .df-generated-brand{{transform:translateY(-2px)}}
|
||||
/* —— 导航:居中,通栏等高下划线式页签 —— */
|
||||
.df-generated-nav{{display:flex;align-items:stretch;align-self:stretch;justify-content:center;gap:6px;min-width:0;
|
||||
overflow-x:auto;scrollbar-width:none}}
|
||||
.df-generated-nav::-webkit-scrollbar{{display:none}}
|
||||
.df-generated-nav__link{{position:relative;display:inline-flex;align-items:center;flex:none;height:100%;
|
||||
padding:0 22px;color:var(--df-chrome-muted);font-size:15px;font-weight:550;letter-spacing:.13em;
|
||||
line-height:1.2;text-decoration:none;white-space:nowrap;transition:color .2s ease}}
|
||||
.df-generated-nav__link::after{{content:"";position:absolute;right:22px;bottom:0;left:22px;height:4px;border-radius:4px 4px 0 0;
|
||||
background:linear-gradient(90deg,var(--df-chrome-accent),var(--df-chrome-accent-2));transform:scaleX(0);transform-origin:center;
|
||||
transition:transform .28s cubic-bezier(.3,.9,.3,1)}}
|
||||
.df-generated-nav__link:hover{{color:var(--df-chrome-fg)}}
|
||||
.df-generated-nav__link:hover::after{{transform:scaleX(.45)}}
|
||||
.df-generated-nav__link:focus-visible{{outline:2px solid var(--df-chrome-accent);outline-offset:-4px}}
|
||||
.df-generated-nav__link[aria-current="page"]{{color:var(--df-chrome-accent);font-weight:700}}
|
||||
.df-generated-nav__link[aria-current="page"]::after{{transform:scaleX(1)}}
|
||||
/* —— 布局 B(center,默认):品牌落在中央基座 + 导航分列两侧 —— */
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-header__inner{{height:64px;min-height:64px;
|
||||
grid-template-columns:1fr auto 1fr;gap:8px 24px;padding:0 26px}}
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-brand{{grid-column:2;grid-row:1;justify-self:center;transform:translateY(-2px)}}
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-nav--l{{grid-column:1;grid-row:1;justify-content:flex-end}}
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-nav--r{{grid-column:3;grid-row:1;justify-content:flex-start}}
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-nav__link{{padding:0 18px;letter-spacing:.14em}}
|
||||
[data-df-replaced-page-nav]{{display:none!important}}
|
||||
@media (max-width:900px){{
|
||||
.df-generated-header__inner{{min-height:58px;grid-template-columns:1fr auto;grid-template-rows:auto auto;padding:0 6px;row-gap:0}}
|
||||
.df-generated-brand{{grid-row:1;grid-column:1;padding:6px 0}}
|
||||
.df-generated-nav{{grid-row:2;grid-column:1 / -1;align-self:stretch;justify-content:flex-start;margin:0 -6px}}
|
||||
.df-generated-nav__link{{height:52px;padding:0 16px;letter-spacing:.08em}}
|
||||
.df-generated-nav__link::after{{right:14px;left:14px}}
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-header__inner{{display:flex;flex-wrap:wrap;height:auto;min-height:0;justify-content:center;padding-top:6px}}
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-brand{{order:1;flex-basis:100%;justify-content:center;justify-self:auto;grid-column:auto;grid-row:auto;padding:4px 0 0}}
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-nav--l,
|
||||
.df-generated-header[data-df-chrome-layout="center"] .df-generated-nav--r{{order:2;flex:1 1 auto;justify-content:center;grid-column:auto;grid-row:auto}}
|
||||
}}
|
||||
@media (max-width:560px){{
|
||||
.df-generated-header__inner{{padding:0 14px}}
|
||||
.df-generated-brand__logo{{height:30px;max-width:128px}}
|
||||
.df-generated-brand__name{{font-size:15.5px}}
|
||||
.df-generated-brand__divider{{height:18px}}
|
||||
.df-generated-nav__link{{height:48px;padding:0 13px;font-size:14px;letter-spacing:.03em}}
|
||||
}}
|
||||
@media (prefers-reduced-motion:reduce){{.df-generated-nav__link{{transition:none}}.df-generated-nav__link::after{{transition:none}}}}
|
||||
</style>"""
|
||||
|
||||
|
||||
def _script_markup(first_page_id: str, *, multi_page: bool) -> str:
|
||||
multi_value = "true" if multi_page else "false"
|
||||
return f"""<script {CHROME_MARKER}>(function(){{
|
||||
var multi={multi_value};
|
||||
var header=document.querySelector('[{HEADER_MARKER}]');
|
||||
function syncHeaderHeight(){{
|
||||
if(!header)return;
|
||||
var height=Math.max(0,Math.ceil(header.getBoundingClientRect().height));
|
||||
document.documentElement.style.setProperty('--df-generated-header-height',height+'px');
|
||||
}}
|
||||
function tone(){{
|
||||
var rootTheme=((document.documentElement.getAttribute('data-theme')||document.documentElement.getAttribute('data-df-theme')||document.body.getAttribute('data-theme')||document.body.getAttribute('data-df-theme')||'')+'').toLowerCase();
|
||||
var color=window.getComputedStyle(document.body).backgroundColor;
|
||||
var parts=color.match(/[\\d.]+/g)||[];
|
||||
if(parts.length>3&&Number(parts[3])===0){{
|
||||
color=window.getComputedStyle(document.documentElement).backgroundColor;
|
||||
parts=color.match(/[\\d.]+/g)||[];
|
||||
}}
|
||||
var transparent=parts.length>3&&Number(parts[3])===0;
|
||||
var dark=rootTheme.indexOf('dark')>=0||(!transparent&&parts.length>=3&&(.2126*Number(parts[0])+.7152*Number(parts[1])+.0722*Number(parts[2]))<118);
|
||||
if(header)header.setAttribute('data-df-tone',dark?'dark':'light');
|
||||
}}
|
||||
function showPage(id){{
|
||||
if(!multi)return;
|
||||
var pages=document.querySelectorAll('.page[data-page]');
|
||||
var target=document.getElementById(id)||document.getElementById('{html_lib.escape(first_page_id, quote=True)}')||pages[0];
|
||||
if(!target)return;
|
||||
for(var i=0;i<pages.length;i++){{
|
||||
var active=pages[i]===target;
|
||||
pages[i].hidden=!active;
|
||||
pages[i].setAttribute('aria-hidden',active?'false':'true');
|
||||
pages[i].classList.toggle('active',active);
|
||||
pages[i].classList.toggle('is-active',active);
|
||||
pages[i].classList.toggle('df-page-active',active);
|
||||
if(active){{
|
||||
pages[i].style.removeProperty('display');
|
||||
if(window.getComputedStyle(pages[i]).display==='none')pages[i].style.setProperty('display','block','important');
|
||||
}}else{{
|
||||
pages[i].style.setProperty('display','none','important');
|
||||
}}
|
||||
}}
|
||||
var links=document.querySelectorAll('[{NAV_MARKER}] a[href^="#"]');
|
||||
for(var j=0;j<links.length;j++){{
|
||||
if(links[j].getAttribute('href')==='#'+target.id)links[j].setAttribute('aria-current','page');
|
||||
else links[j].removeAttribute('aria-current');
|
||||
}}
|
||||
document.body.setAttribute('data-df-active-page',target.id);
|
||||
try{{window.dispatchEvent(new Event('resize'));window.dispatchEvent(new CustomEvent('deerflow:page-change',{{detail:{{pageId:target.id}}}}));}}catch(error){{}}
|
||||
}}
|
||||
if(header)header.addEventListener('click',function(event){{
|
||||
var link=event.target.closest?event.target.closest('[{NAV_MARKER}] a[href^="#"]'):null;
|
||||
if(!link||!header.contains(link))return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
showPage(link.getAttribute('href').slice(1));
|
||||
if(window.scrollTo)window.scrollTo({{top:0,behavior:window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth'}});
|
||||
}},true);
|
||||
function init(){{syncHeaderHeight();tone();if(multi)showPage((window.location.hash||'').slice(1)||'{html_lib.escape(first_page_id, quote=True)}');}}
|
||||
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
|
||||
if(header&&window.ResizeObserver)new ResizeObserver(syncHeaderHeight).observe(header);
|
||||
window.addEventListener('hashchange',function(){{showPage((window.location.hash||'').slice(1));}});
|
||||
window.addEventListener('resize',function(){{syncHeaderHeight();tone();}});
|
||||
}})();</script>"""
|
||||
|
||||
|
||||
_BODY_TOP_SPACING_RE = re.compile(
|
||||
r"(padding|margin)-top\s*:\s*([0-9]+(?:\.[0-9]+)?)(?:px|rem|em|vh|vw|%)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_BODY_TOP_SHORTHAND_RE = re.compile(
|
||||
r"(padding|margin)\s*:\s*([0-9]+(?:\.[0-9]+)?)(?:px|rem|em|vh|vw|%)\s+",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_BODY_RULE_RE = re.compile(
|
||||
r"(?P<prefix>^|[}>{])(?P<spacing>\s*)"
|
||||
r"(?P<selector>(?:html\s*,\s*)?body)\s*\{(?P<block>[^{}]*)\}",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_body_top_spacing(html: str) -> str:
|
||||
"""Zero the top padding/margin on html/body so the sticky header hugs the top.
|
||||
|
||||
Models routinely write ``body { padding: 48px 0 }`` to clear their own
|
||||
header; with the platform header injected that leaves a colored gap above
|
||||
it. Only html/body rules are touched — inner wrappers keep their spacing.
|
||||
"""
|
||||
|
||||
def fix_rule(match: re.Match[str]) -> str:
|
||||
block = match.group("block")
|
||||
fixed = _BODY_TOP_SPACING_RE.sub(
|
||||
lambda m: f"{m.group(1)}-top: 0" if float(m.group(2)) > 0 else m.group(0),
|
||||
block,
|
||||
)
|
||||
fixed = _BODY_TOP_SHORTHAND_RE.sub(lambda m: f"{m.group(1)}: 0 ", fixed)
|
||||
if fixed == block:
|
||||
return match.group(0)
|
||||
# The prefix is a real CSS delimiter: it may be the closing brace of
|
||||
# the previous rule or the opening brace of an enclosing @media block.
|
||||
# Dropping it makes responsive declarations leak into the desktop
|
||||
# layout (for example the X mobile navigation becomes globally active).
|
||||
return (
|
||||
f'{match.group("prefix")}{match.group("spacing")}'
|
||||
f'{match.group("selector")}{{{fixed}}}'
|
||||
)
|
||||
|
||||
return _BODY_RULE_RE.sub(lambda m: fix_rule(m), html)
|
||||
|
||||
|
||||
def _hide_authored_top_navigation(html: str) -> str:
|
||||
"""Hide model-authored top navs that clash with the injected header.
|
||||
|
||||
Only ``nav``/``header`` blocks located BEFORE the first real content
|
||||
container (main/div/section/h1) are treated as top bars; navigation
|
||||
nested inside the content stays untouched.
|
||||
"""
|
||||
|
||||
body_open = re.search(r"<body\b[^>]*>", html, flags=re.IGNORECASE)
|
||||
body_close = re.search(r"</body\s*>", html, flags=re.IGNORECASE)
|
||||
if body_open is None or body_close is None:
|
||||
return html
|
||||
head = html[: body_open.end()]
|
||||
body = html[body_open.end() : body_close.start()]
|
||||
tail = html[body_close.start() :]
|
||||
|
||||
content_start = re.search(r"<(?:main|div|section|h1)\b", body, flags=re.IGNORECASE)
|
||||
top_zone_end = content_start.start() if content_start else min(len(body), 1500)
|
||||
top_zone = body[:top_zone_end]
|
||||
rest = body[top_zone_end:]
|
||||
|
||||
def hide(match: re.Match[str]) -> str:
|
||||
tag, attrs, inner = match.group("tag"), match.group("attrs"), match.group("body")
|
||||
if NAV_MARKER in attrs or "data-df-replaced-page-nav" in attrs:
|
||||
return match.group(0)
|
||||
if "<a" not in inner.lower():
|
||||
return match.group(0)
|
||||
# body 直属 header 只有在包含导航时才视为顶栏,避免误伤主视觉 hero。
|
||||
if tag.lower() == "header" and "<nav" not in inner.lower():
|
||||
return match.group(0)
|
||||
opening = f'<{tag}{attrs} data-df-replaced-page-nav hidden aria-hidden="true">'
|
||||
return opening + inner + f"</{tag}>"
|
||||
|
||||
pattern = re.compile(
|
||||
r"<(?P<tag>nav|header)\b(?P<attrs>[^>]*)>(?P<body>[\s\S]*?)</(?P=tag)>",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
top_zone = pattern.sub(hide, top_zone)
|
||||
return head + top_zone + rest + tail
|
||||
|
||||
|
||||
def apply_generated_page_chrome(
|
||||
html: str,
|
||||
*,
|
||||
system_name: str | None,
|
||||
logo_url: str | None,
|
||||
footer_text: str | None = None,
|
||||
header_layout: str = "center",
|
||||
allow_text_only: bool = False,
|
||||
) -> tuple[str, list[str]]:
|
||||
"""Return HTML with exactly one platform-owned brand header (no footer).
|
||||
|
||||
``allow_text_only`` deliberately defaults to ``False`` for backwards
|
||||
compatibility: a saved name without a custom logo used to mean an
|
||||
incomplete draft. Only the explicit "hide logo" setting opts into a
|
||||
text-only header.
|
||||
"""
|
||||
|
||||
name = (system_name or "").strip() or None
|
||||
logo = (logo_url or "").strip() or None
|
||||
brand_layout = str(header_layout or "").strip().lower()
|
||||
if brand_layout not in {"left", "center"}:
|
||||
brand_layout = "center"
|
||||
if not html or not name or not (logo or allow_text_only):
|
||||
return html, []
|
||||
notes: list[str] = []
|
||||
fixed = _normalize_body_top_spacing(html)
|
||||
if fixed != html:
|
||||
notes.append("已重置页面顶部内边距,页头贴顶")
|
||||
if CHROME_MARKER in fixed:
|
||||
return fixed, notes
|
||||
body_open = re.search(r"<body\b[^>]*>", fixed, flags=re.IGNORECASE)
|
||||
body_close = re.search(r"</body\s*>", fixed, flags=re.IGNORECASE)
|
||||
if body_open is None or body_close is None or body_close.start() <= body_open.end():
|
||||
return fixed, notes
|
||||
|
||||
fixed = _strip_authored_brand_groups(fixed)
|
||||
fixed = _hide_authored_top_navigation(fixed)
|
||||
pages = _logical_pages(fixed)
|
||||
multi_page = len(pages) >= 2
|
||||
if multi_page:
|
||||
fixed = _prepare_logical_pages(fixed, pages)
|
||||
pages = _logical_pages(fixed)
|
||||
fixed = _hide_replaced_page_navigation(fixed, {page.page_id for page in pages})
|
||||
|
||||
style = _style_markup()
|
||||
head_close = re.search(r"</head\s*>", fixed, flags=re.IGNORECASE)
|
||||
if head_close:
|
||||
fixed = fixed[: head_close.start()] + style + fixed[head_close.start() :]
|
||||
else:
|
||||
fixed = style + fixed
|
||||
|
||||
layout = "multi" if multi_page else "single"
|
||||
brand = _brand_markup(name, logo)
|
||||
if brand_layout == "center":
|
||||
# 居中品牌:导航分列两侧(参考大屏居中品牌模板),只保留 Logo + 系统名称。
|
||||
if multi_page:
|
||||
half = max(1, len(pages) // 2)
|
||||
nav_l = _navigation_markup(pages[:half], extra_class=" df-generated-nav--l")
|
||||
nav_r = _navigation_markup(pages[half:], extra_class=" df-generated-nav--r", mark_first=False)
|
||||
inner = f"{nav_l}{brand}{nav_r}"
|
||||
else:
|
||||
inner = brand
|
||||
else:
|
||||
nav = _navigation_markup(pages) if multi_page else ""
|
||||
inner = f"{brand}{nav}"
|
||||
header = (
|
||||
f'<header class="df-generated-header df-generated-header--{layout}" {HEADER_MARKER} '
|
||||
f'data-df-layout="{layout}" data-df-chrome-layout="{brand_layout}">'
|
||||
f'<div class="df-generated-header__inner">{inner}</div></header>'
|
||||
)
|
||||
body_open = re.search(r"<body\b[^>]*>", fixed, flags=re.IGNORECASE)
|
||||
assert body_open is not None
|
||||
fixed = fixed[: body_open.end()] + header + fixed[body_open.end() :]
|
||||
|
||||
first_page_id = pages[0].page_id if pages else ""
|
||||
script = _script_markup(first_page_id, multi_page=multi_page)
|
||||
body_close = re.search(r"</body\s*>", fixed, flags=re.IGNORECASE)
|
||||
assert body_close is not None
|
||||
fixed = fixed[: body_close.start()] + script + fixed[body_close.start() :]
|
||||
note = "已自动应用多页面品牌导航,并确保首页可见" if multi_page else "已自动应用单页面品牌页眉"
|
||||
return fixed, [*notes, note]
|
||||
|
||||
|
||||
def apply_configured_generated_page_chrome(html: str) -> tuple[str, list[str]]:
|
||||
"""Resolve the current admin configuration and inject it into new HTML."""
|
||||
|
||||
try:
|
||||
from deerflow.config.system_settings import generated_page_logo_public_url, load_system_settings
|
||||
from deerflow.html_runtime.addresses import html_runtime_base_url
|
||||
|
||||
branding = load_system_settings().generated_page_branding
|
||||
if not getattr(branding, "chrome_enabled", True):
|
||||
# Master switch off: the configured name/logo stay available to
|
||||
# template skills, but ordinary HTML keeps its normal output.
|
||||
return html, []
|
||||
logo_url = generated_page_logo_public_url(
|
||||
html_runtime_base_url(),
|
||||
branding,
|
||||
)
|
||||
return apply_generated_page_chrome(
|
||||
html,
|
||||
system_name=branding.system_name,
|
||||
logo_url=logo_url,
|
||||
footer_text=getattr(branding, "footer_text", None),
|
||||
header_layout=str(getattr(branding, "header_layout", "") or "center"),
|
||||
allow_text_only=getattr(branding, "logo_mode", "custom") == "none",
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("Could not apply configured generated-page chrome", exc_info=True)
|
||||
return html, []
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CHROME_MARKER",
|
||||
"FOOTER_MARKER",
|
||||
"HEADER_MARKER",
|
||||
"NAV_MARKER",
|
||||
"apply_configured_generated_page_chrome",
|
||||
"apply_generated_page_chrome",
|
||||
]
|
||||
+4
@@ -5,6 +5,8 @@ from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
|
||||
from deerflow.html_runtime.generated_page_chrome import apply_configured_generated_page_chrome
|
||||
|
||||
FIX_MARKER = "data-df-uploaded-bg-fix"
|
||||
_DARK_CONTRAST_FIX_MARKER = "data-df-dark-contrast-fix"
|
||||
_DARK_CHART_TEXT = "#e8f4ff"
|
||||
@@ -236,4 +238,6 @@ def apply_mechanical_html_fixes(path: str, html: str) -> tuple[str, list[str]]:
|
||||
def maybe_fix_generated_html(path: str, content: str) -> str:
|
||||
"""Apply safe generated-page fixes before the sandbox writes an HTML artifact."""
|
||||
fixed, _notes = apply_mechanical_html_fixes(path, content)
|
||||
if path.lower().endswith((".html", ".htm")):
|
||||
fixed, _branding_notes = apply_configured_generated_page_chrome(fixed)
|
||||
return fixed
|
||||
+10
@@ -30,6 +30,16 @@ _GREP_MAX_CANDIDATES = 500
|
||||
_GREP_MAX_RESULTS = 30
|
||||
_GREP_REGEX_TIMEOUT_SECONDS = 0.05
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _slow_diagnostic_threshold_ms() -> float:
|
||||
try:
|
||||
return max(0.0, min(float(os.getenv("DEERFLOW_SLOW_REQUEST_LOG_MS", "500")), 60_000.0))
|
||||
except (TypeError, ValueError):
|
||||
return 500.0
|
||||
|
||||
|
||||
|
||||
class WeKnoraError(RuntimeError):
|
||||
"""Normalized upstream failure that is safe for DeerFlow to translate."""
|
||||
|
||||
+9
@@ -35,6 +35,15 @@ logger = logging.getLogger(__name__)
|
||||
_EMBEDDING_PROVIDER_BACKOFF_INITIAL_SECONDS = 60.0
|
||||
_EMBEDDING_PROVIDER_BACKOFF_MAX_SECONDS = 30.0 * 60.0
|
||||
|
||||
# This breaker is intentionally process-local. The durable sync row already
|
||||
# records the failed run and error, while a transient retry deadline does not
|
||||
# belong in release files or administrator configuration. Rebuilding the
|
||||
# runtime after a provider/config change (or restarting Gateway) resets the
|
||||
# breaker and therefore allows one immediate recovery probe. The state is a
|
||||
# fixed-size provider record rather than a per-page/per-mapping collection.
|
||||
_EMBEDDING_PROVIDER_BACKOFF_INITIAL_SECONDS = 60.0
|
||||
_EMBEDDING_PROVIDER_BACKOFF_MAX_SECONDS = 30.0 * 60.0
|
||||
|
||||
|
||||
class WikiSyncLeaseLost(RuntimeError):
|
||||
pass
|
||||
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>经营分析门户 · 深色多页图表</title>
|
||||
<!--
|
||||
深色多页图表门户模板(Bootstrap + Alpine + ECharts 平台运行时)
|
||||
设计语言参考平台大屏汇报模板:深蓝光晕网格背景、角括号面板、发光数值、下划线式页签。
|
||||
1. 单个 HTML 内的轻量交互门户:.pages 容器 + 多个 .page[data-page] 逻辑页,锚点切页。
|
||||
2. 平台开启网页标识后,会自动注入品牌页眉、页脚与页面导航,并接管切页;模板自带的顶部导航会被隐藏替换。
|
||||
3. 图表使用 data-df-chart 严格 JSON;深色页每张图都要写齐可读的浅色文字。
|
||||
4. 按真实材料替换示例内容;示意数据必须保留「示意数据」标注。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/deerflow-runtime.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #060d1f;
|
||||
--panel: rgba(7, 19, 45, 0.74);
|
||||
--panel-strong: rgba(10, 26, 58, 0.92);
|
||||
--panel-line: rgba(38, 100, 200, 0.4);
|
||||
--ink: #d8ecff;
|
||||
--ink-soft: #9fb9dc;
|
||||
--ink-dim: #6f9bd0;
|
||||
--line: rgba(38, 100, 200, 0.32);
|
||||
--primary: #3fd6ff;
|
||||
--primary-soft: rgba(63, 214, 255, 0.08);
|
||||
--accent: #35e08c;
|
||||
--warn: #ffb03a;
|
||||
--corner: rgba(63, 214, 255, 0.75);
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background:
|
||||
radial-gradient(1200px 600px at 50% -10%, rgba(30, 90, 200, 0.26), transparent 60%),
|
||||
radial-gradient(900px 500px at 100% 100%, rgba(20, 160, 180, 0.12), transparent 55%),
|
||||
var(--page);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
/* 背景层:静态网格(低开销) */
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; opacity: 0.4;
|
||||
background-image:
|
||||
linear-gradient(rgba(60, 140, 255, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(60, 140, 255, 0.05) 1px, transparent 1px);
|
||||
background-size: 42px 42px;
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1240px); margin: 28px auto 56px; position: relative; z-index: 1; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
/* ===== 面板:深蓝 + 左上/右下角括号 ===== */
|
||||
.card {
|
||||
position: relative;
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--panel-line);
|
||||
border-radius: 12px;
|
||||
box-shadow: inset 0 0 30px rgba(20, 70, 160, 0.1);
|
||||
}
|
||||
.card::before, .card::after { content: ""; position: absolute; width: 14px; height: 14px; pointer-events: none; opacity: 0.9; }
|
||||
.card::before { left: -1px; top: -1px; border-left: 2px solid var(--corner); border-top: 2px solid var(--corner); border-top-left-radius: 12px; }
|
||||
.card::after { right: -1px; bottom: -1px; border-right: 2px solid var(--corner); border-bottom: 2px solid var(--corner); border-bottom-right-radius: 12px; }
|
||||
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
/* ===== 多页容器 ===== */
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
|
||||
/* ===== 内容卡 ===== */
|
||||
.section-card { padding: 24px 28px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 700; letter-spacing: 0.14em; color: #eaf6ff; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 4px; height: 16px; border-radius: 2px; flex: none;
|
||||
background: linear-gradient(180deg, var(--primary), #2f7bff);
|
||||
box-shadow: 0 0 9px rgba(63, 214, 255, 0.9);
|
||||
}
|
||||
.section-index { color: var(--ink-dim); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-desc { margin: 0 0 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
|
||||
/* ===== 指标卡(发光数值 + 趋势胶囊) ===== */
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-strong);
|
||||
border: 1px solid var(--panel-line); border-radius: 12px;
|
||||
transition: border-color 0.3s ease, box-shadow 0.3s ease;
|
||||
}
|
||||
.metric:hover { border-color: rgba(63, 214, 255, 0.7); box-shadow: 0 0 28px rgba(63, 214, 255, 0.18); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: #8fb4e2; font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: #5580b8; font-size: 12px; white-space: nowrap; }
|
||||
.metric:hover .metric-more { color: var(--primary); }
|
||||
.metric-value {
|
||||
margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: #ffffff;
|
||||
font-variant-numeric: tabular-nums; text-shadow: 0 0 20px rgba(63, 214, 255, 0.5);
|
||||
}
|
||||
.metric-value small { font-size: 16px; font-weight: 400; margin-left: 4px; color: #8fb4e2; }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim); font-size: 13px; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #7dffc4; background: rgba(53, 224, 140, 0.12); }
|
||||
.delta.down { color: #ffd07d; background: rgba(255, 176, 58, 0.12); }
|
||||
|
||||
.callout { padding: 18px 22px; border-left: 4px solid var(--primary); border-radius: 12px; background: var(--primary-soft); }
|
||||
.callout strong { display: block; margin-bottom: 6px; font-size: 17px; }
|
||||
.chart-box { width: 100%; }
|
||||
.chart-caption { margin: 10px 0 0; color: var(--ink-dim); font-size: 15px; }
|
||||
|
||||
/* ===== 表格 ===== */
|
||||
.data-table { width: 100%; border-collapse: collapse; background: transparent; color: var(--ink); }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: #9df1ff; background: var(--primary-soft); letter-spacing: 0.06em; }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.form-control { font-size: 16px; color: var(--ink); background: var(--panel-strong); border: 1px solid var(--line); }
|
||||
.filter-input { max-width: 320px; }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 10px; }
|
||||
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.section-card { padding: 20px 16px; }
|
||||
.portal-topbar { flex-wrap: wrap; padding: 10px 14px; }
|
||||
.portal-nav { margin-left: 0; flex-basis: 100%; }
|
||||
.portal-nav a { min-height: 48px; padding: 0 14px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.portal-nav a, .portal-nav a::after, .metric { transition: none; }
|
||||
}
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-overview" class="active">态势总览</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">经营分析门户(替换标题)</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-analysis">结构分析</a>
|
||||
<a href="#page-detail">明细数据</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-overview" data-page="overview" data-page-title="态势总览" aria-label="态势总览">
|
||||
<div class="card section-card">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标一(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">1,286<small>件</small></div>
|
||||
<div class="metric-foot"><span class="delta up">↑ 14.8%</span><span>较上期 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标二(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">+18.4<small>%</small></div>
|
||||
<div class="metric-foot"><span class="delta up">↑ 12.6%</span><span>同比增长 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标三(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">96.4<small>%</small></div>
|
||||
<div class="metric-foot"><span class="delta up">↑ 2.1%</span><span>较上期 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标四(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">328<small>件</small></div>
|
||||
<div class="metric-foot"><span class="delta down">↓ 8.6%</span><span>连续两期下降 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>总体态势</h2></div>
|
||||
<p class="section-desc">用两三句话概括本期整体表现、关键变化和需要关注的例外。</p>
|
||||
<div id="overview-trend" class="chart-box" style="height: 420px"></div>
|
||||
<script type="application/json" data-df-chart="overview-trend">
|
||||
{"title":{"text":"月度走势(示意数据,替换为真实口径)","left":"center","textStyle":{"color":"#e8f4ff"}},"textStyle":{"color":"#e8f4ff"},"tooltip":{"trigger":"axis","backgroundColor":"rgba(7,19,45,.94)","borderColor":"rgba(63,214,255,.4)","textStyle":{"color":"#e8f4ff"}},"legend":{"top":"bottom","textStyle":{"color":"#9fb9dc"}},"grid":{"left":16,"right":24,"top":56,"bottom":64,"containLabel":true},"xAxis":{"type":"category","boundaryGap":false,"data":["五月","六月","七月","八月","九月","十月"],"axisLabel":{"color":"#e8f4ff"},"splitLine":{"show":false}},"yAxis":[{"type":"value","name":"数量","nameTextStyle":{"color":"#9fb9dc"},"axisLabel":{"color":"#e8f4ff"},"splitLine":{"lineStyle":{"color":"rgba(38,100,200,.28)"}}},{"type":"value","name":"比率(%)","nameTextStyle":{"color":"#9fb9dc"},"axisLabel":{"color":"#e8f4ff"},"splitLine":{"show":false}}],"series":[{"name":"本期","type":"bar","barMaxWidth":26,"itemStyle":{"color":"#2f7bff","borderRadius":[6,6,0,0]},"data":[320,402,441,486,530,598]},{"name":"目标线","type":"line","yAxisIndex":1,"smooth":true,"symbolSize":8,"lineStyle":{"width":3,"color":"#3fd6ff"},"itemStyle":{"color":"#3fd6ff"},"data":[72,76,79,83,88,94]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 1 · 总览走势:柱为数量、线为达成率;替换数据时同步更新结论。</p>
|
||||
<div class="callout mt-3"><strong>本期结论</strong><span>写成一句完整的话,注明统计区间与数据来源。</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-analysis" data-page="analysis" data-page-title="结构分析" hidden aria-label="结构分析">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>构成与对比</h2></div>
|
||||
<p class="section-desc">说明划分口径;图表回答「占比如何、差距多大、能力如何」。</p>
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-6">
|
||||
<div id="category-bar" class="chart-box" style="height: 380px"></div>
|
||||
<script type="application/json" data-df-chart="category-bar">
|
||||
{"title":{"text":"类别对比(示意数据)","left":"center","textStyle":{"color":"#e8f4ff"}},"textStyle":{"color":"#e8f4ff"},"tooltip":{"trigger":"axis","axisPointer":{"type":"shadow"},"backgroundColor":"rgba(7,19,45,.94)","borderColor":"rgba(63,214,255,.4)","textStyle":{"color":"#e8f4ff"}},"grid":{"left":16,"right":24,"top":56,"bottom":32,"containLabel":true},"xAxis":{"type":"category","data":["类别一","类别二","类别三","类别四","类别五"],"axisLabel":{"color":"#e8f4ff"},"splitLine":{"show":false}},"yAxis":{"type":"value","name":"数量","nameTextStyle":{"color":"#9fb9dc"},"axisLabel":{"color":"#e8f4ff"},"splitLine":{"lineStyle":{"color":"rgba(38,100,200,.28)"}}},"series":[{"name":"本期","type":"bar","barMaxWidth":30,"itemStyle":{"color":"#2f7bff","borderRadius":[6,6,0,0]},"data":[486,317,205,148,92]},{"name":"上期","type":"bar","barMaxWidth":30,"itemStyle":{"color":"#3d5c9e","borderRadius":[6,6,0,0]},"data":[430,332,196,155,88]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 2 · 分组柱状图:本期与上期逐类对比。</p>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<div id="share-pie" class="chart-box" style="height: 380px"></div>
|
||||
<script type="application/json" data-df-chart="share-pie">
|
||||
{"title":{"text":"来源构成(示意数据)","left":"center","textStyle":{"color":"#e8f4ff"}},"textStyle":{"color":"#e8f4ff"},"tooltip":{"trigger":"item","backgroundColor":"rgba(7,19,45,.94)","borderColor":"rgba(63,214,255,.4)","textStyle":{"color":"#e8f4ff"}},"legend":{"top":"bottom","textStyle":{"color":"#9fb9dc"}},"series":[{"name":"来源","type":"pie","radius":["36%","64%"],"center":["50%","46%"],"label":{"color":"#e8f4ff","formatter":"{b} {d}%"},"data":[{"name":"来源一","value":42,"itemStyle":{"color":"#2f7bff"}},{"name":"来源二","value":26,"itemStyle":{"color":"#3fd6ff"}},{"name":"来源三","value":19,"itemStyle":{"color":"#ffb03a"}},{"name":"其他","value":13,"itemStyle":{"color":"#8b7bff"}}]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 3 · 环形图:来源占比按真实材料替换。</p>
|
||||
</div>
|
||||
<div class="col-lg-12">
|
||||
<div id="assess-radar" class="chart-box" style="height: 400px"></div>
|
||||
<script type="application/json" data-df-chart="assess-radar">
|
||||
{"title":{"text":"能力评估(示意数据)","left":"center","textStyle":{"color":"#e8f4ff"}},"textStyle":{"color":"#e8f4ff"},"tooltip":{"backgroundColor":"rgba(7,19,45,.94)","borderColor":"rgba(63,214,255,.4)","textStyle":{"color":"#e8f4ff"}},"legend":{"top":"bottom","textStyle":{"color":"#9fb9dc"}},"radar":{"indicator":[{"name":"覆盖","max":100},{"name":"时效","max":100},{"name":"质量","max":100},{"name":"成本","max":100},{"name":"协同","max":100}],"axisName":{"color":"#e8f4ff"},"splitLine":{"lineStyle":{"color":"rgba(38,100,200,.45)"}},"splitArea":{"show":false},"axisLine":{"lineStyle":{"color":"rgba(38,100,200,.45)"}}},"series":[{"name":"评估","type":"radar","symbolSize":6,"label":{"color":"#e8f4ff"},"areaStyle":{"opacity":0.2},"data":[{"name":"本期","value":[86,74,90,68,82],"lineStyle":{"width":3,"color":"#3fd6ff"},"itemStyle":{"color":"#3fd6ff"}},{"name":"上期","value":[78,70,83,72,74],"lineStyle":{"width":2,"color":"#35e08c"},"itemStyle":{"color":"#35e08c"}}]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 4 · 雷达图:两期能力对比,维度可按业务调整。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-detail" data-page="detail" data-page-title="明细数据" hidden aria-label="明细数据" x-data="{ query: '' }">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>明细数据</h2></div>
|
||||
<p class="section-desc">输入关键词即可过滤下表(Alpine 实现的轻量检索);列按结论需要增删。</p>
|
||||
<div class="mb-3">
|
||||
<input class="form-control filter-input" type="search" placeholder="输入关键词筛选,如:类别一" x-model="query" aria-label="筛选明细" />
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>项目</th><th>类别</th><th>数值</th><th>变化</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>示例项目一(替换)</td><td>类别一</td><td>486</td><td>+12.5%</td><td>关键结论支撑项</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>示例项目二(替换)</td><td>类别二</td><td>317</td><td>-3.8%</td><td>需关注下降原因</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>示例项目三(替换)</td><td>类别三</td><td>205</td><td>+6.2%</td><td>持续跟踪</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>第一条结论:判断 + 依据 + 适用条件。</li>
|
||||
<li>第二条结论:主要风险与所需支持。</li>
|
||||
<li>第三条建议:下一步动作与需补充的数据。</li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>经营分析门户 · 浅色多页图表</title>
|
||||
<!--
|
||||
浅色多页图表门户模板(Bootstrap + Alpine + ECharts 平台运行时)
|
||||
设计语言参考平台大屏汇报模板:玻璃面板、渐变数值、下划线式页签、光斑点阵背景。
|
||||
1. 单个 HTML 内的轻量交互门户:.pages 容器 + 多个 .page[data-page] 逻辑页,锚点切页。
|
||||
2. 平台开启网页标识后,会自动注入品牌页眉、页脚与页面导航,并接管切页;模板自带的顶部导航会被隐藏替换。
|
||||
3. 图表使用 data-df-chart 严格 JSON;禁止 echarts.init 与函数回调。
|
||||
4. 按真实材料替换示例内容;示意数据必须保留「示意数据」标注。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/deerflow-runtime.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #eef3fc;
|
||||
--panel: rgba(255, 255, 255, 0.72);
|
||||
--panel-line: rgba(255, 255, 255, 0.95);
|
||||
--panel-soft: rgba(240, 245, 253, 0.9);
|
||||
--ink: #1e2a4a;
|
||||
--ink-soft: #5d7095;
|
||||
--ink-dim: #8598b8;
|
||||
--line: rgba(154, 174, 210, 0.42);
|
||||
--primary: #4d6bf2;
|
||||
--primary-soft: rgba(77, 107, 242, 0.1);
|
||||
--accent: #17b3ae;
|
||||
--warn: #ec9b2f;
|
||||
--shadow: 0 16px 40px rgba(99, 125, 190, 0.15);
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: linear-gradient(160deg, #eef3fc 0%, #f6f4f0 55%, #eaf6f3 100%);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
/* 背景层:点阵 + 柔光斑(静态、低开销) */
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background-image: radial-gradient(rgba(90, 120, 190, 0.13) 1px, transparent 1.5px);
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
body::after {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background:
|
||||
radial-gradient(42vw 42vw at -10% -16%, rgba(146, 176, 255, 0.34), transparent 62%),
|
||||
radial-gradient(34vw 34vw at 112% 28%, rgba(255, 205, 224, 0.26), transparent 62%),
|
||||
radial-gradient(38vw 38vw at 45% 118%, rgba(152, 232, 216, 0.3), transparent 62%);
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1240px); margin: 28px auto 56px; position: relative; z-index: 1; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
/* ===== 玻璃面板 ===== */
|
||||
.card {
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--panel-line);
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--shadow), inset 0 1px 0 rgba(255, 255, 255, 0.95);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
/* ===== 多页容器 ===== */
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
|
||||
/* ===== 内容卡 ===== */
|
||||
.section-card { padding: 24px 28px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 800; letter-spacing: 0.14em; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 22px; height: 22px; border-radius: 7px; flex: none;
|
||||
background: linear-gradient(135deg, var(--primary), var(--accent));
|
||||
box-shadow: 0 5px 12px rgba(77, 107, 242, 0.3);
|
||||
}
|
||||
.section-index { color: var(--ink-dim); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-desc { margin: 0 0 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
|
||||
/* ===== 指标卡(渐变大数值 + 趋势胶囊) ===== */
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-soft);
|
||||
border: 1px solid var(--panel-line); border-radius: 14px;
|
||||
box-shadow: 0 8px 22px rgba(99, 125, 190, 0.1);
|
||||
transition: box-shadow 0.3s ease, transform 0.3s ease;
|
||||
}
|
||||
.metric:hover { box-shadow: 0 20px 44px rgba(99, 125, 190, 0.22); transform: translateY(-2px); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: var(--ink-soft); font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: var(--ink-dim); font-size: 12px; white-space: nowrap; }
|
||||
.metric-value {
|
||||
margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: var(--primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.metric-value small { font-size: 16px; font-weight: 600; margin-left: 4px; color: var(--ink-soft); }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim); font-size: 13px; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #0e9c8f; background: rgba(23, 179, 174, 0.14); }
|
||||
.delta.down { color: #cf6a15; background: rgba(236, 155, 47, 0.16); }
|
||||
|
||||
.callout { padding: 18px 22px; border-left: 4px solid var(--primary); border-radius: 12px; background: var(--primary-soft); }
|
||||
.callout strong { display: block; margin-bottom: 6px; font-size: 17px; }
|
||||
.chart-box { width: 100%; }
|
||||
.chart-caption { margin: 10px 0 0; color: var(--ink-dim); font-size: 15px; }
|
||||
|
||||
/* ===== 表格 ===== */
|
||||
.data-table { width: 100%; border-collapse: collapse; background: transparent; }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--primary-soft); letter-spacing: 0.06em; }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.form-control { font-size: 16px; color: var(--ink); background: var(--panel-soft); border: 1px solid var(--line); }
|
||||
.filter-input { max-width: 320px; }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 10px; }
|
||||
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.section-card { padding: 20px 16px; }
|
||||
.portal-topbar { flex-wrap: wrap; padding: 10px 14px; }
|
||||
.portal-nav { margin-left: 0; flex-basis: 100%; }
|
||||
.portal-nav a { min-height: 48px; padding: 0 14px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.portal-nav a, .portal-nav a::after, .metric { transition: none; }
|
||||
}
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-overview" class="active">态势总览</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">经营分析门户(替换标题)</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-analysis">结构分析</a>
|
||||
<a href="#page-detail">明细数据</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-overview" data-page="overview" data-page-title="态势总览" aria-label="态势总览">
|
||||
<div class="card section-card">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标一(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">1,286<small>件</small></div>
|
||||
<div class="metric-foot"><span class="delta up">↑ 14.8%</span><span>较上期 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标二(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">+18.4<small>%</small></div>
|
||||
<div class="metric-foot"><span class="delta up">↑ 12.6%</span><span>同比增长 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标三(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">92.6<small>%</small></div>
|
||||
<div class="metric-foot"><span class="delta up">↑ 3.8%</span><span>较上月 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="metric">
|
||||
<div class="metric-label"><span>指标四(替换)</span><span class="metric-more">口径说明 ↗</span></div>
|
||||
<div class="metric-value">37<small>项</small></div>
|
||||
<div class="metric-foot"><span class="delta down">↓ 21.7%</span><span>较年初 · 示意数据</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>总体态势</h2></div>
|
||||
<p class="section-desc">用两三句话概括本期整体表现、关键变化和需要关注的例外。</p>
|
||||
<div id="overview-trend" class="chart-box" style="height: 420px"></div>
|
||||
<script type="application/json" data-df-chart="overview-trend">
|
||||
{"title":{"text":"月度走势(示意数据,替换为真实口径)","left":"center","textStyle":{"color":"#2a3a5c"}},"textStyle":{"color":"#2a3a5c"},"tooltip":{"trigger":"axis","textStyle":{"color":"#2a3a5c"}},"legend":{"top":"bottom","textStyle":{"color":"#5d7095"}},"grid":{"left":16,"right":24,"top":56,"bottom":64,"containLabel":true},"xAxis":{"type":"category","boundaryGap":false,"data":["五月","六月","七月","八月","九月","十月"],"axisLabel":{"color":"#2a3a5c"},"splitLine":{"show":false}},"yAxis":[{"type":"value","name":"数量","nameTextStyle":{"color":"#5d7095"},"axisLabel":{"color":"#2a3a5c"},"splitLine":{"lineStyle":{"color":"rgba(154,174,210,.3)"}}},{"type":"value","name":"比率(%)","nameTextStyle":{"color":"#5d7095"},"axisLabel":{"color":"#2a3a5c"},"splitLine":{"show":false}}],"series":[{"name":"本期","type":"bar","barMaxWidth":26,"itemStyle":{"color":"#4d6bf2","borderRadius":[6,6,0,0]},"data":[320,402,441,486,530,598]},{"name":"目标线","type":"line","yAxisIndex":1,"smooth":true,"symbolSize":8,"lineStyle":{"width":3,"color":"#17b3ae"},"itemStyle":{"color":"#17b3ae"},"data":[72,76,79,83,88,94]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 1 · 总览走势:柱为数量、线为达成率;替换数据时同步更新结论。</p>
|
||||
<div class="callout mt-3"><strong>本期结论</strong><span>写成一句完整的话,注明统计区间与数据来源。</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-analysis" data-page="analysis" data-page-title="结构分析" hidden aria-label="结构分析">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>构成与对比</h2></div>
|
||||
<p class="section-desc">说明划分口径;图表回答「占比如何、差距多大、能力如何」。</p>
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-6">
|
||||
<div id="category-bar" class="chart-box" style="height: 380px"></div>
|
||||
<script type="application/json" data-df-chart="category-bar">
|
||||
{"title":{"text":"类别对比(示意数据)","left":"center","textStyle":{"color":"#2a3a5c"}},"textStyle":{"color":"#2a3a5c"},"tooltip":{"trigger":"axis","axisPointer":{"type":"shadow"},"textStyle":{"color":"#2a3a5c"}},"grid":{"left":16,"right":24,"top":56,"bottom":32,"containLabel":true},"xAxis":{"type":"category","data":["类别一","类别二","类别三","类别四","类别五"],"axisLabel":{"color":"#2a3a5c"},"splitLine":{"show":false}},"yAxis":{"type":"value","name":"数量","nameTextStyle":{"color":"#5d7095"},"axisLabel":{"color":"#2a3a5c"},"splitLine":{"lineStyle":{"color":"rgba(154,174,210,.3)"}}},"series":[{"name":"本期","type":"bar","barMaxWidth":30,"itemStyle":{"color":"#4d6bf2","borderRadius":[6,6,0,0]},"data":[486,317,205,148,92]},{"name":"上期","type":"bar","barMaxWidth":30,"itemStyle":{"color":"#9db4e8","borderRadius":[6,6,0,0]},"data":[430,332,196,155,88]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 2 · 分组柱状图:本期与上期逐类对比。</p>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<div id="share-pie" class="chart-box" style="height: 380px"></div>
|
||||
<script type="application/json" data-df-chart="share-pie">
|
||||
{"title":{"text":"来源构成(示意数据)","left":"center","textStyle":{"color":"#2a3a5c"}},"textStyle":{"color":"#2a3a5c"},"tooltip":{"trigger":"item","textStyle":{"color":"#2a3a5c"}},"legend":{"top":"bottom","textStyle":{"color":"#5d7095"}},"series":[{"name":"来源","type":"pie","radius":["36%","64%"],"center":["50%","46%"],"label":{"color":"#2a3a5c","formatter":"{b} {d}%"},"data":[{"name":"来源一","value":42,"itemStyle":{"color":"#4d6bf2"}},{"name":"来源二","value":26,"itemStyle":{"color":"#17b3ae"}},{"name":"来源三","value":19,"itemStyle":{"color":"#ec9b2f"}},{"name":"其他","value":13,"itemStyle":{"color":"#8b7cf6"}}]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 3 · 环形图:来源占比按真实材料替换。</p>
|
||||
</div>
|
||||
<div class="col-lg-12">
|
||||
<div id="assess-radar" class="chart-box" style="height: 400px"></div>
|
||||
<script type="application/json" data-df-chart="assess-radar">
|
||||
{"title":{"text":"能力评估(示意数据)","left":"center","textStyle":{"color":"#2a3a5c"}},"textStyle":{"color":"#2a3a5c"},"tooltip":{"textStyle":{"color":"#2a3a5c"}},"legend":{"top":"bottom","textStyle":{"color":"#5d7095"}},"radar":{"indicator":[{"name":"覆盖","max":100},{"name":"时效","max":100},{"name":"质量","max":100},{"name":"成本","max":100},{"name":"协同","max":100}],"axisName":{"color":"#2a3a5c"},"splitLine":{"lineStyle":{"color":"rgba(154,174,210,.45)"}},"splitArea":{"show":false},"axisLine":{"lineStyle":{"color":"rgba(154,174,210,.45)"}}},"series":[{"name":"评估","type":"radar","symbolSize":6,"label":{"color":"#2a3a5c"},"areaStyle":{"opacity":0.18},"data":[{"name":"本期","value":[86,74,90,68,82],"lineStyle":{"width":3,"color":"#4d6bf2"},"itemStyle":{"color":"#4d6bf2"}},{"name":"上期","value":[78,70,83,72,74],"lineStyle":{"width":2,"color":"#17b3ae"},"itemStyle":{"color":"#17b3ae"}}]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 4 · 雷达图:两期能力对比,维度可按业务调整。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-detail" data-page="detail" data-page-title="明细数据" hidden aria-label="明细数据" x-data="{ query: '' }">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>明细数据</h2></div>
|
||||
<p class="section-desc">输入关键词即可过滤下表(Alpine 实现的轻量检索);列按结论需要增删。</p>
|
||||
<div class="mb-3">
|
||||
<input class="form-control filter-input" type="search" placeholder="输入关键词筛选,如:类别一" x-model="query" aria-label="筛选明细" />
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>项目</th><th>类别</th><th>数值</th><th>变化</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>示例项目一(替换)</td><td>类别一</td><td>486</td><td>+12.5%</td><td>关键结论支撑项</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>示例项目二(替换)</td><td>类别二</td><td>317</td><td>-3.8%</td><td>需关注下降原因</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>示例项目三(替换)</td><td>类别三</td><td>205</td><td>+6.2%</td><td>持续跟踪</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>第一条结论:判断 + 依据 + 适用条件。</li>
|
||||
<li>第二条结论:主要风险与所需支持。</li>
|
||||
<li>第三条建议:下一步动作与需补充的数据。</li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>项目进度报告 · 深色甘特图</title>
|
||||
<!--
|
||||
深色甘特图单页模板(Bootstrap + ECharts 平台运行时)
|
||||
0. 本模板为双页轻量门户:.pages 容器 + 两个 .page[data-page] 逻辑页,锚点切页;最低页数 2。第 1 页:项目概况、关键指标与总体进度甘特图。第 2 页:里程碑计划、风险依赖与结论建议。
|
||||
1. 甘特图使用 data-df-chart 严格 JSON:时间轴 + 多个重叠柱系列(barGap:-100%)。
|
||||
2. 修改任务时同步调整 yAxis 任务名、各阶段系列的起止日期与「-」占位。
|
||||
3. 日期使用 YYYY-MM-DD 字符串;当前日期参考线按需更新。
|
||||
4. 按真实材料替换示例内容;示意数据必须保留「示意数据」标注;深色图表写齐浅色文字。
|
||||
5. 页面标识(系统名称 + Logo)由平台按系统设置自动注入页眉页脚,不要自己书写。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/deerflow-runtime.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #0c1526;
|
||||
--panel: #131f38;
|
||||
--panel-soft: #182a4a;
|
||||
--ink: #e9f2ff;
|
||||
--ink-soft: #a9bdd6;
|
||||
--line: rgba(128, 180, 255, 0.22);
|
||||
--primary: #7aa5ff;
|
||||
--primary-soft: #1c2c52;
|
||||
--accent: #3ad0c0;
|
||||
--warn: #f2b25c;
|
||||
--danger: #ff8a8a;
|
||||
--shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background:
|
||||
radial-gradient(1200px 600px at 50% -10%, rgba(30, 90, 200, 0.26), transparent 60%),
|
||||
radial-gradient(900px 500px at 100% 100%, rgba(20, 160, 180, 0.12), transparent 55%),
|
||||
var(--page);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; opacity: 0.4;
|
||||
background-image:
|
||||
linear-gradient(rgba(60, 140, 255, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(60, 140, 255, 0.05) 1px, transparent 1px);
|
||||
background-size: 42px 42px;
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1200px); margin: 28px auto 56px; }
|
||||
.card {
|
||||
position: relative;
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
box-shadow: inset 0 0 30px rgba(20, 70, 160, 0.1);
|
||||
}
|
||||
.card::before, .card::after { content: ""; position: absolute; width: 14px; height: 14px; pointer-events: none; opacity: 0.9; }
|
||||
.card::before { left: -1px; top: -1px; border-left: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-top: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-top-left-radius: 12px; }
|
||||
.card::after { right: -1px; bottom: -1px; border-right: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-bottom: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-bottom-right-radius: 12px; }
|
||||
.report-header { padding: 34px 36px; }
|
||||
.eyebrow { margin: 0 0 8px; color: var(--primary); font-weight: 700; letter-spacing: 0.08em; font-size: 16px; }
|
||||
h1 { margin: 0; font-size: clamp(30px, 4.2vw, 42px); line-height: 1.22; letter-spacing: -0.02em; }
|
||||
.lead { max-width: 860px; margin: 14px 0 0; color: var(--ink-soft); font-size: 17px; }
|
||||
.meta { display: flex; flex-wrap: wrap; gap: 8px 20px; margin-top: 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
.section-card { padding: 28px 30px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 700; letter-spacing: 0.14em; color: #eaf6ff; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 4px; height: 16px; border-radius: 2px; flex: none;
|
||||
background: linear-gradient(180deg, var(--primary), #2f7bff);
|
||||
box-shadow: 0 0 9px rgba(63, 214, 255, 0.9);
|
||||
}
|
||||
.section-index { color: var(--ink-dim, var(--ink-soft)); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-title h2 { margin: 0; font-size: 25px; }
|
||||
.section-index { color: var(--primary); font-weight: 800; font-size: 16px; }
|
||||
.section-desc { margin: 0 0 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-strong, var(--panel-soft));
|
||||
border: 1px solid var(--line); border-radius: 12px;
|
||||
transition: border-color 0.3s ease, box-shadow 0.3s ease;
|
||||
}
|
||||
.metric:hover { border-color: rgba(63, 214, 255, 0.7); box-shadow: 0 0 28px rgba(63, 214, 255, 0.18); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: #8fb4e2; font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: #5580b8; font-size: 12px; white-space: nowrap; }
|
||||
.metric:hover .metric-more { color: var(--primary); }
|
||||
.metric-value { margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: #ffffff; font-variant-numeric: tabular-nums; text-shadow: 0 0 20px rgba(63, 214, 255, 0.5); }
|
||||
.metric-value small { font-size: 16px; font-weight: 400; margin-left: 4px; color: #8fb4e2; }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim, var(--ink-soft)); font-size: 13px; flex-wrap: wrap; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #7dffc4; background: rgba(53, 224, 140, 0.12); }
|
||||
.delta.down { color: #ffd07d; background: rgba(255, 176, 58, 0.12); }
|
||||
.metric-note { color: var(--ink-soft); font-size: 16px; }
|
||||
.metric-value { margin-top: 6px; color: var(--primary); font-size: 28px; font-weight: 800; line-height: 1.2; }
|
||||
.chart-box { width: 100%; }
|
||||
.chart-caption { margin: 10px 0 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); color: var(--ink); }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.badge-soft { background: var(--primary-soft); color: var(--primary); border-radius: 999px; padding: 4px 12px; font-size: 16px; font-weight: 600; }
|
||||
.badge-warn { background: rgba(242, 178, 92, 0.16); color: var(--warn); border-radius: 999px; padding: 4px 12px; font-size: 16px; font-weight: 600; }
|
||||
.timeline { display: grid; gap: 0; margin: 0; padding: 0; }
|
||||
.timeline-item { position: relative; padding: 0 0 22px 32px; border-left: 2px solid var(--line); }
|
||||
.timeline-item:last-child { padding-bottom: 0; border-left-color: transparent; }
|
||||
.timeline-item::before { content: ""; position: absolute; left: -7px; top: 8px; width: 12px; height: 12px; border-radius: 50%; background: var(--primary); box-shadow: 0 0 0 4px var(--primary-soft); }
|
||||
.timeline-item time { color: var(--primary); font-weight: 700; }
|
||||
.timeline-item h3 { margin: 4px 0; font-size: 19px; }
|
||||
.timeline-item p { margin: 0; color: var(--ink-soft); }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 10px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.report-header, .section-card { padding: 22px 18px; }
|
||||
}
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
[hidden] { display: none !important; }
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .portal-nav a { transition: none; } }
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-overview" class="active">进度总览</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">项目进度报告</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-plan">里程碑与风险</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-overview" data-page="overview" data-page-title="进度总览" aria-label="进度总览">
|
||||
<header class="card report-header">
|
||||
<p class="eyebrow">项目进度报告</p>
|
||||
<h1>项目名称(替换为真实项目)</h1>
|
||||
<p class="lead">用一句话说明项目目标、当前所处阶段与整体健康度;甘特图用于展示各任务的计划与衔接关系。</p>
|
||||
<div class="meta">
|
||||
<span>计划周期:2026-10-01 至 2026-11-22(示意)</span>
|
||||
<span>编制:待替换</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="card section-card" aria-label="项目概况">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>计划周期</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">8 周</div><div class="metric-foot"><span>示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>阶段数</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">4 个</div><div class="metric-foot"><span>筹备 / 开发 / 测试 / 验收</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>关键里程碑</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">6 项</div><div class="metric-foot"><span>示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>整体完成率</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">42%</div><div class="metric-foot"><span>口径:已完成工作量占比</span></div></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="总体进度甘特图">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>总体进度甘特图</h2></div>
|
||||
<p class="section-desc">横轴为时间,每行一个任务,颜色区分阶段;虚线为当前日期参考线。数据为示意,替换为真实计划。</p>
|
||||
<div id="project-gantt" class="chart-box" style="height: 460px"></div>
|
||||
<script type="application/json" data-df-chart="project-gantt">
|
||||
{"title":{"text":"项目计划甘特图(示意数据)","left":"center","textStyle":{"color":"#e8f4ff"}},"textStyle":{"color":"#e8f4ff"},"tooltip":{"trigger":"axis","axisPointer":{"type":"shadow"},"backgroundColor":"rgba(10,24,46,.92)","borderColor":"rgba(128,180,255,.35)","textStyle":{"color":"#e8f4ff"}},"legend":{"top":"bottom","data":["筹备阶段","开发阶段","联调测试","上线验收"],"textStyle":{"color":"#b8c8d8"}},"grid":{"left":16,"right":28,"top":52,"bottom":72,"containLabel":true},"xAxis":{"type":"time","axisLabel":{"color":"#e8f4ff","formatter":"{MM}-{dd}"},"splitLine":{"lineStyle":{"color":"rgba(140,190,255,.16)"}}},"yAxis":{"type":"category","inverse":true,"data":["需求梳理","方案设计","数据治理开发","看板开发","联调测试","上线验收"],"axisLabel":{"color":"#e8f4ff"},"axisTick":{"show":false},"splitLine":{"show":false}},"series":[{"name":"筹备阶段","type":"bar","barWidth":18,"itemStyle":{"color":"#7aa5ff","borderRadius":4},"markLine":{"silent":false,"symbol":"none","lineStyle":{"color":"#ff8a8a","type":"dashed","width":2},"label":{"color":"#e8f4ff","formatter":"当前"},"data":[{"xAxis":"2026-10-17"}]},"data":[["2026-10-01","2026-10-09"],["2026-10-08","2026-10-16"],"-","-","-","-"]},{"name":"开发阶段","type":"bar","barGap":"-100%","barWidth":18,"itemStyle":{"color":"#3ad0c0","borderRadius":4},"data":["-","-",["2026-10-16","2026-10-31"],["2026-10-21","2026-11-06"],"-","-"]},{"name":"联调测试","type":"bar","barGap":"-100%","barWidth":18,"itemStyle":{"color":"#f2b25c","borderRadius":4},"data":["-","-","-","-",["2026-11-06","2026-11-15"],"-"]},{"name":"上线验收","type":"bar","barGap":"-100%","barWidth":18,"itemStyle":{"color":"#b493ff","borderRadius":4},"data":["-","-","-","-","-",["2026-11-15","2026-11-22"]]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 1 · 甘特图:每个阶段一个柱系列,同一行用「-」占位;起止日期成对出现。</p>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-plan" data-page="plan" data-page-title="里程碑风险" hidden aria-label="里程碑风险">
|
||||
<section class="card section-card" aria-label="里程碑计划">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>里程碑计划</h2></div>
|
||||
<p class="section-desc">只列关键控制点;状态按实际进展更新,不要虚构完成状态。</p>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>里程碑</th><th>计划时间</th><th>责任方</th><th>状态</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>需求基线确认</td><td>2026-10-09</td><td>业务组</td><td><span class="badge-soft">已完成</span></td><td>范围与口径冻结</td></tr>
|
||||
<tr><td>方案评审通过</td><td>2026-10-16</td><td>技术组</td><td><span class="badge-soft">已完成</span></td><td>含数据治理方案</td></tr>
|
||||
<tr><td>开发完成</td><td>2026-11-06</td><td>研发组</td><td><span class="badge-warn">进行中</span></td><td>两项子任务并行</td></tr>
|
||||
<tr><td>上线验收</td><td>2026-11-22</td><td>联合组</td><td><span class="badge-warn">未开始</span></td><td>验收标准见附件(替换)</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="风险与依赖">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>风险与依赖</h2></div>
|
||||
<div class="timeline">
|
||||
<article class="timeline-item"><time>2026-10-中旬</time><h3>数据口径依赖(替换)</h3><p>说明依赖方、影响范围与兜底方案。</p></article>
|
||||
<article class="timeline-item"><time>2026-11-上旬</time><h3>联调环境风险(替换)</h3><p>说明风险等级、触发条件与应对措施。</p></article>
|
||||
<article class="timeline-item"><time>2026-11-下旬</time><h3>验收资源风险(替换)</h3><p>说明所需资源与升级路径。</p></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="结论与建议">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>整体进度判断:是否在计划轨道内,依据是哪些里程碑。</li>
|
||||
<li>关键风险及责任人、化解时间点。</li>
|
||||
<li>下一报告期的关注重点与需要的决策支持。</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
</script>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script> </body>
|
||||
</html>
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>项目进度报告 · 浅色甘特图</title>
|
||||
<!--
|
||||
浅色甘特图单页模板(Bootstrap + ECharts 平台运行时)
|
||||
0. 本模板为双页轻量门户:.pages 容器 + 两个 .page[data-page] 逻辑页,锚点切页;最低页数 2。第 1 页:项目概况、关键指标与总体进度甘特图。第 2 页:里程碑计划、风险依赖与结论建议。
|
||||
1. 甘特图使用 data-df-chart 严格 JSON:时间轴 + 多个重叠柱系列(barGap:-100%)。
|
||||
2. 修改任务时同步调整 yAxis 任务名、各阶段系列的起止日期与「-」占位。
|
||||
3. 日期使用 YYYY-MM-DD 字符串;当前日期参考线按需更新。
|
||||
4. 按真实材料替换示例内容;示意数据必须保留「示意数据」标注。
|
||||
5. 页面标识(系统名称 + Logo)由平台按系统设置自动注入页眉页脚,不要自己书写。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/deerflow-runtime.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #f4f7fb;
|
||||
--panel: #ffffff;
|
||||
--panel-soft: #f7faff;
|
||||
--ink: #1d2a44;
|
||||
--ink-soft: #5d6d88;
|
||||
--line: #dde6f2;
|
||||
--primary: #3457d5;
|
||||
--primary-soft: #eaf0fe;
|
||||
--accent: #0f9b8e;
|
||||
--warn: #c87d1f;
|
||||
--danger: #cc4b4b;
|
||||
--shadow: 0 10px 28px rgba(30, 52, 98, 0.08);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: linear-gradient(160deg, #eef3fc 0%, #f6f4f0 55%, #eaf6f3 100%);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background-image: radial-gradient(rgba(90, 120, 190, 0.13) 1px, transparent 1.5px);
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
body::after {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background:
|
||||
radial-gradient(42vw 42vw at -10% -16%, rgba(146, 176, 255, 0.34), transparent 62%),
|
||||
radial-gradient(34vw 34vw at 112% 28%, rgba(255, 205, 224, 0.26), transparent 62%),
|
||||
radial-gradient(38vw 38vw at 45% 118%, rgba(152, 232, 216, 0.3), transparent 62%);
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1200px); margin: 28px auto 56px; }
|
||||
.card {
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--panel-line, var(--line));
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--shadow, 0 16px 40px rgba(99, 125, 190, 0.15)), inset 0 1px 0 rgba(255, 255, 255, 0.95);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
}
|
||||
.report-header { padding: 34px 36px; }
|
||||
.eyebrow { margin: 0 0 8px; color: var(--primary); font-weight: 700; letter-spacing: 0.08em; font-size: 16px; }
|
||||
h1 { margin: 0; font-size: clamp(30px, 4.2vw, 42px); line-height: 1.22; letter-spacing: -0.02em; }
|
||||
.lead { max-width: 860px; margin: 14px 0 0; color: var(--ink-soft); font-size: 17px; }
|
||||
.meta { display: flex; flex-wrap: wrap; gap: 8px 20px; margin-top: 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
.section-card { padding: 28px 30px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 800; letter-spacing: 0.14em; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 22px; height: 22px; border-radius: 7px; flex: none;
|
||||
background: linear-gradient(135deg, var(--primary), var(--accent, var(--primary)));
|
||||
box-shadow: 0 5px 12px rgba(77, 107, 242, 0.3);
|
||||
}
|
||||
.section-index { color: var(--ink-dim, var(--ink-soft)); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-title h2 { margin: 0; font-size: 25px; }
|
||||
.section-index { color: var(--primary); font-weight: 800; font-size: 16px; }
|
||||
.section-desc { margin: 0 0 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-soft);
|
||||
border: 1px solid var(--panel-line, var(--line)); border-radius: 14px;
|
||||
box-shadow: 0 8px 22px rgba(99, 125, 190, 0.1);
|
||||
transition: box-shadow 0.3s ease, transform 0.3s ease;
|
||||
}
|
||||
.metric:hover { box-shadow: 0 20px 44px rgba(99, 125, 190, 0.22); transform: translateY(-2px); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: var(--ink-soft); font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: var(--ink-dim, var(--ink-soft)); font-size: 12px; white-space: nowrap; }
|
||||
.metric-value { margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: var(--primary); font-variant-numeric: tabular-nums; }
|
||||
.metric-value small { font-size: 16px; font-weight: 600; margin-left: 4px; color: var(--ink-soft); }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim, var(--ink-soft)); font-size: 13px; flex-wrap: wrap; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #0e9c8f; background: rgba(23, 179, 174, 0.14); }
|
||||
.delta.down { color: #cf6a15; background: rgba(236, 155, 47, 0.16); }
|
||||
.metric-note { color: var(--ink-soft); font-size: 16px; }
|
||||
.metric-value { margin-top: 6px; color: var(--primary); font-size: 28px; font-weight: 800; line-height: 1.2; }
|
||||
.chart-box { width: 100%; }
|
||||
.chart-caption { margin: 10px 0 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.badge-soft { background: var(--primary-soft); color: var(--primary); border-radius: 999px; padding: 4px 12px; font-size: 16px; font-weight: 600; }
|
||||
.badge-warn { background: #fdf3e4; color: var(--warn); border-radius: 999px; padding: 4px 12px; font-size: 16px; font-weight: 600; }
|
||||
.timeline { display: grid; gap: 0; margin: 0; padding: 0; }
|
||||
.timeline-item { position: relative; padding: 0 0 22px 32px; border-left: 2px solid var(--line); }
|
||||
.timeline-item:last-child { padding-bottom: 0; border-left-color: transparent; }
|
||||
.timeline-item::before { content: ""; position: absolute; left: -7px; top: 8px; width: 12px; height: 12px; border-radius: 50%; background: var(--primary); box-shadow: 0 0 0 4px var(--primary-soft); }
|
||||
.timeline-item time { color: var(--primary); font-weight: 700; }
|
||||
.timeline-item h3 { margin: 4px 0; font-size: 19px; }
|
||||
.timeline-item p { margin: 0; color: var(--ink-soft); }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 10px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.report-header, .section-card { padding: 22px 18px; }
|
||||
}
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
[hidden] { display: none !important; }
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .portal-nav a { transition: none; } }
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-overview" class="active">进度总览</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">项目进度报告</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-plan">里程碑与风险</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-overview" data-page="overview" data-page-title="进度总览" aria-label="进度总览">
|
||||
<header class="card report-header">
|
||||
<p class="eyebrow">项目进度报告</p>
|
||||
<h1>项目名称(替换为真实项目)</h1>
|
||||
<p class="lead">用一句话说明项目目标、当前所处阶段与整体健康度;甘特图用于展示各任务的计划与衔接关系。</p>
|
||||
<div class="meta">
|
||||
<span>计划周期:2026-10-01 至 2026-11-22(示意)</span>
|
||||
<span>编制:待替换</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="card section-card" aria-label="项目概况">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>计划周期</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">8 周</div><div class="metric-foot"><span>示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>阶段数</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">4 个</div><div class="metric-foot"><span>筹备 / 开发 / 测试 / 验收</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>关键里程碑</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">6 项</div><div class="metric-foot"><span>示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>整体完成率</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">42%</div><div class="metric-foot"><span>口径:已完成工作量占比</span></div></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="总体进度甘特图">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>总体进度甘特图</h2></div>
|
||||
<p class="section-desc">横轴为时间,每行一个任务,颜色区分阶段;虚线为当前日期参考线。数据为示意,替换为真实计划。</p>
|
||||
<div id="project-gantt" class="chart-box" style="height: 460px"></div>
|
||||
<script type="application/json" data-df-chart="project-gantt">
|
||||
{"title":{"text":"项目计划甘特图(示意数据)","left":"center","textStyle":{"color":"#2a3a5c"}},"textStyle":{"color":"#2a3a5c"},"tooltip":{"trigger":"axis","axisPointer":{"type":"shadow"},"textStyle":{"color":"#2a3a5c"}},"legend":{"top":"bottom","data":["筹备阶段","开发阶段","联调测试","上线验收"],"textStyle":{"color":"#5d6d88"}},"grid":{"left":16,"right":28,"top":52,"bottom":72,"containLabel":true},"xAxis":{"type":"time","axisLabel":{"color":"#2a3a5c","formatter":"{MM}-{dd}"},"splitLine":{"lineStyle":{"color":"#e3eaf5"}}},"yAxis":{"type":"category","inverse":true,"data":["需求梳理","方案设计","数据治理开发","看板开发","联调测试","上线验收"],"axisLabel":{"color":"#2a3a5c"},"axisTick":{"show":false},"splitLine":{"show":false}},"series":[{"name":"筹备阶段","type":"bar","barWidth":18,"itemStyle":{"color":"#3457d5","borderRadius":4},"markLine":{"silent":false,"symbol":"none","lineStyle":{"color":"#d85757","type":"dashed","width":2},"label":{"color":"#2a3a5c","formatter":"当前"},"data":[{"xAxis":"2026-10-17"}]},"data":[["2026-10-01","2026-10-09"],["2026-10-08","2026-10-16"],"-","-","-","-"]},{"name":"开发阶段","type":"bar","barGap":"-100%","barWidth":18,"itemStyle":{"color":"#0f9b8e","borderRadius":4},"data":["-","-",["2026-10-16","2026-10-31"],["2026-10-21","2026-11-06"],"-","-"]},{"name":"联调测试","type":"bar","barGap":"-100%","barWidth":18,"itemStyle":{"color":"#f2a03d","borderRadius":4},"data":["-","-","-","-",["2026-11-06","2026-11-15"],"-"]},{"name":"上线验收","type":"bar","barGap":"-100%","barWidth":18,"itemStyle":{"color":"#8a63d2","borderRadius":4},"data":["-","-","-","-","-",["2026-11-15","2026-11-22"]]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 1 · 甘特图:每个阶段一个柱系列,同一行用「-」占位;起止日期成对出现。</p>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-plan" data-page="plan" data-page-title="里程碑风险" hidden aria-label="里程碑风险">
|
||||
<section class="card section-card" aria-label="里程碑计划">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>里程碑计划</h2></div>
|
||||
<p class="section-desc">只列关键控制点;状态按实际进展更新,不要虚构完成状态。</p>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>里程碑</th><th>计划时间</th><th>责任方</th><th>状态</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>需求基线确认</td><td>2026-10-09</td><td>业务组</td><td><span class="badge-soft">已完成</span></td><td>范围与口径冻结</td></tr>
|
||||
<tr><td>方案评审通过</td><td>2026-10-16</td><td>技术组</td><td><span class="badge-soft">已完成</span></td><td>含数据治理方案</td></tr>
|
||||
<tr><td>开发完成</td><td>2026-11-06</td><td>研发组</td><td><span class="badge-warn">进行中</span></td><td>两项子任务并行</td></tr>
|
||||
<tr><td>上线验收</td><td>2026-11-22</td><td>联合组</td><td><span class="badge-warn">未开始</span></td><td>验收标准见附件(替换)</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="风险与依赖">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>风险与依赖</h2></div>
|
||||
<div class="timeline">
|
||||
<article class="timeline-item"><time>2026-10-中旬</time><h3>数据口径依赖(替换)</h3><p>说明依赖方、影响范围与兜底方案。</p></article>
|
||||
<article class="timeline-item"><time>2026-11-上旬</time><h3>联调环境风险(替换)</h3><p>说明风险等级、触发条件与应对措施。</p></article>
|
||||
<article class="timeline-item"><time>2026-11-下旬</time><h3>验收资源风险(替换)</h3><p>说明所需资源与升级路径。</p></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="结论与建议">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>整体进度判断:是否在计划轨道内,依据是哪些里程碑。</li>
|
||||
<li>关键风险及责任人、化解时间点。</li>
|
||||
<li>下一报告期的关注重点与需要的决策支持。</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
</script>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script> </body>
|
||||
</html>
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>态势分析门户 · 深色瓦片地图</title>
|
||||
<!--
|
||||
深色瓦片地图门户模板(Bootstrap + Alpine + ECharts + Leaflet 平台运行时)
|
||||
1. 地图使用 data-df-map 契约:瓦片地址由后台 config.yaml 的 html_runtime.map_tile_url
|
||||
注入运行时,页面源码不写瓦片地址。需要管理员在「外观设置 → HTML 地图」选择「地图网页」。
|
||||
2. 普通图表仍使用 ECharts 的 data-df-chart 严格 JSON;坐标统一 [经度,纬度]。
|
||||
3. 单个 HTML 内的轻量交互门户:.pages 容器 + 多个 .page[data-page] 逻辑页,锚点切页。
|
||||
4. 平台开启网页标识后自动注入品牌页眉、页脚与页面导航并接管切页。
|
||||
5. 按真实材料替换示例内容;示意数据必须保留「示意数据」标注;深色图表写齐浅色文字。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/leaflet.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/leaflet.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/deerflow-runtime.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #0c1526;
|
||||
--panel: #131f38;
|
||||
--panel-soft: #182a4a;
|
||||
--ink: #e9f2ff;
|
||||
--ink-soft: #a9bdd6;
|
||||
--line: rgba(128, 180, 255, 0.22);
|
||||
--primary: #7aa5ff;
|
||||
--primary-soft: #1c2c52;
|
||||
--accent: #3ad0c0;
|
||||
--warn: #f2b25c;
|
||||
--shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background:
|
||||
radial-gradient(1200px 600px at 50% -10%, rgba(30, 90, 200, 0.26), transparent 60%),
|
||||
radial-gradient(900px 500px at 100% 100%, rgba(20, 160, 180, 0.12), transparent 55%),
|
||||
var(--page);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; opacity: 0.4;
|
||||
background-image:
|
||||
linear-gradient(rgba(60, 140, 255, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(60, 140, 255, 0.05) 1px, transparent 1px);
|
||||
background-size: 42px 42px;
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1280px); margin: 28px auto 56px; }
|
||||
[hidden] { display: none !important; }
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
.pages { margin-top: 22px; display: grid; gap: 28px; }
|
||||
.section-card { padding: 26px 28px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 700; letter-spacing: 0.14em; color: #eaf6ff; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 4px; height: 16px; border-radius: 2px; flex: none;
|
||||
background: linear-gradient(180deg, var(--primary), #2f7bff);
|
||||
box-shadow: 0 0 9px rgba(63, 214, 255, 0.9);
|
||||
}
|
||||
.section-index { color: var(--ink-dim, var(--ink-soft)); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-title h2 { margin: 0; font-size: 24px; }
|
||||
.section-index { color: var(--primary); font-weight: 800; font-size: 16px; }
|
||||
.section-desc { margin: 0 0 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-strong, var(--panel-soft));
|
||||
border: 1px solid var(--line); border-radius: 12px;
|
||||
transition: border-color 0.3s ease, box-shadow 0.3s ease;
|
||||
}
|
||||
.metric:hover { border-color: rgba(63, 214, 255, 0.7); box-shadow: 0 0 28px rgba(63, 214, 255, 0.18); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: #8fb4e2; font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: #5580b8; font-size: 12px; white-space: nowrap; }
|
||||
.metric:hover .metric-more { color: var(--primary); }
|
||||
.metric-value { margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: #ffffff; font-variant-numeric: tabular-nums; text-shadow: 0 0 20px rgba(63, 214, 255, 0.5); }
|
||||
.metric-value small { font-size: 16px; font-weight: 400; margin-left: 4px; color: #8fb4e2; }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim, var(--ink-soft)); font-size: 13px; flex-wrap: wrap; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #7dffc4; background: rgba(53, 224, 140, 0.12); }
|
||||
.delta.down { color: #ffd07d; background: rgba(255, 176, 58, 0.12); }
|
||||
.metric-note { color: var(--ink-soft); font-size: 16px; }
|
||||
.metric-value { margin-top: 6px; color: var(--primary); font-size: 30px; font-weight: 800; line-height: 1.2; }
|
||||
.callout { padding: 20px 22px; border-left: 5px solid var(--primary); border-radius: 12px; background: var(--primary-soft); }
|
||||
.callout strong { display: block; margin-bottom: 6px; font-size: 17px; }
|
||||
.chart-box { width: 100%; }
|
||||
.df-map { width: 100%; height: 620px; border-radius: 14px; border: 1px solid var(--line); background: var(--panel-soft); }
|
||||
.chart-caption { margin: 10px 0 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.site-card { padding: 18px 20px; background: var(--panel-soft); border: 1px solid var(--line); border-radius: 14px; height: 100%; }
|
||||
.site-card h3 { margin: 0 0 6px; font-size: 19px; }
|
||||
.site-card p { margin: 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); color: var(--ink); }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.filter-input { max-width: 320px; }
|
||||
.form-control { font-size: 16px; color: var(--ink); background: var(--panel-soft); border: 1px solid var(--line); }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 10px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.section-card { padding: 20px 16px; }
|
||||
.portal-topbar { padding: 14px 16px; }
|
||||
.df-map { height: 480px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.portal-nav a { transition: none; }
|
||||
}
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-overview" class="active">态势总览</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">区域态势分析门户(替换标题)</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-map" class="">地图态势</a>
|
||||
<a href="#page-sites" class="">点位明细</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-overview" data-page="overview" data-page-title="态势总览" aria-label="态势总览">
|
||||
<div class="card section-card">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>覆盖点位(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">18 个</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>重点区域(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">6 个</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>事件数量(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">126 起</div><div class="metric-foot"><span>统计区间 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>响应达标率(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">93.7%</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>总体态势</h2></div>
|
||||
<p class="section-desc">概括本期区域的总体态势、主要变化与关注方向;地图页承载空间分布细节。</p>
|
||||
<div id="overview-trend" class="chart-box" style="height: 400px"></div>
|
||||
<script type="application/json" data-df-chart="overview-trend">
|
||||
{"title":{"text":"月度事件走势(示意数据,替换为真实口径)","left":"center","textStyle":{"color":"#e8f4ff"}},"textStyle":{"color":"#e8f4ff"},"tooltip":{"trigger":"axis","backgroundColor":"rgba(10,24,46,.92)","borderColor":"rgba(128,180,255,.35)","textStyle":{"color":"#e8f4ff"}},"legend":{"top":"bottom","textStyle":{"color":"#b8c8d8"}},"grid":{"left":16,"right":24,"top":56,"bottom":64,"containLabel":true},"xAxis":{"type":"category","boundaryGap":false,"data":["五月","六月","七月","八月","九月","十月"],"axisLabel":{"color":"#e8f4ff"},"splitLine":{"show":false}},"yAxis":{"type":"value","name":"数量","nameTextStyle":{"color":"#b8c8d8"},"axisLabel":{"color":"#e8f4ff"},"splitLine":{"lineStyle":{"color":"rgba(140,190,255,.16)"}}},"series":[{"name":"事件数","type":"line","smooth":true,"symbolSize":8,"areaStyle":{"opacity":0.16},"lineStyle":{"width":3,"color":"#7aa5ff"},"itemStyle":{"color":"#7aa5ff"},"data":[96,110,132,121,138,126]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 1 · 事件走势:替换为真实统计后同步修改结论。</p>
|
||||
<div class="callout mt-3"><strong>总体判断</strong><span>写成一句完整的话,注明数据来源与统计区间。</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-map" data-page="map" data-page-title="地图态势" hidden aria-label="地图态势">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>空间分布态势</h2></div>
|
||||
<p class="section-desc">底图瓦片由平台配置提供;标点、连线与说明按真实材料替换,坐标为 [经度,纬度]。</p>
|
||||
<div id="area-map" class="df-map" role="region" aria-label="态势地图"></div>
|
||||
<script type="application/json" data-df-map="area-map">
|
||||
{"title":"重点区域态势","center":[116.4,39.9],"zoom":5,"markers":[{"name":"北京","coordinate":[116.407,39.904],"description":"华北中心:示意说明,点击标点查看"},{"name":"上海","coordinate":[121.473,31.231],"description":"华东中心:示意说明"},{"name":"广州","coordinate":[113.264,23.129],"description":"华南中心:示意说明"},{"name":"成都","coordinate":[104.066,30.572],"description":"西南中心:示意说明"}],"lines":[{"name":"京沪联络","coordinates":[[116.407,39.904],[121.473,31.231]]},{"name":"京广联络","coordinates":[[116.407,39.904],[113.264,23.129]]}],"polygons":[]}
|
||||
</script>
|
||||
<p class="chart-caption">图 2 · 瓦片地图:示意点位,替换为真实点位与范围。</p>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>重点点位速览</h2></div>
|
||||
<div class="row g-4">
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>北京(替换)</h3><p>华北中心,说明其地位与关注点。</p></div></div>
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>上海(替换)</h3><p>华东中心,说明其地位与关注点。</p></div></div>
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>广州(替换)</h3><p>华南中心,说明其地位与关注点。</p></div></div>
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>成都(替换)</h3><p>西南中心,说明其地位与关注点。</p></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-sites" data-page="sites" data-page-title="点位明细" hidden aria-label="点位明细" x-data="{ query: '' }">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>点位明细</h2></div>
|
||||
<p class="section-desc">输入关键词即可过滤下表(Alpine 轻量检索);列按结论需要增删。</p>
|
||||
<div class="mb-3">
|
||||
<input class="form-control filter-input" type="search" placeholder="输入关键词筛选,如:华北" x-model="query" aria-label="筛选点位" />
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>点位</th><th>区域</th><th>坐标(经,纬)</th><th>类别</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>北京(替换)</td><td>华北</td><td>116.407, 39.904</td><td>中心</td><td>示意说明</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>上海(替换)</td><td>华东</td><td>121.473, 31.231</td><td>中心</td><td>示意说明</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>广州(替换)</td><td>华南</td><td>113.264, 23.129</td><td>中心</td><td>示意说明</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>成都(替换)</td><td>西南</td><td>104.066, 30.572</td><td>中心</td><td>示意说明</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">05</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>空间分布结论:密集区、空白区与形成原因。</li>
|
||||
<li>重点关注点位与处置建议。</li>
|
||||
<li>下一步需要补充的数据与巡查安排。</li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>态势分析门户 · 浅色瓦片地图</title>
|
||||
<!--
|
||||
浅色瓦片地图门户模板(Bootstrap + Alpine + ECharts + Leaflet 平台运行时)
|
||||
1. 地图使用 data-df-map 契约:瓦片地址由后台 config.yaml 的 html_runtime.map_tile_url
|
||||
注入运行时,页面源码不写瓦片地址。需要管理员在「外观设置 → HTML 地图」选择「地图网页」。
|
||||
2. 普通图表仍使用 ECharts 的 data-df-chart 严格 JSON;坐标统一 [经度,纬度]。
|
||||
3. 单个 HTML 内的轻量交互门户:.pages 容器 + 多个 .page[data-page] 逻辑页,锚点切页。
|
||||
4. 平台开启网页标识后自动注入品牌页眉、页脚与页面导航并接管切页。
|
||||
5. 按真实材料替换示例内容;示意数据必须保留「示意数据」标注。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/leaflet.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/leaflet.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/deerflow-runtime.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #f4f7fb;
|
||||
--panel: #ffffff;
|
||||
--panel-soft: #f7faff;
|
||||
--ink: #1d2a44;
|
||||
--ink-soft: #5d6d88;
|
||||
--line: #dde6f2;
|
||||
--primary: #3457d5;
|
||||
--primary-soft: #eaf0fe;
|
||||
--accent: #0f9b8e;
|
||||
--warn: #c87d1f;
|
||||
--shadow: 0 10px 28px rgba(30, 52, 98, 0.08);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: linear-gradient(160deg, #eef3fc 0%, #f6f4f0 55%, #eaf6f3 100%);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background-image: radial-gradient(rgba(90, 120, 190, 0.13) 1px, transparent 1.5px);
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
body::after {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background:
|
||||
radial-gradient(42vw 42vw at -10% -16%, rgba(146, 176, 255, 0.34), transparent 62%),
|
||||
radial-gradient(34vw 34vw at 112% 28%, rgba(255, 205, 224, 0.26), transparent 62%),
|
||||
radial-gradient(38vw 38vw at 45% 118%, rgba(152, 232, 216, 0.3), transparent 62%);
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1280px); margin: 28px auto 56px; }
|
||||
[hidden] { display: none !important; }
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
.pages { margin-top: 22px; display: grid; gap: 28px; }
|
||||
.section-card { padding: 26px 28px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 800; letter-spacing: 0.14em; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 22px; height: 22px; border-radius: 7px; flex: none;
|
||||
background: linear-gradient(135deg, var(--primary), var(--accent, var(--primary)));
|
||||
box-shadow: 0 5px 12px rgba(77, 107, 242, 0.3);
|
||||
}
|
||||
.section-index { color: var(--ink-dim, var(--ink-soft)); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-title h2 { margin: 0; font-size: 24px; }
|
||||
.section-index { color: var(--primary); font-weight: 800; font-size: 16px; }
|
||||
.section-desc { margin: 0 0 18px; color: var(--ink-soft); font-size: 16px; }
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-soft);
|
||||
border: 1px solid var(--panel-line, var(--line)); border-radius: 14px;
|
||||
box-shadow: 0 8px 22px rgba(99, 125, 190, 0.1);
|
||||
transition: box-shadow 0.3s ease, transform 0.3s ease;
|
||||
}
|
||||
.metric:hover { box-shadow: 0 20px 44px rgba(99, 125, 190, 0.22); transform: translateY(-2px); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: var(--ink-soft); font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: var(--ink-dim, var(--ink-soft)); font-size: 12px; white-space: nowrap; }
|
||||
.metric-value { margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: var(--primary); font-variant-numeric: tabular-nums; }
|
||||
.metric-value small { font-size: 16px; font-weight: 600; margin-left: 4px; color: var(--ink-soft); }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim, var(--ink-soft)); font-size: 13px; flex-wrap: wrap; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #0e9c8f; background: rgba(23, 179, 174, 0.14); }
|
||||
.delta.down { color: #cf6a15; background: rgba(236, 155, 47, 0.16); }
|
||||
.metric-note { color: var(--ink-soft); font-size: 16px; }
|
||||
.metric-value { margin-top: 6px; color: var(--primary); font-size: 30px; font-weight: 800; line-height: 1.2; }
|
||||
.callout { padding: 20px 22px; border-left: 5px solid var(--primary); border-radius: 12px; background: var(--primary-soft); }
|
||||
.callout strong { display: block; margin-bottom: 6px; font-size: 17px; }
|
||||
.chart-box { width: 100%; }
|
||||
.df-map { width: 100%; height: 620px; border-radius: 14px; border: 1px solid var(--line); background: var(--panel-soft); }
|
||||
.chart-caption { margin: 10px 0 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.site-card { padding: 18px 20px; background: var(--panel-soft); border: 1px solid var(--line); border-radius: 14px; height: 100%; }
|
||||
.site-card h3 { margin: 0 0 6px; font-size: 19px; }
|
||||
.site-card p { margin: 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.filter-input { max-width: 320px; }
|
||||
.form-control { font-size: 16px; color: var(--ink); background: var(--panel); border: 1px solid var(--line); }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 10px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.section-card { padding: 20px 16px; }
|
||||
.portal-topbar { padding: 14px 16px; }
|
||||
.df-map { height: 480px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.portal-nav a { transition: none; }
|
||||
}
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-overview" class="active">态势总览</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">区域态势分析门户(替换标题)</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-map" class="">地图态势</a>
|
||||
<a href="#page-sites" class="">点位明细</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-overview" data-page="overview" data-page-title="态势总览" aria-label="态势总览">
|
||||
<div class="card section-card">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>覆盖点位(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">18 个</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>重点区域(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">6 个</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>事件数量(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">126 起</div><div class="metric-foot"><span>统计区间 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>响应达标率(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">93.7%</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>总体态势</h2></div>
|
||||
<p class="section-desc">概括本期区域的总体态势、主要变化与关注方向;地图页承载空间分布细节。</p>
|
||||
<div id="overview-trend" class="chart-box" style="height: 400px"></div>
|
||||
<script type="application/json" data-df-chart="overview-trend">
|
||||
{"title":{"text":"月度事件走势(示意数据,替换为真实口径)","left":"center","textStyle":{"color":"#2a3a5c"}},"textStyle":{"color":"#2a3a5c"},"tooltip":{"trigger":"axis","textStyle":{"color":"#2a3a5c"}},"legend":{"top":"bottom","textStyle":{"color":"#5d6d88"}},"grid":{"left":16,"right":24,"top":56,"bottom":64,"containLabel":true},"xAxis":{"type":"category","boundaryGap":false,"data":["五月","六月","七月","八月","九月","十月"],"axisLabel":{"color":"#2a3a5c"},"splitLine":{"show":false}},"yAxis":{"type":"value","name":"数量","nameTextStyle":{"color":"#5d6d88"},"axisLabel":{"color":"#2a3a5c"},"splitLine":{"lineStyle":{"color":"#e3eaf5"}}},"series":[{"name":"事件数","type":"line","smooth":true,"symbolSize":8,"areaStyle":{"opacity":0.12},"lineStyle":{"width":3,"color":"#3457d5"},"itemStyle":{"color":"#3457d5"},"data":[96,110,132,121,138,126]}]}
|
||||
</script>
|
||||
<p class="chart-caption">图 1 · 事件走势:替换为真实统计后同步修改结论。</p>
|
||||
<div class="callout mt-3"><strong>总体判断</strong><span>写成一句完整的话,注明数据来源与统计区间。</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-map" data-page="map" data-page-title="地图态势" hidden aria-label="地图态势">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>空间分布态势</h2></div>
|
||||
<p class="section-desc">底图瓦片由平台配置提供;标点、连线与说明按真实材料替换,坐标为 [经度,纬度]。</p>
|
||||
<div id="area-map" class="df-map" role="region" aria-label="态势地图"></div>
|
||||
<script type="application/json" data-df-map="area-map">
|
||||
{"title":"重点区域态势","center":[116.4,39.9],"zoom":5,"markers":[{"name":"北京","coordinate":[116.407,39.904],"description":"华北中心:示意说明,点击标点查看"},{"name":"上海","coordinate":[121.473,31.231],"description":"华东中心:示意说明"},{"name":"广州","coordinate":[113.264,23.129],"description":"华南中心:示意说明"},{"name":"成都","coordinate":[104.066,30.572],"description":"西南中心:示意说明"}],"lines":[{"name":"京沪联络","coordinates":[[116.407,39.904],[121.473,31.231]]},{"name":"京广联络","coordinates":[[116.407,39.904],[113.264,23.129]]}],"polygons":[]}
|
||||
</script>
|
||||
<p class="chart-caption">图 2 · 瓦片地图:示意点位,替换为真实点位与范围。</p>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>重点点位速览</h2></div>
|
||||
<div class="row g-4">
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>北京(替换)</h3><p>华北中心,说明其地位与关注点。</p></div></div>
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>上海(替换)</h3><p>华东中心,说明其地位与关注点。</p></div></div>
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>广州(替换)</h3><p>华南中心,说明其地位与关注点。</p></div></div>
|
||||
<div class="col-md-6 col-lg-3"><div class="site-card"><h3>成都(替换)</h3><p>西南中心,说明其地位与关注点。</p></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-sites" data-page="sites" data-page-title="点位明细" hidden aria-label="点位明细" x-data="{ query: '' }">
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>点位明细</h2></div>
|
||||
<p class="section-desc">输入关键词即可过滤下表(Alpine 轻量检索);列按结论需要增删。</p>
|
||||
<div class="mb-3">
|
||||
<input class="form-control filter-input" type="search" placeholder="输入关键词筛选,如:华北" x-model="query" aria-label="筛选点位" />
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>点位</th><th>区域</th><th>坐标(经,纬)</th><th>类别</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>北京(替换)</td><td>华北</td><td>116.407, 39.904</td><td>中心</td><td>示意说明</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>上海(替换)</td><td>华东</td><td>121.473, 31.231</td><td>中心</td><td>示意说明</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>广州(替换)</td><td>华南</td><td>113.264, 23.129</td><td>中心</td><td>示意说明</td></tr>
|
||||
<tr x-show="!query || $el.textContent.indexOf(query) > -1"><td>成都(替换)</td><td>西南</td><td>104.066, 30.572</td><td>中心</td><td>示意说明</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card section-card">
|
||||
<div class="section-title"><span class="section-index">05</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>空间分布结论:密集区、空白区与形成原因。</li>
|
||||
<li>重点关注点位与处置建议。</li>
|
||||
<li>下一步需要补充的数据与巡查安排。</li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>研判简报 · 深色结论先行版式</title>
|
||||
<!--
|
||||
深色研判简报单页模板(Bootstrap 排版,无图表)
|
||||
0. 本模板为双页轻量门户:.pages 容器 + 两个 .page[data-page] 逻辑页,锚点切页;最低页数 2。第 1 页:核心结论、关键指标与态势研判。第 2 页:风险清单、行动建议与资料来源。
|
||||
1. 结论先行的响应式单页文档:核心结论带、关键指标、态势研判、风险清单与行动建议。
|
||||
2. 适合快节奏阅读的日报/周报/态势简报:读者应能在第一屏拿到全部结论。
|
||||
3. 按真实材料替换全部示例内容;没有依据的风险与行动项应当删除。
|
||||
4. 页面标识(系统名称 + Logo)由平台按系统设置自动注入页眉页脚,不要自己书写。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #0c1424;
|
||||
--panel: #131d33;
|
||||
--panel-soft: #192747;
|
||||
--ink: #e9f1fd;
|
||||
--ink-soft: #a4b6cc;
|
||||
--line: rgba(126, 172, 226, 0.22);
|
||||
--primary: #85a9f2;
|
||||
--primary-soft: #1b2b52;
|
||||
--accent: #46c8b8;
|
||||
--warn: #eab06a;
|
||||
--danger: #f29292;
|
||||
--shadow: 0 12px 30px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background:
|
||||
radial-gradient(1200px 600px at 50% -10%, rgba(30, 90, 200, 0.26), transparent 60%),
|
||||
radial-gradient(900px 500px at 100% 100%, rgba(20, 160, 180, 0.12), transparent 55%),
|
||||
var(--page);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; opacity: 0.4;
|
||||
background-image:
|
||||
linear-gradient(rgba(60, 140, 255, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(60, 140, 255, 0.05) 1px, transparent 1px);
|
||||
background-size: 42px 42px;
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1080px); margin: 28px auto 56px; }
|
||||
.card {
|
||||
position: relative;
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
box-shadow: inset 0 0 30px rgba(20, 70, 160, 0.1);
|
||||
}
|
||||
.card::before, .card::after { content: ""; position: absolute; width: 14px; height: 14px; pointer-events: none; opacity: 0.9; }
|
||||
.card::before { left: -1px; top: -1px; border-left: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-top: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-top-left-radius: 12px; }
|
||||
.card::after { right: -1px; bottom: -1px; border-right: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-bottom: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-bottom-right-radius: 12px; }
|
||||
.brief-header { padding: 30px 34px; }
|
||||
.brief-top { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 20px; }
|
||||
.eyebrow { margin: 0; color: var(--primary); font-weight: 700; letter-spacing: 0.1em; font-size: 16px; }
|
||||
h1 { margin: 8px 0 0; font-size: clamp(28px, 4vw, 38px); line-height: 1.25; letter-spacing: -0.02em; }
|
||||
.brief-meta { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-top: 14px; color: var(--ink-soft); font-size: 16px; }
|
||||
.section-card { padding: 28px 32px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 700; letter-spacing: 0.14em; color: #eaf6ff; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 4px; height: 16px; border-radius: 2px; flex: none;
|
||||
background: linear-gradient(180deg, var(--primary), #2f7bff);
|
||||
box-shadow: 0 0 9px rgba(63, 214, 255, 0.9);
|
||||
}
|
||||
.section-index { color: var(--ink-dim, var(--ink-soft)); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-title h2 { margin: 0; font-size: 24px; }
|
||||
.section-index { color: var(--primary); font-weight: 800; font-size: 16px; }
|
||||
.conclusion-item { display: flex; gap: 14px; padding: 16px 18px; border: 1px solid var(--line); border-radius: 14px; background: var(--panel-soft); }
|
||||
.conclusion-item + .conclusion-item { margin-top: 12px; }
|
||||
.conclusion-no { flex: none; width: 34px; height: 34px; border-radius: 50%; background: var(--primary); color: #101b31; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 16px; }
|
||||
.conclusion-item h3 { margin: 0 0 4px; font-size: 18px; }
|
||||
.conclusion-item p { margin: 0; color: var(--ink-soft); }
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-strong, var(--panel-soft));
|
||||
border: 1px solid var(--line); border-radius: 12px;
|
||||
transition: border-color 0.3s ease, box-shadow 0.3s ease;
|
||||
}
|
||||
.metric:hover { border-color: rgba(63, 214, 255, 0.7); box-shadow: 0 0 28px rgba(63, 214, 255, 0.18); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: #8fb4e2; font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: #5580b8; font-size: 12px; white-space: nowrap; }
|
||||
.metric:hover .metric-more { color: var(--primary); }
|
||||
.metric-value { margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: #ffffff; font-variant-numeric: tabular-nums; text-shadow: 0 0 20px rgba(63, 214, 255, 0.5); }
|
||||
.metric-value small { font-size: 16px; font-weight: 400; margin-left: 4px; color: #8fb4e2; }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim, var(--ink-soft)); font-size: 13px; flex-wrap: wrap; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #7dffc4; background: rgba(53, 224, 140, 0.12); }
|
||||
.delta.down { color: #ffd07d; background: rgba(255, 176, 58, 0.12); }
|
||||
.metric-note { color: var(--ink-soft); font-size: 16px; }
|
||||
.metric-value { margin-top: 6px; color: var(--primary); font-size: 28px; font-weight: 800; line-height: 1.2; }
|
||||
.prose { max-width: 860px; }
|
||||
.prose p { margin: 0 0 12px; }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); color: var(--ink); }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.level { border-radius: 999px; padding: 4px 12px; font-size: 16px; font-weight: 700; white-space: nowrap; }
|
||||
.level-high { background: rgba(242, 146, 146, 0.16); color: var(--danger); }
|
||||
.level-mid { background: rgba(234, 176, 106, 0.16); color: var(--warn); }
|
||||
.level-low { background: var(--primary-soft); color: var(--primary); }
|
||||
.action-list { margin: 0; padding: 0; list-style: none; }
|
||||
.action-list li { position: relative; padding: 0 0 14px 34px; }
|
||||
.action-list li:last-child { padding-bottom: 0; }
|
||||
.action-list li::before { content: ""; position: absolute; left: 4px; top: 6px; width: 14px; height: 14px; border: 2px solid var(--accent); border-radius: 4px; }
|
||||
.action-list strong { display: block; }
|
||||
.action-list span { color: var(--ink-soft); }
|
||||
.source-list { margin: 0; padding-left: 22px; color: var(--ink-soft); }
|
||||
.source-list li + li { margin-top: 6px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.brief-header, .section-card { padding: 22px 18px; }
|
||||
}
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
[hidden] { display: none !important; }
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .portal-nav a { transition: none; } }
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-core" class="active">核心结论</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">研判简报</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-action">风险与行动</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-core" data-page="core" data-page-title="核心结论" aria-label="核心结论">
|
||||
<header class="card brief-header">
|
||||
<div class="brief-top">
|
||||
<p class="eyebrow">研判简报 · 第 X 期(替换)</p>
|
||||
</div>
|
||||
<h1>简报主题(替换为真实主题)</h1>
|
||||
<div class="brief-meta">
|
||||
<span>资料范围:待替换</span>
|
||||
<span>编制单位:待替换</span>
|
||||
<span>分发范围:待替换</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="card section-card" aria-label="核心结论">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>核心结论</h2></div>
|
||||
<div class="conclusion-item">
|
||||
<span class="conclusion-no">1</span>
|
||||
<div><h3>第一条结论(替换)</h3><p>一句话判断 + 支撑依据。读者只读这一屏也应能拿走全部结论。</p></div>
|
||||
</div>
|
||||
<div class="conclusion-item">
|
||||
<span class="conclusion-no">2</span>
|
||||
<div><h3>第二条结论(替换)</h3><p>一句话判断 + 支撑依据。按重要性排序,最重要的放最前面。</p></div>
|
||||
</div>
|
||||
<div class="conclusion-item">
|
||||
<span class="conclusion-no">3</span>
|
||||
<div><h3>第三条结论(替换)</h3><p>一句话判断 + 支撑依据。没有第三条时可删除本块。</p></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="关键指标">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标一(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">1,286</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标二(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">+18.4%</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标三(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">92.6%</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标四(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">37 项</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="态势研判">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>态势研判</h2></div>
|
||||
<div class="prose">
|
||||
<p>按「事实 — 变化 — 影响」的顺序展开研判:先陈述本期发生的事实,再指出与上期的差异,最后说明对后续的影响与观察窗口。</p>
|
||||
<p>示例占位文字:涉及推断的句子应使用「预计」「可能」「待核实」等限定词,与已核实事实区分表述;每段围绕一个问题,不混合多个主题。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-action" data-page="action" data-page-title="风险行动" hidden aria-label="风险行动">
|
||||
<section class="card section-card" aria-label="风险清单">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>风险清单</h2></div>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>等级</th><th>风险描述</th><th>潜在影响</th><th>应对建议</th><th>责任方</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><span class="level level-high">高</span></td><td>示例风险一(替换)</td><td>影响范围与量级</td><td>处置思路与时间窗</td><td>待定</td></tr>
|
||||
<tr><td><span class="level level-mid">中</span></td><td>示例风险二(替换)</td><td>影响范围与量级</td><td>处置思路与时间窗</td><td>待定</td></tr>
|
||||
<tr><td><span class="level level-low">低</span></td><td>示例风险三(替换)</td><td>影响范围与量级</td><td>处置思路与时间窗</td><td>待定</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="行动建议">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>行动建议</h2></div>
|
||||
<ul class="action-list">
|
||||
<li><strong>建议一(替换)</strong><span>说明执行要点、时限与完成标志。</span></li>
|
||||
<li><strong>建议二(替换)</strong><span>说明执行要点、时限与完成标志。</span></li>
|
||||
<li><strong>建议三(替换)</strong><span>说明执行要点、时限与完成标志;没有依据的建议应删除。</span></li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="附录">
|
||||
<div class="section-title"><span class="section-index">05</span><h2>附录 · 资料来源</h2></div>
|
||||
<ol class="source-list">
|
||||
<li>资料一(替换:名称、来源、时间)</li>
|
||||
<li>资料二(替换:名称、来源、时间)</li>
|
||||
<li>资料三(替换:名称、来源、时间)</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
</script>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script> </body>
|
||||
</html>
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>研判简报 · 浅色结论先行版式</title>
|
||||
<!--
|
||||
浅色研判简报单页模板(Bootstrap 排版,无图表)
|
||||
0. 本模板为双页轻量门户:.pages 容器 + 两个 .page[data-page] 逻辑页,锚点切页;最低页数 2。第 1 页:核心结论、关键指标与态势研判。第 2 页:风险清单、行动建议与资料来源。
|
||||
1. 结论先行的响应式单页文档:核心结论带、关键指标、态势研判、风险清单与行动建议。
|
||||
2. 适合快节奏阅读的日报/周报/态势简报:读者应能在第一屏拿到全部结论。
|
||||
3. 按真实材料替换全部示例内容;没有依据的风险与行动项应当删除。
|
||||
4. 页面标识(系统名称 + Logo)由平台按系统设置自动注入页眉页脚,不要自己书写。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #f4f6f9;
|
||||
--panel: #ffffff;
|
||||
--panel-soft: #f7f9fc;
|
||||
--ink: #1f2733;
|
||||
--ink-soft: #5a6779;
|
||||
--line: #dbe2ec;
|
||||
--primary: #2c5cc5;
|
||||
--primary-soft: #e9effb;
|
||||
--accent: #0e8f82;
|
||||
--warn: #b97514;
|
||||
--danger: #c34f4f;
|
||||
--shadow: 0 10px 26px rgba(35, 52, 84, 0.08);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: linear-gradient(160deg, #eef3fc 0%, #f6f4f0 55%, #eaf6f3 100%);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background-image: radial-gradient(rgba(90, 120, 190, 0.13) 1px, transparent 1.5px);
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
body::after {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background:
|
||||
radial-gradient(42vw 42vw at -10% -16%, rgba(146, 176, 255, 0.34), transparent 62%),
|
||||
radial-gradient(34vw 34vw at 112% 28%, rgba(255, 205, 224, 0.26), transparent 62%),
|
||||
radial-gradient(38vw 38vw at 45% 118%, rgba(152, 232, 216, 0.3), transparent 62%);
|
||||
}
|
||||
.wrap { width: min(100% - 40px, 1080px); margin: 28px auto 56px; }
|
||||
.card {
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--panel-line, var(--line));
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--shadow, 0 16px 40px rgba(99, 125, 190, 0.15)), inset 0 1px 0 rgba(255, 255, 255, 0.95);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
}
|
||||
.brief-header { padding: 30px 34px; }
|
||||
.brief-top { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 20px; }
|
||||
.eyebrow { margin: 0; color: var(--primary); font-weight: 700; letter-spacing: 0.1em; font-size: 16px; }
|
||||
h1 { margin: 8px 0 0; font-size: clamp(28px, 4vw, 38px); line-height: 1.25; letter-spacing: -0.02em; }
|
||||
.brief-meta { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-top: 14px; color: var(--ink-soft); font-size: 16px; }
|
||||
.section-card { padding: 28px 32px; }
|
||||
.section-title { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
|
||||
.section-title h2 { display: flex; align-items: center; gap: 12px; margin: 0; font-size: 18px; font-weight: 800; letter-spacing: 0.14em; }
|
||||
.section-title h2::before {
|
||||
content: ""; width: 22px; height: 22px; border-radius: 7px; flex: none;
|
||||
background: linear-gradient(135deg, var(--primary), var(--accent, var(--primary)));
|
||||
box-shadow: 0 5px 12px rgba(77, 107, 242, 0.3);
|
||||
}
|
||||
.section-index { color: var(--ink-dim, var(--ink-soft)); font-weight: 700; font-size: 14px; letter-spacing: 0.1em; }
|
||||
.section-title h2 { margin: 0; font-size: 24px; }
|
||||
.section-index { color: var(--primary); font-weight: 800; font-size: 16px; }
|
||||
.conclusion-item { display: flex; gap: 14px; padding: 16px 18px; border: 1px solid var(--line); border-radius: 14px; background: var(--panel-soft); }
|
||||
.conclusion-item + .conclusion-item { margin-top: 12px; }
|
||||
.conclusion-no { flex: none; width: 34px; height: 34px; border-radius: 50%; background: var(--primary); color: #ffffff; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 16px; }
|
||||
.conclusion-item h3 { margin: 0 0 4px; font-size: 18px; }
|
||||
.conclusion-item p { margin: 0; color: var(--ink-soft); }
|
||||
.metric {
|
||||
padding: 18px 20px; height: 100%;
|
||||
background: var(--panel-soft);
|
||||
border: 1px solid var(--panel-line, var(--line)); border-radius: 14px;
|
||||
box-shadow: 0 8px 22px rgba(99, 125, 190, 0.1);
|
||||
transition: box-shadow 0.3s ease, transform 0.3s ease;
|
||||
}
|
||||
.metric:hover { box-shadow: 0 20px 44px rgba(99, 125, 190, 0.22); transform: translateY(-2px); }
|
||||
.metric-label { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: var(--ink-soft); font-size: 15px; letter-spacing: 0.04em; }
|
||||
.metric-more { color: var(--ink-dim, var(--ink-soft)); font-size: 12px; white-space: nowrap; }
|
||||
.metric-value { margin-top: 10px; font-size: 36px; font-weight: 800; line-height: 1.15; color: var(--primary); font-variant-numeric: tabular-nums; }
|
||||
.metric-value small { font-size: 16px; font-weight: 600; margin-left: 4px; color: var(--ink-soft); }
|
||||
.metric-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; color: var(--ink-dim, var(--ink-soft)); font-size: 13px; flex-wrap: wrap; }
|
||||
.delta { padding: 2px 10px; border-radius: 999px; font-weight: 700; font-size: 13px; }
|
||||
.delta.up { color: #0e9c8f; background: rgba(23, 179, 174, 0.14); }
|
||||
.delta.down { color: #cf6a15; background: rgba(236, 155, 47, 0.16); }
|
||||
.metric-note { color: var(--ink-soft); font-size: 16px; }
|
||||
.metric-value { margin-top: 6px; color: var(--primary); font-size: 28px; font-weight: 800; line-height: 1.2; }
|
||||
.prose { max-width: 860px; }
|
||||
.prose p { margin: 0 0 12px; }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); }
|
||||
.data-table th, .data-table td { padding: 13px 15px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.level { border-radius: 999px; padding: 4px 12px; font-size: 16px; font-weight: 700; white-space: nowrap; }
|
||||
.level-high { background: #fbeaea; color: var(--danger); }
|
||||
.level-mid { background: #fdf3e3; color: var(--warn); }
|
||||
.level-low { background: var(--primary-soft); color: var(--primary); }
|
||||
.action-list { margin: 0; padding: 0; list-style: none; }
|
||||
.action-list li { position: relative; padding: 0 0 14px 34px; }
|
||||
.action-list li:last-child { padding-bottom: 0; }
|
||||
.action-list li::before { content: ""; position: absolute; left: 4px; top: 6px; width: 14px; height: 14px; border: 2px solid var(--accent); border-radius: 4px; }
|
||||
.action-list strong { display: block; }
|
||||
.action-list span { color: var(--ink-soft); }
|
||||
.source-list { margin: 0; padding-left: 22px; color: var(--ink-soft); }
|
||||
.source-list li + li { margin-top: 6px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.brief-header, .section-card { padding: 22px 18px; }
|
||||
}
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
[hidden] { display: none !important; }
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .portal-nav a { transition: none; } }
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-core" class="active">核心结论</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">研判简报</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-action">风险与行动</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-core" data-page="core" data-page-title="核心结论" aria-label="核心结论">
|
||||
<header class="card brief-header">
|
||||
<div class="brief-top">
|
||||
<p class="eyebrow">研判简报 · 第 X 期(替换)</p>
|
||||
</div>
|
||||
<h1>简报主题(替换为真实主题)</h1>
|
||||
<div class="brief-meta">
|
||||
<span>资料范围:待替换</span>
|
||||
<span>编制单位:待替换</span>
|
||||
<span>分发范围:待替换</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="card section-card" aria-label="核心结论">
|
||||
<div class="section-title"><span class="section-index">01</span><h2>核心结论</h2></div>
|
||||
<div class="conclusion-item">
|
||||
<span class="conclusion-no">1</span>
|
||||
<div><h3>第一条结论(替换)</h3><p>一句话判断 + 支撑依据。读者只读这一屏也应能拿走全部结论。</p></div>
|
||||
</div>
|
||||
<div class="conclusion-item">
|
||||
<span class="conclusion-no">2</span>
|
||||
<div><h3>第二条结论(替换)</h3><p>一句话判断 + 支撑依据。按重要性排序,最重要的放最前面。</p></div>
|
||||
</div>
|
||||
<div class="conclusion-item">
|
||||
<span class="conclusion-no">3</span>
|
||||
<div><h3>第三条结论(替换)</h3><p>一句话判断 + 支撑依据。没有第三条时可删除本块。</p></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="关键指标">
|
||||
<div class="row g-4">
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标一(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">1,286</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标二(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">+18.4%</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标三(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">92.6%</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
<div class="col-6 col-lg-3"><div class="metric"><div class="metric-label"><span>指标四(替换)</span><span class="metric-more">口径说明 ↗</span></div><div class="metric-value">37 项</div><div class="metric-foot"><span>口径说明 · 示意数据</span></div></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="态势研判">
|
||||
<div class="section-title"><span class="section-index">02</span><h2>态势研判</h2></div>
|
||||
<div class="prose">
|
||||
<p>按「事实 — 变化 — 影响」的顺序展开研判:先陈述本期发生的事实,再指出与上期的差异,最后说明对后续的影响与观察窗口。</p>
|
||||
<p>示例占位文字:涉及推断的句子应使用「预计」「可能」「待核实」等限定词,与已核实事实区分表述;每段围绕一个问题,不混合多个主题。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-action" data-page="action" data-page-title="风险行动" hidden aria-label="风险行动">
|
||||
<section class="card section-card" aria-label="风险清单">
|
||||
<div class="section-title"><span class="section-index">03</span><h2>风险清单</h2></div>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>等级</th><th>风险描述</th><th>潜在影响</th><th>应对建议</th><th>责任方</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><span class="level level-high">高</span></td><td>示例风险一(替换)</td><td>影响范围与量级</td><td>处置思路与时间窗</td><td>待定</td></tr>
|
||||
<tr><td><span class="level level-mid">中</span></td><td>示例风险二(替换)</td><td>影响范围与量级</td><td>处置思路与时间窗</td><td>待定</td></tr>
|
||||
<tr><td><span class="level level-low">低</span></td><td>示例风险三(替换)</td><td>影响范围与量级</td><td>处置思路与时间窗</td><td>待定</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="行动建议">
|
||||
<div class="section-title"><span class="section-index">04</span><h2>行动建议</h2></div>
|
||||
<ul class="action-list">
|
||||
<li><strong>建议一(替换)</strong><span>说明执行要点、时限与完成标志。</span></li>
|
||||
<li><strong>建议二(替换)</strong><span>说明执行要点、时限与完成标志。</span></li>
|
||||
<li><strong>建议三(替换)</strong><span>说明执行要点、时限与完成标志;没有依据的建议应删除。</span></li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="附录">
|
||||
<div class="section-title"><span class="section-index">05</span><h2>附录 · 资料来源</h2></div>
|
||||
<ol class="source-list">
|
||||
<li>资料一(替换:名称、来源、时间)</li>
|
||||
<li>资料二(替换:名称、来源、时间)</li>
|
||||
<li>资料三(替换:名称、来源、时间)</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
</script>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script> </body>
|
||||
</html>
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>专题研究报告 · 深色文字杂志版式</title>
|
||||
<!--
|
||||
深色文字杂志单页模板(Bootstrap 排版,无图表)
|
||||
0. 本模板为双页轻量门户:.pages 容器 + 两个 .page[data-page] 逻辑页,锚点切页;最低页数 2。第 1 页:内容摘要、背景与问题、主体分析。第 2 页:发展脉络、方案对照与结论建议。
|
||||
1. 面向长文阅读的响应式单页文档:杂志式章节、引用、时间线、对照表与要点卡。
|
||||
2. 适合材料以文字为主、结构层次比数据更重要的专题报告、调研纪要与研判综述。
|
||||
3. 按真实材料替换全部示例内容;章节按需增删,不要为凑版式编造内容。
|
||||
4. 页面标识(系统名称 + Logo)由平台按系统设置自动注入页眉页脚,不要自己书写。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #0d1420;
|
||||
--panel: #141e30;
|
||||
--panel-soft: #1a2941;
|
||||
--ink: #eaf1fb;
|
||||
--ink-soft: #a7b7c9;
|
||||
--line: rgba(132, 172, 220, 0.22);
|
||||
--primary: #7fb3a3;
|
||||
--primary-soft: #1a3129;
|
||||
--accent: #d2a86a;
|
||||
--shadow: 0 12px 30px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background:
|
||||
radial-gradient(1200px 600px at 50% -10%, rgba(30, 90, 200, 0.26), transparent 60%),
|
||||
radial-gradient(900px 500px at 100% 100%, rgba(20, 160, 180, 0.12), transparent 55%),
|
||||
var(--page);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; opacity: 0.4;
|
||||
background-image:
|
||||
linear-gradient(rgba(60, 140, 255, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(60, 140, 255, 0.05) 1px, transparent 1px);
|
||||
background-size: 42px 42px;
|
||||
}
|
||||
.wrap { width: min(100% - 44px, 980px); margin: 28px auto 56px; }
|
||||
.card {
|
||||
position: relative;
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
box-shadow: inset 0 0 30px rgba(20, 70, 160, 0.1);
|
||||
}
|
||||
.card::before, .card::after { content: ""; position: absolute; width: 14px; height: 14px; pointer-events: none; opacity: 0.9; }
|
||||
.card::before { left: -1px; top: -1px; border-left: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-top: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-top-left-radius: 12px; }
|
||||
.card::after { right: -1px; bottom: -1px; border-right: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-bottom: 2px solid var(--corner, rgba(63, 214, 255, 0.75)); border-bottom-right-radius: 12px; }
|
||||
.hero { padding: 44px 46px; }
|
||||
.eyebrow { margin: 0 0 10px; color: var(--primary); font-weight: 700; letter-spacing: 0.12em; font-size: 16px; }
|
||||
h1 { margin: 0; font-size: clamp(30px, 4.4vw, 44px); line-height: 1.24; letter-spacing: -0.02em; }
|
||||
.lead { max-width: 780px; margin: 16px 0 0; color: var(--ink-soft); font-size: 18px; }
|
||||
.meta { display: flex; flex-wrap: wrap; gap: 8px 22px; margin-top: 20px; color: var(--ink-soft); font-size: 16px; }
|
||||
.section-card { padding: 32px 36px; }
|
||||
.chapter-head { display: flex; align-items: baseline; gap: 14px; margin-bottom: 14px; }
|
||||
.chapter-no { color: var(--accent); font-weight: 800; font-size: 16px; letter-spacing: 0.08em; }
|
||||
h2 { margin: 0; font-size: 26px; line-height: 1.35; }
|
||||
.prose { max-width: 840px; }
|
||||
.prose p { margin: 0 0 14px; }
|
||||
.abstract { padding: 22px 26px; border-left: 5px solid var(--primary); border-radius: 12px; background: var(--primary-soft); }
|
||||
.abstract strong { display: block; margin-bottom: 8px; font-size: 18px; }
|
||||
.abstract p { margin: 0; }
|
||||
.point-card { padding: 20px 22px; background: var(--panel-soft); border: 1px solid var(--line); border-radius: 14px; height: 100%; }
|
||||
.point-card h3 { margin: 0 0 8px; font-size: 19px; }
|
||||
.point-card p { margin: 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.pull-quote { margin: 26px 0 0; padding: 6px 0 6px 26px; border-left: 4px solid var(--accent); color: var(--ink); font-size: 20px; line-height: 1.7; font-weight: 600; }
|
||||
.pull-quote cite { display: block; margin-top: 8px; color: var(--ink-soft); font-size: 16px; font-style: normal; font-weight: 400; }
|
||||
.timeline { display: grid; gap: 0; margin: 0; padding: 0; }
|
||||
.timeline-item { position: relative; padding: 0 0 24px 32px; border-left: 2px solid var(--line); }
|
||||
.timeline-item:last-child { padding-bottom: 0; border-left-color: transparent; }
|
||||
.timeline-item::before { content: ""; position: absolute; left: -7px; top: 9px; width: 12px; height: 12px; border-radius: 50%; background: var(--primary); box-shadow: 0 0 0 4px var(--primary-soft); }
|
||||
.timeline-item time { color: var(--primary); font-weight: 700; }
|
||||
.timeline-item h3 { margin: 4px 0; font-size: 19px; }
|
||||
.timeline-item p { margin: 0; color: var(--ink-soft); }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); color: var(--ink); }
|
||||
.data-table th, .data-table td { padding: 14px 16px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 12px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.hero, .section-card { padding: 24px 20px; }
|
||||
}
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
[hidden] { display: none !important; }
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .portal-nav a { transition: none; } }
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-body" class="active">正文论述</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">专题研究报告</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-review">脉络与结论</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-body" data-page="body" data-page-title="正文论述" aria-label="正文论述">
|
||||
<header class="card hero">
|
||||
<p class="eyebrow">专题研究报告</p>
|
||||
<h1>研究主题(替换为真实标题)</h1>
|
||||
<p class="lead">用一段话交代研究对象、材料范围、方法与全文最重要的结论,让读者三分钟内判断这份报告与自己的关系。</p>
|
||||
<div class="meta">
|
||||
<span>资料范围:待替换</span>
|
||||
<span>编制:待替换</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="card section-card" aria-label="内容摘要">
|
||||
<div class="abstract">
|
||||
<strong>内容摘要</strong>
|
||||
<p>这里放置两百字左右的摘要:先给核心判断,再概述支撑判断的三条主要证据,最后指出结论的适用边界与需要持续跟踪的问题。摘要应当独立成文,不依赖正文即可被引用。示例文字仅用于占位,交付前请整体替换为真实内容。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="背景与问题">
|
||||
<div class="chapter-head"><span class="chapter-no">第一章</span><h2>背景与问题</h2></div>
|
||||
<div class="prose">
|
||||
<p>第一章说明问题从哪里来:宏观背景、直接动因与本次研究要回答的具体问题。写作时保持段落完整,一段只推进一个意思,先事实后判断。</p>
|
||||
<p>示例占位文字:可以从政策、行业、组织或事件四个维度中选取与主题最相关的维度展开,交代时间、范围与关键参与者,并明确本研究不覆盖的部分。</p>
|
||||
</div>
|
||||
<div class="row g-3 mt-2">
|
||||
<div class="col-md-4"><div class="point-card"><h3>要点一</h3><p>用一句话概括本章第一个支撑点,正文段落负责展开论证。</p></div></div>
|
||||
<div class="col-md-4"><div class="point-card"><h3>要点二</h3><p>用一句话概括本章第二个支撑点,注意与要点一的关系。</p></div></div>
|
||||
<div class="col-md-4"><div class="point-card"><h3>要点三</h3><p>用一句话概括本章第三个支撑点,或指出尚待核实的问题。</p></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="主体分析">
|
||||
<div class="chapter-head"><span class="chapter-no">第二章</span><h2>主体分析</h2></div>
|
||||
<div class="prose">
|
||||
<p>第二章是全文的主体:按逻辑把材料组织成若干小节,每一节回答一个具体问题。小节之间应有明确的推进关系,而不是简单罗列。</p>
|
||||
<p>示例占位文字:分析可以按对象、按时间、按层级或按因果链展开;引用材料时注明出处与时间,推断与事实分开表述,避免把可能性写成确定性。</p>
|
||||
</div>
|
||||
<blockquote class="pull-quote">
|
||||
这里放置全文最值得记住的一句话结论,作为引文突出展示。
|
||||
<cite>—— 出处或章节(替换)</cite>
|
||||
</blockquote>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-review" data-page="review" data-page-title="脉络结论" hidden aria-label="脉络结论">
|
||||
<section class="card section-card" aria-label="发展脉络">
|
||||
<div class="chapter-head"><span class="chapter-no">第三章</span><h2>发展脉络</h2></div>
|
||||
<div class="timeline">
|
||||
<article class="timeline-item"><time>阶段一(替换时间)</time><h3>起点与背景</h3><p>交代事件或态势的起点,以及它为什么值得注意。</p></article>
|
||||
<article class="timeline-item"><time>阶段二(替换时间)</time><h3>关键变化</h3><p>说明推动变化的主要因素与标志性事件。</p></article>
|
||||
<article class="timeline-item"><time>阶段三(替换时间)</time><h3>当前状态</h3><p>总结现状、限制条件与可以观察到的趋势。</p></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="方案对照">
|
||||
<div class="chapter-head"><span class="chapter-no">第四章</span><h2>方案对照</h2></div>
|
||||
<p class="prose" style="margin-bottom:14px;color:var(--ink-soft)">对照表用于并置两个及以上对象的异同;维度按决策需要选取,不要贪多。</p>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>维度</th><th>方案一(替换)</th><th>方案二(替换)</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>适用条件</td><td>示例:资源充足、周期长</td><td>示例:快速验证、范围小</td><td>先决条件差异</td></tr>
|
||||
<tr><td>主要优势</td><td>示例:覆盖全面</td><td>示例:落地快</td><td>各自最强的点</td></tr>
|
||||
<tr><td>主要风险</td><td>示例:投入大</td><td>示例:扩展性弱</td><td>需要预案的部分</td></tr>
|
||||
<tr><td>成本量级</td><td>示例:高</td><td>示例:中</td><td>量级即可,不必精确</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="结论与建议">
|
||||
<div class="chapter-head"><span class="chapter-no">第五章</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>核心结论:一句话判断,附正文对应章节作为依据。</li>
|
||||
<li>主要建议:分近期可执行与中长期布局两层表述。</li>
|
||||
<li>需持续跟踪的信号与需要补充的数据。</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
</script>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script> </body>
|
||||
</html>
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>专题研究报告 · 浅色文字杂志版式</title>
|
||||
<!--
|
||||
浅色文字杂志单页模板(Bootstrap 排版,无图表)
|
||||
0. 本模板为双页轻量门户:.pages 容器 + 两个 .page[data-page] 逻辑页,锚点切页;最低页数 2。第 1 页:内容摘要、背景与问题、主体分析。第 2 页:发展脉络、方案对照与结论建议。
|
||||
1. 面向长文阅读的响应式单页文档:杂志式章节、引用、时间线、对照表与要点卡。
|
||||
2. 适合材料以文字为主、结构层次比数据更重要的专题报告、调研纪要与研判综述。
|
||||
3. 按真实材料替换全部示例内容;章节按需增删,不要为凑版式编造内容。
|
||||
4. 页面标识(系统名称 + Logo)由平台按系统设置自动注入页眉页脚,不要自己书写。
|
||||
-->
|
||||
<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css" />
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>
|
||||
<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #f5f6f2;
|
||||
--panel: #ffffff;
|
||||
--panel-soft: #f8faf7;
|
||||
--ink: #232b26;
|
||||
--ink-soft: #5f6b63;
|
||||
--line: #dfe5df;
|
||||
--primary: #2f6d5a;
|
||||
--primary-soft: #e8f2ee;
|
||||
--accent: #b0803c;
|
||||
--shadow: 0 10px 26px rgba(43, 58, 50, 0.07);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: linear-gradient(160deg, #eef3fc 0%, #f6f4f0 55%, #eaf6f3 100%);
|
||||
color: var(--ink);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
body::before {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background-image: radial-gradient(rgba(90, 120, 190, 0.13) 1px, transparent 1.5px);
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
body::after {
|
||||
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
||||
background:
|
||||
radial-gradient(42vw 42vw at -10% -16%, rgba(146, 176, 255, 0.34), transparent 62%),
|
||||
radial-gradient(34vw 34vw at 112% 28%, rgba(255, 205, 224, 0.26), transparent 62%),
|
||||
radial-gradient(38vw 38vw at 45% 118%, rgba(152, 232, 216, 0.3), transparent 62%);
|
||||
}
|
||||
.wrap { width: min(100% - 44px, 980px); margin: 28px auto 56px; }
|
||||
.card {
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--panel-line, var(--line));
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--shadow, 0 16px 40px rgba(99, 125, 190, 0.15)), inset 0 1px 0 rgba(255, 255, 255, 0.95);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
}
|
||||
.hero { padding: 44px 46px; }
|
||||
.eyebrow { margin: 0 0 10px; color: var(--primary); font-weight: 700; letter-spacing: 0.12em; font-size: 16px; }
|
||||
h1 { margin: 0; font-size: clamp(30px, 4.4vw, 44px); line-height: 1.24; letter-spacing: -0.02em; }
|
||||
.lead { max-width: 780px; margin: 16px 0 0; color: var(--ink-soft); font-size: 18px; }
|
||||
.meta { display: flex; flex-wrap: wrap; gap: 8px 22px; margin-top: 20px; color: var(--ink-soft); font-size: 16px; }
|
||||
.section-card { padding: 32px 36px; }
|
||||
.chapter-head { display: flex; align-items: baseline; gap: 14px; margin-bottom: 14px; }
|
||||
.chapter-no { color: var(--accent); font-weight: 800; font-size: 16px; letter-spacing: 0.08em; }
|
||||
h2 { margin: 0; font-size: 26px; line-height: 1.35; }
|
||||
.prose { max-width: 840px; }
|
||||
.prose p { margin: 0 0 14px; }
|
||||
.abstract { padding: 22px 26px; border-left: 5px solid var(--primary); border-radius: 12px; background: var(--primary-soft); }
|
||||
.abstract strong { display: block; margin-bottom: 8px; font-size: 18px; }
|
||||
.abstract p { margin: 0; }
|
||||
.point-card { padding: 20px 22px; background: var(--panel-soft); border: 1px solid var(--line); border-radius: 14px; height: 100%; }
|
||||
.point-card h3 { margin: 0 0 8px; font-size: 19px; }
|
||||
.point-card p { margin: 0; color: var(--ink-soft); font-size: 16px; }
|
||||
.pull-quote { margin: 26px 0 0; padding: 6px 0 6px 26px; border-left: 4px solid var(--accent); color: var(--ink); font-size: 20px; line-height: 1.7; font-weight: 600; }
|
||||
.pull-quote cite { display: block; margin-top: 8px; color: var(--ink-soft); font-size: 16px; font-style: normal; font-weight: 400; }
|
||||
.timeline { display: grid; gap: 0; margin: 0; padding: 0; }
|
||||
.timeline-item { position: relative; padding: 0 0 24px 32px; border-left: 2px solid var(--line); }
|
||||
.timeline-item:last-child { padding-bottom: 0; border-left-color: transparent; }
|
||||
.timeline-item::before { content: ""; position: absolute; left: -7px; top: 9px; width: 12px; height: 12px; border-radius: 50%; background: var(--primary); box-shadow: 0 0 0 4px var(--primary-soft); }
|
||||
.timeline-item time { color: var(--primary); font-weight: 700; }
|
||||
.timeline-item h3 { margin: 4px 0; font-size: 19px; }
|
||||
.timeline-item p { margin: 0; color: var(--ink-soft); }
|
||||
.data-table { width: 100%; border-collapse: collapse; background: var(--panel); }
|
||||
.data-table th, .data-table td { padding: 14px 16px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; color: var(--ink); }
|
||||
.data-table th { color: var(--primary); background: var(--panel-soft); }
|
||||
.data-table tr:last-child td { border-bottom: 0; }
|
||||
.key-points { margin: 0; padding-left: 22px; }
|
||||
.key-points li + li { margin-top: 12px; }
|
||||
@media (max-width: 767px) {
|
||||
body { padding-top: 0; }
|
||||
.hero, .section-card { padding: 24px 20px; }
|
||||
}
|
||||
/* ===== 兜底导航条:宽度同内容,品牌左 + 导航居中;平台注入页头时自动隐藏 ===== */
|
||||
[hidden] { display: none !important; }
|
||||
.pages { margin-top: 20px; display: grid; gap: 28px; }
|
||||
.page { display: grid; gap: 28px; align-content: start; }
|
||||
body:has([data-df-generated-header]) .portal-topbar { display: none !important; }
|
||||
.portal-topbar {
|
||||
position: sticky; top: 0; z-index: 900; width: 100%; height: 64px; margin: 0;
|
||||
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 clamp(20px, 3vw, 44px);
|
||||
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||
box-shadow: 0 10px 30px rgba(99, 125, 190, 0.12);
|
||||
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
|
||||
}
|
||||
.portal-brand { min-width: 0; justify-self: start; display: inline-flex; align-items: center; gap: 12px; white-space: nowrap; }
|
||||
.portal-title { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.08em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.portal-sub { margin: 1px 0 0; color: var(--ink-soft); font-size: 12px; letter-spacing: 0.04em; }
|
||||
.portal-nav { align-self: stretch; display: flex; align-items: stretch; justify-content: center; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.portal-nav::-webkit-scrollbar { display: none; }
|
||||
.portal-nav a {
|
||||
position: relative; display: inline-flex; align-items: center; flex: none; height: 100%; padding: 0 22px;
|
||||
color: var(--ink-soft); font-size: 15px; letter-spacing: 0.13em; font-weight: 550; text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
.portal-nav a::after {
|
||||
content: ""; position: absolute; right: 22px; bottom: 0; left: 22px; height: 4px; border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(90deg, var(--primary), var(--accent, var(--primary)));
|
||||
transform: scaleX(0); transform-origin: center;
|
||||
transition: transform 0.28s cubic-bezier(0.3, 0.9, 0.3, 1);
|
||||
}
|
||||
.portal-nav a:hover { color: var(--ink); }
|
||||
.portal-nav a:hover::after { transform: scaleX(0.45); }
|
||||
.portal-nav a.active { color: var(--primary); font-weight: 700; }
|
||||
.portal-nav a.active::after { transform: scaleX(1); }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; grid-template-columns: 1fr; grid-template-rows: auto auto; padding: 4px 14px 0; row-gap: 0; }
|
||||
.portal-nav { grid-row: 2; align-self: stretch; justify-content: flex-start; margin: 0 -6px; }
|
||||
.portal-nav a { height: 52px; padding: 0 14px; letter-spacing: 0.08em; }
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.portal-topbar { width: min(100% - 28px, 1240px); margin-top: 12px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .portal-nav a { transition: none; } }
|
||||
/* ===== 居中品牌兜底条(覆盖基线):品牌居中 + 导航分列两侧 ===== */
|
||||
.portal-topbar { height: 70px; padding: 0 26px; }
|
||||
.portal-brand { justify-self: center; position: relative; padding-bottom: 10px; }
|
||||
.portal-brand::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%);
|
||||
width: min(220px, 100%); height: 2px; border-radius: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--primary) 55%, transparent), transparent);
|
||||
}
|
||||
.portal-title { font-size: 20px; letter-spacing: 0.3em; }
|
||||
.portal-nav--l { justify-content: flex-end; }
|
||||
.portal-nav--r { justify-content: flex-start; }
|
||||
.portal-nav a { padding: 0 18px; letter-spacing: 0.14em; }
|
||||
@media (max-width: 900px) {
|
||||
.portal-topbar { height: auto; display: flex; flex-wrap: wrap; justify-content: center; padding: 6px 14px 0; }
|
||||
.portal-brand { order: 1; flex-basis: 100%; justify-content: center; justify-self: auto; padding-bottom: 2px; }
|
||||
.portal-nav--l, .portal-nav--r { order: 2; flex: 1 1 auto; justify-content: center; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="portal-topbar">
|
||||
<nav class="portal-nav portal-nav--l" aria-label="页面导航">
|
||||
<a href="#page-body" class="active">正文论述</a>
|
||||
</nav>
|
||||
<div class="portal-brand">
|
||||
<h1 class="portal-title">专题研究报告</h1>
|
||||
</div>
|
||||
<nav class="portal-nav portal-nav--r" aria-label="页面导航">
|
||||
<a href="#page-review">脉络与结论</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="wrap">
|
||||
|
||||
<main class="pages">
|
||||
<section class="page active" id="page-body" data-page="body" data-page-title="正文论述" aria-label="正文论述">
|
||||
<header class="card hero">
|
||||
<p class="eyebrow">专题研究报告</p>
|
||||
<h1>研究主题(替换为真实标题)</h1>
|
||||
<p class="lead">用一段话交代研究对象、材料范围、方法与全文最重要的结论,让读者三分钟内判断这份报告与自己的关系。</p>
|
||||
<div class="meta">
|
||||
<span>资料范围:待替换</span>
|
||||
<span>编制:待替换</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="card section-card" aria-label="内容摘要">
|
||||
<div class="abstract">
|
||||
<strong>内容摘要</strong>
|
||||
<p>这里放置两百字左右的摘要:先给核心判断,再概述支撑判断的三条主要证据,最后指出结论的适用边界与需要持续跟踪的问题。摘要应当独立成文,不依赖正文即可被引用。示例文字仅用于占位,交付前请整体替换为真实内容。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="背景与问题">
|
||||
<div class="chapter-head"><span class="chapter-no">第一章</span><h2>背景与问题</h2></div>
|
||||
<div class="prose">
|
||||
<p>第一章说明问题从哪里来:宏观背景、直接动因与本次研究要回答的具体问题。写作时保持段落完整,一段只推进一个意思,先事实后判断。</p>
|
||||
<p>示例占位文字:可以从政策、行业、组织或事件四个维度中选取与主题最相关的维度展开,交代时间、范围与关键参与者,并明确本研究不覆盖的部分。</p>
|
||||
</div>
|
||||
<div class="row g-3 mt-2">
|
||||
<div class="col-md-4"><div class="point-card"><h3>要点一</h3><p>用一句话概括本章第一个支撑点,正文段落负责展开论证。</p></div></div>
|
||||
<div class="col-md-4"><div class="point-card"><h3>要点二</h3><p>用一句话概括本章第二个支撑点,注意与要点一的关系。</p></div></div>
|
||||
<div class="col-md-4"><div class="point-card"><h3>要点三</h3><p>用一句话概括本章第三个支撑点,或指出尚待核实的问题。</p></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="主体分析">
|
||||
<div class="chapter-head"><span class="chapter-no">第二章</span><h2>主体分析</h2></div>
|
||||
<div class="prose">
|
||||
<p>第二章是全文的主体:按逻辑把材料组织成若干小节,每一节回答一个具体问题。小节之间应有明确的推进关系,而不是简单罗列。</p>
|
||||
<p>示例占位文字:分析可以按对象、按时间、按层级或按因果链展开;引用材料时注明出处与时间,推断与事实分开表述,避免把可能性写成确定性。</p>
|
||||
</div>
|
||||
<blockquote class="pull-quote">
|
||||
这里放置全文最值得记住的一句话结论,作为引文突出展示。
|
||||
<cite>—— 出处或章节(替换)</cite>
|
||||
</blockquote>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section class="page" id="page-review" data-page="review" data-page-title="脉络结论" hidden aria-label="脉络结论">
|
||||
<section class="card section-card" aria-label="发展脉络">
|
||||
<div class="chapter-head"><span class="chapter-no">第三章</span><h2>发展脉络</h2></div>
|
||||
<div class="timeline">
|
||||
<article class="timeline-item"><time>阶段一(替换时间)</time><h3>起点与背景</h3><p>交代事件或态势的起点,以及它为什么值得注意。</p></article>
|
||||
<article class="timeline-item"><time>阶段二(替换时间)</time><h3>关键变化</h3><p>说明推动变化的主要因素与标志性事件。</p></article>
|
||||
<article class="timeline-item"><time>阶段三(替换时间)</time><h3>当前状态</h3><p>总结现状、限制条件与可以观察到的趋势。</p></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="方案对照">
|
||||
<div class="chapter-head"><span class="chapter-no">第四章</span><h2>方案对照</h2></div>
|
||||
<p class="prose" style="margin-bottom:14px;color:var(--ink-soft)">对照表用于并置两个及以上对象的异同;维度按决策需要选取,不要贪多。</p>
|
||||
<div class="table-responsive">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>维度</th><th>方案一(替换)</th><th>方案二(替换)</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>适用条件</td><td>示例:资源充足、周期长</td><td>示例:快速验证、范围小</td><td>先决条件差异</td></tr>
|
||||
<tr><td>主要优势</td><td>示例:覆盖全面</td><td>示例:落地快</td><td>各自最强的点</td></tr>
|
||||
<tr><td>主要风险</td><td>示例:投入大</td><td>示例:扩展性弱</td><td>需要预案的部分</td></tr>
|
||||
<tr><td>成本量级</td><td>示例:高</td><td>示例:中</td><td>量级即可,不必精确</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card section-card" aria-label="结论与建议">
|
||||
<div class="chapter-head"><span class="chapter-no">第五章</span><h2>结论与建议</h2></div>
|
||||
<ol class="key-points">
|
||||
<li>核心结论:一句话判断,附正文对应章节作为依据。</li>
|
||||
<li>主要建议:分近期可执行与中长期布局两层表述。</li>
|
||||
<li>需持续跟踪的信号与需要补充的数据。</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
</script>
|
||||
<script>
|
||||
// 平台品牌套壳存在时由其接管切页;否则用这份轻量兜底脚本按锚点切换逻辑页。
|
||||
(function () {
|
||||
function activate(id) {
|
||||
var pages = document.querySelectorAll(".pages .page[data-page]");
|
||||
var found = false;
|
||||
for (var i = 0; i < pages.length; i += 1) {
|
||||
var match = pages[i].id === id;
|
||||
pages[i].hidden = !match;
|
||||
pages[i].classList.toggle("active", match);
|
||||
if (match) {
|
||||
// 兼容第三方预览脚本:清掉它可能写上的 inline display。
|
||||
pages[i].style.removeProperty("display");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found && pages.length) { pages[0].hidden = false; pages[0].classList.add("active"); }
|
||||
var links = document.querySelectorAll('.portal-nav a[href^="#page-"]');
|
||||
for (var j = 0; j < links.length; j += 1) {
|
||||
links[j].classList.toggle("active", links[j].getAttribute("href") === "#" + id);
|
||||
}
|
||||
}
|
||||
function onHash() {
|
||||
var hash = (window.location.hash || "").replace(/^#/, "");
|
||||
if (hash && document.getElementById(hash)) activate(hash);
|
||||
}
|
||||
if (document.querySelector("[data-df-generated-header]")) {
|
||||
var bar = document.querySelector(".portal-topbar");
|
||||
if (bar) bar.setAttribute("hidden", "");
|
||||
return;
|
||||
}
|
||||
// 预览器等第三方锚点脚本只切 display、不清 hidden;点击导航时先自行激活。
|
||||
document.addEventListener("click", function (event) {
|
||||
var link = event.target.closest ? event.target.closest('.portal-nav a[href^="#page-"]') : null;
|
||||
if (!link) return;
|
||||
activate(link.getAttribute("href").slice(1));
|
||||
}, true);
|
||||
|
||||
window.addEventListener("hashchange", onHash);
|
||||
document.addEventListener("DOMContentLoaded", onHash);
|
||||
})();
|
||||
</script> </body>
|
||||
</html>
|
||||
@@ -152,6 +152,120 @@ _TEMPLATES: tuple[PageTemplateProfile, ...] = (
|
||||
data_entry="reportData(日期、可见页面)+ 页面结构",
|
||||
best_for=("多页面", "文字为主", "汇报研判", "行动督办"),
|
||||
),
|
||||
# Bootstrap 平台模板套件:运行库全部来自设置里保存的 HTML 运行库地址,
|
||||
# 图形走 deerflow-runtime 声明式契约;网页标识由平台
|
||||
# 统一注入,模板自身不携带品牌内容。套件只提供多页面模板(最低 2 页),
|
||||
# 单页请求自动回落共享响应式文档模板。
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-charts-portal-light",
|
||||
filename="report-bootstrap-charts-portal-light-template.html",
|
||||
theme="light",
|
||||
title="浅色图表门户(Bootstrap 多页)",
|
||||
style="Bootstrap + Alpine 轻量门户、锚点切页、ECharts 声明式图表",
|
||||
page_count=3,
|
||||
features=("kpi", "line", "bar", "pie", "radar", "table", "text-panels", "chart", "animation"),
|
||||
data_entry="页面结构直接编辑(data-df-chart JSON 块逐个替换)",
|
||||
best_for=("多页面", "经营分析门户", "图表优先", "Bootstrap 风格"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-charts-portal-dark",
|
||||
filename="report-bootstrap-charts-portal-dark-template.html",
|
||||
theme="dark",
|
||||
title="深色图表门户(Bootstrap 多页)",
|
||||
style="Bootstrap + Alpine 深色轻量门户、锚点切页、ECharts 声明式图表",
|
||||
page_count=3,
|
||||
features=("kpi", "line", "bar", "pie", "radar", "table", "text-panels", "chart", "animation"),
|
||||
data_entry="页面结构直接编辑(data-df-chart JSON 块逐个替换)",
|
||||
best_for=("多页面", "经营分析门户", "图表优先", "深色风格"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-gantt-light",
|
||||
filename="report-bootstrap-gantt-light-template.html",
|
||||
theme="light",
|
||||
title="浅色甘特图门户(Bootstrap 双页)",
|
||||
style="Bootstrap 双页门户:进度总览 + 甘特图 / 里程碑风险时间线",
|
||||
page_count=2,
|
||||
features=("kpi", "gantt", "table", "timeline", "text-panels", "chart"),
|
||||
data_entry="页面结构直接编辑(甘特 data-df-chart JSON 块替换)",
|
||||
best_for=("项目进度", "计划排期", "里程碑督办", "甘特图"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-gantt-dark",
|
||||
filename="report-bootstrap-gantt-dark-template.html",
|
||||
theme="dark",
|
||||
title="深色甘特图门户(Bootstrap 双页)",
|
||||
style="Bootstrap 深色双页门户:进度总览 + 甘特图 / 里程碑风险时间线",
|
||||
page_count=2,
|
||||
features=("kpi", "gantt", "table", "timeline", "text-panels", "chart"),
|
||||
data_entry="页面结构直接编辑(甘特 data-df-chart JSON 块替换)",
|
||||
best_for=("项目进度", "计划排期", "里程碑督办", "深色风格"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-map-portal-light",
|
||||
filename="report-bootstrap-map-portal-light-template.html",
|
||||
theme="light",
|
||||
title="浅色瓦片地图门户(Bootstrap 多页)",
|
||||
style="Leaflet 瓦片地图(后台 map_tile_url)+ ECharts 走势、态势总览/地图/明细三页",
|
||||
page_count=3,
|
||||
features=("kpi", "map", "line", "table", "text-panels", "chart"),
|
||||
data_entry="页面结构直接编辑(data-df-map 与 data-df-chart JSON 块替换)",
|
||||
best_for=("地图态势", "点位分布", "区域研判", "瓦片地图"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-map-portal-dark",
|
||||
filename="report-bootstrap-map-portal-dark-template.html",
|
||||
theme="dark",
|
||||
title="深色瓦片地图门户(Bootstrap 多页)",
|
||||
style="Leaflet 瓦片地图(后台 map_tile_url)+ ECharts 走势、深色态势总览/地图/明细三页",
|
||||
page_count=3,
|
||||
features=("kpi", "map", "line", "table", "text-panels", "chart"),
|
||||
data_entry="页面结构直接编辑(data-df-map 与 data-df-chart JSON 块替换)",
|
||||
best_for=("地图态势", "点位分布", "区域研判", "深色风格"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-text-magazine-light",
|
||||
filename="report-bootstrap-text-magazine-light-template.html",
|
||||
theme="light",
|
||||
title="浅色文字杂志门户(Bootstrap 双页)",
|
||||
style="双页杂志排版:正文论述 / 发展脉络与结论,无图表",
|
||||
page_count=2,
|
||||
features=("text-panels", "table", "timeline"),
|
||||
data_entry="页面结构直接编辑(章节与段落逐段替换)",
|
||||
best_for=("专题研究", "调研综述", "长文阅读", "文字为主"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-text-magazine-dark",
|
||||
filename="report-bootstrap-text-magazine-dark-template.html",
|
||||
theme="dark",
|
||||
title="深色文字杂志门户(Bootstrap 双页)",
|
||||
style="深色双页杂志排版:正文论述 / 发展脉络与结论,无图表",
|
||||
page_count=2,
|
||||
features=("text-panels", "table", "timeline"),
|
||||
data_entry="页面结构直接编辑(章节与段落逐段替换)",
|
||||
best_for=("专题研究", "调研综述", "长文阅读", "深色风格"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-text-briefing-light",
|
||||
filename="report-bootstrap-text-briefing-light-template.html",
|
||||
theme="light",
|
||||
title="浅色研判简报门户(Bootstrap 双页)",
|
||||
style="双页结论先行版式:核心结论 / 风险清单与行动建议",
|
||||
page_count=2,
|
||||
features=("kpi", "text-panels", "table"),
|
||||
data_entry="页面结构直接编辑(结论、风险与行动项逐条替换)",
|
||||
best_for=("研判简报", "日报周报", "风险督办", "快速阅读"),
|
||||
),
|
||||
PageTemplateProfile(
|
||||
id="bootstrap-text-briefing-dark",
|
||||
filename="report-bootstrap-text-briefing-dark-template.html",
|
||||
theme="dark",
|
||||
title="深色研判简报门户(Bootstrap 双页)",
|
||||
style="深色双页结论先行版式:核心结论 / 风险清单与行动建议",
|
||||
page_count=2,
|
||||
features=("kpi", "text-panels", "table"),
|
||||
data_entry="页面结构直接编辑(结论、风险与行动项逐条替换)",
|
||||
best_for=("研判简报", "日报周报", "风险督办", "深色风格"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -31,6 +31,16 @@ class AgentStore(ABC):
|
||||
async def ensure_builtin(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def migration_upsert(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Create or fully reconcile one row from a trusted migration manifest.
|
||||
|
||||
Unlike ordinary CRUD this may change ownership and source timestamps so
|
||||
a startup-created built-in placeholder can be converted back into the
|
||||
original user-owned record. Caller must enforce administrator access.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def update(self, agent_id: str, user_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
raise NotImplementedError
|
||||
|
||||
+25
@@ -19,6 +19,10 @@ def _copy(data: dict[str, Any]) -> dict[str, Any]:
|
||||
return copied
|
||||
|
||||
|
||||
def _stamp(value: Any, fallback: str) -> str:
|
||||
return value.isoformat() if isinstance(value, datetime) else str(value or fallback)
|
||||
|
||||
|
||||
class MemoryAgentStore(AgentStore):
|
||||
def __init__(self) -> None:
|
||||
self._agents: dict[str, dict[str, Any]] = {}
|
||||
@@ -106,6 +110,27 @@ class MemoryAgentStore(AgentStore):
|
||||
row["updated_at"] = _now()
|
||||
return _copy(row)
|
||||
|
||||
async def migration_upsert(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
existing = self._agents.get(data["id"])
|
||||
now = _now()
|
||||
row = existing if existing is not None else {"id": data["id"]}
|
||||
row.update(
|
||||
{
|
||||
"name": data["name"],
|
||||
"description": data.get("description") or "",
|
||||
"user_id": data.get("user_id"),
|
||||
"published": bool(data.get("published", False)),
|
||||
"is_private": bool(data.get("is_private", False)),
|
||||
"square_id": str(data.get("square_id") or ""),
|
||||
"hidden": bool(data.get("hidden", False)),
|
||||
"featured_order": data.get("featured_order"),
|
||||
"created_at": _stamp(data.get("created_at"), row.get("created_at") or now),
|
||||
"updated_at": _stamp(data.get("updated_at"), now),
|
||||
}
|
||||
)
|
||||
self._agents[row["id"]] = row
|
||||
return _copy(row)
|
||||
|
||||
async def update(self, agent_id: str, user_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
row = self._agents.get(agent_id)
|
||||
if row is None or row.get("user_id") != user_id:
|
||||
|
||||
@@ -39,6 +39,14 @@ def _row_to_dict(row: AgentRow) -> dict[str, Any]:
|
||||
return data
|
||||
|
||||
|
||||
def _as_datetime(value: Any, fallback: datetime) -> datetime:
|
||||
if isinstance(value, datetime):
|
||||
return value
|
||||
if isinstance(value, str) and value.strip():
|
||||
return datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
|
||||
return fallback
|
||||
|
||||
|
||||
class AgentRepository(AgentStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
@@ -209,6 +217,30 @@ class AgentRepository(AgentStore):
|
||||
await session.refresh(row)
|
||||
return _row_to_dict(row)
|
||||
|
||||
async def migration_upsert(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(AgentRow, data["id"])
|
||||
now = datetime.now(UTC)
|
||||
if row is None:
|
||||
row = AgentRow(id=data["id"], name=data["name"])
|
||||
session.add(row)
|
||||
row.name = data["name"]
|
||||
row.description = data.get("description") or ""
|
||||
row.user_id = data.get("user_id")
|
||||
row.published = bool(data.get("published", False))
|
||||
row.is_private = bool(data.get("is_private", False))
|
||||
row.square_id = str(data.get("square_id") or "")
|
||||
if "hidden" in data:
|
||||
row.hidden = bool(data.get("hidden", False))
|
||||
row.featured_order = data.get("featured_order")
|
||||
row.created_at = _as_datetime(
|
||||
data.get("created_at"), getattr(row, "created_at", None) or now
|
||||
)
|
||||
row.updated_at = _as_datetime(data.get("updated_at"), now)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _row_to_dict(row)
|
||||
|
||||
async def update(self, agent_id: str, user_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(AgentRow, agent_id)
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ A "business mapping" row binds a fixed business code (3Q / 6BF / 3q-0…3q-6 /
|
||||
6-1…6-4 / 7BF / 7-1…7-4 / 8BF / AFX) to an optional 智能体 (``agent_id``) and an optional 业务链条
|
||||
(``chain_id`` → a ``roundtable_chains`` row, which must be **public** so every
|
||||
account can resolve it). Used to auto-pick the business chain when a task page
|
||||
launches the multi-agent roundtable. ``3q-1…3q-6`` are seeded as custom-type rows.
|
||||
launches the multi-agent roundtable.
|
||||
|
||||
Unlike ``roundtable_chains`` (per-user), this mapping is **global / shared** —
|
||||
there is no ``user_id`` column; all accounts see and use the same configuration.
|
||||
|
||||
+10
-28
@@ -23,8 +23,6 @@ _UNSET = object()
|
||||
# AFX = goPath=agentfx 深链(新系统 iframe 嵌入的智能体问答,任务详情取本系统 cop-task-detail)。
|
||||
# b5-1 = 外部写入本系统详情后,由本系统读取的任务分析单智能体深链。
|
||||
# 3q-0…3q-6 / 6-1…6-4 / 7-1…7-4 = 独立配置位(与 3Q/6BF/7BF 等无关),固定排在表尾。
|
||||
# 3q-1…3q-6 默认按「自定义类型」落库(goPath 走自定义深链);配置管理页默认不展示这 6 行。
|
||||
_CUSTOM_SLOT = {"is_custom": True, "mapping_type": "自定义类型"}
|
||||
DEFAULT_BUSINESS_ROWS: list[dict[str, Any]] = [
|
||||
{"business_code": "3Q", "label": "3QFX"},
|
||||
{"business_code": "6BF", "label": "任务FX"},
|
||||
@@ -34,12 +32,12 @@ DEFAULT_BUSINESS_ROWS: list[dict[str, Any]] = [
|
||||
{"business_code": "b5-1", "label": "任务分析"},
|
||||
# 独立配置位,与上方业务码无关;固定排在表尾。
|
||||
{"business_code": "3q-0", "label": "3q-0"},
|
||||
{"business_code": "3q-1", "label": "3q-1", **_CUSTOM_SLOT},
|
||||
{"business_code": "3q-2", "label": "3q-2", **_CUSTOM_SLOT},
|
||||
{"business_code": "3q-3", "label": "3q-3", **_CUSTOM_SLOT},
|
||||
{"business_code": "3q-4", "label": "3q-4", **_CUSTOM_SLOT},
|
||||
{"business_code": "3q-5", "label": "3q-5", **_CUSTOM_SLOT},
|
||||
{"business_code": "3q-6", "label": "3q-6", **_CUSTOM_SLOT},
|
||||
{"business_code": "3q-1", "label": "3q-1"},
|
||||
{"business_code": "3q-2", "label": "3q-2"},
|
||||
{"business_code": "3q-3", "label": "3q-3"},
|
||||
{"business_code": "3q-4", "label": "3q-4"},
|
||||
{"business_code": "3q-5", "label": "3q-5"},
|
||||
{"business_code": "3q-6", "label": "3q-6"},
|
||||
{"business_code": "6-1", "label": "6-1"},
|
||||
{"business_code": "6-2", "label": "6-2"},
|
||||
{"business_code": "6-3", "label": "6-3"},
|
||||
@@ -51,14 +49,6 @@ DEFAULT_BUSINESS_ROWS: list[dict[str, Any]] = [
|
||||
]
|
||||
|
||||
|
||||
def _seed_type(seed: dict[str, Any]) -> tuple[bool, str]:
|
||||
is_custom = bool(seed.get("is_custom", False))
|
||||
mapping_type = str(seed.get("mapping_type") or "").strip()
|
||||
if not mapping_type:
|
||||
mapping_type = "自定义类型" if is_custom else "内置业务"
|
||||
return is_custom, mapping_type
|
||||
|
||||
|
||||
class BusinessMappingRepository:
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
@@ -168,16 +158,14 @@ class BusinessMappingRepository:
|
||||
"""Idempotently insert the fixed business rows if missing. Returns inserted count.
|
||||
|
||||
Never overwrites an existing row's agent/chain (respects user config).
|
||||
Re-syncs ``sort_order``, empty ``label``, and seed ``is_custom`` /
|
||||
``mapping_type`` so newly inserted codes keep the intended table order
|
||||
and 3q-1…3q-6 stay classified as custom type.
|
||||
Re-syncs ``sort_order`` (and empty ``label``) so newly inserted codes keep
|
||||
the intended table order next to older seeded rows.
|
||||
"""
|
||||
inserted = 0
|
||||
dirty = False
|
||||
now = datetime.now(UTC)
|
||||
async with self._sf() as session:
|
||||
for idx, seed in enumerate(DEFAULT_BUSINESS_ROWS):
|
||||
is_custom, mapping_type = _seed_type(seed)
|
||||
existing = await session.get(BusinessMappingRow, seed["business_code"])
|
||||
if existing is not None:
|
||||
if existing.sort_order != idx:
|
||||
@@ -187,19 +175,13 @@ class BusinessMappingRepository:
|
||||
if seed_label and not (existing.label or "").strip():
|
||||
existing.label = seed_label
|
||||
dirty = True
|
||||
if bool(existing.is_custom) != is_custom:
|
||||
existing.is_custom = is_custom
|
||||
dirty = True
|
||||
if (existing.mapping_type or "") != mapping_type:
|
||||
existing.mapping_type = mapping_type
|
||||
dirty = True
|
||||
continue
|
||||
session.add(
|
||||
BusinessMappingRow(
|
||||
business_code=seed["business_code"],
|
||||
label=seed.get("label", ""),
|
||||
mapping_type=mapping_type,
|
||||
is_custom=is_custom,
|
||||
mapping_type="内置业务",
|
||||
is_custom=False,
|
||||
agent_id=None,
|
||||
agent_name=None,
|
||||
chain_id=None,
|
||||
|
||||
@@ -251,24 +251,6 @@ def _pooled_engine_kwargs(*, backend, url, echo, pool_size, max_overflow, pool_t
|
||||
return kwargs
|
||||
|
||||
|
||||
def _pooled_engine_kwargs(*, backend, url, echo, pool_size, max_overflow, pool_timeout, pool_recycle, command_timeout):
|
||||
"""Use identical pool/deadline settings on initial connect and DB-create retry."""
|
||||
kwargs = dict(
|
||||
echo=echo,
|
||||
pool_size=pool_size,
|
||||
max_overflow=max_overflow,
|
||||
pool_timeout=pool_timeout,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=pool_recycle,
|
||||
json_serializer=_json_serializer,
|
||||
)
|
||||
# asyncpg command deadlines also bound the SELECT used by pool_pre_ping.
|
||||
# These are not MySQL/psycopg connection arguments.
|
||||
if backend in {"postgres", "gauss"} and make_url(url).drivername.endswith("+asyncpg"):
|
||||
kwargs["connect_args"] = {"command_timeout": command_timeout}
|
||||
return kwargs
|
||||
|
||||
|
||||
async def _run_alembic_upgrade(url: str) -> None:
|
||||
"""Apply pending Alembic migrations against ``url`` (``alembic upgrade head``).
|
||||
|
||||
|
||||
+16
@@ -64,6 +64,22 @@ class LightAppRepository(LightAppStore):
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [_to_dict(row) for row in result.scalars()]
|
||||
|
||||
async def list_sidebar_apps(self) -> list[dict[str, Any]]:
|
||||
"""Avoid loading descriptions, icons, route JSON, tags, and audit data."""
|
||||
stmt = (
|
||||
select(
|
||||
LightAppRow.app_id,
|
||||
LightAppRow.name,
|
||||
LightAppRow.mount_location,
|
||||
LightAppRow.sort_order,
|
||||
)
|
||||
.where(LightAppRow.app_type == "iframe", LightAppRow.enabled.is_(True))
|
||||
.order_by(LightAppRow.sort_order.asc(), LightAppRow.created_at.desc())
|
||||
)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [dict(row._mapping) for row in result]
|
||||
|
||||
async def list_sidebar_apps(self) -> list[dict[str, Any]]:
|
||||
"""Avoid loading descriptions, icons, route JSON, tags, and audit data."""
|
||||
|
||||
+362
-362
@@ -1,362 +1,362 @@
|
||||
"""ORM model registration entry point.
|
||||
|
||||
Importing this module ensures all ORM models are registered with
|
||||
``Base.metadata`` so Alembic autogenerate detects every table.
|
||||
|
||||
The actual ORM classes have moved to entity-specific subpackages:
|
||||
- ``deerflow.persistence.thread_meta``
|
||||
- ``deerflow.persistence.run``
|
||||
- ``deerflow.persistence.feedback``
|
||||
- ``deerflow.persistence.user``
|
||||
- ``deerflow.persistence.agents``
|
||||
|
||||
``RunEventRow`` remains in ``deerflow.persistence.models.run_event`` because
|
||||
its storage implementation lives in ``deerflow.runtime.events.store.db`` and
|
||||
there is no matching entity directory.
|
||||
"""
|
||||
|
||||
from deerflow.knowledge.models import (
|
||||
KnowledgeEmbeddingRow,
|
||||
KnowledgeEntityRow,
|
||||
KnowledgeExtractTemplateRow,
|
||||
KnowledgeFolderRow,
|
||||
KnowledgeGraphBlacklistRow,
|
||||
KnowledgeNoteRow,
|
||||
KnowledgeNoteTagRow,
|
||||
KnowledgeNoteVersionRow,
|
||||
KnowledgeRelationRow,
|
||||
KnowledgeSourceRow,
|
||||
KnowledgeTagRow,
|
||||
)
|
||||
from deerflow.persistence.admin_stats.model import AdminLeaderboardDailyStatRow
|
||||
from deerflow.persistence.agents.model import (
|
||||
AgentExtrasRow,
|
||||
AgentFavoriteRow,
|
||||
AgentRow,
|
||||
AgentSkillRow,
|
||||
)
|
||||
from deerflow.persistence.api_read_cache_settings.model import ApiReadCacheSettingRow
|
||||
from deerflow.persistence.ai_writing_sessions.model import AIWritingSessionRow
|
||||
from deerflow.persistence.analysis_project_memory.model import (
|
||||
AnalysisProjectMemoryItemRow,
|
||||
AnalysisProjectMemoryJobRow,
|
||||
AnalysisProjectMemoryStateRow,
|
||||
)
|
||||
from deerflow.persistence.analysis_projects import AnalysisProjectConfigRow, AnalysisProjectRow, AnalysisProjectThreadRow
|
||||
from deerflow.persistence.article_types.model import ArticleTypeRow
|
||||
from deerflow.persistence.artifact_library.model import (
|
||||
ArtifactLibraryItemRow,
|
||||
ArtifactLibrarySyncStateRow,
|
||||
)
|
||||
from deerflow.persistence.assistant_knowledge.model import (
|
||||
AssistantKnowledgeBaseRow,
|
||||
AssistantKnowledgeEntityContributionRow,
|
||||
AssistantKnowledgeEntityRow,
|
||||
AssistantKnowledgeImportJobRow,
|
||||
AssistantKnowledgeRelationContributionRow,
|
||||
AssistantKnowledgeRelationRow,
|
||||
AssistantKnowledgeSourceRow,
|
||||
AssistantKnowledgeVectorRow,
|
||||
AssistantKnowledgeWikiPageRow,
|
||||
AssistantKnowledgeWikiRevisionRow,
|
||||
)
|
||||
from deerflow.persistence.business_mapping.model import BusinessMappingRow
|
||||
from deerflow.persistence.compact_menu_overrides.model import CompactMenuOverrideRow, UserCompactMenuOverrideConfigRow
|
||||
from deerflow.persistence.concurrency.model import ConcurrencySampleRow
|
||||
from deerflow.persistence.dashboard_sessions.model import DashboardSessionRow
|
||||
from deerflow.persistence.deep_research_events.model import DeepResearchEventRow
|
||||
from deerflow.persistence.deep_research_jobs.model import DeepResearchJobRow
|
||||
from deerflow.persistence.deep_research_messages.model import DeepResearchMessageRow
|
||||
from deerflow.persistence.deep_research_sessions.model import DeepResearchSessionRow
|
||||
from deerflow.persistence.deep_research_sources.model import DeepResearchSourceRow
|
||||
from deerflow.persistence.document_rewrite_versions.model import DocumentRewriteVersionRow
|
||||
from deerflow.persistence.embed_sessions.model import EmbedSessionRow
|
||||
from deerflow.persistence.feedback.model import FeedbackRow
|
||||
from deerflow.persistence.fixed_questions.model import FixedQuestionRow
|
||||
from deerflow.persistence.force_situation.model import (
|
||||
ForceSituationDetailRow,
|
||||
ForceSituationDetailVersionRow,
|
||||
)
|
||||
from deerflow.persistence.gongwen_documents.model import GongwenDocumentRow, GongwenDocumentVersionRow
|
||||
from deerflow.persistence.html_pages.model import HtmlPageFavoriteRow, ScheduledHtmlPageRow
|
||||
from deerflow.persistence.intent_turns.model import IntentTurnRow
|
||||
from deerflow.persistence.knowledge_research import KnowledgeResearchSessionRow
|
||||
from deerflow.persistence.knowledge_retrieval_settings.model import KnowledgeRetrievalSettingsRow
|
||||
from deerflow.persistence.light_apps.model import LightAppRow
|
||||
from deerflow.persistence.llm_metrics.model import LlmCallMetricRow
|
||||
from deerflow.persistence.llmwiki.model import LlmWikiConversationDepositRow, LlmWikiKnowledgeBaseRow
|
||||
from deerflow.persistence.llmwiki_index.model import (
|
||||
LlmWikiWikiEdgeRow,
|
||||
LlmWikiWikiPageRow,
|
||||
LlmWikiWikiSyncStateRow,
|
||||
LlmWikiWikiVectorRow,
|
||||
)
|
||||
from deerflow.persistence.memory_config.model import UserMemoryConfigRow
|
||||
from deerflow.persistence.menu_overrides.model import MenuOverrideRow, UserMenuOverrideConfigRow
|
||||
from deerflow.persistence.model_capabilities.model import ModelCapabilityRow
|
||||
from deerflow.persistence.models.run_event import RunEventRow
|
||||
from deerflow.persistence.notifications.model import NotificationRow
|
||||
from deerflow.persistence.parallel_agent_tasks.model import ParallelAgentTaskRow
|
||||
from deerflow.persistence.position_roles.model import PositionRoleRow
|
||||
from deerflow.persistence.position_roundtable.model import (
|
||||
PositionRoundtableNodeRow,
|
||||
PositionRoundtableSessionRow,
|
||||
)
|
||||
from deerflow.persistence.positions.model import PositionRow, PositionTagBindingRow
|
||||
from deerflow.persistence.recommended_questions.model import RecommendedQuestionRow
|
||||
from deerflow.persistence.report_collaboration.model import (
|
||||
ReportCollaborationAgentRunRow,
|
||||
ReportCollaborationArtifactRow,
|
||||
ReportCollaborationAuditRow,
|
||||
ReportCollaborationCommandRow,
|
||||
ReportCollaborationEventRow,
|
||||
ReportCollaborationMessageRow,
|
||||
ReportCollaborationNodeRunRow,
|
||||
ReportCollaborationPlanRow,
|
||||
ReportCollaborationReportVersionRow,
|
||||
ReportCollaborationRewriteProposalRow,
|
||||
ReportCollaborationRunRow,
|
||||
ReportCollaborationSessionRow,
|
||||
)
|
||||
from deerflow.persistence.report_structures.model import ReportStructureRow
|
||||
from deerflow.persistence.research_templates.model import ResearchTemplateRow
|
||||
from deerflow.persistence.roundtable_artifact_submissions.model import RoundtableArtifactSubmissionRow
|
||||
from deerflow.persistence.roundtable_chains.model import RoundtableChainRow
|
||||
from deerflow.persistence.roundtable_diagnostics.model import RoundtableDiagnosticRow
|
||||
from deerflow.persistence.roundtable_draft_shares.model import RoundtableDraftShareRow
|
||||
from deerflow.persistence.roundtable_drafts.model import (
|
||||
RoundtableDraftRow,
|
||||
RoundtableRecommendHistoryRow,
|
||||
)
|
||||
from deerflow.persistence.roundtable_jobs.model import RoundtableJobRow
|
||||
from deerflow.persistence.roundtable_rooms.model import RoundtableRoomLeaseRow
|
||||
from deerflow.persistence.roundtable_task_drafts.model import RoundtableTaskDraftRow
|
||||
from deerflow.persistence.run.model import RunRow
|
||||
from deerflow.persistence.scheduled_tasks.model import (
|
||||
ScheduledTaskDeliveryProfileRow,
|
||||
ScheduledTaskRow,
|
||||
ScheduledTaskRunRow,
|
||||
ScheduledTaskSubscriptionRow,
|
||||
SchedulerThreadRow,
|
||||
)
|
||||
from deerflow.persistence.sensitive_words.model import SensitiveWordRow
|
||||
from deerflow.persistence.skill_knowledge.model import (
|
||||
SkillKnowledgeArtifactRow,
|
||||
SkillKnowledgeBindingRow,
|
||||
SkillKnowledgeEntityContributionRow,
|
||||
SkillKnowledgeEntityRow,
|
||||
SkillKnowledgeRelationContributionRow,
|
||||
SkillKnowledgeRelationRow,
|
||||
SkillKnowledgeReviewRow,
|
||||
SkillKnowledgeSnapshotRow,
|
||||
SkillKnowledgeSyncItemRow,
|
||||
SkillKnowledgeSyncJobRow,
|
||||
)
|
||||
from deerflow.persistence.skills.model import (
|
||||
SkillCatalogSnapshotRow,
|
||||
SkillDisplayAdapterRow,
|
||||
SkillFavoriteRow,
|
||||
SkillRow,
|
||||
)
|
||||
from deerflow.persistence.strategy_agent_roles.model import StrategyAgentRoleRow
|
||||
from deerflow.persistence.tags.model import TagAssignmentRow, TagRow
|
||||
from deerflow.persistence.task_analysis.model import (
|
||||
TaskAnalysisBindingRow,
|
||||
TaskAnalysisContentVersionRow,
|
||||
TaskAnalysisRunMessageRow,
|
||||
TaskAnalysisRunRow,
|
||||
TaskAnalysisSettingRow,
|
||||
TaskAnalysisTaskRow,
|
||||
TaskDataBlockDefRow,
|
||||
TaskDataBlockRow,
|
||||
TaskDataPeriodRow,
|
||||
TaskDataSubmissionRow,
|
||||
)
|
||||
from deerflow.persistence.task_buttons.model import TaskButtonRow
|
||||
from deerflow.persistence.task_deeplink_details.model import TaskDeeplinkDetailRow
|
||||
from deerflow.persistence.task_deeplink_threads.model import TaskDeeplinkThreadRow
|
||||
from deerflow.persistence.task_reports.model import TaskReportRow
|
||||
from deerflow.persistence.taskcop_tasks.model import TaskCopTaskRow
|
||||
from deerflow.persistence.thread_meta.model import ThreadMetaRow
|
||||
from deerflow.persistence.thread_shares.model import ThreadShareRow
|
||||
from deerflow.persistence.tool_metrics.model import ToolCallMetricRow
|
||||
from deerflow.persistence.stream_truncation.model import StreamTruncationEventRow
|
||||
from deerflow.persistence.upload_policy.model import UploadPolicyRow
|
||||
from deerflow.persistence.user.model import UserRow
|
||||
from deerflow.persistence.user_preferences.model import UserPreferencesRow
|
||||
from deerflow.persistence.user_prompts.model import UserCustomPromptRow
|
||||
from deerflow.persistence.workflow_data_sources.model import WorkflowDataSourceRow
|
||||
from deerflow.persistence.workflow_events.model import WorkflowRunEventRow
|
||||
from deerflow.persistence.workflow_planning.model import (
|
||||
WorkflowPlanningProposalRow,
|
||||
WorkflowPlanningSessionRow,
|
||||
)
|
||||
from deerflow.persistence.workflow_runs.model import (
|
||||
WorkflowNodeRunRow,
|
||||
WorkflowRunArtifactRow,
|
||||
WorkflowRunRow,
|
||||
)
|
||||
from deerflow.persistence.workflows.model import WorkflowDefinitionRow, WorkflowVersionRow
|
||||
|
||||
__all__ = [
|
||||
"AIWritingSessionRow",
|
||||
"AnalysisProjectConfigRow",
|
||||
"AnalysisProjectMemoryItemRow",
|
||||
"AnalysisProjectMemoryJobRow",
|
||||
"AnalysisProjectMemoryStateRow",
|
||||
"ArtifactLibraryItemRow",
|
||||
"ArtifactLibrarySyncStateRow",
|
||||
"ArticleTypeRow",
|
||||
"FeedbackRow",
|
||||
"FixedQuestionRow",
|
||||
"ForceSituationDetailRow",
|
||||
"ForceSituationDetailVersionRow",
|
||||
"GongwenDocumentRow",
|
||||
"GongwenDocumentVersionRow",
|
||||
"HtmlPageFavoriteRow",
|
||||
"AgentExtrasRow",
|
||||
"AgentFavoriteRow",
|
||||
"AgentRow",
|
||||
"ApiReadCacheSettingRow",
|
||||
"AgentSkillRow",
|
||||
"AdminLeaderboardDailyStatRow",
|
||||
"BusinessMappingRow",
|
||||
"AssistantKnowledgeBaseRow",
|
||||
"AssistantKnowledgeSourceRow",
|
||||
"AssistantKnowledgeVectorRow",
|
||||
"AssistantKnowledgeImportJobRow",
|
||||
"AssistantKnowledgeWikiPageRow",
|
||||
"AssistantKnowledgeWikiRevisionRow",
|
||||
"AssistantKnowledgeEntityRow",
|
||||
"AssistantKnowledgeEntityContributionRow",
|
||||
"AssistantKnowledgeRelationRow",
|
||||
"AssistantKnowledgeRelationContributionRow",
|
||||
"CompactMenuOverrideRow",
|
||||
"UserCompactMenuOverrideConfigRow",
|
||||
"ConcurrencySampleRow",
|
||||
"DashboardSessionRow",
|
||||
"DocumentRewriteVersionRow",
|
||||
"DeepResearchEventRow",
|
||||
"DeepResearchJobRow",
|
||||
"DeepResearchMessageRow",
|
||||
"DeepResearchSessionRow",
|
||||
"DeepResearchSourceRow",
|
||||
"KnowledgeEmbeddingRow",
|
||||
"KnowledgeEntityRow",
|
||||
"KnowledgeExtractTemplateRow",
|
||||
"KnowledgeFolderRow",
|
||||
"KnowledgeGraphBlacklistRow",
|
||||
"KnowledgeNoteRow",
|
||||
"KnowledgeNoteTagRow",
|
||||
"KnowledgeNoteVersionRow",
|
||||
"KnowledgeRelationRow",
|
||||
"KnowledgeSourceRow",
|
||||
"KnowledgeTagRow",
|
||||
"KnowledgeResearchSessionRow",
|
||||
"KnowledgeRetrievalSettingsRow",
|
||||
"LightAppRow",
|
||||
"WorkflowDataSourceRow",
|
||||
"WorkflowDefinitionRow",
|
||||
"WorkflowNodeRunRow",
|
||||
"WorkflowRunArtifactRow",
|
||||
"WorkflowRunEventRow",
|
||||
"WorkflowRunRow",
|
||||
"WorkflowPlanningProposalRow",
|
||||
"WorkflowPlanningSessionRow",
|
||||
"WorkflowVersionRow",
|
||||
"LlmCallMetricRow",
|
||||
"LlmWikiKnowledgeBaseRow",
|
||||
"LlmWikiConversationDepositRow",
|
||||
"LlmWikiWikiPageRow",
|
||||
"LlmWikiWikiEdgeRow",
|
||||
"LlmWikiWikiVectorRow",
|
||||
"LlmWikiWikiSyncStateRow",
|
||||
"MenuOverrideRow",
|
||||
"ModelCapabilityRow",
|
||||
"UserMenuOverrideConfigRow",
|
||||
"NotificationRow",
|
||||
"ParallelAgentTaskRow",
|
||||
"PositionRoundtableNodeRow",
|
||||
"PositionRoundtableSessionRow",
|
||||
"PositionRow",
|
||||
"PositionTagBindingRow",
|
||||
"RecommendedQuestionRow",
|
||||
"ReportCollaborationAgentRunRow",
|
||||
"ReportCollaborationArtifactRow",
|
||||
"ReportCollaborationCommandRow",
|
||||
"ReportCollaborationEventRow",
|
||||
"ReportCollaborationMessageRow",
|
||||
"ReportCollaborationNodeRunRow",
|
||||
"ReportCollaborationPlanRow",
|
||||
"ReportCollaborationReportVersionRow",
|
||||
"ReportCollaborationAuditRow",
|
||||
"ReportCollaborationRewriteProposalRow",
|
||||
"ReportCollaborationRunRow",
|
||||
"ReportCollaborationSessionRow",
|
||||
"ReportStructureRow",
|
||||
"ResearchTemplateRow",
|
||||
"RoundtableChainRow",
|
||||
"RoundtableArtifactSubmissionRow",
|
||||
"RoundtableDraftRow",
|
||||
"RoundtableDraftShareRow",
|
||||
"RoundtableDiagnosticRow",
|
||||
"RoundtableJobRow",
|
||||
"RoundtableRoomLeaseRow",
|
||||
"RoundtableRecommendHistoryRow",
|
||||
"RoundtableTaskDraftRow",
|
||||
"PositionRoleRow",
|
||||
"RunEventRow",
|
||||
"RunRow",
|
||||
"ScheduledTaskDeliveryProfileRow",
|
||||
"ScheduledHtmlPageRow",
|
||||
"ScheduledTaskRow",
|
||||
"ScheduledTaskRunRow",
|
||||
"ScheduledTaskSubscriptionRow",
|
||||
"SchedulerThreadRow",
|
||||
"SensitiveWordRow",
|
||||
"SkillCatalogSnapshotRow",
|
||||
"SkillRow",
|
||||
"SkillDisplayAdapterRow",
|
||||
"SkillFavoriteRow",
|
||||
"SkillKnowledgeArtifactRow",
|
||||
"SkillKnowledgeBindingRow",
|
||||
"SkillKnowledgeEntityContributionRow",
|
||||
"SkillKnowledgeEntityRow",
|
||||
"SkillKnowledgeRelationContributionRow",
|
||||
"SkillKnowledgeRelationRow",
|
||||
"SkillKnowledgeReviewRow",
|
||||
"SkillKnowledgeSnapshotRow",
|
||||
"SkillKnowledgeSyncItemRow",
|
||||
"SkillKnowledgeSyncJobRow",
|
||||
"StrategyAgentRoleRow",
|
||||
"TagAssignmentRow",
|
||||
"TagRow",
|
||||
"TaskButtonRow",
|
||||
"TaskAnalysisBindingRow",
|
||||
"TaskAnalysisContentVersionRow",
|
||||
"TaskAnalysisRunMessageRow",
|
||||
"TaskAnalysisRunRow",
|
||||
"TaskAnalysisSettingRow",
|
||||
"TaskAnalysisTaskRow",
|
||||
"TaskDataBlockDefRow",
|
||||
"TaskDataBlockRow",
|
||||
"TaskDataPeriodRow",
|
||||
"TaskDataSubmissionRow",
|
||||
"TaskDeeplinkDetailRow",
|
||||
"TaskDeeplinkThreadRow",
|
||||
"AnalysisProjectRow",
|
||||
"AnalysisProjectThreadRow",
|
||||
"TaskCopTaskRow",
|
||||
"TaskReportRow",
|
||||
"EmbedSessionRow",
|
||||
"IntentTurnRow",
|
||||
"ThreadMetaRow",
|
||||
"ThreadShareRow",
|
||||
"ToolCallMetricRow",
|
||||
"StreamTruncationEventRow",
|
||||
"UploadPolicyRow",
|
||||
"UserCustomPromptRow",
|
||||
"UserMemoryConfigRow",
|
||||
"UserPreferencesRow",
|
||||
"UserRow",
|
||||
]
|
||||
"""ORM model registration entry point.
|
||||
|
||||
Importing this module ensures all ORM models are registered with
|
||||
``Base.metadata`` so Alembic autogenerate detects every table.
|
||||
|
||||
The actual ORM classes have moved to entity-specific subpackages:
|
||||
- ``deerflow.persistence.thread_meta``
|
||||
- ``deerflow.persistence.run``
|
||||
- ``deerflow.persistence.feedback``
|
||||
- ``deerflow.persistence.user``
|
||||
- ``deerflow.persistence.agents``
|
||||
|
||||
``RunEventRow`` remains in ``deerflow.persistence.models.run_event`` because
|
||||
its storage implementation lives in ``deerflow.runtime.events.store.db`` and
|
||||
there is no matching entity directory.
|
||||
"""
|
||||
|
||||
from deerflow.knowledge.models import (
|
||||
KnowledgeEmbeddingRow,
|
||||
KnowledgeEntityRow,
|
||||
KnowledgeExtractTemplateRow,
|
||||
KnowledgeFolderRow,
|
||||
KnowledgeGraphBlacklistRow,
|
||||
KnowledgeNoteRow,
|
||||
KnowledgeNoteTagRow,
|
||||
KnowledgeNoteVersionRow,
|
||||
KnowledgeRelationRow,
|
||||
KnowledgeSourceRow,
|
||||
KnowledgeTagRow,
|
||||
)
|
||||
from deerflow.persistence.admin_stats.model import AdminLeaderboardDailyStatRow
|
||||
from deerflow.persistence.agents.model import (
|
||||
AgentExtrasRow,
|
||||
AgentFavoriteRow,
|
||||
AgentRow,
|
||||
AgentSkillRow,
|
||||
)
|
||||
from deerflow.persistence.api_read_cache_settings.model import ApiReadCacheSettingRow
|
||||
from deerflow.persistence.ai_writing_sessions.model import AIWritingSessionRow
|
||||
from deerflow.persistence.analysis_project_memory.model import (
|
||||
AnalysisProjectMemoryItemRow,
|
||||
AnalysisProjectMemoryJobRow,
|
||||
AnalysisProjectMemoryStateRow,
|
||||
)
|
||||
from deerflow.persistence.analysis_projects import AnalysisProjectConfigRow, AnalysisProjectRow, AnalysisProjectThreadRow
|
||||
from deerflow.persistence.article_types.model import ArticleTypeRow
|
||||
from deerflow.persistence.artifact_library.model import (
|
||||
ArtifactLibraryItemRow,
|
||||
ArtifactLibrarySyncStateRow,
|
||||
)
|
||||
from deerflow.persistence.assistant_knowledge.model import (
|
||||
AssistantKnowledgeBaseRow,
|
||||
AssistantKnowledgeEntityContributionRow,
|
||||
AssistantKnowledgeEntityRow,
|
||||
AssistantKnowledgeImportJobRow,
|
||||
AssistantKnowledgeRelationContributionRow,
|
||||
AssistantKnowledgeRelationRow,
|
||||
AssistantKnowledgeSourceRow,
|
||||
AssistantKnowledgeVectorRow,
|
||||
AssistantKnowledgeWikiPageRow,
|
||||
AssistantKnowledgeWikiRevisionRow,
|
||||
)
|
||||
from deerflow.persistence.business_mapping.model import BusinessMappingRow
|
||||
from deerflow.persistence.compact_menu_overrides.model import CompactMenuOverrideRow, UserCompactMenuOverrideConfigRow
|
||||
from deerflow.persistence.concurrency.model import ConcurrencySampleRow
|
||||
from deerflow.persistence.dashboard_sessions.model import DashboardSessionRow
|
||||
from deerflow.persistence.deep_research_events.model import DeepResearchEventRow
|
||||
from deerflow.persistence.deep_research_jobs.model import DeepResearchJobRow
|
||||
from deerflow.persistence.deep_research_messages.model import DeepResearchMessageRow
|
||||
from deerflow.persistence.deep_research_sessions.model import DeepResearchSessionRow
|
||||
from deerflow.persistence.deep_research_sources.model import DeepResearchSourceRow
|
||||
from deerflow.persistence.document_rewrite_versions.model import DocumentRewriteVersionRow
|
||||
from deerflow.persistence.embed_sessions.model import EmbedSessionRow
|
||||
from deerflow.persistence.feedback.model import FeedbackRow
|
||||
from deerflow.persistence.fixed_questions.model import FixedQuestionRow
|
||||
from deerflow.persistence.force_situation.model import (
|
||||
ForceSituationDetailRow,
|
||||
ForceSituationDetailVersionRow,
|
||||
)
|
||||
from deerflow.persistence.gongwen_documents.model import GongwenDocumentRow, GongwenDocumentVersionRow
|
||||
from deerflow.persistence.html_pages.model import HtmlPageFavoriteRow, ScheduledHtmlPageRow
|
||||
from deerflow.persistence.intent_turns.model import IntentTurnRow
|
||||
from deerflow.persistence.knowledge_research import KnowledgeResearchSessionRow
|
||||
from deerflow.persistence.knowledge_retrieval_settings.model import KnowledgeRetrievalSettingsRow
|
||||
from deerflow.persistence.light_apps.model import LightAppRow
|
||||
from deerflow.persistence.llm_metrics.model import LlmCallMetricRow
|
||||
from deerflow.persistence.llmwiki.model import LlmWikiConversationDepositRow, LlmWikiKnowledgeBaseRow
|
||||
from deerflow.persistence.llmwiki_index.model import (
|
||||
LlmWikiWikiEdgeRow,
|
||||
LlmWikiWikiPageRow,
|
||||
LlmWikiWikiSyncStateRow,
|
||||
LlmWikiWikiVectorRow,
|
||||
)
|
||||
from deerflow.persistence.memory_config.model import UserMemoryConfigRow
|
||||
from deerflow.persistence.menu_overrides.model import MenuOverrideRow, UserMenuOverrideConfigRow
|
||||
from deerflow.persistence.model_capabilities.model import ModelCapabilityRow
|
||||
from deerflow.persistence.models.run_event import RunEventRow
|
||||
from deerflow.persistence.notifications.model import NotificationRow
|
||||
from deerflow.persistence.parallel_agent_tasks.model import ParallelAgentTaskRow
|
||||
from deerflow.persistence.position_roles.model import PositionRoleRow
|
||||
from deerflow.persistence.position_roundtable.model import (
|
||||
PositionRoundtableNodeRow,
|
||||
PositionRoundtableSessionRow,
|
||||
)
|
||||
from deerflow.persistence.positions.model import PositionRow, PositionTagBindingRow
|
||||
from deerflow.persistence.recommended_questions.model import RecommendedQuestionRow
|
||||
from deerflow.persistence.report_collaboration.model import (
|
||||
ReportCollaborationAgentRunRow,
|
||||
ReportCollaborationArtifactRow,
|
||||
ReportCollaborationAuditRow,
|
||||
ReportCollaborationCommandRow,
|
||||
ReportCollaborationEventRow,
|
||||
ReportCollaborationMessageRow,
|
||||
ReportCollaborationNodeRunRow,
|
||||
ReportCollaborationPlanRow,
|
||||
ReportCollaborationReportVersionRow,
|
||||
ReportCollaborationRewriteProposalRow,
|
||||
ReportCollaborationRunRow,
|
||||
ReportCollaborationSessionRow,
|
||||
)
|
||||
from deerflow.persistence.report_structures.model import ReportStructureRow
|
||||
from deerflow.persistence.research_templates.model import ResearchTemplateRow
|
||||
from deerflow.persistence.roundtable_artifact_submissions.model import RoundtableArtifactSubmissionRow
|
||||
from deerflow.persistence.roundtable_chains.model import RoundtableChainRow
|
||||
from deerflow.persistence.roundtable_diagnostics.model import RoundtableDiagnosticRow
|
||||
from deerflow.persistence.roundtable_draft_shares.model import RoundtableDraftShareRow
|
||||
from deerflow.persistence.roundtable_drafts.model import (
|
||||
RoundtableDraftRow,
|
||||
RoundtableRecommendHistoryRow,
|
||||
)
|
||||
from deerflow.persistence.roundtable_jobs.model import RoundtableJobRow
|
||||
from deerflow.persistence.roundtable_rooms.model import RoundtableRoomLeaseRow
|
||||
from deerflow.persistence.roundtable_task_drafts.model import RoundtableTaskDraftRow
|
||||
from deerflow.persistence.run.model import RunRow
|
||||
from deerflow.persistence.scheduled_tasks.model import (
|
||||
ScheduledTaskDeliveryProfileRow,
|
||||
ScheduledTaskRow,
|
||||
ScheduledTaskRunRow,
|
||||
ScheduledTaskSubscriptionRow,
|
||||
SchedulerThreadRow,
|
||||
)
|
||||
from deerflow.persistence.sensitive_words.model import SensitiveWordRow
|
||||
from deerflow.persistence.skill_knowledge.model import (
|
||||
SkillKnowledgeArtifactRow,
|
||||
SkillKnowledgeBindingRow,
|
||||
SkillKnowledgeEntityContributionRow,
|
||||
SkillKnowledgeEntityRow,
|
||||
SkillKnowledgeRelationContributionRow,
|
||||
SkillKnowledgeRelationRow,
|
||||
SkillKnowledgeReviewRow,
|
||||
SkillKnowledgeSnapshotRow,
|
||||
SkillKnowledgeSyncItemRow,
|
||||
SkillKnowledgeSyncJobRow,
|
||||
)
|
||||
from deerflow.persistence.skills.model import (
|
||||
SkillCatalogSnapshotRow,
|
||||
SkillDisplayAdapterRow,
|
||||
SkillFavoriteRow,
|
||||
SkillRow,
|
||||
)
|
||||
from deerflow.persistence.strategy_agent_roles.model import StrategyAgentRoleRow
|
||||
from deerflow.persistence.tags.model import TagAssignmentRow, TagRow
|
||||
from deerflow.persistence.task_analysis.model import (
|
||||
TaskAnalysisBindingRow,
|
||||
TaskAnalysisContentVersionRow,
|
||||
TaskAnalysisRunMessageRow,
|
||||
TaskAnalysisRunRow,
|
||||
TaskAnalysisSettingRow,
|
||||
TaskAnalysisTaskRow,
|
||||
TaskDataBlockDefRow,
|
||||
TaskDataBlockRow,
|
||||
TaskDataPeriodRow,
|
||||
TaskDataSubmissionRow,
|
||||
)
|
||||
from deerflow.persistence.task_buttons.model import TaskButtonRow
|
||||
from deerflow.persistence.task_deeplink_details.model import TaskDeeplinkDetailRow
|
||||
from deerflow.persistence.task_deeplink_threads.model import TaskDeeplinkThreadRow
|
||||
from deerflow.persistence.task_reports.model import TaskReportRow
|
||||
from deerflow.persistence.taskcop_tasks.model import TaskCopTaskRow
|
||||
from deerflow.persistence.thread_meta.model import ThreadMetaRow
|
||||
from deerflow.persistence.thread_shares.model import ThreadShareRow
|
||||
from deerflow.persistence.tool_metrics.model import ToolCallMetricRow
|
||||
from deerflow.persistence.stream_truncation.model import StreamTruncationEventRow
|
||||
from deerflow.persistence.upload_policy.model import UploadPolicyRow
|
||||
from deerflow.persistence.user.model import UserRow
|
||||
from deerflow.persistence.user_preferences.model import UserPreferencesRow
|
||||
from deerflow.persistence.user_prompts.model import UserCustomPromptRow
|
||||
from deerflow.persistence.workflow_data_sources.model import WorkflowDataSourceRow
|
||||
from deerflow.persistence.workflow_events.model import WorkflowRunEventRow
|
||||
from deerflow.persistence.workflow_planning.model import (
|
||||
WorkflowPlanningProposalRow,
|
||||
WorkflowPlanningSessionRow,
|
||||
)
|
||||
from deerflow.persistence.workflow_runs.model import (
|
||||
WorkflowNodeRunRow,
|
||||
WorkflowRunArtifactRow,
|
||||
WorkflowRunRow,
|
||||
)
|
||||
from deerflow.persistence.workflows.model import WorkflowDefinitionRow, WorkflowVersionRow
|
||||
|
||||
__all__ = [
|
||||
"AIWritingSessionRow",
|
||||
"AnalysisProjectConfigRow",
|
||||
"AnalysisProjectMemoryItemRow",
|
||||
"AnalysisProjectMemoryJobRow",
|
||||
"AnalysisProjectMemoryStateRow",
|
||||
"ArtifactLibraryItemRow",
|
||||
"ArtifactLibrarySyncStateRow",
|
||||
"ArticleTypeRow",
|
||||
"FeedbackRow",
|
||||
"FixedQuestionRow",
|
||||
"ForceSituationDetailRow",
|
||||
"ForceSituationDetailVersionRow",
|
||||
"GongwenDocumentRow",
|
||||
"GongwenDocumentVersionRow",
|
||||
"HtmlPageFavoriteRow",
|
||||
"AgentExtrasRow",
|
||||
"AgentFavoriteRow",
|
||||
"AgentRow",
|
||||
"ApiReadCacheSettingRow",
|
||||
"AgentSkillRow",
|
||||
"AdminLeaderboardDailyStatRow",
|
||||
"BusinessMappingRow",
|
||||
"AssistantKnowledgeBaseRow",
|
||||
"AssistantKnowledgeSourceRow",
|
||||
"AssistantKnowledgeVectorRow",
|
||||
"AssistantKnowledgeImportJobRow",
|
||||
"AssistantKnowledgeWikiPageRow",
|
||||
"AssistantKnowledgeWikiRevisionRow",
|
||||
"AssistantKnowledgeEntityRow",
|
||||
"AssistantKnowledgeEntityContributionRow",
|
||||
"AssistantKnowledgeRelationRow",
|
||||
"AssistantKnowledgeRelationContributionRow",
|
||||
"CompactMenuOverrideRow",
|
||||
"UserCompactMenuOverrideConfigRow",
|
||||
"ConcurrencySampleRow",
|
||||
"DashboardSessionRow",
|
||||
"DocumentRewriteVersionRow",
|
||||
"DeepResearchEventRow",
|
||||
"DeepResearchJobRow",
|
||||
"DeepResearchMessageRow",
|
||||
"DeepResearchSessionRow",
|
||||
"DeepResearchSourceRow",
|
||||
"KnowledgeEmbeddingRow",
|
||||
"KnowledgeEntityRow",
|
||||
"KnowledgeExtractTemplateRow",
|
||||
"KnowledgeFolderRow",
|
||||
"KnowledgeGraphBlacklistRow",
|
||||
"KnowledgeNoteRow",
|
||||
"KnowledgeNoteTagRow",
|
||||
"KnowledgeNoteVersionRow",
|
||||
"KnowledgeRelationRow",
|
||||
"KnowledgeSourceRow",
|
||||
"KnowledgeTagRow",
|
||||
"KnowledgeResearchSessionRow",
|
||||
"KnowledgeRetrievalSettingsRow",
|
||||
"LightAppRow",
|
||||
"WorkflowDataSourceRow",
|
||||
"WorkflowDefinitionRow",
|
||||
"WorkflowNodeRunRow",
|
||||
"WorkflowRunArtifactRow",
|
||||
"WorkflowRunEventRow",
|
||||
"WorkflowRunRow",
|
||||
"WorkflowPlanningProposalRow",
|
||||
"WorkflowPlanningSessionRow",
|
||||
"WorkflowVersionRow",
|
||||
"LlmCallMetricRow",
|
||||
"LlmWikiKnowledgeBaseRow",
|
||||
"LlmWikiConversationDepositRow",
|
||||
"LlmWikiWikiPageRow",
|
||||
"LlmWikiWikiEdgeRow",
|
||||
"LlmWikiWikiVectorRow",
|
||||
"LlmWikiWikiSyncStateRow",
|
||||
"MenuOverrideRow",
|
||||
"ModelCapabilityRow",
|
||||
"UserMenuOverrideConfigRow",
|
||||
"NotificationRow",
|
||||
"ParallelAgentTaskRow",
|
||||
"PositionRoundtableNodeRow",
|
||||
"PositionRoundtableSessionRow",
|
||||
"PositionRow",
|
||||
"PositionTagBindingRow",
|
||||
"RecommendedQuestionRow",
|
||||
"ReportCollaborationAgentRunRow",
|
||||
"ReportCollaborationArtifactRow",
|
||||
"ReportCollaborationCommandRow",
|
||||
"ReportCollaborationEventRow",
|
||||
"ReportCollaborationMessageRow",
|
||||
"ReportCollaborationNodeRunRow",
|
||||
"ReportCollaborationPlanRow",
|
||||
"ReportCollaborationReportVersionRow",
|
||||
"ReportCollaborationAuditRow",
|
||||
"ReportCollaborationRewriteProposalRow",
|
||||
"ReportCollaborationRunRow",
|
||||
"ReportCollaborationSessionRow",
|
||||
"ReportStructureRow",
|
||||
"ResearchTemplateRow",
|
||||
"RoundtableChainRow",
|
||||
"RoundtableArtifactSubmissionRow",
|
||||
"RoundtableDraftRow",
|
||||
"RoundtableDraftShareRow",
|
||||
"RoundtableDiagnosticRow",
|
||||
"RoundtableJobRow",
|
||||
"RoundtableRoomLeaseRow",
|
||||
"RoundtableRecommendHistoryRow",
|
||||
"RoundtableTaskDraftRow",
|
||||
"PositionRoleRow",
|
||||
"RunEventRow",
|
||||
"RunRow",
|
||||
"ScheduledTaskDeliveryProfileRow",
|
||||
"ScheduledHtmlPageRow",
|
||||
"ScheduledTaskRow",
|
||||
"ScheduledTaskRunRow",
|
||||
"ScheduledTaskSubscriptionRow",
|
||||
"SchedulerThreadRow",
|
||||
"SensitiveWordRow",
|
||||
"SkillCatalogSnapshotRow",
|
||||
"SkillRow",
|
||||
"SkillDisplayAdapterRow",
|
||||
"SkillFavoriteRow",
|
||||
"SkillKnowledgeArtifactRow",
|
||||
"SkillKnowledgeBindingRow",
|
||||
"SkillKnowledgeEntityContributionRow",
|
||||
"SkillKnowledgeEntityRow",
|
||||
"SkillKnowledgeRelationContributionRow",
|
||||
"SkillKnowledgeRelationRow",
|
||||
"SkillKnowledgeReviewRow",
|
||||
"SkillKnowledgeSnapshotRow",
|
||||
"SkillKnowledgeSyncItemRow",
|
||||
"SkillKnowledgeSyncJobRow",
|
||||
"StrategyAgentRoleRow",
|
||||
"TagAssignmentRow",
|
||||
"TagRow",
|
||||
"TaskButtonRow",
|
||||
"TaskAnalysisBindingRow",
|
||||
"TaskAnalysisContentVersionRow",
|
||||
"TaskAnalysisRunMessageRow",
|
||||
"TaskAnalysisRunRow",
|
||||
"TaskAnalysisSettingRow",
|
||||
"TaskAnalysisTaskRow",
|
||||
"TaskDataBlockDefRow",
|
||||
"TaskDataBlockRow",
|
||||
"TaskDataPeriodRow",
|
||||
"TaskDataSubmissionRow",
|
||||
"TaskDeeplinkDetailRow",
|
||||
"TaskDeeplinkThreadRow",
|
||||
"AnalysisProjectRow",
|
||||
"AnalysisProjectThreadRow",
|
||||
"TaskCopTaskRow",
|
||||
"TaskReportRow",
|
||||
"EmbedSessionRow",
|
||||
"IntentTurnRow",
|
||||
"ThreadMetaRow",
|
||||
"ThreadShareRow",
|
||||
"ToolCallMetricRow",
|
||||
"StreamTruncationEventRow",
|
||||
"UploadPolicyRow",
|
||||
"UserCustomPromptRow",
|
||||
"UserMemoryConfigRow",
|
||||
"UserPreferencesRow",
|
||||
"UserRow",
|
||||
]
|
||||
+19
@@ -80,6 +80,25 @@ class PositionRepository(PositionStore):
|
||||
position = row[0] or row[1]
|
||||
return _position_to_dict(position, 0) if position is not None else None
|
||||
|
||||
async def get_effective_position(self, user_id: str) -> dict[str, Any] | None:
|
||||
"""Resolve the assigned/default position with one narrow indexed query."""
|
||||
assigned = aliased(PositionRow)
|
||||
default = aliased(PositionRow)
|
||||
stmt = (
|
||||
select(assigned, default)
|
||||
.select_from(UserRow)
|
||||
.outerjoin(assigned, UserRow.position_id == assigned.id)
|
||||
.outerjoin(default, default.is_default.is_(True))
|
||||
.where(UserRow.id == user_id)
|
||||
.limit(1)
|
||||
)
|
||||
async with self._sf() as session:
|
||||
row = (await session.execute(stmt)).first()
|
||||
if row is None:
|
||||
return None
|
||||
position = row[0] or row[1]
|
||||
return _position_to_dict(position, 0) if position is not None else None
|
||||
|
||||
async def create_position(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
is_default = bool(data.get("is_default"))
|
||||
|
||||
+24
@@ -489,6 +489,30 @@ class RoundtableJobRepository:
|
||||
await session.commit()
|
||||
return int(result.rowcount or 0)
|
||||
|
||||
async def request_cancel_expired_step2(
|
||||
self,
|
||||
*,
|
||||
created_before: datetime,
|
||||
non_occupying_phases: tuple[str, ...],
|
||||
) -> int:
|
||||
"""Cancel unfinished Step-2 jobs that exceeded the room hard lifetime."""
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(
|
||||
update(RoundtableJobRow)
|
||||
.where(
|
||||
RoundtableJobRow.status.in_(list(CANCELLABLE_STATUSES)),
|
||||
RoundtableJobRow.created_at <= created_before,
|
||||
RoundtableJobRow.phase.not_in(list(non_occupying_phases)),
|
||||
)
|
||||
.values(
|
||||
status="cancel_requested",
|
||||
version=RoundtableJobRow.version + 1,
|
||||
updated_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
return int(result.rowcount or 0)
|
||||
|
||||
async def list_cancel_reapable(self, *, now: datetime, limit: int = 20) -> list[str]:
|
||||
"""列出可以由 dispatcher 收口的取消请求。
|
||||
|
||||
|
||||
@@ -40,6 +40,24 @@ class SkillStore(ABC):
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def migration_upsert(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Create or fully reconcile metadata from a trusted migration manifest.
|
||||
|
||||
This may replace a startup-created legacy placeholder's owner and
|
||||
source timestamps. Caller must enforce administrator access.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def migration_upsert_many(self, items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Batch version of ``migration_upsert`` for a trusted migration manifest.
|
||||
|
||||
Implementations should persist the whole list in one write cycle.
|
||||
Caller must enforce administrator access.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def update(self, name: str, user_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""Owner-only update. Returns None if the caller doesn't own the skill."""
|
||||
|
||||
+27
@@ -24,6 +24,10 @@ def _with_derived(record: dict[str, Any]) -> dict[str, Any]:
|
||||
return out
|
||||
|
||||
|
||||
def _stamp(value: Any, fallback: str) -> str:
|
||||
return value.isoformat() if isinstance(value, datetime) else str(value or fallback)
|
||||
|
||||
|
||||
class MemorySkillStore(SkillStore):
|
||||
def __init__(self) -> None:
|
||||
self._skills: dict[str, dict[str, Any]] = {}
|
||||
@@ -101,6 +105,29 @@ class MemorySkillStore(SkillStore):
|
||||
record["updated_at"] = _now()
|
||||
return _with_derived(_copy(record)) # type: ignore[arg-type]
|
||||
|
||||
async def migration_upsert(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
name = data["name"]
|
||||
existing = self._skills.get(name)
|
||||
now = _now()
|
||||
record = existing if existing is not None else {"name": name}
|
||||
record.update(
|
||||
{
|
||||
"owner_user_id": data.get("owner_user_id"),
|
||||
"published": bool(data.get("published", False)),
|
||||
"detail": data.get("detail"),
|
||||
"name_zh": data.get("name_zh"),
|
||||
"always_on": bool(data.get("always_on", False)),
|
||||
"square_id": str(data.get("square_id") or ""),
|
||||
"created_at": _stamp(data.get("created_at"), record.get("created_at") or now),
|
||||
"updated_at": _stamp(data.get("updated_at"), now),
|
||||
}
|
||||
)
|
||||
self._skills[name] = record
|
||||
return _with_derived(_copy(record)) # type: ignore[arg-type]
|
||||
|
||||
async def migration_upsert_many(self, items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [await self.migration_upsert(item) for item in items]
|
||||
|
||||
async def update(self, name: str, user_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
record = self._skills.get(name)
|
||||
if record is None or record.get("owner_user_id") != user_id:
|
||||
|
||||
@@ -22,6 +22,14 @@ def _row_to_dict(row: SkillRow) -> dict[str, Any]:
|
||||
return data
|
||||
|
||||
|
||||
def _as_datetime(value: Any, fallback: datetime) -> datetime:
|
||||
if isinstance(value, datetime):
|
||||
return value
|
||||
if isinstance(value, str) and value.strip():
|
||||
return datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
|
||||
return fallback
|
||||
|
||||
|
||||
class SkillRepository(SkillStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
@@ -100,6 +108,57 @@ class SkillRepository(SkillStore):
|
||||
await session.refresh(row)
|
||||
return _row_to_dict(row)
|
||||
|
||||
async def migration_upsert(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(SkillRow, data["name"])
|
||||
now = datetime.now(UTC)
|
||||
if row is None:
|
||||
row = SkillRow(name=data["name"])
|
||||
session.add(row)
|
||||
row.owner_user_id = data.get("owner_user_id")
|
||||
row.published = bool(data.get("published", False))
|
||||
row.detail = data.get("detail")
|
||||
row.name_zh = data.get("name_zh")
|
||||
row.always_on = bool(data.get("always_on", False))
|
||||
row.square_id = str(data.get("square_id") or "")
|
||||
row.created_at = _as_datetime(data.get("created_at"), getattr(row, "created_at", None) or now)
|
||||
row.updated_at = _as_datetime(data.get("updated_at"), now)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _row_to_dict(row)
|
||||
|
||||
async def migration_upsert_many(self, items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
if not items:
|
||||
return []
|
||||
async with self._sf() as session:
|
||||
now = datetime.now(UTC)
|
||||
names = [item["name"] for item in items]
|
||||
existing = (
|
||||
await session.execute(select(SkillRow).where(SkillRow.name.in_(names)))
|
||||
).scalars().all()
|
||||
by_name = {row.name: row for row in existing}
|
||||
for data in items:
|
||||
row = by_name.get(data["name"])
|
||||
if row is None:
|
||||
row = SkillRow(name=data["name"])
|
||||
session.add(row)
|
||||
by_name[data["name"]] = row
|
||||
row.owner_user_id = data.get("owner_user_id")
|
||||
row.published = bool(data.get("published", False))
|
||||
row.detail = data.get("detail")
|
||||
row.name_zh = data.get("name_zh")
|
||||
row.always_on = bool(data.get("always_on", False))
|
||||
row.square_id = str(data.get("square_id") or "")
|
||||
row.created_at = _as_datetime(data.get("created_at"), getattr(row, "created_at", None) or now)
|
||||
row.updated_at = _as_datetime(data.get("updated_at"), now)
|
||||
await session.commit()
|
||||
results: list[dict[str, Any]] = []
|
||||
for data in items:
|
||||
row = by_name[data["name"]]
|
||||
await session.refresh(row)
|
||||
results.append(_row_to_dict(row))
|
||||
return results
|
||||
|
||||
async def update(self, name: str, user_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(SkillRow, name)
|
||||
|
||||
@@ -59,6 +59,19 @@ class TagStore(ABC):
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def set_target_tags_bulk(
|
||||
self,
|
||||
target_type: str,
|
||||
assignments: dict[str, list[str]],
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
"""Replace tags for many resources of the same type in one write cycle.
|
||||
|
||||
``assignments`` maps ``target_id`` to the desired tag ids. Each id must
|
||||
reference an existing tag whose ``tag_type`` equals ``target_type``.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def list_assignments(self, target_type: str, target_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
|
||||
"""Bulk-fetch tags for many resources at once (avoids N+1 on list pages).
|
||||
|
||||
@@ -117,6 +117,16 @@ class MemoryTagStore(TagStore):
|
||||
}
|
||||
return self._tags_for(target_type, target_id)
|
||||
|
||||
async def set_target_tags_bulk(
|
||||
self,
|
||||
target_type: str,
|
||||
assignments: dict[str, list[str]],
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
return {
|
||||
target_id: await self.set_target_tags(target_type, target_id, tag_ids)
|
||||
for target_id, tag_ids in assignments.items()
|
||||
}
|
||||
|
||||
async def list_assignments(self, target_type: str, target_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
|
||||
wanted = set(target_ids)
|
||||
out: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
@@ -157,6 +157,49 @@ class TagRepository(TagStore):
|
||||
await session.commit()
|
||||
return await self._tags_for(session, target_type, target_id)
|
||||
|
||||
async def set_target_tags_bulk(
|
||||
self,
|
||||
target_type: str,
|
||||
assignments: dict[str, list[str]],
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
if not assignments:
|
||||
return {}
|
||||
unique_by_target = {
|
||||
target_id: list(dict.fromkeys(tag_ids))
|
||||
for target_id, tag_ids in assignments.items()
|
||||
}
|
||||
all_tag_ids = list(dict.fromkeys(tid for tag_ids in unique_by_target.values() for tid in tag_ids))
|
||||
async with self._sf() as session:
|
||||
if all_tag_ids:
|
||||
found = list((await session.execute(select(TagRow).where(TagRow.id.in_(all_tag_ids)))).scalars())
|
||||
by_id = {row.id: row for row in found}
|
||||
for tid in all_tag_ids:
|
||||
tag = by_id.get(tid)
|
||||
if tag is None:
|
||||
raise ValueError(f"Tag '{tid}' does not exist")
|
||||
if tag.tag_type != target_type:
|
||||
raise ValueError(f"Tag '{tid}' is type '{tag.tag_type}', cannot tag a '{target_type}' resource")
|
||||
await session.execute(
|
||||
delete(TagAssignmentRow).where(
|
||||
TagAssignmentRow.target_type == target_type,
|
||||
TagAssignmentRow.target_id.in_(list(unique_by_target)),
|
||||
)
|
||||
)
|
||||
now = datetime.now(UTC)
|
||||
for target_id, tag_ids in unique_by_target.items():
|
||||
for tid in tag_ids:
|
||||
session.add(
|
||||
TagAssignmentRow(
|
||||
id=uuid.uuid4().hex,
|
||||
tag_id=tid,
|
||||
target_type=target_type,
|
||||
target_id=target_id,
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
return await self.list_assignments(target_type, list(unique_by_target))
|
||||
|
||||
async def list_assignments(self, target_type: str, target_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
|
||||
if not target_ids:
|
||||
return {}
|
||||
|
||||
+18
-18
@@ -1,16 +1,16 @@
|
||||
"""ORM model for thread metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
"""ORM model for thread metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Index, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime, PortableJSON
|
||||
|
||||
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime, PortableJSON
|
||||
|
||||
|
||||
class ThreadMetaRow(Base):
|
||||
__tablename__ = "threads_meta"
|
||||
__table_args__ = (
|
||||
@@ -26,8 +26,8 @@ class ThreadMetaRow(Base):
|
||||
# updated-at ordering. This prevents a full table sort there too.
|
||||
Index("ix_threads_meta_user_updated", "user_id", "updated_at", "thread_id"),
|
||||
)
|
||||
|
||||
thread_id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
|
||||
thread_id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
assistant_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
user_id: Mapped[str | None] = mapped_column(String(64), index=True)
|
||||
# Indexed projections of the corresponding metadata values. The JSON
|
||||
@@ -37,7 +37,7 @@ class ThreadMetaRow(Base):
|
||||
agent_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
action_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
display_name: Mapped[str | None] = mapped_column(String(256))
|
||||
status: Mapped[str] = mapped_column(String(20), default="idle")
|
||||
metadata_json: Mapped[dict] = mapped_column(PortableJSON(), default=dict)
|
||||
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))
|
||||
status: Mapped[str] = mapped_column(String(20), default="idle")
|
||||
metadata_json: Mapped[dict] = mapped_column(PortableJSON(), default=dict)
|
||||
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))
|
||||
+104
-104
@@ -1,104 +1,104 @@
|
||||
"""ORM model for the users table.
|
||||
|
||||
Lives in the harness persistence package so it is picked up by
|
||||
``Base.metadata.create_all()`` alongside ``threads_meta``, ``runs``,
|
||||
``run_events``, and ``feedback``. Using the shared engine means:
|
||||
|
||||
- One SQLite/Postgres database, one connection pool
|
||||
- One schema initialisation codepath
|
||||
- Consistent async sessions across auth and persistence reads
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Index, String, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime
|
||||
|
||||
|
||||
class AuthInitializationRow(Base):
|
||||
"""Singleton transaction claim for the public first-admin setup endpoint."""
|
||||
|
||||
__tablename__ = "auth_initialization"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
|
||||
|
||||
class AuthUsernameRow(Base):
|
||||
"""Reserve new account local-parts across concurrent email-domain variants."""
|
||||
|
||||
__tablename__ = "auth_usernames"
|
||||
username: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
|
||||
|
||||
class AuthServiceNonceRow(Base):
|
||||
"""One-time service exchange nonce shared by every gateway worker."""
|
||||
|
||||
__tablename__ = "auth_service_nonces"
|
||||
nonce_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
client_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, index=True)
|
||||
|
||||
|
||||
class UserRow(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
# UUIDs are stored as 36-char strings for cross-backend portability.
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||
|
||||
email: Mapped[str] = mapped_column(String(191), unique=True, nullable=False, index=True)
|
||||
# Canonical local part used by SSO / username login. Keeping it separately
|
||||
# avoids applying LOWER()/LIKE to every users.email row on each login.
|
||||
username_key: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
password_hash: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
|
||||
# "admin" | "user" — kept as plain string to avoid ALTER TABLE pain
|
||||
# when new roles are introduced.
|
||||
system_role: Mapped[str] = mapped_column(String(16), nullable=False, default="user")
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
nullable=False,
|
||||
default=lambda: datetime.now(UTC),
|
||||
)
|
||||
|
||||
# OAuth linkage (optional). A partial unique index enforces one
|
||||
# account per (provider, oauth_id) pair, leaving NULL/NULL rows
|
||||
# unconstrained so plain password accounts can coexist.
|
||||
oauth_provider: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
oauth_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
|
||||
# Auth lifecycle flags
|
||||
needs_setup: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
token_version: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||
|
||||
# 登录白名单(放行)标记 —— **黑名单模式**。仅当系统设置 ``login_whitelist.enabled``
|
||||
# 打开时生效:关 → 忽略此列,人人可登录;开 → 仅 approved=False(被管理员显式
|
||||
# 「取消放行」)的用户被拦,其余(含从未登录过的新账号)放行。新账号默认 True
|
||||
# (首次登录即放行);存量用户由迁移回填 True。server_default=1 让迁移 ADD COLUMN
|
||||
# 时把已存在行置为已放行。
|
||||
approved: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text("1"))
|
||||
|
||||
# Unified password/passphrase. New writes store the same versioned hash as
|
||||
# password_hash; historical plaintext remains accepted until the next reset.
|
||||
# Never serialize hashes into user-list or login responses.
|
||||
login_password: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
|
||||
# 岗位 (position) the user is assigned to (1:1). NULL = no explicit
|
||||
# position → the user inherits the ``is_default`` position's grants. Drives
|
||||
# the subscription sync engine (see ``deerflow.services.position_sync``).
|
||||
position_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_users_username_key_created_at", "username_key", "created_at"),
|
||||
Index(
|
||||
"idx_users_oauth_identity",
|
||||
"oauth_provider",
|
||||
"oauth_id",
|
||||
unique=True,
|
||||
sqlite_where=text("oauth_provider IS NOT NULL AND oauth_id IS NOT NULL"),
|
||||
),
|
||||
)
|
||||
"""ORM model for the users table.
|
||||
|
||||
Lives in the harness persistence package so it is picked up by
|
||||
``Base.metadata.create_all()`` alongside ``threads_meta``, ``runs``,
|
||||
``run_events``, and ``feedback``. Using the shared engine means:
|
||||
|
||||
- One SQLite/Postgres database, one connection pool
|
||||
- One schema initialisation codepath
|
||||
- Consistent async sessions across auth and persistence reads
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Index, String, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime
|
||||
|
||||
|
||||
class AuthInitializationRow(Base):
|
||||
"""Singleton transaction claim for the public first-admin setup endpoint."""
|
||||
|
||||
__tablename__ = "auth_initialization"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
|
||||
|
||||
class AuthUsernameRow(Base):
|
||||
"""Reserve new account local-parts across concurrent email-domain variants."""
|
||||
|
||||
__tablename__ = "auth_usernames"
|
||||
username: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
|
||||
|
||||
class AuthServiceNonceRow(Base):
|
||||
"""One-time service exchange nonce shared by every gateway worker."""
|
||||
|
||||
__tablename__ = "auth_service_nonces"
|
||||
nonce_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
client_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, index=True)
|
||||
|
||||
|
||||
class UserRow(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
# UUIDs are stored as 36-char strings for cross-backend portability.
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||
|
||||
email: Mapped[str] = mapped_column(String(191), unique=True, nullable=False, index=True)
|
||||
# Canonical local part used by SSO / username login. Keeping it separately
|
||||
# avoids applying LOWER()/LIKE to every users.email row on each login.
|
||||
username_key: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
password_hash: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
|
||||
# "admin" | "user" — kept as plain string to avoid ALTER TABLE pain
|
||||
# when new roles are introduced.
|
||||
system_role: Mapped[str] = mapped_column(String(16), nullable=False, default="user")
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
nullable=False,
|
||||
default=lambda: datetime.now(UTC),
|
||||
)
|
||||
|
||||
# OAuth linkage (optional). A partial unique index enforces one
|
||||
# account per (provider, oauth_id) pair, leaving NULL/NULL rows
|
||||
# unconstrained so plain password accounts can coexist.
|
||||
oauth_provider: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
oauth_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
|
||||
# Auth lifecycle flags
|
||||
needs_setup: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
token_version: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||
|
||||
# 登录白名单(放行)标记 —— **黑名单模式**。仅当系统设置 ``login_whitelist.enabled``
|
||||
# 打开时生效:关 → 忽略此列,人人可登录;开 → 仅 approved=False(被管理员显式
|
||||
# 「取消放行」)的用户被拦,其余(含从未登录过的新账号)放行。新账号默认 True
|
||||
# (首次登录即放行);存量用户由迁移回填 True。server_default=1 让迁移 ADD COLUMN
|
||||
# 时把已存在行置为已放行。
|
||||
approved: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text("1"))
|
||||
|
||||
# Unified password/passphrase. New writes store the same versioned hash as
|
||||
# password_hash; historical plaintext remains accepted until the next reset.
|
||||
# Never serialize hashes into user-list or login responses.
|
||||
login_password: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
|
||||
# 岗位 (position) the user is assigned to (1:1). NULL = no explicit
|
||||
# position → the user inherits the ``is_default`` position's grants. Drives
|
||||
# the subscription sync engine (see ``deerflow.services.position_sync``).
|
||||
position_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_users_username_key_created_at", "username_key", "created_at"),
|
||||
Index(
|
||||
"idx_users_oauth_identity",
|
||||
"oauth_provider",
|
||||
"oauth_id",
|
||||
unique=True,
|
||||
sqlite_where=text("oauth_provider IS NOT NULL AND oauth_id IS NOT NULL"),
|
||||
),
|
||||
)
|
||||
+14
@@ -24,6 +24,14 @@ from deerflow.runtime.checkpointer.chat_archive import (
|
||||
thread_archive_lock,
|
||||
)
|
||||
|
||||
from deerflow.runtime.checkpointer.chat_archive import (
|
||||
archive_db_path,
|
||||
archived_month_for_thread,
|
||||
catalog_path,
|
||||
remove_archived_thread,
|
||||
thread_archive_lock,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -292,6 +300,12 @@ class DualReadCheckpointer:
|
||||
return found
|
||||
configurable = (config or {}).get("configurable", {}) or {}
|
||||
archive = await self._archive_source_for_thread(configurable.get("thread_id"))
|
||||
if archive is not None:
|
||||
found = await archive.saver.aget(config)
|
||||
if found is not None:
|
||||
return found
|
||||
configurable = (config or {}).get("configurable", {}) or {}
|
||||
archive = await self._archive_source_for_thread(configurable.get("thread_id"))
|
||||
if archive is not None:
|
||||
found = await archive.saver.aget(config)
|
||||
if found is not None:
|
||||
|
||||
@@ -414,6 +414,40 @@ class RunManager:
|
||||
self._retention_task.cancel()
|
||||
await asyncio.gather(self._retention_task, return_exceptions=True)
|
||||
|
||||
def watch_completion(self, record: RunRecord) -> None:
|
||||
def finished(_):
|
||||
if self._runs.get(record.run_id) is record:
|
||||
self._finished_at[record.run_id] = time.monotonic()
|
||||
|
||||
if record.task is not None:
|
||||
record.task.add_done_callback(finished)
|
||||
|
||||
async def reap_completed(self, retention_seconds: float = 300) -> None:
|
||||
cutoff = time.monotonic() - retention_seconds
|
||||
for run_id in [key for key, finished in self._finished_at.items() if finished <= cutoff][:200]:
|
||||
await self.cleanup(run_id, delay=0)
|
||||
if run_id in self._finished_at:
|
||||
self._finished_at[run_id] = time.monotonic()
|
||||
|
||||
def start_retention(self, *, retention_seconds=300, interval_seconds=10) -> None:
|
||||
if self._retention_task is not None and not self._retention_task.done():
|
||||
return
|
||||
|
||||
async def sweep():
|
||||
while True:
|
||||
await asyncio.sleep(interval_seconds)
|
||||
try:
|
||||
await self.reap_completed(retention_seconds)
|
||||
except Exception:
|
||||
logger.exception("Completed run retention failed; retaining in-memory records")
|
||||
|
||||
self._retention_task = asyncio.create_task(sweep(), name="completed-run-retention")
|
||||
|
||||
async def aclose(self) -> None:
|
||||
if self._retention_task is not None:
|
||||
self._retention_task.cancel()
|
||||
await asyncio.gather(self._retention_task, return_exceptions=True)
|
||||
|
||||
|
||||
class ConflictError(Exception):
|
||||
"""Raised when multitask_strategy=reject and thread has inflight runs."""
|
||||
|
||||
+706
-701
File diff suppressed because it is too large.
Load diff
@@ -1421,6 +1421,7 @@ def _refresh_cached_view_locked(
|
||||
config_key = _config_key()
|
||||
source_snapshot = _scan_tree(skills_root, source=True)
|
||||
extensions = ExtensionsConfig.from_file()
|
||||
storage.invalidate_skills_cache()
|
||||
discovered = storage.load_skills(enabled_only=False)
|
||||
enabled = [skill for skill in discovered if extensions.is_skill_enabled(skill.name, skill.category)]
|
||||
enabled_names = frozenset(skill.name for skill in enabled)
|
||||
@@ -1514,6 +1515,39 @@ def _refresh_uncached_coalesced(*, storage: SkillStorage | None) -> SkillSandbox
|
||||
)
|
||||
|
||||
|
||||
def _refresh_uncached_coalesced(*, storage: SkillStorage | None) -> SkillSandboxView:
|
||||
"""One in-process catalogue copy, even when the metadata cache is off.
|
||||
|
||||
Task-analysis seats call ``read_file`` / ``bash`` together. Without this,
|
||||
each call takes the process lock and copies every enabled skill. The lock
|
||||
holder keeps it for the whole copy, and a later seat fails the tool with
|
||||
``Timed out waiting for skill view process lock``.
|
||||
"""
|
||||
if storage is None:
|
||||
from deerflow.skills.storage import get_or_new_skill_storage
|
||||
|
||||
storage = get_or_new_skill_storage()
|
||||
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
skills_root = Path(storage.get_skills_root_path()).resolve()
|
||||
runtime_root = get_paths().base_dir
|
||||
runtime_root.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
config_key = _config_key()
|
||||
except OSError:
|
||||
config_key = "extensions-unavailable"
|
||||
# Instance id keeps differently filtered storage objects from sharing a
|
||||
# result. The process singleton is one object, so parallel tool calls join.
|
||||
flight_config = f"uncached:{id(storage)}:{config_key}"
|
||||
return _refresh_singleflight(
|
||||
_cache_key(skills_root, runtime_root.resolve(), storage),
|
||||
flight_config,
|
||||
lambda: _refresh_uncached_skill_sandbox_view(storage=storage),
|
||||
require_cache=False,
|
||||
)
|
||||
|
||||
|
||||
def _local_view_context(storage: SkillStorage | None):
|
||||
"""Return ``(storage, skills_root, runtime_root, cache_key)`` for a local tree."""
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
+5
@@ -232,6 +232,11 @@ class SkillStorage(ABC):
|
||||
# Final template-method flows
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def invalidate_skills_cache(self) -> None:
|
||||
"""Force rediscovery after a sandbox source snapshot changes."""
|
||||
with self._skills_cache_lock:
|
||||
self._skills_cache_signature = None
|
||||
|
||||
def load_skills(self, *, enabled_only: bool = False) -> list[Skill]:
|
||||
"""Discover all skills, merge enabled state, sort and optionally filter.
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import tempfile
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -167,6 +168,42 @@ def mark_uploaded(name: str) -> None:
|
||||
_update_entry(name, {"source": SOURCE_UPLOAD, "created_at": _now_iso()})
|
||||
|
||||
|
||||
def set_migration_metadata_batch(entries: dict[str, dict[str, Any]]) -> None:
|
||||
"""Write trusted migration metadata for many skills in a single sidecar write."""
|
||||
if not entries:
|
||||
return
|
||||
try:
|
||||
with _usage_lock:
|
||||
data = _read_all()
|
||||
now = _now_iso()
|
||||
for name, metadata in entries.items():
|
||||
entry = {**_DEFAULT_ENTRY, **data.get(name, {})}
|
||||
updates: dict[str, Any] = {}
|
||||
if "state" in metadata:
|
||||
state = metadata["state"]
|
||||
updates["state"] = state
|
||||
if state == STATE_ARCHIVED:
|
||||
updates["archived_at"] = entry.get("archived_at") or now
|
||||
elif state == STATE_ACTIVE:
|
||||
updates["archived_at"] = None
|
||||
if "pinned" in metadata:
|
||||
updates["pinned"] = bool(metadata["pinned"])
|
||||
if "featured" in metadata:
|
||||
updates["featured"] = bool(metadata["featured"])
|
||||
if "source" in metadata and metadata["source"]:
|
||||
updates["source"] = metadata["source"]
|
||||
created_at = metadata.get("created_at")
|
||||
if created_at:
|
||||
updates["created_at"] = created_at
|
||||
elif not entry.get("created_at"):
|
||||
updates["created_at"] = now
|
||||
entry.update(updates)
|
||||
data[name] = entry
|
||||
_write_all(data)
|
||||
except Exception:
|
||||
logger.debug("Failed to write migration usage metadata batch", exc_info=True)
|
||||
|
||||
|
||||
def latest_activity_at(name: str) -> str | None:
|
||||
"""Return the most recent activity timestamp, falling back to created_at."""
|
||||
entry = get_entry(name)
|
||||
|
||||
+211
-7
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html as html_lib
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
@@ -12,6 +13,12 @@ from langgraph.typing import ContextT
|
||||
|
||||
from deerflow.agents.thread_state import ThreadState
|
||||
from deerflow.config.paths import VIRTUAL_PATH_PREFIX, get_paths
|
||||
from deerflow.html_runtime.generated_page_chrome import (
|
||||
CHROME_MARKER,
|
||||
HEADER_MARKER,
|
||||
NAV_MARKER,
|
||||
apply_generated_page_chrome,
|
||||
)
|
||||
from deerflow.html_runtime.html_postprocess import apply_mechanical_html_fixes
|
||||
from deerflow.page_reports.templates import (
|
||||
choose_template,
|
||||
@@ -147,13 +154,16 @@ def _choose_page_profile(
|
||||
layout_mode: str = "document",
|
||||
):
|
||||
multi_page = requested_page_count > 1
|
||||
# An explicitly requested catalog id is authoritative (the Bootstrap suite
|
||||
# is multi-page only, and skill-driven selection decides the page count);
|
||||
# only the automatic paths below honor the requested page count.
|
||||
explicit = get_template_profile(template_id) if (template_id or "").strip() else None
|
||||
if explicit is not None:
|
||||
return explicit
|
||||
if not multi_page and layout_mode == "document":
|
||||
normalized_theme = (theme or "").strip().lower()
|
||||
document_id = "dark-document" if normalized_theme in {"dark", "deep-blue", "dark-blue"} else "light-document"
|
||||
return get_template_profile(document_id)
|
||||
explicit = get_template_profile(template_id) if (template_id or "").strip() else None
|
||||
if explicit is not None and (explicit.page_count > 1) == multi_page:
|
||||
return explicit
|
||||
|
||||
wrong_mode_ids = {
|
||||
profile.id
|
||||
@@ -266,6 +276,30 @@ def _apply_document_theme(html: str, theme: str) -> str:
|
||||
return re.sub(r"<html\b", f'<html data-theme="{theme}"', html, count=1, flags=re.IGNORECASE)
|
||||
|
||||
|
||||
def _resolve_prepare_theme(
|
||||
runtime: ToolRuntime[ContextT, ThreadState],
|
||||
requested_theme: str,
|
||||
) -> str:
|
||||
"""Resolve ``auto`` against the current UI theme, with light as a safe fallback."""
|
||||
normalized = (requested_theme or "").strip().lower()
|
||||
if normalized in {"dark", "deep-blue", "dark-blue"}:
|
||||
return "dark"
|
||||
if normalized == "light":
|
||||
return "light"
|
||||
|
||||
sources = [getattr(runtime, "context", None)]
|
||||
config = getattr(runtime, "config", None) or {}
|
||||
if isinstance(config, dict):
|
||||
sources.extend([config.get("context"), config.get("configurable")])
|
||||
for source in sources:
|
||||
if not isinstance(source, dict):
|
||||
continue
|
||||
presentation_theme = str(source.get("presentation_theme") or "").strip().lower()
|
||||
if presentation_theme in {"dark", "light"}:
|
||||
return presentation_theme
|
||||
return "light"
|
||||
|
||||
|
||||
def _prepare(
|
||||
runtime: ToolRuntime[ContextT, ThreadState],
|
||||
*,
|
||||
@@ -282,8 +316,9 @@ def _prepare(
|
||||
required_visualizations = _required_visualizations(required_features, page_brief)
|
||||
requested_page_count = _requested_page_count(preferred_page_count, page_brief)
|
||||
layout_mode = _requested_layout_mode(page_brief)
|
||||
resolved_theme = _resolve_prepare_theme(runtime, theme)
|
||||
profile = _choose_page_profile(
|
||||
theme=theme,
|
||||
theme=resolved_theme,
|
||||
content_density=content_density,
|
||||
required_features=required_features,
|
||||
requested_page_count=requested_page_count,
|
||||
@@ -292,6 +327,11 @@ def _prepare(
|
||||
template_id=template_id,
|
||||
layout_mode=layout_mode,
|
||||
)
|
||||
# The Bootstrap suite is multi-page only (minimum two logical pages). When a
|
||||
# skill picks one explicitly, the template's page count wins over a smaller
|
||||
# requested count so validate checks the multi-page portal contract.
|
||||
if (template_id or "").strip() and requested_page_count < profile.page_count:
|
||||
requested_page_count = profile.page_count
|
||||
source = resolve_template_file(profile.id)
|
||||
thread_id, user_id, workspace, outputs = _thread_directories(runtime)
|
||||
filename = _safe_output_filename(output_name)
|
||||
@@ -307,11 +347,30 @@ def _prepare(
|
||||
template_html = _apply_minimum_font_size(source.read_text(encoding="utf-8"))
|
||||
template_html = _apply_document_theme(template_html, profile.theme)
|
||||
runtime_base_url = _html_runtime_base_url()
|
||||
# Bootstrap 套件模板以占位符引用 Gateway 运行库;在会话副本中解析成部署相关的
|
||||
# 浏览器可达地址,模板源文件保持部署无关。
|
||||
template_html = template_html.replace(_RUNTIME_BASE_PLACEHOLDER, runtime_base_url)
|
||||
brand_name, brand_logo_url, brand_footer_text, brand_chrome_enabled = _active_branding_requirements()
|
||||
text_only_branding = _text_only_branding_enabled()
|
||||
pre_injected = False
|
||||
if brand_name and brand_chrome_enabled:
|
||||
# 生成开始就带上平台页头:工作副本从第一秒起就有品牌导航,模型只编辑
|
||||
# 下方内容,不会再自写顶部导航或为想象中的页头留 padding。
|
||||
template_html, _chrome_notes = apply_generated_page_chrome(
|
||||
template_html,
|
||||
system_name=brand_name,
|
||||
logo_url=brand_logo_url,
|
||||
footer_text=brand_footer_text,
|
||||
header_layout=_active_branding_header_layout(),
|
||||
allow_text_only=text_only_branding,
|
||||
)
|
||||
pre_injected = CHROME_MARKER in template_html
|
||||
working_copy.write_text(template_html, encoding="utf-8")
|
||||
map_engine = _active_html_map_engine()
|
||||
brief = {
|
||||
"template": profile.to_dict(),
|
||||
"requested_theme": theme or "auto",
|
||||
"resolved_theme": resolved_theme,
|
||||
"requested_content_density": content_density or "balanced",
|
||||
"requested_page_count": requested_page_count,
|
||||
"page_mode": "multi" if requested_page_count > 1 else "single",
|
||||
@@ -323,6 +382,33 @@ def _prepare(
|
||||
"required_visualizations": sorted(required_visualizations),
|
||||
"visualization_contract": _visualization_contract(required_visualizations),
|
||||
"edit_contract": _edit_contract(profile.id),
|
||||
"runtime_base_url": runtime_base_url,
|
||||
"platform_branding": {
|
||||
"enabled": bool(brand_name and brand_chrome_enabled),
|
||||
"pre_injected": pre_injected,
|
||||
"system_name": brand_name,
|
||||
"logo_url": brand_logo_url,
|
||||
"footer_text": brand_footer_text,
|
||||
"chrome_enabled": brand_chrome_enabled,
|
||||
"rule": (
|
||||
"管理员已配置生成网页标识,且工作副本在 prepare 时就注入了平台品牌页头(顶部导航条)。"
|
||||
"编辑时保留页头结构(header[data-df-generated-header] 与其 style/script)不要改动或删除,"
|
||||
"只编辑页头下方的内容;不要另写顶部导航,不要为页头添加 padding/margin,正文不要书写系统名称或 Logo。"
|
||||
if pre_injected
|
||||
else (
|
||||
"管理员已配置生成网页标识:平台会在写入与校验时自动注入统一品牌页头(多页面含导航)。"
|
||||
"正文不要书写系统名称、引用系统 Logo 或创建 data-df-brand。"
|
||||
if brand_name and brand_chrome_enabled
|
||||
else (
|
||||
"平台自动注入品牌页头已关闭;使用自带品牌位的平台模板时,模板会展示管理员配置的名称与 Logo,"
|
||||
"其余普通网页正文不要虚构系统名称或 Logo。"
|
||||
if brand_name
|
||||
else "当前未配置完整的生成网页标识;不要虚构系统名称或 Logo。"
|
||||
)
|
||||
)
|
||||
),
|
||||
},
|
||||
"map_engine": map_engine,
|
||||
"font_rule": "所有可见文字最小字号为 16px;写 HTML 时直接达到,不再单独做字号校验。",
|
||||
"layout_rule": (
|
||||
"普通单页报告必须是可纵向滚动的响应式文档;禁止固定 1920×1080 舞台、body overflow:hidden 和视口缩放脚本。"
|
||||
@@ -330,6 +416,12 @@ def _prepare(
|
||||
else "用户明确要求大屏,可使用固定单屏布局,但仍需保证各区块不重叠。"
|
||||
),
|
||||
}
|
||||
if map_engine != "leaflet" and "data-df-map" in template_html:
|
||||
brief["map_engine_warning"] = (
|
||||
"此模板使用「地图网页」(Leaflet 瓦片,data-df-map)契约,而系统设置当前的网页地图引擎是 "
|
||||
"ECharts GeoJSON。需要管理员在「外观设置 → HTML 地图」切换为「地图网页」,"
|
||||
"或把地图区块改写为当前引擎契约,否则 validate 会报地图契约错误。"
|
||||
)
|
||||
brief_path.write_text(json.dumps(brief, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return json.dumps(
|
||||
{
|
||||
@@ -899,6 +991,87 @@ def _map_contract_errors(html: str) -> list[str]:
|
||||
return errors
|
||||
|
||||
|
||||
def _branding_errors(
|
||||
html: str,
|
||||
*,
|
||||
system_name: str | None,
|
||||
logo_url: str | None,
|
||||
text_only: bool = False,
|
||||
) -> list[str]:
|
||||
"""Require the configured identity only inside a generated webpage."""
|
||||
|
||||
if not (system_name and (logo_url or text_only)):
|
||||
return []
|
||||
|
||||
errors: list[str] = []
|
||||
if system_name:
|
||||
visible_text = html_lib.unescape(_visible_markup(html))
|
||||
if system_name not in visible_text:
|
||||
errors.append(f"页面缺少管理员配置的网页展示名称“{system_name}”。")
|
||||
if logo_url:
|
||||
logo_found = False
|
||||
for tag in re.findall(r"<img\b[^>]*>", html, flags=re.IGNORECASE):
|
||||
source = re.search(r"\bsrc\s*=\s*[\"']([^\"']+)[\"']", tag, flags=re.IGNORECASE)
|
||||
if source and html_lib.unescape(source.group(1)) == logo_url:
|
||||
logo_found = True
|
||||
break
|
||||
if not logo_found:
|
||||
errors.append("页面缺少管理员配置的网页 Logo,必须按生成网页标识地址通过 <img> 原样引用。")
|
||||
brand_marker = re.search(
|
||||
r"<([a-z][\w:-]*)\b[^>]*\bdata-df-brand(?:\s*=\s*[\"'][^\"']*[\"'])?[^>]*>",
|
||||
html,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
if brand_marker is None:
|
||||
errors.append("生成网页标识必须放入带 data-df-brand 的紧凑标识组。")
|
||||
if HEADER_MARKER not in html:
|
||||
errors.append("页面缺少平台统一生成的顶部标识栏。")
|
||||
if _count_page_views(html) > 1 and NAV_MARKER not in html:
|
||||
errors.append("多页面缺少平台统一生成的页面导航栏。")
|
||||
return errors
|
||||
|
||||
|
||||
def _active_branding_requirements() -> tuple[str | None, str | None, str | None, bool]:
|
||||
"""Return the configured identity plus the chrome master switch.
|
||||
|
||||
The name/logo mode/footer stay visible while ``chrome_enabled`` is False so
|
||||
template skills that embed the identity themselves can still read them;
|
||||
the switch only stops the platform from auto-injecting its own shell.
|
||||
"""
|
||||
from deerflow.config.system_settings import generated_page_logo_public_url, load_system_settings
|
||||
|
||||
branding = load_system_settings().generated_page_branding
|
||||
logo_url = generated_page_logo_public_url(
|
||||
_html_runtime_base_url(),
|
||||
branding,
|
||||
)
|
||||
chrome_enabled = bool(getattr(branding, "chrome_enabled", True))
|
||||
text_only = getattr(branding, "logo_mode", "custom") == "none"
|
||||
if not (branding.system_name and (logo_url or text_only)):
|
||||
return None, None, None, chrome_enabled
|
||||
return branding.system_name, logo_url, getattr(branding, "footer_text", None), chrome_enabled
|
||||
|
||||
|
||||
def _text_only_branding_enabled() -> bool:
|
||||
"""True only when the administrator explicitly chose a header without a logo."""
|
||||
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
|
||||
return getattr(load_system_settings().generated_page_branding, "logo_mode", "custom") == "none"
|
||||
|
||||
|
||||
def _active_branding_header_layout() -> str:
|
||||
"""Brand lockup position for the injected header: center (default) or left."""
|
||||
try:
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
|
||||
value = str(getattr(load_system_settings().generated_page_branding, "header_layout", "") or "")
|
||||
normalized = value.strip().lower()
|
||||
return normalized if normalized in {"left", "center"} else "center"
|
||||
except Exception:
|
||||
return "left"
|
||||
|
||||
|
||||
def _quality_report(
|
||||
html: str,
|
||||
*,
|
||||
@@ -906,6 +1079,9 @@ def _quality_report(
|
||||
expected_features: set[str],
|
||||
expected_page_count: int | None = None,
|
||||
expected_layout_mode: str | None = None,
|
||||
required_brand_name: str | None = None,
|
||||
required_brand_logo_url: str | None = None,
|
||||
required_brand_text_only: bool = False,
|
||||
) -> dict[str, object]:
|
||||
lowered = html.lower()
|
||||
errors: list[str] = []
|
||||
@@ -960,6 +1136,14 @@ def _quality_report(
|
||||
errors.append("用户明确要求多页面,但 HTML 未检测到多个页面视图。")
|
||||
if expected_page_count is not None and expected_page_count > 1:
|
||||
errors.extend(_multi_page_portal_errors(html, page_views))
|
||||
errors.extend(
|
||||
_branding_errors(
|
||||
html,
|
||||
system_name=required_brand_name,
|
||||
logo_url=required_brand_logo_url,
|
||||
text_only=required_brand_text_only,
|
||||
)
|
||||
)
|
||||
return {
|
||||
"ok": not errors,
|
||||
"errors": errors,
|
||||
@@ -1015,8 +1199,6 @@ def _validate(
|
||||
raise ValueError(f"HTML 超过 {_MAX_HTML_BYTES // 1024 // 1024}MB,拒绝读取。")
|
||||
html = actual.read_text(encoding="utf-8")
|
||||
html, auto_fixed = apply_mechanical_html_fixes(str(actual), html)
|
||||
if auto_fixed:
|
||||
actual.write_text(html, encoding="utf-8")
|
||||
workspace = get_paths().sandbox_work_dir(thread_id, user_id=user_id)
|
||||
persisted_visualizations = _brief_visualizations(actual, workspace)
|
||||
expected_page_count = _brief_page_count(actual, workspace)
|
||||
@@ -1026,6 +1208,23 @@ def _validate(
|
||||
merged_features = {item.strip().lower() for item in expected_features if item.strip()}
|
||||
merged_features.update(persisted_visualizations)
|
||||
merged_features.update(_required_visualizations([], page_brief))
|
||||
required_brand_name, required_brand_logo_url, required_footer_text, brand_chrome_enabled = (
|
||||
_active_branding_requirements()
|
||||
)
|
||||
text_only_branding = _text_only_branding_enabled()
|
||||
branding_fixed: list[str] = []
|
||||
if brand_chrome_enabled:
|
||||
html, branding_fixed = apply_generated_page_chrome(
|
||||
html,
|
||||
system_name=required_brand_name,
|
||||
logo_url=required_brand_logo_url,
|
||||
footer_text=required_footer_text,
|
||||
header_layout=_active_branding_header_layout(),
|
||||
allow_text_only=text_only_branding,
|
||||
)
|
||||
auto_fixed.extend(branding_fixed)
|
||||
if auto_fixed:
|
||||
actual.write_text(html, encoding="utf-8")
|
||||
report = _attach_repair_plan(
|
||||
_quality_report(
|
||||
html,
|
||||
@@ -1033,6 +1232,10 @@ def _validate(
|
||||
expected_features=merged_features,
|
||||
expected_page_count=expected_page_count,
|
||||
expected_layout_mode=expected_layout_mode,
|
||||
# 开关关闭 = 完全不做品牌要求:既不注入,也不逼模型自写。
|
||||
required_brand_name=required_brand_name if brand_chrome_enabled else None,
|
||||
required_brand_logo_url=required_brand_logo_url if brand_chrome_enabled else None,
|
||||
required_brand_text_only=text_only_branding if brand_chrome_enabled else False,
|
||||
),
|
||||
auto_fixed,
|
||||
)
|
||||
@@ -1077,7 +1280,8 @@ def page_report_template_tool(
|
||||
template into this thread's outputs; ``validate`` also supports
|
||||
from-scratch HTML and writes a JSON quality report next to it.
|
||||
theme: ``dark`` or ``light``. Use the UI-provided presentation theme when
|
||||
available; ``auto`` lets the selector use all profiles.
|
||||
available; ``auto`` resolves to the current UI mode and falls back to
|
||||
light only when the UI mode is unavailable.
|
||||
content_density: ``text-heavy``, ``balanced``, or ``data-heavy``.
|
||||
required_features: Needed components such as ``flowchart``, ``chart``,
|
||||
``map``, ``line``, ``pie``, ``radar``, ``scatter``, ``gantt``,
|
||||
|
||||
+29
@@ -134,9 +134,38 @@ def _normalize_presented_filepath(
|
||||
if not actual_path.is_file():
|
||||
raise ValueError(f"Path is not a regular file: {filepath}")
|
||||
|
||||
_ensure_generated_html_chrome(actual_path)
|
||||
return f"{OUTPUTS_VIRTUAL_PREFIX}/{relative_path.as_posix()}"
|
||||
|
||||
|
||||
_PRESENT_HTML_MAX_BYTES = 4 * 1024 * 1024
|
||||
|
||||
|
||||
def _ensure_generated_html_chrome(actual_path: Path) -> None:
|
||||
"""Backstop branding injection at delivery time.
|
||||
|
||||
write_file / str_replace / page_report_template validate already inject the
|
||||
configured brand header, but an agent may author HTML through bash or an
|
||||
older artifact may predate the configuration. present_files is the single
|
||||
choke point every delivery passes, so apply the (idempotent) chrome here to
|
||||
make the admin-configured identity reach every account and every agent.
|
||||
"""
|
||||
if actual_path.suffix.lower() not in {".html", ".htm"}:
|
||||
return
|
||||
try:
|
||||
if actual_path.stat().st_size > _PRESENT_HTML_MAX_BYTES:
|
||||
return
|
||||
from deerflow.html_runtime.html_postprocess import maybe_fix_generated_html
|
||||
|
||||
content = actual_path.read_text(encoding="utf-8")
|
||||
fixed = maybe_fix_generated_html(str(actual_path), content)
|
||||
if fixed != content:
|
||||
actual_path.write_text(fixed, encoding="utf-8")
|
||||
except Exception:
|
||||
# Delivery must never fail because of the optional brand shell.
|
||||
logger.debug("Generated-page chrome backstop failed for %s", actual_path, exc_info=True)
|
||||
|
||||
|
||||
@tool("present_files", parse_docstring=True)
|
||||
def present_file_tool(
|
||||
runtime: ToolRuntime[ContextT, ThreadState],
|
||||
|
||||
+2
@@ -31,6 +31,7 @@ def test_invalid_command_timeouts_fail_config_validation(value):
|
||||
@pytest.mark.parametrize("retry", [False, True])
|
||||
@pytest.mark.parametrize("timeout", [7.5, None])
|
||||
def test_postgres_uses_same_deadline_on_initial_and_retry_engines(monkeypatch, retry, timeout):
|
||||
monkeypatch.setattr(persistence, "_install_slow_sql_logging", lambda *args: None)
|
||||
async def run():
|
||||
created = []
|
||||
|
||||
@@ -124,6 +125,7 @@ def test_gauss_asyncpg_receives_command_timeout():
|
||||
|
||||
|
||||
def test_sqlite_initialization_never_receives_network_pool_arguments(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(persistence, "_install_slow_sql_logging", lambda *args: None)
|
||||
async def run():
|
||||
actual_create = persistence.create_async_engine
|
||||
calls = []
|
||||
|
||||
+75
@@ -1,6 +1,7 @@
|
||||
"""A completed/cancelled graph must not leave SSE alive on metadata I/O."""
|
||||
|
||||
import asyncio
|
||||
import gc
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
@@ -184,3 +185,77 @@ async def test_completion_budget_does_not_time_out_executing_graph(monkeypatch):
|
||||
finally:
|
||||
graph_release.set()
|
||||
await asyncio.wait_for(run.task, 1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_background_title_task_survives_gc(monkeypatch):
|
||||
started = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def slow_finalize(**kwargs):
|
||||
started.set()
|
||||
await release.wait()
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(worker, "finalize_thread_title", slow_finalize)
|
||||
monkeypatch.setattr(worker, "_RUN_FINALIZATION_TIMEOUT_SECONDS", 1.0)
|
||||
|
||||
async def checkpoint(*args):
|
||||
return SimpleNamespace(
|
||||
checkpoint={"channel_values": {"title": "Draft", "title_provisional": True}},
|
||||
config={},
|
||||
)
|
||||
|
||||
fake_journal = SimpleNamespace(flush=AsyncMock(), get_completion_data=lambda: {})
|
||||
monkeypatch.setattr(journal_module, "RunJournal", lambda **kwargs: fake_journal)
|
||||
manager = RunManager()
|
||||
record = await manager.create("title-gc-test")
|
||||
bridge = MemoryStreamBridge()
|
||||
monkeypatch.setattr(bridge, "cleanup", AsyncMock())
|
||||
thread_store = SimpleNamespace(update_display_name=AsyncMock(), update_status=AsyncMock())
|
||||
task = asyncio.create_task(
|
||||
worker.run_agent(
|
||||
bridge,
|
||||
manager,
|
||||
record,
|
||||
ctx=worker.RunContext(
|
||||
checkpointer=SimpleNamespace(aget_tuple=checkpoint),
|
||||
event_store=object(),
|
||||
thread_store=thread_store,
|
||||
),
|
||||
agent_factory=lambda **kwargs: FinishedAgent(),
|
||||
graph_input={},
|
||||
config={},
|
||||
)
|
||||
)
|
||||
record.task = task
|
||||
try:
|
||||
await asyncio.wait_for(task, 1)
|
||||
await asyncio.wait_for(started.wait(), 1)
|
||||
pending = [item for item in worker._BACKGROUND_TITLE_TASKS if not item.done()]
|
||||
assert pending
|
||||
gc.collect()
|
||||
await asyncio.sleep(0)
|
||||
pending = [item for item in worker._BACKGROUND_TITLE_TASKS if not item.done()]
|
||||
assert pending
|
||||
assert not pending[0].cancelled()
|
||||
finally:
|
||||
release.set()
|
||||
leftover = [item for item in list(worker._BACKGROUND_TITLE_TASKS) if not item.done()]
|
||||
if leftover:
|
||||
await asyncio.wait_for(asyncio.gather(*leftover), 1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_title_callback_does_not_raise():
|
||||
async def never():
|
||||
await asyncio.Event().wait()
|
||||
return True
|
||||
|
||||
title_task = asyncio.create_task(never())
|
||||
worker._BACKGROUND_TITLE_TASKS.add(title_task)
|
||||
title_task.add_done_callback(worker._log_background_title_finalize_failure("t1"))
|
||||
title_task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await title_task
|
||||
assert title_task not in worker._BACKGROUND_TITLE_TASKS
|
||||
+7
-1
@@ -84,6 +84,9 @@ def test_create_list_and_metadata_do_not_touch_checkpoint(monkeypatch):
|
||||
@pytest.mark.asyncio
|
||||
async def test_roundtable_init_stream_creates_only_metadata_and_keeps_seat_mapping(monkeypatch):
|
||||
from app.gateway.routers import multi_agent
|
||||
from deerflow.config.system_settings import RoundtableRoomLimitSettings
|
||||
from app.gateway import roundtable_room_gate
|
||||
monkeypatch.setattr(roundtable_room_gate, "get_roundtable_room_limit_settings", lambda: RoundtableRoomLimitSettings(enabled=False))
|
||||
|
||||
monkeypatch.setattr(multi_agent, "ensure_roundtable_functional_agents", lambda: None)
|
||||
monkeypatch.setattr(multi_agent, "_get_agents_batch_direct", AsyncMock(return_value={"seat-a": {"name": "A"}, "seat-b": {"name": "B"}}))
|
||||
@@ -243,11 +246,14 @@ def test_cancelled_history_closes_iterator():
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["foreground", "background"])
|
||||
def test_roundtable_internal_creation_defers_checkpoint_and_can_run_twice(kind):
|
||||
def test_roundtable_internal_creation_defers_checkpoint_and_can_run_twice(kind, monkeypatch):
|
||||
from starlette.requests import Request
|
||||
|
||||
from app.gateway import roundtable_inprocess_gateway
|
||||
from app.gateway.routers import multi_agent
|
||||
from deerflow.config.system_settings import RoundtableRoomLimitSettings
|
||||
from app.gateway import roundtable_room_gate
|
||||
monkeypatch.setattr(roundtable_room_gate, "get_roundtable_room_limit_settings", lambda: RoundtableRoomLimitSettings(enabled=False))
|
||||
|
||||
class State(TypedDict):
|
||||
messages: Annotated[list, add_messages]
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synchronize bundled public skills into a deployment's live skill root."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
from app.builtin_skill_sync import ( # noqa: E402
|
||||
ROUTED_PAGE_SKILLS,
|
||||
SkillSyncError,
|
||||
publish_bundled_public_skills,
|
||||
)
|
||||
from app.builtin_skill_sync import sync_builtin_public_skills as sync_builtin_public_skills # noqa: E402
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--source", type=Path, required=True)
|
||||
parser.add_argument("--target", type=Path, required=True)
|
||||
parser.add_argument("--required", action="append", default=[])
|
||||
parser.add_argument("--require-routed-page-skills", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
required = list(args.required)
|
||||
if args.require_routed_page_skills:
|
||||
required = [*ROUTED_PAGE_SKILLS, *required]
|
||||
try:
|
||||
result = publish_bundled_public_skills(
|
||||
args.source,
|
||||
args.target,
|
||||
required=tuple(dict.fromkeys(required)),
|
||||
)
|
||||
except (OSError, SkillSyncError) as exc:
|
||||
print(
|
||||
json.dumps(
|
||||
{"status": "error", "error": str(exc)},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 2
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,756 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.gateway import agent_skill_migration as migration_module
|
||||
from app.gateway.agent_skill_migration import (
|
||||
AgentManifestItem,
|
||||
MigrationManifest,
|
||||
OwnerReference,
|
||||
SkillManifestItem,
|
||||
SupportDirectoryManifestItem,
|
||||
apply_migration_manifest,
|
||||
build_agent_migration_manifest,
|
||||
build_skill_migration_manifest,
|
||||
compute_tree_hash,
|
||||
preflight_manifest,
|
||||
prepare_manifest_for_apply,
|
||||
)
|
||||
from deerflow.persistence.agents.memory import MemoryAgentStore
|
||||
from deerflow.persistence.agents.sql import AgentRepository
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.skills.memory import MemorySkillStore
|
||||
from deerflow.persistence.skills.sql import SkillRepository
|
||||
from deerflow.persistence.tags.memory import MemoryTagStore
|
||||
from deerflow.skills import usage as skill_usage
|
||||
|
||||
|
||||
def _write(path: Path, content: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
|
||||
|
||||
def _manifest(agents_root: Path, skills_root: Path) -> MigrationManifest:
|
||||
agent_dir = agents_root / "agent-one"
|
||||
skill_dir = skills_root / "custom" / "folder-does-not-match-name"
|
||||
return MigrationManifest(
|
||||
bundle_id="bundle-1",
|
||||
agents=[
|
||||
AgentManifestItem(
|
||||
id="agent-one",
|
||||
relative_dir="agent-one",
|
||||
tree_hash=compute_tree_hash(agent_dir),
|
||||
name="智能体一",
|
||||
owner=OwnerReference(source_user_id="source-u1", email="owner@example.com"),
|
||||
skills=["skill-one"],
|
||||
)
|
||||
],
|
||||
skills=[
|
||||
SkillManifestItem(
|
||||
name="skill-one",
|
||||
category="custom",
|
||||
relative_dir="custom/folder-does-not-match-name",
|
||||
tree_hash=compute_tree_hash(skill_dir),
|
||||
owner=OwnerReference(source_user_id="source-u1", email="owner@example.com"),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_preflight_matches_live_directories_by_agent_id_and_skill_manifest_name(tmp_path: Path) -> None:
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
_write(agents_root / "agent-one" / "config.yaml", "id: agent-one\nname: 智能体一\nskills:\n - skill-one\n")
|
||||
_write(
|
||||
skills_root / "custom" / "folder-does-not-match-name" / "SKILL.md",
|
||||
"---\nname: skill-one\ndescription: test\n---\nbody\n",
|
||||
)
|
||||
|
||||
result = preflight_manifest(
|
||||
_manifest(agents_root, skills_root),
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={"owner@example.com": "target-u9"},
|
||||
)
|
||||
|
||||
assert result.ready is True
|
||||
assert result.agents[0].status == "matched"
|
||||
assert result.skills[0].status == "matched"
|
||||
assert result.owner_mappings[0].target_user_id == "target-u9"
|
||||
|
||||
|
||||
def test_preflight_blocks_missing_or_changed_live_content(tmp_path: Path) -> None:
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
_write(agents_root / "agent-one" / "config.yaml", "id: agent-one\nname: 智能体一\n")
|
||||
_write(
|
||||
skills_root / "custom" / "folder-does-not-match-name" / "SKILL.md",
|
||||
"---\nname: skill-one\ndescription: test\n---\nbody\n",
|
||||
)
|
||||
manifest = _manifest(agents_root, skills_root)
|
||||
_write(agents_root / "agent-one" / "SOUL.md", "changed after export")
|
||||
(skills_root / "custom" / "folder-does-not-match-name" / "SKILL.md").unlink()
|
||||
|
||||
result = preflight_manifest(
|
||||
manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={"owner@example.com": "target-u9"},
|
||||
)
|
||||
|
||||
assert result.ready is False
|
||||
assert result.agents[0].status == "hash_mismatch"
|
||||
assert result.skills[0].status == "missing"
|
||||
|
||||
|
||||
def test_preflight_blocks_unresolved_owner_and_identity_mismatch(tmp_path: Path) -> None:
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
_write(agents_root / "agent-one" / "config.yaml", "id: another-agent\nname: wrong\n")
|
||||
_write(
|
||||
skills_root / "custom" / "folder-does-not-match-name" / "SKILL.md",
|
||||
"---\nname: another-skill\ndescription: wrong\n---\nbody\n",
|
||||
)
|
||||
manifest = _manifest(agents_root, skills_root)
|
||||
# Re-sign the mismatching content so identity validation, rather than the
|
||||
# checksum, is what rejects it.
|
||||
manifest.agents[0].tree_hash = compute_tree_hash(agents_root / "agent-one")
|
||||
manifest.skills[0].tree_hash = compute_tree_hash(skills_root / "custom" / "folder-does-not-match-name")
|
||||
|
||||
result = preflight_manifest(
|
||||
manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={},
|
||||
)
|
||||
|
||||
assert result.ready is False
|
||||
assert result.agents[0].status == "identity_mismatch"
|
||||
assert result.skills[0].status == "identity_mismatch"
|
||||
assert result.owner_mappings[0].status == "unresolved"
|
||||
|
||||
|
||||
def test_preflight_checks_many_skill_trees_with_bounded_parallelism(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
active = 0
|
||||
peak_active = 0
|
||||
lock = threading.Lock()
|
||||
|
||||
def fake_resource_preflight(**kwargs):
|
||||
nonlocal active, peak_active
|
||||
with lock:
|
||||
active += 1
|
||||
peak_active = max(peak_active, active)
|
||||
time.sleep(0.02)
|
||||
with lock:
|
||||
active -= 1
|
||||
return migration_module.ResourcePreflightItem(
|
||||
kind=kwargs["kind"],
|
||||
key=kwargs["key"],
|
||||
relative_dir=kwargs["relative_dir"],
|
||||
status="matched",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
migration_module,
|
||||
"_resource_preflight",
|
||||
fake_resource_preflight,
|
||||
)
|
||||
manifest = MigrationManifest(
|
||||
bundle_id="parallel-preflight",
|
||||
skills=[
|
||||
SkillManifestItem(
|
||||
name=f"skill-{index}",
|
||||
category="custom",
|
||||
relative_dir=f"custom/skill-{index}",
|
||||
tree_hash="0" * 64,
|
||||
)
|
||||
for index in range(12)
|
||||
],
|
||||
)
|
||||
|
||||
result = preflight_manifest(
|
||||
manifest,
|
||||
agents_root=tmp_path / "agents",
|
||||
skills_root=tmp_path / "skills",
|
||||
users_by_email={},
|
||||
)
|
||||
|
||||
assert result.ready is True
|
||||
assert peak_active > 1
|
||||
|
||||
|
||||
def test_prepare_manifest_can_skip_invalid_skills_and_their_support_dependants(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
good_dir = skills_root / "custom" / "good"
|
||||
missing_dir = skills_root / "custom" / "missing"
|
||||
support_dir = skills_root / "public" / "shared-support"
|
||||
_write(good_dir / "SKILL.md", "---\nname: good\n---\nbody\n")
|
||||
_write(missing_dir / "SKILL.md", "---\nname: missing\n---\nbody\n")
|
||||
_write(support_dir / "helper.py", "VALUE = 1\n")
|
||||
manifest = MigrationManifest(
|
||||
bundle_id="skills-with-one-bad-entry",
|
||||
skills=[
|
||||
SkillManifestItem(
|
||||
name="good",
|
||||
category="custom",
|
||||
relative_dir="custom/good",
|
||||
tree_hash=compute_tree_hash(good_dir),
|
||||
),
|
||||
SkillManifestItem(
|
||||
name="missing",
|
||||
category="custom",
|
||||
relative_dir="custom/missing",
|
||||
tree_hash=compute_tree_hash(missing_dir),
|
||||
),
|
||||
],
|
||||
support_directories=[
|
||||
SupportDirectoryManifestItem(
|
||||
relative_dir="public/shared-support",
|
||||
tree_hash=compute_tree_hash(support_dir),
|
||||
required_by=["missing"],
|
||||
)
|
||||
],
|
||||
)
|
||||
(missing_dir / "SKILL.md").unlink()
|
||||
(support_dir / "helper.py").unlink()
|
||||
preflight = preflight_manifest(
|
||||
manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={},
|
||||
)
|
||||
|
||||
effective_manifest, effective_preflight, skipped = prepare_manifest_for_apply(
|
||||
manifest,
|
||||
preflight,
|
||||
skip_invalid_skills=True,
|
||||
)
|
||||
|
||||
assert [item.name for item in effective_manifest.skills] == ["good"]
|
||||
assert effective_manifest.support_directories == []
|
||||
assert skipped == ["missing"]
|
||||
assert effective_preflight.ready is True
|
||||
assert [item.key for item in effective_preflight.skills] == ["custom:good"]
|
||||
|
||||
|
||||
def test_prepare_manifest_does_not_skip_failures_without_explicit_opt_in(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
skill_dir = skills_root / "custom" / "missing"
|
||||
_write(skill_dir / "SKILL.md", "---\nname: missing\n---\nbody\n")
|
||||
manifest = MigrationManifest(
|
||||
bundle_id="strict-skill-import",
|
||||
skills=[
|
||||
SkillManifestItem(
|
||||
name="missing",
|
||||
category="custom",
|
||||
relative_dir="custom/missing",
|
||||
tree_hash=compute_tree_hash(skill_dir),
|
||||
)
|
||||
],
|
||||
)
|
||||
(skill_dir / "SKILL.md").unlink()
|
||||
preflight = preflight_manifest(
|
||||
manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={},
|
||||
)
|
||||
|
||||
effective_manifest, effective_preflight, skipped = prepare_manifest_for_apply(
|
||||
manifest,
|
||||
preflight,
|
||||
skip_invalid_skills=False,
|
||||
)
|
||||
|
||||
assert effective_manifest is manifest
|
||||
assert effective_preflight is preflight
|
||||
assert skipped == []
|
||||
assert effective_preflight.ready is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_apply_manifest_skips_invalid_skill_and_applies_matched_skill(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
good_dir = skills_root / "custom" / "good"
|
||||
missing_dir = skills_root / "custom" / "missing"
|
||||
_write(good_dir / "SKILL.md", "---\nname: good\n---\nbody\n")
|
||||
_write(missing_dir / "SKILL.md", "---\nname: missing\n---\nbody\n")
|
||||
manifest = MigrationManifest(
|
||||
bundle_id="partial-skill-import",
|
||||
skills=[
|
||||
SkillManifestItem(
|
||||
name="good",
|
||||
category="custom",
|
||||
relative_dir="custom/good",
|
||||
tree_hash=compute_tree_hash(good_dir),
|
||||
),
|
||||
SkillManifestItem(
|
||||
name="missing",
|
||||
category="custom",
|
||||
relative_dir="custom/missing",
|
||||
tree_hash=compute_tree_hash(missing_dir),
|
||||
),
|
||||
],
|
||||
)
|
||||
(missing_dir / "SKILL.md").unlink()
|
||||
preflight = preflight_manifest(
|
||||
manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={},
|
||||
)
|
||||
extensions_path = tmp_path / "extensions_config.json"
|
||||
extensions_path.write_text("{}", encoding="utf-8")
|
||||
monkeypatch.setattr(
|
||||
"app.gateway.agent_skill_migration._apply_usage_metadata",
|
||||
lambda _name, _metadata: None,
|
||||
)
|
||||
skills = MemorySkillStore()
|
||||
|
||||
result = await apply_migration_manifest(
|
||||
manifest,
|
||||
preflight=preflight,
|
||||
agent_store=MemoryAgentStore(),
|
||||
skill_store=skills,
|
||||
tag_store=MemoryTagStore(),
|
||||
agents_root=agents_root,
|
||||
users_by_email={},
|
||||
fallback_owner_user_id=None,
|
||||
extensions_config_path=extensions_path,
|
||||
skip_invalid_skills=True,
|
||||
)
|
||||
|
||||
assert result.skills_applied == 1
|
||||
assert result.skills_skipped == 1
|
||||
assert result.skipped_skill_names == ["missing"]
|
||||
assert await skills.get_any("good") is not None
|
||||
assert await skills.get_any("missing") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_apply_many_skills_uses_batch_persistence_tags_and_usage(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
class CountingSkillStore(MemorySkillStore):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.single_calls = 0
|
||||
self.batch_calls = 0
|
||||
|
||||
async def migration_upsert(self, data):
|
||||
self.single_calls += 1
|
||||
return await super().migration_upsert(data)
|
||||
|
||||
async def migration_upsert_many(self, items):
|
||||
self.batch_calls += 1
|
||||
return [
|
||||
await MemorySkillStore.migration_upsert(self, item)
|
||||
for item in items
|
||||
]
|
||||
|
||||
class CountingTagStore(MemoryTagStore):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.list_calls = 0
|
||||
self.single_assignment_calls = 0
|
||||
self.batch_assignment_calls = 0
|
||||
|
||||
async def list_tags(self, tag_type=None):
|
||||
self.list_calls += 1
|
||||
return await super().list_tags(tag_type)
|
||||
|
||||
async def set_target_tags(self, target_type, target_id, tag_ids):
|
||||
self.single_assignment_calls += 1
|
||||
return await super().set_target_tags(target_type, target_id, tag_ids)
|
||||
|
||||
async def set_target_tags_bulk(self, target_type, assignments):
|
||||
self.batch_assignment_calls += 1
|
||||
return {
|
||||
target_id: await MemoryTagStore.set_target_tags(
|
||||
self,
|
||||
target_type,
|
||||
target_id,
|
||||
tag_ids,
|
||||
)
|
||||
for target_id, tag_ids in assignments.items()
|
||||
}
|
||||
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
manifest_skills: list[SkillManifestItem] = []
|
||||
for index in range(8):
|
||||
name = f"skill-{index}"
|
||||
skill_dir = skills_root / "custom" / name
|
||||
_write(skill_dir / "SKILL.md", f"---\nname: {name}\n---\nbody\n")
|
||||
manifest_skills.append(
|
||||
SkillManifestItem(
|
||||
name=name,
|
||||
category="custom",
|
||||
relative_dir=f"custom/{name}",
|
||||
tree_hash=compute_tree_hash(skill_dir),
|
||||
)
|
||||
)
|
||||
manifest = MigrationManifest(
|
||||
bundle_id="batch-skill-apply",
|
||||
skills=manifest_skills,
|
||||
)
|
||||
preflight = preflight_manifest(
|
||||
manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={},
|
||||
)
|
||||
extensions_path = tmp_path / "extensions_config.json"
|
||||
extensions_path.write_text("{}", encoding="utf-8")
|
||||
usage_batches: list[dict[str, dict]] = []
|
||||
monkeypatch.setattr(
|
||||
migration_module,
|
||||
"_apply_usage_metadata",
|
||||
lambda _name, _metadata: None,
|
||||
raising=False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
migration_module,
|
||||
"_apply_usage_metadata_batch",
|
||||
lambda entries: usage_batches.append(entries),
|
||||
raising=False,
|
||||
)
|
||||
skills = CountingSkillStore()
|
||||
tags = CountingTagStore()
|
||||
|
||||
result = await apply_migration_manifest(
|
||||
manifest,
|
||||
preflight=preflight,
|
||||
agent_store=MemoryAgentStore(),
|
||||
skill_store=skills,
|
||||
tag_store=tags,
|
||||
agents_root=agents_root,
|
||||
users_by_email={},
|
||||
fallback_owner_user_id=None,
|
||||
extensions_config_path=extensions_path,
|
||||
)
|
||||
|
||||
assert result.skills_applied == 8
|
||||
assert skills.batch_calls == 1
|
||||
assert skills.single_calls == 0
|
||||
assert tags.list_calls == 1
|
||||
assert tags.batch_assignment_calls == 1
|
||||
assert tags.single_assignment_calls == 0
|
||||
assert len(usage_batches) == 1
|
||||
assert set(usage_batches[0]) == {f"skill-{index}" for index in range(8)}
|
||||
|
||||
|
||||
def test_skill_usage_migration_metadata_is_written_once_for_a_batch(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
writes: list[dict] = []
|
||||
monkeypatch.setattr(skill_usage, "_read_all", lambda: {})
|
||||
monkeypatch.setattr(skill_usage, "_write_all", lambda data: writes.append(data))
|
||||
|
||||
skill_usage.set_migration_metadata_batch(
|
||||
{
|
||||
f"skill-{index}": {
|
||||
"state": "stale",
|
||||
"pinned": index % 2 == 0,
|
||||
"featured": False,
|
||||
"source": "upload",
|
||||
}
|
||||
for index in range(100)
|
||||
}
|
||||
)
|
||||
|
||||
assert len(writes) == 1
|
||||
assert len(writes[0]) == 100
|
||||
assert writes[0]["skill-0"]["state"] == "stale"
|
||||
assert writes[0]["skill-0"]["pinned"] is True
|
||||
|
||||
|
||||
def test_manifest_rejects_absolute_and_parent_relative_paths() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
AgentManifestItem(
|
||||
id="agent-one",
|
||||
relative_dir="../agent-one",
|
||||
tree_hash="0" * 64,
|
||||
name="bad",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
SkillManifestItem(
|
||||
name="skill-one",
|
||||
category="custom",
|
||||
relative_dir="C:/skills/custom/skill-one",
|
||||
tree_hash="0" * 64,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
SkillManifestItem(
|
||||
name="skill-one",
|
||||
category="custom",
|
||||
relative_dir="public/skill-one",
|
||||
tree_hash="0" * 64,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_migration_upsert_converts_startup_placeholder_rows() -> None:
|
||||
agents = MemoryAgentStore()
|
||||
skills = MemorySkillStore()
|
||||
await agents.ensure_builtin({"id": "agent-one", "name": "placeholder", "description": "", "published": True})
|
||||
await skills.ensure_legacy({"name": "skill-one", "owner_user_id": None, "published": True})
|
||||
|
||||
agent = await agents.migration_upsert(
|
||||
{
|
||||
"id": "agent-one",
|
||||
"name": "source name",
|
||||
"description": "source description",
|
||||
"user_id": "target-u9",
|
||||
"published": False,
|
||||
"is_private": True,
|
||||
"square_id": "private",
|
||||
"featured_order": None,
|
||||
"created_at": "2026-01-01T00:00:00+00:00",
|
||||
"updated_at": "2026-01-02T00:00:00+00:00",
|
||||
}
|
||||
)
|
||||
skill = await skills.migration_upsert(
|
||||
{
|
||||
"name": "skill-one",
|
||||
"owner_user_id": "target-u9",
|
||||
"published": False,
|
||||
"detail": "source detail",
|
||||
"name_zh": "技能一",
|
||||
"always_on": True,
|
||||
"square_id": "private",
|
||||
"created_at": "2026-01-01T00:00:00+00:00",
|
||||
"updated_at": "2026-01-02T00:00:00+00:00",
|
||||
}
|
||||
)
|
||||
|
||||
assert agent["user_id"] == "target-u9"
|
||||
assert agent["published"] is False
|
||||
assert agent["is_private"] is True
|
||||
assert agent["created_at"] == "2026-01-01T00:00:00+00:00"
|
||||
assert skill["owner_user_id"] == "target-u9"
|
||||
assert skill["published"] is False
|
||||
assert skill["always_on"] is True
|
||||
assert skill["created_at"] == "2026-01-01T00:00:00+00:00"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_build_and_apply_manifest_round_trip_preserves_metadata_and_unknown_extension_fields(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
agents_root = tmp_path / "agents"
|
||||
skills_root = tmp_path / "skills"
|
||||
agent_dir = agents_root / "agent-one"
|
||||
skill_dir = skills_root / "custom" / "folder-does-not-match-name"
|
||||
support_dir = skills_root / "public" / "support-lib"
|
||||
_write(
|
||||
agent_dir / "config.yaml",
|
||||
"id: agent-one\nname: 智能体一\nskills:\n - skill-one\n - agent_orchestration\nmodel: m1\ntool_groups:\n - web\nllmwiki_knowledge_base_ids:\n - wiki-1\n",
|
||||
)
|
||||
_write(agent_dir / "SOUL.md", "soul")
|
||||
_write(skill_dir / "SKILL.md", "---\nname: skill-one\ndescription: test\n---\nbody\n")
|
||||
_write(support_dir / ".deerflow-skill-support.json", '{"required_by":["skill-one"]}')
|
||||
_write(support_dir / "helper.py", "VALUE = 1\n")
|
||||
|
||||
source_agents = MemoryAgentStore()
|
||||
source_skills = MemorySkillStore()
|
||||
source_tags = MemoryTagStore()
|
||||
await source_agents.migration_upsert(
|
||||
{
|
||||
"id": "agent-one",
|
||||
"name": "智能体一",
|
||||
"description": "desc",
|
||||
"user_id": "source-u1",
|
||||
"published": False,
|
||||
"is_private": True,
|
||||
"square_id": "private",
|
||||
"featured_order": None,
|
||||
}
|
||||
)
|
||||
await source_skills.migration_upsert(
|
||||
{
|
||||
"name": "skill-one",
|
||||
"owner_user_id": "source-u1",
|
||||
"published": False,
|
||||
"detail": "detail",
|
||||
"name_zh": "技能一",
|
||||
"always_on": True,
|
||||
"square_id": "private",
|
||||
}
|
||||
)
|
||||
await source_tags.create_tag({"id": "agent-tag", "name": "研判", "tag_type": "agent", "color": "blue"})
|
||||
await source_tags.set_target_tags("agent", "agent-one", ["agent-tag"])
|
||||
|
||||
discovered = [
|
||||
SimpleNamespace(
|
||||
name="skill-one",
|
||||
category="custom",
|
||||
relative_path=Path("folder-does-not-match-name"),
|
||||
skill_dir=skill_dir,
|
||||
enabled=False,
|
||||
)
|
||||
]
|
||||
agent_manifest = await build_agent_migration_manifest(
|
||||
["agent-one"],
|
||||
agent_store=source_agents,
|
||||
tag_store=source_tags,
|
||||
agents_root=agents_root,
|
||||
users_by_id={"source-u1": "owner@example.com"},
|
||||
)
|
||||
|
||||
assert [item.id for item in agent_manifest.agents] == ["agent-one"]
|
||||
assert agent_manifest.agents[0].skills == ["skill-one", "agent_orchestration"]
|
||||
assert agent_manifest.skills == []
|
||||
assert agent_manifest.support_directories == []
|
||||
assert any("知识库数据不在本迁移清单范围内" in warning for warning in agent_manifest.warnings)
|
||||
|
||||
skill_manifest = await build_skill_migration_manifest(
|
||||
["skill-one"],
|
||||
skill_store=source_skills,
|
||||
tag_store=source_tags,
|
||||
skills_root=skills_root,
|
||||
discovered_skills=discovered,
|
||||
users_by_id={"source-u1": "owner@example.com"},
|
||||
usage_entries={"skill-one": {"state": "stale", "pinned": True, "source": "agent"}},
|
||||
)
|
||||
assert skill_manifest.agents == []
|
||||
assert skill_manifest.skills[0].relative_dir == "custom/folder-does-not-match-name"
|
||||
assert skill_manifest.skills[0].enabled is False
|
||||
assert skill_manifest.skills[0].state == "stale"
|
||||
assert skill_manifest.support_directories[0].relative_dir == "public/support-lib"
|
||||
|
||||
target_agents = MemoryAgentStore()
|
||||
target_skills = MemorySkillStore()
|
||||
target_tags = MemoryTagStore()
|
||||
await target_agents.ensure_builtin({"id": "agent-one", "name": "startup placeholder", "published": True})
|
||||
await target_skills.ensure_legacy({"name": "skill-one", "owner_user_id": None, "published": True})
|
||||
extensions_path = tmp_path / "extensions_config.json"
|
||||
extensions_path.write_text(
|
||||
'{"mcpServers":{"keep":{"command":"secret-placeholder"}},"skills":{"unrelated":{"enabled":true}}}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
usage_batches: list[dict[str, dict]] = []
|
||||
monkeypatch.setattr(
|
||||
"app.gateway.agent_skill_migration._apply_usage_metadata",
|
||||
lambda _name, _metadata: None,
|
||||
raising=False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.gateway.agent_skill_migration._apply_usage_metadata_batch",
|
||||
lambda entries: usage_batches.append(entries),
|
||||
)
|
||||
|
||||
skill_preflight = preflight_manifest(
|
||||
skill_manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={"owner@example.com": "target-u9"},
|
||||
)
|
||||
skill_result = await apply_migration_manifest(
|
||||
skill_manifest,
|
||||
preflight=skill_preflight,
|
||||
agent_store=target_agents,
|
||||
skill_store=target_skills,
|
||||
tag_store=target_tags,
|
||||
agents_root=agents_root,
|
||||
users_by_email={"owner@example.com": "target-u9"},
|
||||
fallback_owner_user_id=None,
|
||||
extensions_config_path=extensions_path,
|
||||
)
|
||||
agent_preflight = preflight_manifest(
|
||||
agent_manifest,
|
||||
agents_root=agents_root,
|
||||
skills_root=skills_root,
|
||||
users_by_email={"owner@example.com": "target-u9"},
|
||||
)
|
||||
agent_result = await apply_migration_manifest(
|
||||
agent_manifest,
|
||||
preflight=agent_preflight,
|
||||
agent_store=target_agents,
|
||||
skill_store=target_skills,
|
||||
tag_store=target_tags,
|
||||
agents_root=agents_root,
|
||||
users_by_email={"owner@example.com": "target-u9"},
|
||||
fallback_owner_user_id=None,
|
||||
extensions_config_path=None,
|
||||
)
|
||||
|
||||
assert agent_result.agents_applied == 1
|
||||
assert agent_result.skills_applied == 0
|
||||
assert skill_result.agents_applied == 0
|
||||
assert skill_result.skills_applied == 1
|
||||
assert (await target_agents.get_any("agent-one"))["user_id"] == "target-u9"
|
||||
assert (await target_agents.get_extras_for(["agent-one"]))["agent-one"] == {
|
||||
"skills": ["skill-one", "agent_orchestration"],
|
||||
"tool_groups": ["web"],
|
||||
"model": "m1",
|
||||
}
|
||||
assert (await target_skills.get_any("skill-one"))["owner_user_id"] == "target-u9"
|
||||
assert [tag["name"] for tag in await target_tags.get_target_tags("agent", "agent-one")] == ["研判"]
|
||||
raw_extensions = extensions_path.read_text(encoding="utf-8")
|
||||
assert "secret-placeholder" in raw_extensions
|
||||
assert '"unrelated"' in raw_extensions
|
||||
assert '"skill-one"' in raw_extensions
|
||||
assert usage_batches == [{"skill-one": {"state": "stale", "pinned": True, "featured": False, "source": "agent"}}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sql_migration_upsert_can_replace_placeholder_ownership(tmp_path: Path) -> None:
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'migration.db'}")
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
sessions = async_sessionmaker(engine, expire_on_commit=False)
|
||||
agents = AgentRepository(sessions)
|
||||
skills = SkillRepository(sessions)
|
||||
try:
|
||||
await agents.ensure_builtin({"id": "agent-one", "name": "placeholder", "published": True})
|
||||
await skills.ensure_legacy({"name": "skill-one", "owner_user_id": None, "published": True})
|
||||
agent = await agents.migration_upsert(
|
||||
{
|
||||
"id": "agent-one",
|
||||
"name": "source",
|
||||
"user_id": "target-u9",
|
||||
"published": False,
|
||||
"is_private": True,
|
||||
"featured_order": 7,
|
||||
}
|
||||
)
|
||||
skill = await skills.migration_upsert(
|
||||
{
|
||||
"name": "skill-one",
|
||||
"owner_user_id": "target-u9",
|
||||
"published": False,
|
||||
"always_on": True,
|
||||
}
|
||||
)
|
||||
assert agent["user_id"] == "target-u9"
|
||||
assert agent["featured_order"] == 7
|
||||
assert skill["owner_user_id"] == "target-u9"
|
||||
assert skill["always_on"] is True
|
||||
finally:
|
||||
await engine.dispose()
|
||||
(apply_migration_manifest,)
|
||||
(build_agent_migration_manifest, build_skill_migration_manifest)
|
||||
@@ -71,6 +71,30 @@ async def _add_sql_agent(sf, *, agent_id: str, user_id: str | None) -> None:
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sidebar_agent_query_returns_only_lightweight_visible_fields(sql_session_factory):
|
||||
await _add_sql_agent(sql_session_factory, agent_id="owned-agent", user_id="user-1")
|
||||
await _add_sql_agent(sql_session_factory, agent_id="public-agent", user_id=None)
|
||||
|
||||
agents = await AgentRepository(sql_session_factory).list_sidebar("user-1", limit=3)
|
||||
|
||||
assert agents == [
|
||||
{"id": "owned-agent", "name": "owned-agent"},
|
||||
{"id": "public-agent", "name": "public-agent"},
|
||||
]
|
||||
assert all(set(item) == {"id", "name"} for item in agents)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_memory_sidebar_query_returns_only_lightweight_fields():
|
||||
store = MemoryAgentStore()
|
||||
await store.create({"id": "owned-agent", "name": "我的智能体", "user_id": "user-1"})
|
||||
|
||||
agents = await store.list_sidebar("user-1", limit=3)
|
||||
|
||||
assert agents == [{"id": "owned-agent", "name": "我的智能体"}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -96,12 +96,6 @@ def test_seed_includes_independent_3q_slots() -> None:
|
||||
assert "6-1" in codes and "7-4" in codes
|
||||
assert codes.index("3q-0") < codes.index("3q-1")
|
||||
assert codes.index("3q-6") < codes.index("6-1")
|
||||
custom_codes = {row["business_code"] for row in DEFAULT_BUSINESS_ROWS if row.get("is_custom")}
|
||||
assert custom_codes == {"3q-1", "3q-2", "3q-3", "3q-4", "3q-5", "3q-6"}
|
||||
for code in custom_codes:
|
||||
seed = DEFAULT_BUSINESS_ROWS[codes.index(code)]
|
||||
assert seed["mapping_type"] == "自定义类型"
|
||||
assert DEFAULT_BUSINESS_ROWS[codes.index("3q-0")].get("is_custom") is not True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,619 @@
|
||||
"""Built-in chat-history migration assistant and its offline bundle tool."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
|
||||
def _load():
|
||||
from app.gateway.routers import _chat_history_migration_seed as seed
|
||||
|
||||
path = seed._ASSETS_DIR / "skills" / seed.CHAT_HISTORY_MIGRATION_SKILL_NAME / "scripts" / "migrate_chat_history.py"
|
||||
spec = importlib.util.spec_from_file_location("chat_history_migration", path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
APP_SCHEMA = """
|
||||
CREATE TABLE threads_meta (
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
assistant_id TEXT,
|
||||
user_id TEXT,
|
||||
display_name TEXT,
|
||||
status TEXT,
|
||||
metadata_json TEXT,
|
||||
created_at TEXT,
|
||||
updated_at TEXT
|
||||
);
|
||||
CREATE TABLE runs (
|
||||
run_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT,
|
||||
user_id TEXT,
|
||||
status TEXT,
|
||||
kwargs_json TEXT,
|
||||
first_human_message TEXT,
|
||||
created_at TEXT,
|
||||
updated_at TEXT
|
||||
);
|
||||
CREATE TABLE run_events (
|
||||
id INTEGER PRIMARY KEY,
|
||||
thread_id TEXT,
|
||||
run_id TEXT,
|
||||
user_id TEXT,
|
||||
event_type TEXT,
|
||||
category TEXT,
|
||||
content TEXT,
|
||||
event_metadata TEXT,
|
||||
seq INTEGER,
|
||||
created_at TEXT,
|
||||
UNIQUE (thread_id, seq)
|
||||
);
|
||||
CREATE TABLE feedback (
|
||||
feedback_id TEXT PRIMARY KEY,
|
||||
run_id TEXT,
|
||||
thread_id TEXT,
|
||||
user_id TEXT,
|
||||
message_id TEXT,
|
||||
agent_id TEXT,
|
||||
target_key TEXT,
|
||||
rating INTEGER,
|
||||
comment TEXT,
|
||||
reasons TEXT,
|
||||
created_at TEXT,
|
||||
updated_at TEXT
|
||||
);
|
||||
CREATE TABLE analysis_projects (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT,
|
||||
name TEXT,
|
||||
mode TEXT,
|
||||
background TEXT,
|
||||
knowledge_base_ids TEXT,
|
||||
assistant_knowledge_base_ids TEXT,
|
||||
created_at TEXT,
|
||||
updated_at TEXT
|
||||
);
|
||||
CREATE TABLE analysis_project_threads (
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
project_id TEXT,
|
||||
created_at TEXT
|
||||
);
|
||||
"""
|
||||
|
||||
CHECKPOINT_SCHEMA = """
|
||||
CREATE TABLE checkpoints (
|
||||
thread_id TEXT NOT NULL,
|
||||
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
||||
checkpoint_id TEXT NOT NULL,
|
||||
parent_checkpoint_id TEXT,
|
||||
type TEXT,
|
||||
checkpoint BLOB,
|
||||
metadata BLOB,
|
||||
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
|
||||
);
|
||||
CREATE TABLE writes (
|
||||
thread_id TEXT NOT NULL,
|
||||
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
||||
checkpoint_id TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL,
|
||||
idx INTEGER NOT NULL,
|
||||
channel TEXT NOT NULL,
|
||||
type TEXT,
|
||||
value BLOB,
|
||||
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def _connect(path: Path) -> sqlite3.Connection:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
return sqlite3.connect(path)
|
||||
|
||||
|
||||
def _build_source(root: Path) -> dict[str, Path]:
|
||||
app = root / "source-app.sqlite"
|
||||
checkpoint = root / "source-checkpoints.sqlite"
|
||||
threads = root / "deer-flow"
|
||||
with _connect(app) as conn:
|
||||
conn.executescript(APP_SCHEMA)
|
||||
conn.executemany(
|
||||
"""
|
||||
INSERT INTO threads_meta
|
||||
(thread_id, assistant_id, user_id, display_name, status, metadata_json, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, 'idle', ?, '2026-10-21 08:00:00', ?)
|
||||
""",
|
||||
[
|
||||
(
|
||||
"thread-1",
|
||||
"lead",
|
||||
"user-a",
|
||||
"O'Brien 的会话",
|
||||
json.dumps({"taskId": "42", "token": "super-secret"}, ensure_ascii=False),
|
||||
"2026-10-21 08:00:00",
|
||||
),
|
||||
(
|
||||
"thread-2",
|
||||
"lead",
|
||||
"user-a",
|
||||
"项目会话",
|
||||
json.dumps({"taskId": "43"}),
|
||||
"2026-10-20 08:00:00",
|
||||
),
|
||||
(
|
||||
"thread-sys",
|
||||
"lead",
|
||||
"user-a",
|
||||
"内部线程",
|
||||
json.dumps({"system": True}),
|
||||
"2026-10-21 09:00:00",
|
||||
),
|
||||
(
|
||||
"thread-old",
|
||||
"lead",
|
||||
"user-a",
|
||||
"过期会话",
|
||||
"{}",
|
||||
"2020-01-01 00:00:00",
|
||||
),
|
||||
],
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO runs
|
||||
(run_id, thread_id, user_id, status, kwargs_json, first_human_message, created_at, updated_at)
|
||||
VALUES ('run-1', 'thread-1', 'user-a', 'success', ?, ?, '2026-10-21 08:00:00', '2026-10-21 08:00:00')
|
||||
""",
|
||||
(
|
||||
json.dumps({"token": "super-secret", "ok": True}),
|
||||
"请保留这句话 use token carefully",
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO runs (run_id, thread_id, user_id, status, first_human_message, created_at, updated_at)
|
||||
VALUES ('run-old', 'thread-old', 'user-a', 'success', 'OLD-SECRET', '2020-01-01 00:00:00', '2020-01-01 00:00:00')
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO runs (run_id, thread_id, user_id, status, first_human_message, created_at, updated_at)
|
||||
VALUES ('run-sys', 'thread-sys', 'user-a', 'success', 'SYS-SECRET', '2026-10-21 09:00:00', '2026-10-21 09:00:00')
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO run_events
|
||||
(id, thread_id, run_id, user_id, event_type, category, content, seq, created_at)
|
||||
VALUES (1, 'thread-1', 'run-1', 'user-a', 'message', 'message', '事件正文', 1, '2026-10-21 08:00:00')
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO feedback
|
||||
(feedback_id, run_id, thread_id, user_id, agent_id, target_key, rating, comment, created_at, updated_at)
|
||||
VALUES ('feedback-1', 'run-1', 'thread-1', 'user-a', 'lead', 'target-1', 1, '有用', '2026-10-21 08:00:00', '2026-10-21 08:00:00')
|
||||
"""
|
||||
)
|
||||
conn.executemany(
|
||||
"INSERT INTO analysis_projects (id, user_id, name, mode, created_at, updated_at) VALUES (?, 'user-a', ?, 'qa', '2026-10-21 08:00:00', '2026-10-21 08:00:00')",
|
||||
[("project-1", "新项目"), ("project-2", "源项目")],
|
||||
)
|
||||
conn.executemany(
|
||||
"INSERT INTO analysis_project_threads (thread_id, project_id, created_at) VALUES (?, ?, '2026-10-21 08:00:00')",
|
||||
[("thread-1", "project-1"), ("thread-2", "project-2")],
|
||||
)
|
||||
with _connect(checkpoint) as conn:
|
||||
conn.executescript(CHECKPOINT_SCHEMA)
|
||||
conn.executemany(
|
||||
"INSERT INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, type, checkpoint, metadata) VALUES (?, '', 'cp-1', 'msgpack', ?, x'7b7d')",
|
||||
[
|
||||
("thread-1", b"\x00\xffhello-body"),
|
||||
("thread-old", b"old-checkpoint"),
|
||||
("thread-sys", b"system-body"),
|
||||
],
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES ('thread-1', '', 'cp-1', 'task', 0, 'messages', 'msgpack', ?)",
|
||||
(b"write-body",),
|
||||
)
|
||||
note = threads / "users" / "user-a" / "threads" / "thread-1" / "user-data" / "outputs" / "note.txt"
|
||||
note.parent.mkdir(parents=True)
|
||||
note.write_text("附件还在", encoding="utf-8")
|
||||
other = threads / "users" / "user-a" / "threads" / "thread-2" / "user-data" / "outputs" / "b.txt"
|
||||
other.parent.mkdir(parents=True)
|
||||
other.write_text("乙", encoding="utf-8")
|
||||
return {"app": app, "checkpoint": checkpoint, "threads": threads}
|
||||
|
||||
|
||||
def _prepare_target(path: Path) -> None:
|
||||
with _connect(path) as conn:
|
||||
conn.executescript(APP_SCHEMA)
|
||||
conn.execute(
|
||||
"INSERT INTO threads_meta (thread_id, user_id, display_name, status, metadata_json, created_at, updated_at) VALUES ('thread-local', 'user-local', '本地会话', 'idle', '{}', '2026-10-01 00:00:00', '2026-10-01 00:00:00')"
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO analysis_projects (id, user_id, name, mode, created_at, updated_at) VALUES ('project-2', 'user-a', '目标项目', 'qa', '2026-09-01 00:00:00', '2026-09-01 00:00:00')"
|
||||
)
|
||||
|
||||
|
||||
def _cell(path: Path, query: str, params: tuple = ()) -> object:
|
||||
with sqlite3.connect(path) as conn:
|
||||
row = conn.execute(query, params).fetchone()
|
||||
return None if row is None else row[0]
|
||||
|
||||
|
||||
def test_seed_assets_define_a_read_only_migration_agent() -> None:
|
||||
from app.gateway.routers import _chat_history_migration_seed as seed
|
||||
|
||||
agent_root = seed._ASSETS_DIR / seed.CHAT_HISTORY_MIGRATION_AGENT_ID
|
||||
config = yaml.safe_load((agent_root / "config.yaml").read_text(encoding="utf-8"))
|
||||
soul = (agent_root / "SOUL.md").read_text(encoding="utf-8")
|
||||
skill_root = seed._ASSETS_DIR / "skills" / seed.CHAT_HISTORY_MIGRATION_SKILL_NAME
|
||||
skill = (skill_root / "SKILL.md").read_text(encoding="utf-8")
|
||||
|
||||
assert config["id"] == seed.CHAT_HISTORY_MIGRATION_AGENT_ID
|
||||
assert config["name"] == "聊天记录迁移助手"
|
||||
assert config["skills"] == [seed.CHAT_HISTORY_MIGRATION_SKILL_NAME]
|
||||
assert set(config["tool_groups"]) == {"file:read", "file:write", "bash"}
|
||||
assert "web" not in config["tool_groups"]
|
||||
assert len(config["common_questions"]) >= 4
|
||||
|
||||
assert "高斯" in soul
|
||||
assert "检查点" in soul
|
||||
assert "不要把 LangGraph 的 PostgreSQL checkpointer 迁移执行到高斯库上" in soul
|
||||
assert "--apply" in soul
|
||||
assert "密码" in soul
|
||||
|
||||
assert skill.startswith("---")
|
||||
assert "name: chat-history-migration" in skill
|
||||
assert "references/storage-map.md" in skill
|
||||
assert "references/runbook.md" in skill
|
||||
assert "migrate_chat_history.py" in skill
|
||||
assert (skill_root / "scripts" / "migrate_chat_history.py").is_file()
|
||||
|
||||
|
||||
def test_seed_is_idempotent_and_preserves_local_edits(tmp_path, monkeypatch) -> None:
|
||||
from app.gateway.routers import _chat_history_migration_seed as seed
|
||||
|
||||
class FakePaths:
|
||||
def agent_dir(self, agent_id: str) -> Path:
|
||||
return tmp_path / "agents" / agent_id
|
||||
|
||||
monkeypatch.setattr(seed, "get_paths", lambda: FakePaths())
|
||||
monkeypatch.setattr(seed, "_skills_public_dir", lambda: tmp_path / "skills" / "public")
|
||||
|
||||
assert seed.ensure_chat_history_migration_agent() is True
|
||||
agent_soul = tmp_path / "agents" / seed.CHAT_HISTORY_MIGRATION_AGENT_ID / "SOUL.md"
|
||||
skill_file = tmp_path / "skills" / "public" / seed.CHAT_HISTORY_MIGRATION_SKILL_NAME / "SKILL.md"
|
||||
assert agent_soul.is_file()
|
||||
assert skill_file.is_file()
|
||||
|
||||
agent_soul.write_text("现场智能体修改", encoding="utf-8")
|
||||
skill_file.write_text("现场技能修改", encoding="utf-8")
|
||||
assert seed.ensure_chat_history_migration_agent() is False
|
||||
assert agent_soul.read_text(encoding="utf-8") == "现场智能体修改"
|
||||
assert skill_file.read_text(encoding="utf-8") == "现场技能修改"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seeded_agent_syncs_into_the_builtin_catalog(tmp_path, monkeypatch) -> None:
|
||||
from app.gateway.routers import _chat_history_migration_seed as seed
|
||||
from app.gateway.routers.agents import _sync_legacy_agents
|
||||
from deerflow.config import agents_config
|
||||
from deerflow.persistence.agents import MemoryAgentStore
|
||||
|
||||
class FakePaths:
|
||||
@property
|
||||
def agents_dir(self) -> Path:
|
||||
return tmp_path / "agents"
|
||||
|
||||
def agent_dir(self, agent_id: str) -> Path:
|
||||
return self.agents_dir / agent_id
|
||||
|
||||
paths = FakePaths()
|
||||
monkeypatch.setattr(seed, "get_paths", lambda: paths)
|
||||
monkeypatch.setattr(agents_config, "get_paths", lambda: paths)
|
||||
monkeypatch.setattr(seed, "_skills_public_dir", lambda: tmp_path / "skills" / "public")
|
||||
|
||||
assert seed.ensure_chat_history_migration_agent() is True
|
||||
store = MemoryAgentStore()
|
||||
await _sync_legacy_agents(store)
|
||||
|
||||
row = await store.get_any(seed.CHAT_HISTORY_MIGRATION_AGENT_ID)
|
||||
assert row is not None
|
||||
assert row["user_id"] is None
|
||||
assert row["published"] is True
|
||||
assert row["name"] == "聊天记录迁移助手"
|
||||
extras = await store.get_extras_for([seed.CHAT_HISTORY_MIGRATION_AGENT_ID])
|
||||
assert extras[seed.CHAT_HISTORY_MIGRATION_AGENT_ID]["skills"] == [seed.CHAT_HISTORY_MIGRATION_SKILL_NAME]
|
||||
assert set(extras[seed.CHAT_HISTORY_MIGRATION_AGENT_ID]["tool_groups"]) == {"file:read", "file:write", "bash"}
|
||||
|
||||
|
||||
def test_export_import_roundtrip_preserves_messages_and_skips_existing_threads(tmp_path: Path) -> None:
|
||||
tool = _load()
|
||||
source = _build_source(tmp_path / "source")
|
||||
bundle = tmp_path / "bundle"
|
||||
exported = tool.export_bundle(
|
||||
out=bundle,
|
||||
app_sqlite=source["app"],
|
||||
checkpoint_sqlite=source["checkpoint"],
|
||||
threads_root=source["threads"],
|
||||
since="2026-06-01T00:00:00",
|
||||
)
|
||||
|
||||
assert exported["threads"] == 2
|
||||
assert exported["excluded_system_threads"] == 1
|
||||
manifest = json.loads((bundle / "manifest.json").read_text(encoding="utf-8"))
|
||||
assert manifest["thread_ids"] == ["thread-1", "thread-2"]
|
||||
assert "thread-sys" in manifest["excluded_system_thread_ids"]
|
||||
assert tool.GAUSS_PROHIBITION in manifest["constraints"]
|
||||
packed = (bundle / "app" / "threads_meta.jsonl").read_text(encoding="utf-8")
|
||||
runs = (bundle / "app" / "runs.jsonl").read_text(encoding="utf-8")
|
||||
assert "super-secret" not in packed
|
||||
assert "super-secret" not in runs
|
||||
assert "OLD-SECRET" not in runs
|
||||
assert "SYS-SECRET" not in runs
|
||||
assert "taskId" in packed
|
||||
assert "use token carefully" in runs
|
||||
with sqlite3.connect(bundle / "checkpoints.sqlite") as conn:
|
||||
body = conn.execute("SELECT checkpoint FROM checkpoints WHERE thread_id = 'thread-1'").fetchone()[0]
|
||||
assert body == b"\x00\xffhello-body"
|
||||
assert conn.execute("SELECT checkpoint FROM checkpoints WHERE thread_id = 'thread-old'").fetchone() is None
|
||||
assert conn.execute("SELECT value FROM writes WHERE thread_id = 'thread-1'").fetchone()[0] == b"write-body"
|
||||
|
||||
missing_app = tmp_path / "missing-app.sqlite"
|
||||
missing_root = tmp_path / "missing-root"
|
||||
preview = tool.import_bundle(
|
||||
bundle=bundle,
|
||||
app_sqlite=missing_app,
|
||||
checkpoint_sqlite=tmp_path / "missing-checkpoints.sqlite",
|
||||
threads_root=missing_root,
|
||||
)
|
||||
assert preview["dry_run"] is True
|
||||
assert preview["inserted"]["threads_meta"] == 2
|
||||
assert not missing_app.exists()
|
||||
assert not (tmp_path / "missing-checkpoints.sqlite").exists()
|
||||
assert not missing_root.exists()
|
||||
|
||||
target_app = tmp_path / "target-app.sqlite"
|
||||
target_checkpoint = tmp_path / "target-checkpoints.sqlite"
|
||||
target_root = tmp_path / "target-deer-flow"
|
||||
_prepare_target(target_app)
|
||||
applied = tool.import_bundle(
|
||||
bundle=bundle,
|
||||
app_sqlite=target_app,
|
||||
checkpoint_sqlite=target_checkpoint,
|
||||
threads_root=target_root,
|
||||
apply=True,
|
||||
)
|
||||
assert applied["dry_run"] is False
|
||||
assert applied["inserted"]["threads_meta"] == 2
|
||||
assert _cell(target_app, "SELECT display_name FROM threads_meta WHERE thread_id = 'thread-1'") == "O'Brien 的会话"
|
||||
assert _cell(target_app, "SELECT comment FROM feedback WHERE feedback_id = 'feedback-1'") == "有用"
|
||||
assert _cell(target_app, "SELECT content FROM run_events WHERE thread_id = 'thread-1'") == "事件正文"
|
||||
assert _cell(target_app, "SELECT name FROM analysis_projects WHERE id = 'project-1'") == "新项目"
|
||||
assert _cell(target_app, "SELECT name FROM analysis_projects WHERE id = 'project-2'") == "目标项目"
|
||||
assert _cell(target_app, "SELECT project_id FROM analysis_project_threads WHERE thread_id = 'thread-2'") == "project-2"
|
||||
assert (target_root / "users" / "user-a" / "threads" / "thread-1" / "user-data" / "outputs" / "note.txt").read_text(encoding="utf-8") == "附件还在"
|
||||
with sqlite3.connect(target_checkpoint) as conn:
|
||||
assert conn.execute("SELECT checkpoint FROM checkpoints WHERE thread_id = 'thread-1'").fetchone()[0] == b"\x00\xffhello-body"
|
||||
|
||||
verified = tool.verify_bundle(bundle=bundle, app_sqlite=target_app, checkpoint_sqlite=target_checkpoint, threads_root=target_root)
|
||||
assert verified["ok"] is True
|
||||
|
||||
with sqlite3.connect(target_app) as conn:
|
||||
conn.execute("UPDATE threads_meta SET display_name = '已改' WHERE thread_id = 'thread-1'")
|
||||
skipped = tool.import_bundle(
|
||||
bundle=bundle,
|
||||
app_sqlite=target_app,
|
||||
checkpoint_sqlite=target_checkpoint,
|
||||
threads_root=target_root,
|
||||
apply=True,
|
||||
)
|
||||
assert "thread-1" in skipped["skipped_threads"]
|
||||
assert skipped["inserted"]["threads_meta"] == 0
|
||||
assert _cell(target_app, "SELECT display_name FROM threads_meta WHERE thread_id = 'thread-1'") == "已改"
|
||||
|
||||
replaced = tool.import_bundle(
|
||||
bundle=bundle,
|
||||
app_sqlite=target_app,
|
||||
checkpoint_sqlite=target_checkpoint,
|
||||
threads_root=target_root,
|
||||
on_conflict="replace",
|
||||
apply=True,
|
||||
)
|
||||
assert replaced["inserted"]["threads_meta"] == 2
|
||||
assert _cell(target_app, "SELECT display_name FROM threads_meta WHERE thread_id = 'thread-1'") == "O'Brien 的会话"
|
||||
assert _cell(target_app, "SELECT display_name FROM threads_meta WHERE thread_id = 'thread-local'") == "本地会话"
|
||||
assert _cell(target_app, "SELECT name FROM analysis_projects WHERE id = 'project-2'") == "目标项目"
|
||||
|
||||
with pytest.raises(tool.MigrationError, match="thread-1"):
|
||||
tool.import_bundle(
|
||||
bundle=bundle,
|
||||
app_sqlite=target_app,
|
||||
checkpoint_sqlite=target_checkpoint,
|
||||
threads_root=target_root,
|
||||
on_conflict="fail",
|
||||
apply=True,
|
||||
)
|
||||
assert _cell(target_app, "SELECT display_name FROM threads_meta WHERE thread_id = 'thread-1'") == "O'Brien 的会话"
|
||||
|
||||
|
||||
def test_user_map_and_checkpoint_repair(tmp_path: Path) -> None:
|
||||
tool = _load()
|
||||
source = _build_source(tmp_path / "source")
|
||||
bundle = tmp_path / "bundle"
|
||||
tool.export_bundle(
|
||||
out=bundle,
|
||||
app_sqlite=source["app"],
|
||||
checkpoint_sqlite=source["checkpoint"],
|
||||
threads_root=source["threads"],
|
||||
since="2026-06-01T00:00:00",
|
||||
)
|
||||
mapped_app = tmp_path / "mapped-app.sqlite"
|
||||
mapped_root = tmp_path / "mapped-root"
|
||||
_prepare_target(mapped_app)
|
||||
tool.import_bundle(
|
||||
bundle=bundle,
|
||||
app_sqlite=mapped_app,
|
||||
checkpoint_sqlite=tmp_path / "mapped-checkpoints.sqlite",
|
||||
threads_root=mapped_root,
|
||||
apply=True,
|
||||
user_map={"user-a": "user-b"},
|
||||
)
|
||||
assert _cell(mapped_app, "SELECT user_id FROM threads_meta WHERE thread_id = 'thread-1'") == "user-b"
|
||||
mapped_note = mapped_root / "users" / "user-b" / "threads" / "thread-1" / "user-data" / "outputs" / "note.txt"
|
||||
assert mapped_note.read_text(encoding="utf-8") == "附件还在"
|
||||
assert not (mapped_root / "users" / "user-a").exists()
|
||||
|
||||
repair_app = tmp_path / "repair-app.sqlite"
|
||||
repair_checkpoint = tmp_path / "repair-checkpoints.sqlite"
|
||||
_prepare_target(repair_app)
|
||||
tool.import_bundle(bundle=bundle, app_sqlite=repair_app, threads_root=tmp_path / "repair-files", apply=True)
|
||||
assert not repair_checkpoint.exists()
|
||||
tool.import_bundle(
|
||||
bundle=bundle,
|
||||
app_sqlite=repair_app,
|
||||
checkpoint_sqlite=repair_checkpoint,
|
||||
threads_root=tmp_path / "repair-files",
|
||||
apply=True,
|
||||
)
|
||||
assert _cell(repair_app, "SELECT COUNT(*) FROM threads_meta WHERE thread_id = 'thread-1'") == 1
|
||||
with sqlite3.connect(repair_checkpoint) as conn:
|
||||
assert conn.execute("SELECT checkpoint FROM checkpoints WHERE thread_id = 'thread-1'").fetchone()[0] == b"\x00\xffhello-body"
|
||||
|
||||
|
||||
def test_unified_sqlite_and_gauss_jsonl_do_not_copy_secrets_or_checkpoints_into_sql(tmp_path: Path) -> None:
|
||||
tool = _load()
|
||||
unified = tmp_path / "unified.sqlite"
|
||||
with _connect(unified) as conn:
|
||||
conn.executescript(APP_SCHEMA)
|
||||
conn.executescript(CHECKPOINT_SCHEMA)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO threads_meta (thread_id, user_id, display_name, status, metadata_json, created_at, updated_at)
|
||||
VALUES ('thread-1', 'user-a', '统一库', 'idle', '{}', '2026-10-21 08:00:00', '2026-10-21 08:00:00')
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, type, checkpoint) VALUES ('thread-1', '', 'cp-1', 'msgpack', ?)",
|
||||
(b"unified-body",),
|
||||
)
|
||||
bundle = tmp_path / "unified-bundle"
|
||||
tool.export_bundle(out=bundle, app_sqlite=unified)
|
||||
with sqlite3.connect(bundle / "checkpoints.sqlite") as conn:
|
||||
assert conn.execute("SELECT checkpoint FROM checkpoints WHERE thread_id = 'thread-1'").fetchone()[0] == b"unified-body"
|
||||
|
||||
jsonl = tmp_path / "threads_meta.jsonl"
|
||||
jsonl.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"thread_id": "thread-9",
|
||||
"user_id": "user-a",
|
||||
"display_name": "O'Brien 的会话",
|
||||
"metadata_json": {"token": "super-secret", "taskId": "7"},
|
||||
"updated_at": "2026-10-21 08:00:00",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
json.dumps(
|
||||
{
|
||||
"thread_id": "thread-sys",
|
||||
"user_id": "user-a",
|
||||
"display_name": "内部",
|
||||
"metadata_json": {"system": True},
|
||||
"updated_at": "2026-10-21 08:00:00",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
packed = tmp_path / "packed"
|
||||
tool.pack_jsonl(out=packed, table_files={"threads_meta": jsonl})
|
||||
packed_text = (packed / "app" / "threads_meta.jsonl").read_text(encoding="utf-8")
|
||||
assert "thread-9" in packed_text
|
||||
assert "thread-sys" not in packed_text
|
||||
assert "super-secret" not in packed_text
|
||||
assert "taskId" in packed_text
|
||||
|
||||
sql = tool.gauss_load_sql(packed)
|
||||
opengauss = tool.export_sql("opengauss")
|
||||
mysql = tool.export_sql("mysql")
|
||||
assert "O''Brien" in sql
|
||||
assert tool.GAUSS_PROHIBITION in sql
|
||||
assert tool.GAUSS_PROHIBITION in opengauss
|
||||
assert r"\copy" in opengauss
|
||||
assert "threads_meta" in opengauss
|
||||
assert "JSON_OBJECT" in mysql
|
||||
assert "password_hash" not in sql
|
||||
assert "password_hash" not in opengauss
|
||||
assert 'INSERT INTO "checkpoints"' not in sql
|
||||
assert "checkpoint_migrations" not in sql
|
||||
assert "super-secret" not in sql
|
||||
assert tool.redact_text("opengauss://user:s3cret@10.0.0.1:26000/deerflow") == "opengauss://user:<redacted>@10.0.0.1:26000/deerflow"
|
||||
|
||||
inventory = tool.inventory(app_sqlite=unified)
|
||||
assert inventory["app"]["tables"]["threads_meta"] == 1
|
||||
assert inventory["checkpoints"]["threads"] == 1
|
||||
assert tool.GAUSS_PROHIBITION in inventory["constraints"]
|
||||
|
||||
|
||||
def test_bundle_rejects_path_escape_and_ignores_files_outside_thread_dirs(tmp_path: Path) -> None:
|
||||
tool = _load()
|
||||
source = _build_source(tmp_path / "source")
|
||||
bundle = tmp_path / "bundle"
|
||||
tool.export_bundle(out=bundle, app_sqlite=source["app"], checkpoint_sqlite=source["checkpoint"], threads_root=source["threads"])
|
||||
stray = bundle / "files" / "data" / "secret.txt"
|
||||
stray.parent.mkdir(parents=True)
|
||||
stray.write_text("DO-NOT-COPY", encoding="utf-8")
|
||||
target_root = tmp_path / "target-root"
|
||||
app = tmp_path / "target-app.sqlite"
|
||||
_prepare_target(app)
|
||||
tool.import_bundle(bundle=bundle, app_sqlite=app, threads_root=target_root, apply=True)
|
||||
assert list(target_root.rglob("secret.txt")) == []
|
||||
with pytest.raises(tool.MigrationError):
|
||||
tool._bundle_relative("../outside.txt")
|
||||
with pytest.raises(tool.MigrationError):
|
||||
tool._bundle_relative("data/secret.txt")
|
||||
|
||||
|
||||
def test_verify_cli_reports_missing_checkpoints(tmp_path: Path) -> None:
|
||||
tool = _load()
|
||||
source = _build_source(tmp_path / "source")
|
||||
bundle = tmp_path / "bundle"
|
||||
tool.export_bundle(
|
||||
out=bundle,
|
||||
app_sqlite=source["app"],
|
||||
checkpoint_sqlite=source["checkpoint"],
|
||||
threads_root=source["threads"],
|
||||
since="2026-06-01T00:00:00",
|
||||
)
|
||||
app = tmp_path / "app.sqlite"
|
||||
checkpoint = tmp_path / "checkpoints.sqlite"
|
||||
_prepare_target(app)
|
||||
tool.import_bundle(bundle=bundle, app_sqlite=app, checkpoint_sqlite=checkpoint, threads_root=tmp_path / "root", apply=True)
|
||||
with sqlite3.connect(checkpoint) as conn:
|
||||
conn.execute("DELETE FROM checkpoints WHERE thread_id = 'thread-1'")
|
||||
assert tool.main(
|
||||
[
|
||||
"verify",
|
||||
"--bundle",
|
||||
str(bundle),
|
||||
"--app-sqlite",
|
||||
str(app),
|
||||
"--checkpoint-sqlite",
|
||||
str(checkpoint),
|
||||
]
|
||||
) == 2
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Account-scoped chat history transfer: skip oversized/failed threads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from langgraph.checkpoint.base import empty_checkpoint
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
from langgraph.store.memory import InMemoryStore
|
||||
|
||||
from app.gateway.routers import chat_history_transfer as transfer
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore
|
||||
|
||||
|
||||
def run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
async def _seed_thread(
|
||||
store: MemoryThreadMetaStore,
|
||||
saver: InMemorySaver,
|
||||
*,
|
||||
thread_id: str,
|
||||
user_id: str,
|
||||
title: str,
|
||||
messages: list[dict],
|
||||
metadata: dict | None = None,
|
||||
) -> None:
|
||||
await store.create(
|
||||
thread_id,
|
||||
user_id=user_id,
|
||||
display_name=title,
|
||||
assistant_id="agent-a",
|
||||
metadata=metadata or {"agent_id": "agent-a"},
|
||||
)
|
||||
cfg = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
||||
checkpoint = empty_checkpoint()
|
||||
version = saver.get_next_version(None, None)
|
||||
checkpoint["channel_values"] = {"messages": messages, "title": title}
|
||||
checkpoint["channel_versions"]["messages"] = version
|
||||
await saver.aput(cfg, checkpoint, {"step": 1, "source": "loop"}, {"messages": version})
|
||||
|
||||
|
||||
class VersionedChannelSaver:
|
||||
"""Mimic Postgres/SQLite: only persist channels listed in new_versions."""
|
||||
|
||||
def __init__(self, inner: InMemorySaver) -> None:
|
||||
self._inner = inner
|
||||
|
||||
def get_next_version(self, current, channel):
|
||||
return self._inner.get_next_version(current, channel)
|
||||
|
||||
async def aget_tuple(self, config):
|
||||
return await self._inner.aget_tuple(config)
|
||||
|
||||
async def aput(self, config, checkpoint, metadata, new_versions):
|
||||
stored = dict(checkpoint)
|
||||
channel_values = dict(stored.get("channel_values") or {})
|
||||
stored["channel_values"] = {
|
||||
key: value for key, value in channel_values.items() if key in (new_versions or {})
|
||||
}
|
||||
return await self._inner.aput(config, stored, metadata, new_versions)
|
||||
|
||||
|
||||
def _setup(tmp_path, monkeypatch):
|
||||
paths = Paths(base_dir=tmp_path)
|
||||
monkeypatch.setattr(transfer, "get_paths", lambda: paths)
|
||||
store = MemoryThreadMetaStore(InMemoryStore())
|
||||
saver = InMemorySaver()
|
||||
return paths, store, saver
|
||||
|
||||
|
||||
def test_export_includes_messages_and_files_and_skips_oversized(tmp_path, monkeypatch):
|
||||
paths, store, saver = _setup(tmp_path, monkeypatch)
|
||||
|
||||
async def scenario():
|
||||
await _seed_thread(
|
||||
store,
|
||||
saver,
|
||||
thread_id="ok-1",
|
||||
user_id="alice",
|
||||
title="正常对话",
|
||||
messages=[{"type": "human", "content": "你好"}, {"type": "ai", "content": "世界"}],
|
||||
)
|
||||
await _seed_thread(
|
||||
store,
|
||||
saver,
|
||||
thread_id="huge-1",
|
||||
user_id="alice",
|
||||
title="超大对话",
|
||||
messages=[{"type": "human", "content": "x" * 200}],
|
||||
)
|
||||
ok_dir = paths.sandbox_uploads_dir("ok-1", user_id="alice")
|
||||
ok_dir.mkdir(parents=True)
|
||||
(ok_dir / "note.txt").write_text("附件内容", encoding="utf-8")
|
||||
huge_dir = paths.sandbox_outputs_dir("huge-1", user_id="alice")
|
||||
huge_dir.mkdir(parents=True)
|
||||
(huge_dir / "big.bin").write_bytes(b"z" * 80)
|
||||
|
||||
ok, skip = await transfer.export_one_thread(
|
||||
thread_id="ok-1",
|
||||
user_id="alice",
|
||||
thread_store=store,
|
||||
checkpointer=saver,
|
||||
)
|
||||
assert skip is None
|
||||
assert ok is not None
|
||||
assert ok.title == "正常对话"
|
||||
assert ok.values["messages"][0]["content"] == "你好"
|
||||
assert ok.files[0].path == "uploads/note.txt"
|
||||
assert ok.files[0].size > 0
|
||||
|
||||
huge, huge_skip = await transfer.export_one_thread(
|
||||
thread_id="huge-1",
|
||||
user_id="alice",
|
||||
thread_store=store,
|
||||
checkpointer=saver,
|
||||
max_bytes=40,
|
||||
)
|
||||
assert huge is None
|
||||
assert huge_skip is not None
|
||||
assert huge_skip.reason == "too_large"
|
||||
assert huge_skip.title == "超大对话"
|
||||
|
||||
run(scenario())
|
||||
|
||||
|
||||
def test_export_skips_oversized_files_but_keeps_thread(tmp_path, monkeypatch):
|
||||
paths, store, saver = _setup(tmp_path, monkeypatch)
|
||||
|
||||
async def scenario():
|
||||
await _seed_thread(
|
||||
store,
|
||||
saver,
|
||||
thread_id="mixed-1",
|
||||
user_id="alice",
|
||||
title="混合附件",
|
||||
messages=[{"type": "human", "content": "hi"}],
|
||||
)
|
||||
uploads = paths.sandbox_uploads_dir("mixed-1", user_id="alice")
|
||||
uploads.mkdir(parents=True)
|
||||
(uploads / "small.txt").write_text("ok", encoding="utf-8")
|
||||
(uploads / "huge.bin").write_bytes(b"z" * 4000)
|
||||
|
||||
exported, skip = await transfer.export_one_thread(
|
||||
thread_id="mixed-1",
|
||||
user_id="alice",
|
||||
thread_store=store,
|
||||
checkpointer=saver,
|
||||
max_bytes=800,
|
||||
)
|
||||
assert skip is None
|
||||
assert exported is not None
|
||||
assert exported.values["messages"][0]["content"] == "hi"
|
||||
assert [item.path for item in exported.files] == ["uploads/small.txt"]
|
||||
assert "uploads/huge.bin" in exported.skipped_files
|
||||
|
||||
run(scenario())
|
||||
|
||||
|
||||
def test_import_restores_files_skips_existing_and_keeps_going(tmp_path, monkeypatch):
|
||||
paths, store, saver = _setup(tmp_path, monkeypatch)
|
||||
|
||||
async def scenario():
|
||||
await _seed_thread(
|
||||
store,
|
||||
saver,
|
||||
thread_id="exists-1",
|
||||
user_id="bob",
|
||||
title="已有对话",
|
||||
messages=[{"type": "human", "content": "旧"}],
|
||||
)
|
||||
exported = transfer.TransferThread(
|
||||
thread_id="new-1",
|
||||
title="导入对话",
|
||||
assistant_id="agent-a",
|
||||
metadata={"agent_id": "agent-a", "user_id": "alice", "is_favorite": True},
|
||||
values={
|
||||
"title": "导入对话",
|
||||
"messages": [
|
||||
{"type": "human", "id": "m1", "content": "问题"},
|
||||
{"type": "ai", "id": "m2", "content": "回答"},
|
||||
],
|
||||
},
|
||||
files=[
|
||||
transfer.TransferFile(
|
||||
path="uploads/a.txt",
|
||||
content_b64=__import__("base64").b64encode(b"hello-file").decode("ascii"),
|
||||
size=10,
|
||||
)
|
||||
],
|
||||
)
|
||||
checkpointer = VersionedChannelSaver(saver)
|
||||
assert (
|
||||
await transfer.import_one_thread(
|
||||
item=exported,
|
||||
user_id="bob",
|
||||
thread_store=store,
|
||||
checkpointer=checkpointer,
|
||||
)
|
||||
is None
|
||||
)
|
||||
created = await store.get("new-1", user_id="bob")
|
||||
assert created is not None
|
||||
assert created["display_name"] == "导入对话"
|
||||
assert "user_id" not in (created.get("metadata") or {})
|
||||
assert (created.get("metadata") or {}).get("is_favorite") is True
|
||||
assert (paths.sandbox_uploads_dir("new-1", user_id="bob") / "a.txt").read_bytes() == b"hello-file"
|
||||
restored = await saver.aget_tuple(
|
||||
{"configurable": {"thread_id": "new-1", "checkpoint_ns": ""}}
|
||||
)
|
||||
assert restored is not None
|
||||
restored_values = restored.checkpoint.get("channel_values") or {}
|
||||
assert restored_values["title"] == "导入对话"
|
||||
assert restored_values["messages"][0]["content"] == "问题"
|
||||
assert restored_values["messages"][1]["content"] == "回答"
|
||||
|
||||
skip_existing = await transfer.import_one_thread(
|
||||
item=transfer.TransferThread(thread_id="exists-1", title="已有对话", values={"messages": []}),
|
||||
user_id="bob",
|
||||
thread_store=store,
|
||||
checkpointer=saver,
|
||||
)
|
||||
assert skip_existing is not None
|
||||
assert skip_existing.reason == "exists"
|
||||
|
||||
skip_bad = await transfer.import_one_thread(
|
||||
item=transfer.TransferThread(thread_id="../bad", title="坏 id", values={"messages": []}),
|
||||
user_id="bob",
|
||||
thread_store=store,
|
||||
checkpointer=saver,
|
||||
)
|
||||
assert skip_bad is not None
|
||||
assert skip_bad.reason == "invalid_id"
|
||||
assert await store.get("new-1", user_id="bob") is not None
|
||||
|
||||
run(scenario())
|
||||
|
||||
|
||||
def test_export_batch_skips_missing_without_aborting_others(tmp_path, monkeypatch):
|
||||
paths, store, saver = _setup(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
transfer,
|
||||
"load_system_settings",
|
||||
lambda: type("Settings", (), {"agent_skill_migration": type("Flag", (), {"enabled": True})()})(),
|
||||
)
|
||||
|
||||
async def scenario():
|
||||
await _seed_thread(
|
||||
store,
|
||||
saver,
|
||||
thread_id="ok-http",
|
||||
user_id="default",
|
||||
title="HTTP 对话",
|
||||
messages=[{"type": "human", "content": "ping"}],
|
||||
)
|
||||
uploads = paths.sandbox_uploads_dir("ok-http", user_id="default")
|
||||
uploads.mkdir(parents=True)
|
||||
(uploads / "pic.txt").write_text("img", encoding="utf-8")
|
||||
request = SimpleNamespace(
|
||||
_deerflow_test_bypass_auth=True,
|
||||
state=SimpleNamespace(user=SimpleNamespace(id="default"), auth=None),
|
||||
app=SimpleNamespace(state=SimpleNamespace(thread_store=store, checkpointer=saver)),
|
||||
)
|
||||
monkeypatch.setattr(transfer, "get_thread_store", lambda _request: store)
|
||||
monkeypatch.setattr(transfer, "get_checkpointer", lambda _request: saver)
|
||||
exported_threads = []
|
||||
exported_skipped = []
|
||||
for thread_id in ("ok-http", "missing-http"):
|
||||
one = await transfer.export_chat_history(
|
||||
body=transfer.ExportRequest(thread_ids=[thread_id]),
|
||||
request=request,
|
||||
)
|
||||
exported_threads.extend(one.threads)
|
||||
exported_skipped.extend(one.skipped)
|
||||
exported = transfer.ExportResponse(threads=exported_threads, skipped=exported_skipped)
|
||||
assert [item.thread_id for item in exported.threads] == ["ok-http"]
|
||||
assert exported.skipped[0].thread_id == "missing-http"
|
||||
assert exported.skipped[0].reason == "not_found"
|
||||
assert exported.threads[0].files[0].path == "uploads/pic.txt"
|
||||
|
||||
target_store = MemoryThreadMetaStore(InMemoryStore())
|
||||
target_saver = InMemorySaver()
|
||||
monkeypatch.setattr(transfer, "get_thread_store", lambda _request: target_store)
|
||||
monkeypatch.setattr(transfer, "get_checkpointer", lambda _request: target_saver)
|
||||
imported = await transfer.import_chat_history(
|
||||
body=transfer.ImportRequest(threads=exported.threads),
|
||||
request=SimpleNamespace(
|
||||
_deerflow_test_bypass_auth=True,
|
||||
state=SimpleNamespace(user=SimpleNamespace(id="carol"), auth=None),
|
||||
app=SimpleNamespace(state=SimpleNamespace()),
|
||||
),
|
||||
)
|
||||
assert imported.imported == 1
|
||||
assert await target_store.get("ok-http", user_id="carol") is not None
|
||||
assert (paths.sandbox_uploads_dir("ok-http", user_id="carol") / "pic.txt").read_text(
|
||||
encoding="utf-8"
|
||||
) == "img"
|
||||
|
||||
run(scenario())
|
||||
|
||||
|
||||
def test_export_api_requires_migration_switch(tmp_path, monkeypatch):
|
||||
_, store, saver = _setup(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
transfer,
|
||||
"load_system_settings",
|
||||
lambda: type("Settings", (), {"agent_skill_migration": type("Flag", (), {"enabled": False})()})(),
|
||||
)
|
||||
request = SimpleNamespace(
|
||||
_deerflow_test_bypass_auth=True,
|
||||
state=SimpleNamespace(user=SimpleNamespace(id="alice"), auth=None),
|
||||
app=SimpleNamespace(state=SimpleNamespace(thread_store=store, checkpointer=saver)),
|
||||
)
|
||||
monkeypatch.setattr(transfer, "get_thread_store", lambda _request: store)
|
||||
monkeypatch.setattr(transfer, "get_checkpointer", lambda _request: saver)
|
||||
|
||||
async def scenario():
|
||||
with pytest.raises(transfer.HTTPException) as exc:
|
||||
await transfer.export_chat_history(
|
||||
body=transfer.ExportRequest(thread_ids=["one"]),
|
||||
request=request,
|
||||
)
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
run(scenario())
|
||||
|
||||
|
||||
def test_export_all_job_runs_on_backend_one_by_one(tmp_path, monkeypatch):
|
||||
paths, store, saver = _setup(tmp_path, monkeypatch)
|
||||
transfer._EXPORT_JOBS.clear()
|
||||
|
||||
async def scenario():
|
||||
await _seed_thread(
|
||||
store,
|
||||
saver,
|
||||
thread_id="one",
|
||||
user_id="alice",
|
||||
title="第一条",
|
||||
messages=[{"type": "human", "content": "一"}],
|
||||
)
|
||||
await _seed_thread(
|
||||
store,
|
||||
saver,
|
||||
thread_id="two",
|
||||
user_id="alice",
|
||||
title="第二条",
|
||||
messages=[{"type": "human", "content": "二"}],
|
||||
)
|
||||
job = transfer.ExportAllJob(job_id="job-1", user_id="alice")
|
||||
transfer._EXPORT_JOBS[job.job_id] = job
|
||||
await transfer.run_export_all_job(job, thread_store=store, checkpointer=saver)
|
||||
assert job.status == "done"
|
||||
assert job.total == 2
|
||||
assert job.succeeded == 2
|
||||
assert job.path is not None
|
||||
bundle = json.loads(job.path.read_text(encoding="utf-8"))
|
||||
assert bundle["format"] == transfer.FORMAT
|
||||
titles = {item["title"] for item in bundle["threads"]}
|
||||
assert titles == {"第一条", "第二条"}
|
||||
assert all(item["values"]["messages"] for item in bundle["threads"])
|
||||
status = transfer.job_status(job)
|
||||
assert status.succeeded == 2
|
||||
assert status.status == "done"
|
||||
|
||||
run(scenario())
|
||||
@@ -124,6 +124,47 @@ def test_sync_idempotent_repeated_runs_do_not_duplicate_index():
|
||||
inspector = inspect(engine)
|
||||
idx_names = [ix["name"] for ix in inspector.get_indexes("roundtable_jobs")]
|
||||
assert idx_names.count("uq_roundtable_jobs_active_dedupe_key") == 1
|
||||
|
||||
|
||||
def test_legacy_thread_metadata_gains_and_backfills_task_lookup_projections():
|
||||
"""Startup sync must make historical task chats immediately searchable."""
|
||||
from deerflow.persistence.engine import (
|
||||
_backfill_thread_meta_task_projections_sync,
|
||||
_ensure_orm_columns_sync,
|
||||
)
|
||||
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"CREATE TABLE threads_meta ("
|
||||
"thread_id VARCHAR(64) PRIMARY KEY, assistant_id VARCHAR(128), user_id VARCHAR(64), "
|
||||
"display_name VARCHAR(256), status VARCHAR(20) NOT NULL, metadata_json JSON, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL)"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO threads_meta (thread_id, status, metadata_json, created_at, updated_at) VALUES "
|
||||
"('legacy-task', 'idle', '{\"taskId\":\"108\",\"agent_id\":\"rwfx-agent\",\"actionId\":\"A-9\"}', "
|
||||
"CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
)
|
||||
)
|
||||
_ensure_orm_columns_sync(conn)
|
||||
_backfill_thread_meta_task_projections_sync(conn)
|
||||
|
||||
with engine.connect() as conn:
|
||||
columns = {column["name"] for column in inspect(conn).get_columns("threads_meta")}
|
||||
indexes = {index["name"] for index in inspect(conn).get_indexes("threads_meta")}
|
||||
assert {"task_id", "agent_id", "action_id"} <= columns
|
||||
assert {
|
||||
"ix_threads_meta_task_agent_updated",
|
||||
"ix_threads_meta_task_action_agent_updated",
|
||||
"ix_threads_meta_user_updated",
|
||||
} <= indexes
|
||||
assert conn.execute(
|
||||
text("SELECT task_id, agent_id, action_id FROM threads_meta WHERE thread_id = 'legacy-task'")
|
||||
).one() == ("108", "rwfx-agent", "A-9")
|
||||
|
||||
|
||||
def test_legacy_thread_metadata_gains_and_backfills_task_lookup_projections():
|
||||
|
||||
@@ -7,10 +7,13 @@ from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.gateway.routers import html_runtime
|
||||
from app.gateway.services import merge_run_context_overrides
|
||||
from deerflow.agents.lead_agent import agent as agent_module
|
||||
from deerflow.agents.lead_agent import prompt as prompt_module
|
||||
from deerflow.config import system_settings as system_settings_module
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.config.skills_config import EsQueryRoutingConfig, SkillsConfig
|
||||
from deerflow.html_runtime.generated_page_chrome import apply_generated_page_chrome
|
||||
from deerflow.html_runtime.html_postprocess import maybe_fix_generated_html
|
||||
from deerflow.tools.builtins import page_report_template_tool as page_tool
|
||||
from deerflow.tools.builtins.page_report_template_tool import (
|
||||
@@ -23,6 +26,7 @@ from deerflow.tools.builtins.page_report_template_tool import (
|
||||
_requested_layout_mode,
|
||||
_requested_page_count,
|
||||
_required_visualizations,
|
||||
_resolve_prepare_theme,
|
||||
)
|
||||
|
||||
|
||||
@@ -326,9 +330,412 @@ def test_html_artifact_visualizations_use_local_declarative_contracts(monkeypatc
|
||||
assert "Bootstrap 组件可能覆盖它" in ordinary_prompt
|
||||
assert "中间地图舞台" in ordinary_prompt
|
||||
assert "中间至少 65% 的地图画面保持无遮挡" in ordinary_prompt
|
||||
assert "必须跟随系统提示中的【当前界面主题】明暗模式" in ordinary_prompt
|
||||
assert "不要复制系统的红、蓝、绿等主题主色" in ordinary_prompt
|
||||
assert "不得仅因科技、数据、看板、驾驶舱或地图题材自行改成深色" in ordinary_prompt
|
||||
assert "默认采用“深蓝三栏态势数据大屏”" not in ordinary_prompt
|
||||
assert '<html_artifact_visualization>' not in writing_prompt
|
||||
|
||||
|
||||
def test_presentation_theme_context_reaches_agent_and_builds_safe_prompt() -> None:
|
||||
config: dict[str, object] = {}
|
||||
merge_run_context_overrides(
|
||||
config,
|
||||
{
|
||||
"presentation_theme": "light",
|
||||
"presentation_theme_id": "lightgreen",
|
||||
"presentation_primary_color": "#07c05f",
|
||||
"presentation_action_color": "#049b38",
|
||||
},
|
||||
)
|
||||
|
||||
assert config["configurable"] == {"presentation_theme": "light"}
|
||||
prompt = agent_module._build_presentation_theme_prompt(config["configurable"])
|
||||
assert "浅色 (light)" in prompt
|
||||
assert "只跟随明暗模式" in prompt
|
||||
assert "不得根据系统的红、蓝、绿等主题色或自定义主色改变网页配色" in prompt
|
||||
assert "#07C05F" not in prompt
|
||||
assert "#049B38" not in prompt
|
||||
assert "不得仅因页面属于科技、数据、看板、驾驶舱或地图类型就擅自改成深色" in prompt
|
||||
|
||||
|
||||
def test_template_auto_theme_follows_runtime_presentation_theme() -> None:
|
||||
dark_runtime = SimpleNamespace(
|
||||
context={"presentation_theme": "dark"},
|
||||
config={"configurable": {"presentation_theme": "light"}},
|
||||
)
|
||||
light_runtime = SimpleNamespace(
|
||||
context={},
|
||||
config={"configurable": {"presentation_theme": "light"}},
|
||||
)
|
||||
|
||||
assert _resolve_prepare_theme(dark_runtime, "auto") == "dark"
|
||||
assert _resolve_prepare_theme(light_runtime, "auto") == "light"
|
||||
assert _resolve_prepare_theme(dark_runtime, "light") == "light"
|
||||
assert _resolve_prepare_theme(light_runtime, "dark") == "dark"
|
||||
|
||||
|
||||
def test_html_artifact_prompt_includes_generated_page_identity_only_when_configured(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
config = _app_config(enabled=False)
|
||||
branding = SimpleNamespace(
|
||||
system_name="测试指挥系统",
|
||||
logo_filename="logo-0123456789abcdef0123456789abcdef.png",
|
||||
logo_version="brand-v1",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
prompt_module,
|
||||
"load_system_settings",
|
||||
lambda: SimpleNamespace(generated_page_branding=branding),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
system_settings_module,
|
||||
"generated_page_logo_public_url",
|
||||
lambda base_url, _branding: f"{base_url}/generated-page-logo?v=brand-v1",
|
||||
)
|
||||
monkeypatch.setattr("deerflow.html_runtime.map_engine.html_map_engine", lambda: "echarts")
|
||||
|
||||
branded = prompt_module._build_html_artifact_visualization_section(config)
|
||||
|
||||
assert "<generated_page_branding>" in branded
|
||||
assert "平台会在 HTML 写入与校验时自动注入统一页眉、页脚" in branded
|
||||
assert "多页面还会自动注入居中标识和页面导航" in branded
|
||||
assert "data-df-brand" in branded
|
||||
assert "禁止在主视觉、内容卡片、标题区或自定义导航里再次书写系统名称" in branded
|
||||
assert "简短的 `data-page-title`" in branded
|
||||
assert "不要另写顶部 nav" in branded
|
||||
|
||||
for partial_name, partial_logo_url in [
|
||||
("测试指挥系统", None),
|
||||
(None, "http://localhost:8001/api/public/html-runtime/generated-page-logo?v=brand-v1"),
|
||||
]:
|
||||
monkeypatch.setattr(
|
||||
prompt_module,
|
||||
"load_system_settings",
|
||||
lambda name=partial_name: SimpleNamespace(
|
||||
generated_page_branding=SimpleNamespace(
|
||||
system_name=name,
|
||||
logo_filename=None,
|
||||
logo_version=None,
|
||||
)
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
system_settings_module,
|
||||
"generated_page_logo_public_url",
|
||||
lambda _base_url, _branding, url=partial_logo_url: url,
|
||||
)
|
||||
partial = prompt_module._build_html_artifact_visualization_section(config)
|
||||
assert "<generated_page_branding>" not in partial
|
||||
|
||||
monkeypatch.setattr(
|
||||
prompt_module,
|
||||
"load_system_settings",
|
||||
lambda: SimpleNamespace(
|
||||
generated_page_branding=SimpleNamespace(
|
||||
chrome_enabled=False,
|
||||
system_name="测试指挥系统",
|
||||
logo_filename="logo-0123456789abcdef0123456789abcdef.png",
|
||||
logo_version="brand-v1",
|
||||
)
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
system_settings_module,
|
||||
"generated_page_logo_public_url",
|
||||
lambda base_url, _branding: f"{base_url}/generated-page-logo?v=brand-v1",
|
||||
)
|
||||
switched_off = prompt_module._build_html_artifact_visualization_section(config)
|
||||
assert "<generated_page_branding>" not in switched_off
|
||||
|
||||
monkeypatch.setattr(
|
||||
prompt_module,
|
||||
"load_system_settings",
|
||||
lambda: SimpleNamespace(
|
||||
generated_page_branding=SimpleNamespace(
|
||||
system_name=None,
|
||||
logo_filename=None,
|
||||
logo_version=None,
|
||||
)
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
system_settings_module,
|
||||
"generated_page_logo_public_url",
|
||||
lambda _base_url, _branding: None,
|
||||
)
|
||||
defaulted = prompt_module._build_html_artifact_visualization_section(config)
|
||||
|
||||
assert "<generated_page_branding>" not in defaulted
|
||||
assert "__DF_GENERATED_PAGE_BRANDING__" not in defaulted
|
||||
|
||||
|
||||
def test_page_quality_requires_configured_generated_page_name_and_logo() -> None:
|
||||
logo_url = "http://localhost:8001/api/public/html-runtime/generated-page-logo?v=abc"
|
||||
plain = (
|
||||
"<!doctype html><html><head><title>报告</title></head>"
|
||||
"<body><main>" + "报告正文" * 180 + "</main></body></html>"
|
||||
)
|
||||
missing = _quality_report(
|
||||
plain,
|
||||
data_mode="provided",
|
||||
expected_features=set(),
|
||||
required_brand_name="测试指挥系统",
|
||||
required_brand_logo_url=logo_url,
|
||||
)
|
||||
name_only = _quality_report(
|
||||
plain,
|
||||
data_mode="provided",
|
||||
expected_features=set(),
|
||||
required_brand_name="测试指挥系统",
|
||||
required_brand_logo_url=None,
|
||||
)
|
||||
logo_only = _quality_report(
|
||||
plain,
|
||||
data_mode="provided",
|
||||
expected_features=set(),
|
||||
required_brand_name=None,
|
||||
required_brand_logo_url=logo_url,
|
||||
)
|
||||
branded_html, notes = apply_generated_page_chrome(
|
||||
plain,
|
||||
system_name="测试指挥系统",
|
||||
logo_url=logo_url,
|
||||
)
|
||||
branded = _quality_report(
|
||||
branded_html,
|
||||
data_mode="provided",
|
||||
expected_features=set(),
|
||||
required_brand_name="测试指挥系统",
|
||||
required_brand_logo_url=logo_url,
|
||||
)
|
||||
|
||||
assert missing["ok"] is False
|
||||
assert any("网页展示名称" in error for error in missing["errors"])
|
||||
assert any("网页 Logo" in error for error in missing["errors"])
|
||||
assert name_only["ok"] is True
|
||||
assert logo_only["ok"] is True
|
||||
assert notes == ["已自动应用单页面品牌页眉与页脚"]
|
||||
assert branded["ok"] is True
|
||||
|
||||
|
||||
def test_page_quality_rejects_hand_authored_identity_without_platform_chrome() -> None:
|
||||
logo_url = "http://localhost:8001/api/public/html-runtime/generated-page-logo?v=abc"
|
||||
detached = (
|
||||
"<!doctype html><html><head><title>报告</title></head><body>"
|
||||
f'<div class="brand-card" data-df-brand><img src="{logo_url}" alt="">测试指挥系统</div>'
|
||||
"<header><h1>市场分析报告</h1></header>"
|
||||
"<main>" + "报告正文" * 180 + "</main></body></html>"
|
||||
)
|
||||
|
||||
report = _quality_report(
|
||||
detached,
|
||||
data_mode="provided",
|
||||
expected_features=set(),
|
||||
required_brand_name="测试指挥系统",
|
||||
required_brand_logo_url=logo_url,
|
||||
)
|
||||
|
||||
assert report["ok"] is False
|
||||
assert any("顶部标识栏" in error for error in report["errors"])
|
||||
assert any("品牌页脚" in error for error in report["errors"])
|
||||
|
||||
|
||||
def test_generated_page_chrome_uses_single_page_template_and_is_idempotent() -> None:
|
||||
logo_url = "http://localhost:8001/api/public/html-runtime/generated-page-logo?v=abc"
|
||||
source = (
|
||||
"<!doctype html><html><head><title>报告</title></head><body>"
|
||||
'<header><div data-df-brand><img src="old-logo.png">测试系统</div>'
|
||||
"<h1>市场分析报告</h1></header><main>正文</main></body></html>"
|
||||
)
|
||||
|
||||
fixed, notes = apply_generated_page_chrome(
|
||||
source,
|
||||
system_name="测试系统",
|
||||
logo_url=logo_url,
|
||||
)
|
||||
repeated, repeated_notes = apply_generated_page_chrome(
|
||||
fixed,
|
||||
system_name="测试系统",
|
||||
logo_url=logo_url,
|
||||
)
|
||||
|
||||
assert notes == ["已自动应用单页面品牌页眉与页脚"]
|
||||
assert 'data-df-layout="single"' in fixed
|
||||
assert fixed.count("<header class=\"df-generated-header") == 1
|
||||
assert fixed.count("<footer class=\"df-generated-footer") == 1
|
||||
assert fixed.count(logo_url) == 2
|
||||
assert "old-logo.png" not in fixed
|
||||
assert "--df-chrome-accent:#4f6ff5" in fixed
|
||||
assert "--df-chrome-accent:#72d8ff" in fixed
|
||||
assert "<h1>市场分析报告</h1>" in fixed
|
||||
assert repeated == fixed
|
||||
assert repeated_notes == []
|
||||
|
||||
|
||||
def test_generated_page_logo_uses_packaged_runtime_fallback(monkeypatch) -> None:
|
||||
monkeypatch.setattr(
|
||||
"deerflow.config.get_app_config",
|
||||
lambda: SimpleNamespace(
|
||||
html_runtime=SimpleNamespace(
|
||||
base_url="https://example.test/deerflow/api/public/html-runtime",
|
||||
)
|
||||
),
|
||||
)
|
||||
source = "<!doctype html><html><head><title>报告</title></head><body><main>正文</main></body></html>"
|
||||
|
||||
fixed, _notes = apply_generated_page_chrome(
|
||||
source,
|
||||
system_name="测试系统",
|
||||
logo_url="https://example.test/deerflow/api/public/html-runtime/generated-page-logo?v=abc",
|
||||
)
|
||||
|
||||
assert (
|
||||
'data-df-fallback-src="https://example.test/deerflow/api/public/html-runtime/brand-logo-dark.png"'
|
||||
in fixed
|
||||
)
|
||||
assert "this.src=this.dataset.dfFallbackSrc" in fixed
|
||||
assert "this.hidden=true" in fixed
|
||||
|
||||
|
||||
def test_generated_page_chrome_footer_text_replaces_default_brand_footer() -> None:
|
||||
logo_url = "http://localhost:8001/api/public/html-runtime/generated-page-logo?v=abc"
|
||||
source = (
|
||||
"<!doctype html><html><head><title>报告</title></head><body>"
|
||||
"<main>正文</main></body></html>"
|
||||
)
|
||||
|
||||
fixed, notes = apply_generated_page_chrome(
|
||||
source,
|
||||
system_name="测试系统",
|
||||
logo_url=logo_url,
|
||||
footer_text="© 2026 测试系统 · 数据仅供内部参考",
|
||||
)
|
||||
repeated, repeated_notes = apply_generated_page_chrome(
|
||||
fixed,
|
||||
system_name="测试系统",
|
||||
logo_url=logo_url,
|
||||
footer_text="© 2026 测试系统 · 数据仅供内部参考",
|
||||
)
|
||||
|
||||
assert notes == ["已自动应用单页面品牌页眉与页脚"]
|
||||
assert 'class="df-generated-footer__text">© 2026 测试系统 · 数据仅供内部参考</p>' in fixed
|
||||
assert "data-df-brand-footer" not in fixed
|
||||
assert fixed.count(logo_url) == 1
|
||||
assert fixed.count("<footer class=\"df-generated-footer") == 1
|
||||
assert repeated == fixed
|
||||
assert repeated_notes == []
|
||||
|
||||
|
||||
def test_configured_chrome_master_switch_disables_auto_injection(monkeypatch) -> None:
|
||||
from deerflow.html_runtime.generated_page_chrome import apply_configured_generated_page_chrome
|
||||
|
||||
html = "<!doctype html><html><head><title>报告</title></head><body><main>正文</main></body></html>"
|
||||
|
||||
def configure(chrome_enabled: bool) -> None:
|
||||
branding = SimpleNamespace(
|
||||
chrome_enabled=chrome_enabled,
|
||||
system_name="测试系统",
|
||||
footer_text=None,
|
||||
logo_filename="logo-0123456789abcdef0123456789abcdef.png",
|
||||
logo_version="v1",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"deerflow.config.get_app_config",
|
||||
lambda: SimpleNamespace(
|
||||
html_runtime=SimpleNamespace(base_url="http://localhost:8001/api/public/html-runtime")
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
system_settings_module,
|
||||
"load_system_settings",
|
||||
lambda: SimpleNamespace(generated_page_branding=branding),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
system_settings_module,
|
||||
"generated_page_logo_public_url",
|
||||
lambda base_url, _branding: f"{base_url}/generated-page-logo?v=abc",
|
||||
)
|
||||
|
||||
configure(chrome_enabled=False)
|
||||
off_html, off_notes = apply_configured_generated_page_chrome(html)
|
||||
assert off_html == html
|
||||
assert off_notes == []
|
||||
|
||||
configure(chrome_enabled=True)
|
||||
on_html, on_notes = apply_configured_generated_page_chrome(html)
|
||||
assert on_notes == ["已自动应用单页面品牌页眉与页脚"]
|
||||
assert on_html != html
|
||||
|
||||
|
||||
def test_generated_page_chrome_builds_multi_page_navigation_and_visible_home() -> None:
|
||||
logo_url = "http://localhost:8001/api/public/html-runtime/generated-page-logo?v=abc"
|
||||
source = (
|
||||
"<!doctype html><html><head><title>门户</title></head><body>"
|
||||
'<nav><a href="#page-overview">市场总览</a><a href="#page-brand">品牌竞争</a>'
|
||||
'<a href="#page-channel">渠道分析</a></nav><main class="pages">'
|
||||
'<section class="page" id="page-overview" data-page="overview"><h1>市场总览</h1></section>'
|
||||
'<section class="page active" id="page-brand" data-page="brand"><h2>品牌竞争</h2></section>'
|
||||
'<section class="page" id="page-channel" data-page="channel"><h2>渠道分析</h2></section>'
|
||||
"</main></body></html>"
|
||||
)
|
||||
|
||||
fixed, notes = apply_generated_page_chrome(
|
||||
source,
|
||||
system_name="测试系统",
|
||||
logo_url=logo_url,
|
||||
)
|
||||
|
||||
assert notes == ["已自动应用多页面品牌导航与页脚,并确保首页可见"]
|
||||
assert 'data-df-layout="multi"' in fixed
|
||||
assert fixed.index('<div class="df-generated-brand" data-df-brand>') < fixed.index(
|
||||
'<nav class="df-generated-nav" data-df-generated-nav'
|
||||
)
|
||||
assert fixed.count('class="df-generated-nav__link"') == 3
|
||||
assert '<a class="df-generated-nav__link" href="#page-overview" aria-current="page">市场总览</a>' in fixed
|
||||
assert "data-df-replaced-page-nav" in fixed
|
||||
assert "df-page-active" in fixed
|
||||
assert "pages[i].hidden=!active" in fixed
|
||||
assert "pages[i].style.setProperty('display','block','important')" in fixed
|
||||
assert "event.stopImmediatePropagation()" in fixed
|
||||
assert "prefers-reduced-motion: reduce" in fixed
|
||||
|
||||
|
||||
def test_generated_page_chrome_requires_both_name_and_logo() -> None:
|
||||
logo_url = "http://localhost:8001/api/public/html-runtime/generated-page-logo?v=abc"
|
||||
source = (
|
||||
"<!doctype html><html><head><title>门户</title></head><body><main class=\"pages\">"
|
||||
'<section class="page" data-page="overview"><h2>经营概览</h2></section>'
|
||||
'<section class="page" id="detail" data-page="detail"><h2>明细</h2></section>'
|
||||
"</main></body></html>"
|
||||
)
|
||||
|
||||
fixed, _ = apply_generated_page_chrome(source, system_name="测试系统", logo_url=logo_url)
|
||||
name_only, name_only_notes = apply_generated_page_chrome(
|
||||
source,
|
||||
system_name="测试系统",
|
||||
logo_url=None,
|
||||
)
|
||||
logo_only, logo_only_notes = apply_generated_page_chrome(
|
||||
source,
|
||||
system_name=None,
|
||||
logo_url=logo_url,
|
||||
)
|
||||
unchanged, notes = apply_generated_page_chrome(source, system_name=None, logo_url=None)
|
||||
|
||||
assert 'id="page-overview"' in fixed
|
||||
assert 'id="page-detail"' in fixed
|
||||
assert 'href="#page-overview"' in fixed
|
||||
assert 'href="#page-detail"' in fixed
|
||||
assert name_only == source
|
||||
assert name_only_notes == []
|
||||
assert logo_only == source
|
||||
assert logo_only_notes == []
|
||||
assert unchanged == source
|
||||
assert notes == []
|
||||
|
||||
|
||||
def test_html_map_webpage_setting_switches_the_map_contract(monkeypatch) -> None:
|
||||
config = _app_config(enabled=False)
|
||||
monkeypatch.setattr(prompt_module, "_get_memory_context", lambda *args, **kwargs: "")
|
||||
|
||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.html_runtime.generated_page_chrome import apply_generated_page_chrome
|
||||
from deerflow.skills.parser import parse_skill_file
|
||||
from deerflow.skills.storage.local_skill_storage import LocalSkillStorage
|
||||
from deerflow.skills.types import SkillCategory
|
||||
@@ -98,6 +99,23 @@ def test_default_json_renders_editable_facebook_html(tmp_path: Path) -> None:
|
||||
renderer._write_new(output, html)
|
||||
|
||||
|
||||
def test_generated_brand_header_offsets_facebook_fixed_chrome() -> None:
|
||||
template = (SKILL_ROOT / "assets" / "facebook-template.html").read_text(encoding="utf-8")
|
||||
|
||||
branded, _notes = apply_generated_page_chrome(
|
||||
template,
|
||||
system_name="测试系统001",
|
||||
logo_url="/api/public/html-runtime/generated-page-logo?v=test",
|
||||
)
|
||||
|
||||
assert ":root{--df-generated-header-height:64px}" in branded
|
||||
assert "function syncHeaderHeight()" in branded
|
||||
assert "new ResizeObserver(syncHeaderHeight).observe(header)" in branded
|
||||
assert "inset: var(--df-generated-header-height, 0px) 0 auto" in branded
|
||||
assert "top: calc(var(--df-generated-header-height, 0px) + var(--header-h) + 20px)" in branded
|
||||
assert "100dvh - var(--df-generated-header-height, 0px) - var(--header-h)" in branded
|
||||
|
||||
|
||||
def test_validation_rejects_missing_module_and_duplicate_posts() -> None:
|
||||
renderer = _load_renderer()
|
||||
data = json.loads((SKILL_ROOT / "assets" / "default-data.json").read_text(encoding="utf-8"))
|
||||
|
||||
@@ -8,6 +8,11 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.html_runtime.generated_page_chrome import (
|
||||
_normalize_body_top_spacing,
|
||||
apply_generated_page_chrome,
|
||||
)
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
SKILLS_ROOT = BACKEND_ROOT / "skills" / "public"
|
||||
LEAD_PROMPT_PATH = BACKEND_ROOT / "packages" / "harness" / "deerflow" / "agents" / "lead_agent" / "prompt.py"
|
||||
@@ -86,6 +91,31 @@ SPECIALIZED_FAST_SKILLS = {"threads-page-generator", "cnn-page-generator"}
|
||||
SHARED_FAST_SKILLS = tuple(skill_name for skill_name in FAST_SKILLS if skill_name not in SPECIALIZED_FAST_SKILLS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skill_name", BRANDED_PAGE_SKILLS)
|
||||
def test_brand_header_preserves_responsive_css_boundaries(skill_name: str) -> None:
|
||||
templates = list((SKILLS_ROOT / skill_name / "assets").glob("*-template.html"))
|
||||
assert len(templates) == 1
|
||||
template = templates[0].read_text(encoding="utf-8")
|
||||
media_openings = re.findall(r"@media[^{}]+\{", template, flags=re.IGNORECASE)
|
||||
|
||||
normalized = _normalize_body_top_spacing(template)
|
||||
branded, notes = apply_generated_page_chrome(
|
||||
template,
|
||||
system_name="测试系统001",
|
||||
logo_url="/api/public/html-runtime/generated-page-logo?v=test",
|
||||
)
|
||||
|
||||
assert normalized.count("{") == template.count("{")
|
||||
assert normalized.count("}") == template.count("}")
|
||||
assert not re.search(r"@media\s*\([^)]*\)\s+body\s*\{", normalized, flags=re.IGNORECASE)
|
||||
for opening in media_openings:
|
||||
assert opening in normalized
|
||||
assert opening in branded
|
||||
assert 'data-df-generated-header' in branded
|
||||
assert "new ResizeObserver(syncHeaderHeight).observe(header)" in branded
|
||||
assert notes[-1] == "已自动应用单页面品牌页眉"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skill_name", BRANDED_PAGE_SKILLS)
|
||||
def test_platform_chrome_is_offset_below_generated_brand_header(skill_name: str) -> None:
|
||||
templates = list((SKILLS_ROOT / skill_name / "assets").glob("*-template.html"))
|
||||
@@ -111,6 +141,14 @@ def test_platform_modals_render_above_generated_brand_header(skill_name: str) ->
|
||||
else:
|
||||
assert "translateY(calc(-100%-var(--df-generated-header-height,0px)-24px))" in compact_template
|
||||
|
||||
branded, _notes = apply_generated_page_chrome(
|
||||
template,
|
||||
system_name="测试系统001",
|
||||
logo_url="/api/public/html-runtime/generated-page-logo?v=test",
|
||||
)
|
||||
assert ".df-generated-header{position:sticky;top:0;z-index:1000" in branded
|
||||
|
||||
|
||||
def test_fast_workflow_is_declared_by_all_fixed_template_skills() -> None:
|
||||
for skill_name in FAST_SKILLS:
|
||||
skill_text = (SKILLS_ROOT / skill_name / "SKILL.md").read_text(encoding="utf-8")
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Gauss adaptation agent answers with a concrete change and preserves local edits."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _load_tool():
|
||||
path = (
|
||||
Path(__file__).resolve().parents[1]
|
||||
/ "app"
|
||||
/ "gateway"
|
||||
/ "routers"
|
||||
/ "_gauss_data_adaptation_seed_assets"
|
||||
/ "skills"
|
||||
/ "gauss-data-adaptation"
|
||||
/ "scripts"
|
||||
/ "print_gauss_adaptation.py"
|
||||
)
|
||||
spec = importlib.util.spec_from_file_location("gauss_data_adaptation", path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _drivers(**overrides: bool) -> dict[str, bool]:
|
||||
found = {
|
||||
"asyncpg": True,
|
||||
"opengauss_sqlalchemy": True,
|
||||
"asyncmy": True,
|
||||
"aiomysql": False,
|
||||
}
|
||||
found.update(overrides)
|
||||
return found
|
||||
|
||||
|
||||
def test_soul_answers_from_the_error_before_a_tutorial() -> None:
|
||||
from app.gateway.routers import _gauss_data_adaptation_seed as seed
|
||||
|
||||
soul = (seed._ASSETS_DIR / seed.GAUSS_DATA_ADAPTATION_AGENT_ID / "SOUL.md").read_text(encoding="utf-8")
|
||||
guide = (seed._ASSETS_DIR / "skills" / seed.GAUSS_DATA_ADAPTATION_SKILL_NAME / "references" / "adaptation-map.md").read_text(encoding="utf-8")
|
||||
assert soul.index("报错原文已经能对应") < soul.index("先确认模式")
|
||||
assert "要改的地方" in soul
|
||||
assert "先不要改" in soul
|
||||
assert "不要先给安装教程" in soul
|
||||
assert "Automatic ORM schema creation failed" in soul
|
||||
for phrase in (
|
||||
"asyncpg is not installed",
|
||||
"322",
|
||||
"in-memory fallback",
|
||||
"current_schema()",
|
||||
"VARCHAR(n)",
|
||||
"standard_conforming_strings",
|
||||
"UV_EXTRAS=gauss",
|
||||
"DEERFLOW_DATABASE_PRODUCT=gauss_mysql",
|
||||
seed_prohibition(),
|
||||
"通用问答",
|
||||
"智能体",
|
||||
):
|
||||
assert phrase in guide
|
||||
|
||||
|
||||
def seed_prohibition() -> str:
|
||||
return _load_tool().PROHIBITION
|
||||
|
||||
|
||||
def test_seed_is_idempotent_and_preserves_local_edits(tmp_path, monkeypatch) -> None:
|
||||
from app.gateway.routers import _gauss_data_adaptation_seed as seed
|
||||
|
||||
class FakePaths:
|
||||
def agent_dir(self, agent_id: str) -> Path:
|
||||
return tmp_path / "agents" / agent_id
|
||||
|
||||
monkeypatch.setattr(seed, "get_paths", lambda: FakePaths())
|
||||
monkeypatch.setattr(seed, "_ensure_skill", lambda: False)
|
||||
|
||||
assert seed.ensure_gauss_data_adaptation_agent() is True
|
||||
soul = tmp_path / "agents" / seed.GAUSS_DATA_ADAPTATION_AGENT_ID / "SOUL.md"
|
||||
soul.write_text("现场调整", encoding="utf-8")
|
||||
|
||||
assert seed.ensure_gauss_data_adaptation_agent() is False
|
||||
assert soul.read_text(encoding="utf-8") == "现场调整"
|
||||
|
||||
|
||||
def test_native_gauss_redacts_secret_and_flags_postgres_checkpointer() -> None:
|
||||
tool = _load_tool()
|
||||
printed = "\n".join(
|
||||
tool.classify(
|
||||
{
|
||||
"backend": "gauss",
|
||||
"gauss_url": "opengauss+asyncpg://user:s3cret@10.0.0.1:26000/deerflow",
|
||||
},
|
||||
{"type": "postgres", "connection_string": "postgresql://user:s3cret@10.0.0.1:26000/deerflow"},
|
||||
"",
|
||||
_drivers(),
|
||||
)
|
||||
)
|
||||
assert "判定模式:原生 openGauss" in printed
|
||||
assert "10.0.0.1:26000/deerflow" in printed
|
||||
assert "s3cret" not in printed
|
||||
assert "user:" not in printed
|
||||
assert tool.PROHIBITION in printed
|
||||
assert "checkpointer.type 改为 sqlite" in printed
|
||||
|
||||
|
||||
def test_script_does_not_read_the_url_environment_variable(tmp_path, monkeypatch, capsys) -> None:
|
||||
tool = _load_tool()
|
||||
config = tmp_path / "config.yaml"
|
||||
config.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"database:",
|
||||
" backend: gauss",
|
||||
" gauss_url: $GAUSS_DATABASE_URL",
|
||||
"checkpointer:",
|
||||
" type: sqlite",
|
||||
" connection_string: .deer-flow/data/checkpoints.db",
|
||||
" # gauss_url: opengauss://user:hidden@10.9.9.9/db",
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("GAUSS_DATABASE_URL", "opengauss://user:supersecret@10.1.1.1/db")
|
||||
monkeypatch.delenv("DEERFLOW_DATABASE_PRODUCT", raising=False)
|
||||
monkeypatch.setattr(tool, "config_candidates", lambda: [config])
|
||||
monkeypatch.setattr(tool, "driver_status", lambda: _drivers())
|
||||
tool.main()
|
||||
printed = capsys.readouterr().out
|
||||
assert "环境变量 GAUSS_DATABASE_URL(不读取变量值)" in printed
|
||||
assert "supersecret" not in printed
|
||||
assert "hidden" not in printed
|
||||
assert "10.1.1.1" not in printed
|
||||
assert ".deer-flow/data/checkpoints.db" in printed
|
||||
assert "配置层面没有必须修改的项" in printed
|
||||
|
||||
|
||||
def test_dolphin_and_conflict_modes_name_the_change() -> None:
|
||||
tool = _load_tool()
|
||||
dolphin = "\n".join(
|
||||
tool.classify(
|
||||
{"backend": "mysql", "mysql_url": "mysql://user:s3cret@10.0.0.8:3306/deerflow"},
|
||||
{"type": "sqlite", "connection_string": ".deer-flow/data/checkpoints.db"},
|
||||
"gauss_mysql",
|
||||
_drivers(asyncmy=False, aiomysql=False),
|
||||
)
|
||||
)
|
||||
assert "判定模式:Dolphin" in dolphin
|
||||
assert "s3cret" not in dolphin
|
||||
assert ".deer-flow/python-vendor" in dolphin
|
||||
assert "SHOW CREATE TABLE" in dolphin
|
||||
|
||||
conflict = "\n".join(
|
||||
tool.classify(
|
||||
{"backend": "gauss", "gauss_url": "$GAUSS_DATABASE_URL"},
|
||||
{"type": "sqlite"},
|
||||
" GAUSS_MYSQL ",
|
||||
_drivers(),
|
||||
)
|
||||
)
|
||||
assert "判定模式:冲突" in conflict
|
||||
assert "database.backend 改回 mysql" in conflict
|
||||
|
||||
|
||||
def test_missing_native_driver_points_at_the_offline_image() -> None:
|
||||
tool = _load_tool()
|
||||
printed = "\n".join(
|
||||
tool.classify(
|
||||
{"backend": "gauss", "gauss_url": "$GAUSS_DATABASE_URL"},
|
||||
{"type": "sqlite", "connection_string": ".deer-flow/data/checkpoints.db"},
|
||||
"",
|
||||
_drivers(asyncpg=False, opengauss_sqlalchemy=False),
|
||||
)
|
||||
)
|
||||
assert "UV_EXTRAS=gauss" in printed
|
||||
assert "不要在内网访问公网安装" in printed
|
||||
assert "判定模式:原生 openGauss" in printed
|
||||
@@ -1,415 +1,415 @@
|
||||
"""Regression coverage for openGauss/Dolphin through the MySQL protocol."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Column, Integer, MetaData, String, Table
|
||||
|
||||
from deerflow.persistence.gauss_mysql_compat import (
|
||||
GAUSS_MYSQL_SQLALCHEMY_VERSION,
|
||||
_gauss_mysql_default_schema_name,
|
||||
_gauss_mysql_has_table,
|
||||
_gauss_mysql_isolation_level,
|
||||
_gauss_mysql_server_version_info,
|
||||
decode_gauss_mysql_json,
|
||||
install_gauss_mysql_dialect_compatibility,
|
||||
is_gauss_mysql_product,
|
||||
)
|
||||
from deerflow.persistence.gauss_schema import ensure_gauss_schema_sync
|
||||
from deerflow.persistence.types import PortableJSON
|
||||
|
||||
|
||||
def _mysql_escape(value: str) -> str:
|
||||
table = {
|
||||
"\0": "\\0",
|
||||
"\\": "\\\\",
|
||||
"\n": "\\n",
|
||||
"\r": "\\r",
|
||||
"\x1a": "\\Z",
|
||||
'"': '\\"',
|
||||
"'": "\\'",
|
||||
}
|
||||
return "".join(table.get(character, character) for character in value)
|
||||
|
||||
|
||||
def test_product_switch_is_explicit_and_case_insensitive(monkeypatch) -> None:
|
||||
monkeypatch.delenv("DEERFLOW_DATABASE_PRODUCT", raising=False)
|
||||
assert not is_gauss_mysql_product()
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", "mysql")
|
||||
assert not is_gauss_mysql_product()
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", " GAUSS_MYSQL ")
|
||||
assert is_gauss_mysql_product()
|
||||
|
||||
|
||||
def test_json_decoder_accepts_strict_and_bounded_legacy_formats() -> None:
|
||||
strict = {"name": "中文", "enabled": True, "items": [1, None]}
|
||||
assert decode_gauss_mysql_json(json.dumps(strict, ensure_ascii=False)) == strict
|
||||
assert decode_gauss_mysql_json("{'name': 'legacy', 'enabled': True}") == {
|
||||
"name": "legacy",
|
||||
"enabled": True,
|
||||
}
|
||||
escaped = _mysql_escape(json.dumps(["web", "file:read", "bash"]))
|
||||
assert decode_gauss_mysql_json(escaped) == ["web", "file:read", "bash"]
|
||||
assert decode_gauss_mysql_json(memoryview(escaped.encode())) == ["web", "file:read", "bash"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
r"[\"web\",",
|
||||
r"[\"bad\q\"]",
|
||||
r'[\"a\", "b"]',
|
||||
"__import__('os').system('echo unsafe')",
|
||||
"{1, 2}",
|
||||
"(1, 2)",
|
||||
"{'nested': {1, 2}}",
|
||||
"{'nested': (1, 2)}",
|
||||
"{1: 'non-string key'}",
|
||||
"{'nested': b'bytes'}",
|
||||
],
|
||||
)
|
||||
def test_json_decoder_rejects_malformed_or_unsafe_values(value: str) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
decode_gauss_mysql_json(value)
|
||||
|
||||
|
||||
def test_portable_json_fallback_is_dolphin_only() -> None:
|
||||
ordinary_mysql = SimpleNamespace(name="mysql")
|
||||
dolphin = SimpleNamespace(name="mysql", _deerflow_gauss_mysql_compat_installed=True)
|
||||
column_type = PortableJSON()
|
||||
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
column_type.process_result_value("{'enabled': True}", ordinary_mysql)
|
||||
assert column_type.process_result_value("{'enabled': True}", dolphin) == {"enabled": True}
|
||||
|
||||
|
||||
def test_dialect_helpers_use_current_schema_version_and_isolation() -> None:
|
||||
class Cursor:
|
||||
def __init__(self, row):
|
||||
self.row = row
|
||||
self.statement = None
|
||||
self.closed = False
|
||||
|
||||
def execute(self, statement):
|
||||
self.statement = statement
|
||||
|
||||
def fetchone(self):
|
||||
return self.row
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
version_cursor = Cursor(("openGauss 6.0.5",))
|
||||
dialect = SimpleNamespace(
|
||||
_set_mariadb=lambda *_args: None,
|
||||
server_version_info=None,
|
||||
)
|
||||
connection = SimpleNamespace(connection=SimpleNamespace(cursor=lambda: version_cursor))
|
||||
assert _gauss_mysql_server_version_info(dialect, connection) == GAUSS_MYSQL_SQLALCHEMY_VERSION
|
||||
assert dialect.server_version_info == GAUSS_MYSQL_SQLALCHEMY_VERSION
|
||||
assert version_cursor.statement == "SELECT VERSION()"
|
||||
assert version_cursor.closed
|
||||
|
||||
isolation_cursor = Cursor(("read-committed",))
|
||||
dbapi = SimpleNamespace(cursor=lambda: isolation_cursor)
|
||||
assert _gauss_mysql_isolation_level(dialect, dbapi) == "READ COMMITTED"
|
||||
assert isolation_cursor.statement == "SELECT @@transaction_isolation"
|
||||
|
||||
class ScalarResult:
|
||||
def scalar(self):
|
||||
return b"deerflow"
|
||||
|
||||
class SchemaConnection:
|
||||
def exec_driver_sql(self, statement):
|
||||
assert statement == "SELECT current_schema()"
|
||||
return ScalarResult()
|
||||
|
||||
assert _gauss_mysql_default_schema_name(dialect, SchemaConnection()) == "deerflow"
|
||||
|
||||
|
||||
def test_has_table_uses_native_catalog_instead_of_describe() -> None:
|
||||
observed = {}
|
||||
|
||||
class Result:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args):
|
||||
return False
|
||||
|
||||
def fetchone(self):
|
||||
return (1,)
|
||||
|
||||
class Connection:
|
||||
def exec_driver_sql(self, statement, parameters, execution_options):
|
||||
observed.update(
|
||||
statement=statement,
|
||||
parameters=parameters,
|
||||
execution_options=execution_options,
|
||||
)
|
||||
return Result()
|
||||
|
||||
dialect = SimpleNamespace(
|
||||
default_schema_name="deerflow",
|
||||
_ensure_has_table_connection=lambda _connection: None,
|
||||
)
|
||||
assert _gauss_mysql_has_table(dialect, Connection(), "users")
|
||||
assert "pg_catalog.pg_class" in observed["statement"]
|
||||
assert "DESCRIBE" not in observed["statement"].upper()
|
||||
assert observed["parameters"] == ("deerflow", "users")
|
||||
|
||||
|
||||
def test_installer_is_driver_scoped_and_idempotent(monkeypatch) -> None:
|
||||
from sqlalchemy.dialects.mysql import asyncmy as asyncmy_module
|
||||
|
||||
class FakeDialect:
|
||||
calls = 0
|
||||
|
||||
def create_connect_args(self, _url):
|
||||
type(self).calls += 1
|
||||
return [], {"charset": "utf8mb4"}
|
||||
|
||||
monkeypatch.setattr(asyncmy_module, "MySQLDialect_asyncmy", FakeDialect)
|
||||
install_gauss_mysql_dialect_compatibility("asyncmy")
|
||||
first_original = FakeDialect._deerflow_gauss_mysql_original_create_connect_args
|
||||
install_gauss_mysql_dialect_compatibility("asyncmy")
|
||||
|
||||
_args, kwargs = FakeDialect().create_connect_args(object())
|
||||
assert kwargs["charset"] == "utf8mb4"
|
||||
assert kwargs["init_command"] == "SET standard_conforming_strings TO off"
|
||||
assert FakeDialect.calls == 1
|
||||
assert FakeDialect._deerflow_gauss_mysql_original_create_connect_args is first_original
|
||||
assert FakeDialect._deerflow_gauss_mysql_compat_installed is True
|
||||
|
||||
|
||||
def test_installer_rejects_conflicting_init_command(monkeypatch) -> None:
|
||||
from sqlalchemy.dialects.mysql import asyncmy as asyncmy_module
|
||||
|
||||
class FakeDialect:
|
||||
def create_connect_args(self, _url):
|
||||
return [], {"init_command": "SET time_zone = '+00:00'"}
|
||||
|
||||
monkeypatch.setattr(asyncmy_module, "MySQLDialect_asyncmy", FakeDialect)
|
||||
install_gauss_mysql_dialect_compatibility("asyncmy")
|
||||
|
||||
with pytest.raises(ValueError, match="standard_conforming_strings"):
|
||||
FakeDialect().create_connect_args(object())
|
||||
|
||||
|
||||
class _RowsResult:
|
||||
def __init__(self, *, scalar=None, rows=()):
|
||||
self._scalar = scalar
|
||||
self._rows = list(rows)
|
||||
|
||||
def scalar_one_or_none(self):
|
||||
return self._scalar
|
||||
|
||||
def fetchall(self):
|
||||
return list(self._rows)
|
||||
|
||||
|
||||
def test_schema_integrity_preflights_all_columns_before_ddl() -> None:
|
||||
metadata = MetaData()
|
||||
Table(
|
||||
"example",
|
||||
metadata,
|
||||
Column("id", Integer, primary_key=True),
|
||||
Column("safe_note", String(20), nullable=True),
|
||||
Column("unsafe_required", String(20), nullable=False),
|
||||
)
|
||||
|
||||
class Connection:
|
||||
engine = SimpleNamespace(url=SimpleNamespace(database="deerflow"))
|
||||
|
||||
def __init__(self):
|
||||
self.statements = []
|
||||
|
||||
def exec_driver_sql(self, statement, parameters=None):
|
||||
self.statements.append((statement, parameters))
|
||||
if statement == "SELECT current_schema()":
|
||||
return _RowsResult(scalar="deerflow")
|
||||
if "pg_catalog.pg_attribute" in statement:
|
||||
return _RowsResult(rows=[("example", "r", "id")])
|
||||
raise AssertionError(f"DDL must not run after unsafe preflight: {statement}")
|
||||
|
||||
connection = Connection()
|
||||
with pytest.raises(RuntimeError, match="NOT NULL column has no server_default"):
|
||||
ensure_gauss_schema_sync(connection, metadata)
|
||||
assert not any(statement.lstrip().startswith("ALTER TABLE") for statement, _ in connection.statements)
|
||||
|
||||
|
||||
def test_active_feature_models_are_registered_without_enterprise_research() -> None:
|
||||
import deerflow.persistence.models # noqa: F401
|
||||
from deerflow.persistence.base import Base
|
||||
|
||||
expected = {
|
||||
"ai_writing_sessions",
|
||||
"ai_writing_article_types",
|
||||
"scheduled_html_pages",
|
||||
"html_page_favorites",
|
||||
"task_analysis_tasks",
|
||||
"task_analysis_settings",
|
||||
}
|
||||
assert expected <= set(Base.metadata.tables)
|
||||
assert "enterprise_research_tasks" not in Base.metadata.tables
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("product", "expects_gauss"),
|
||||
[("mysql", False), ("gauss_mysql", True)],
|
||||
)
|
||||
async def test_engine_selects_dolphin_hooks_without_changing_mysql(
|
||||
monkeypatch,
|
||||
product: str,
|
||||
expects_gauss: bool,
|
||||
) -> None:
|
||||
import deerflow.persistence.engine as engine_module
|
||||
import deerflow.persistence.gauss_mysql_compat as compat_module
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
class Connection:
|
||||
async def run_sync(self, function, *_args):
|
||||
calls.append(function.__name__)
|
||||
|
||||
class Begin:
|
||||
async def __aenter__(self):
|
||||
return Connection()
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
class Engine:
|
||||
dialect = SimpleNamespace(name="mysql")
|
||||
|
||||
def begin(self):
|
||||
return Begin()
|
||||
|
||||
async def dispose(self):
|
||||
calls.append("dispose")
|
||||
|
||||
fake_engine = Engine()
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", product)
|
||||
monkeypatch.setattr(engine_module, "find_spec", lambda _name: object())
|
||||
monkeypatch.setattr(engine_module, "_add_runtime_vendor_path", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "create_async_engine", lambda *_args, **_kwargs: fake_engine)
|
||||
monkeypatch.setattr(engine_module, "_acquire_gauss_mysql_schema_bootstrap_lock", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "_release_gauss_mysql_schema_bootstrap_lock", lambda _handle: None)
|
||||
monkeypatch.setattr(
|
||||
compat_module,
|
||||
"install_gauss_mysql_dialect_compatibility",
|
||||
lambda driver: calls.append(f"install:{driver}"),
|
||||
)
|
||||
|
||||
await engine_module.close_engine()
|
||||
try:
|
||||
await engine_module.init_engine(
|
||||
"mysql",
|
||||
url="mysql+asyncmy://user:pass@db.example/deerflow",
|
||||
)
|
||||
finally:
|
||||
await engine_module.close_engine()
|
||||
|
||||
assert ("install:asyncmy" in calls) is expects_gauss
|
||||
assert ("ensure_gauss_schema_sync" in calls) is expects_gauss
|
||||
assert ("_ensure_orm_columns_sync" in calls) is (not expects_gauss)
|
||||
assert ("_backfill_thread_meta_task_projections_sync" in calls) is (not expects_gauss)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dolphin_unknown_schema_never_runs_mysql_create_database(monkeypatch) -> None:
|
||||
import deerflow.persistence.engine as engine_module
|
||||
import deerflow.persistence.gauss_mysql_compat as compat_module
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
class Connection:
|
||||
async def run_sync(self, function, *_args):
|
||||
if function.__name__ == "create_all":
|
||||
raise RuntimeError("1049 unknown database")
|
||||
|
||||
class Begin:
|
||||
async def __aenter__(self):
|
||||
return Connection()
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
class Engine:
|
||||
dialect = SimpleNamespace(name="mysql")
|
||||
|
||||
def begin(self):
|
||||
return Begin()
|
||||
|
||||
async def dispose(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", "gauss_mysql")
|
||||
monkeypatch.setattr(engine_module, "find_spec", lambda _name: object())
|
||||
monkeypatch.setattr(engine_module, "_add_runtime_vendor_path", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "create_async_engine", lambda *_args, **_kwargs: Engine())
|
||||
monkeypatch.setattr(engine_module, "_acquire_gauss_mysql_schema_bootstrap_lock", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "_release_gauss_mysql_schema_bootstrap_lock", lambda _handle: None)
|
||||
monkeypatch.setattr(
|
||||
engine_module,
|
||||
"_auto_create_mysql_db",
|
||||
lambda _url: calls.append("mysql-create-database"),
|
||||
)
|
||||
monkeypatch.setattr(compat_module, "install_gauss_mysql_dialect_compatibility", lambda _driver: None)
|
||||
|
||||
await engine_module.close_engine()
|
||||
try:
|
||||
# Startup remains best-effort by repository invariant, but the MySQL
|
||||
# CREATE DATABASE retry must not be attempted against Dolphin.
|
||||
await engine_module.init_engine(
|
||||
"mysql",
|
||||
url="mysql+asyncmy://user:pass@db.example/deerflow",
|
||||
)
|
||||
finally:
|
||||
await engine_module.close_engine()
|
||||
|
||||
assert "mysql-create-database" not in calls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dolphin_analytics_skips_mysql_session_variables(monkeypatch) -> None:
|
||||
from app.gateway.routers.admin_users import _set_analytics_read_timeout
|
||||
|
||||
class Session:
|
||||
async def connection(self):
|
||||
raise AssertionError("Dolphin must return before touching MySQL session variables")
|
||||
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", "gauss_mysql")
|
||||
await _set_analytics_read_timeout(Session())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skill_display_table_accepts_only_duplicate_create_race(monkeypatch) -> None:
|
||||
import app.gateway.routers.skills as skills_router
|
||||
|
||||
class DuplicateBegin:
|
||||
async def __aenter__(self):
|
||||
raise RuntimeError('relation "skill_display_adapters" already exists')
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
class DuplicateEngine:
|
||||
def begin(self):
|
||||
return DuplicateBegin()
|
||||
|
||||
duplicate_engine = DuplicateEngine()
|
||||
monkeypatch.setattr(skills_router, "_skill_display_table_engine", None)
|
||||
monkeypatch.setattr(skills_router, "_SKILL_DISPLAY_TABLE_LOCK", asyncio.Lock())
|
||||
monkeypatch.setattr(skills_router, "get_engine", lambda: duplicate_engine)
|
||||
monkeypatch.setattr(skills_router, "get_session_factory", lambda: object())
|
||||
|
||||
assert await skills_router._ensure_skill_display_table()
|
||||
assert skills_router._skill_display_table_engine is duplicate_engine
|
||||
assert skills_router._skill_display_table_already_exists(RuntimeError("error 1050"))
|
||||
assert not skills_router._skill_display_table_already_exists(RuntimeError("permission denied"))
|
||||
"""Regression coverage for openGauss/Dolphin through the MySQL protocol."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Column, Integer, MetaData, String, Table
|
||||
|
||||
from deerflow.persistence.gauss_mysql_compat import (
|
||||
GAUSS_MYSQL_SQLALCHEMY_VERSION,
|
||||
_gauss_mysql_default_schema_name,
|
||||
_gauss_mysql_has_table,
|
||||
_gauss_mysql_isolation_level,
|
||||
_gauss_mysql_server_version_info,
|
||||
decode_gauss_mysql_json,
|
||||
install_gauss_mysql_dialect_compatibility,
|
||||
is_gauss_mysql_product,
|
||||
)
|
||||
from deerflow.persistence.gauss_schema import ensure_gauss_schema_sync
|
||||
from deerflow.persistence.types import PortableJSON
|
||||
|
||||
|
||||
def _mysql_escape(value: str) -> str:
|
||||
table = {
|
||||
"\0": "\\0",
|
||||
"\\": "\\\\",
|
||||
"\n": "\\n",
|
||||
"\r": "\\r",
|
||||
"\x1a": "\\Z",
|
||||
'"': '\\"',
|
||||
"'": "\\'",
|
||||
}
|
||||
return "".join(table.get(character, character) for character in value)
|
||||
|
||||
|
||||
def test_product_switch_is_explicit_and_case_insensitive(monkeypatch) -> None:
|
||||
monkeypatch.delenv("DEERFLOW_DATABASE_PRODUCT", raising=False)
|
||||
assert not is_gauss_mysql_product()
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", "mysql")
|
||||
assert not is_gauss_mysql_product()
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", " GAUSS_MYSQL ")
|
||||
assert is_gauss_mysql_product()
|
||||
|
||||
|
||||
def test_json_decoder_accepts_strict_and_bounded_legacy_formats() -> None:
|
||||
strict = {"name": "中文", "enabled": True, "items": [1, None]}
|
||||
assert decode_gauss_mysql_json(json.dumps(strict, ensure_ascii=False)) == strict
|
||||
assert decode_gauss_mysql_json("{'name': 'legacy', 'enabled': True}") == {
|
||||
"name": "legacy",
|
||||
"enabled": True,
|
||||
}
|
||||
escaped = _mysql_escape(json.dumps(["web", "file:read", "bash"]))
|
||||
assert decode_gauss_mysql_json(escaped) == ["web", "file:read", "bash"]
|
||||
assert decode_gauss_mysql_json(memoryview(escaped.encode())) == ["web", "file:read", "bash"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
r"[\"web\",",
|
||||
r"[\"bad\q\"]",
|
||||
r'[\"a\", "b"]',
|
||||
"__import__('os').system('echo unsafe')",
|
||||
"{1, 2}",
|
||||
"(1, 2)",
|
||||
"{'nested': {1, 2}}",
|
||||
"{'nested': (1, 2)}",
|
||||
"{1: 'non-string key'}",
|
||||
"{'nested': b'bytes'}",
|
||||
],
|
||||
)
|
||||
def test_json_decoder_rejects_malformed_or_unsafe_values(value: str) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
decode_gauss_mysql_json(value)
|
||||
|
||||
|
||||
def test_portable_json_fallback_is_dolphin_only() -> None:
|
||||
ordinary_mysql = SimpleNamespace(name="mysql")
|
||||
dolphin = SimpleNamespace(name="mysql", _deerflow_gauss_mysql_compat_installed=True)
|
||||
column_type = PortableJSON()
|
||||
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
column_type.process_result_value("{'enabled': True}", ordinary_mysql)
|
||||
assert column_type.process_result_value("{'enabled': True}", dolphin) == {"enabled": True}
|
||||
|
||||
|
||||
def test_dialect_helpers_use_current_schema_version_and_isolation() -> None:
|
||||
class Cursor:
|
||||
def __init__(self, row):
|
||||
self.row = row
|
||||
self.statement = None
|
||||
self.closed = False
|
||||
|
||||
def execute(self, statement):
|
||||
self.statement = statement
|
||||
|
||||
def fetchone(self):
|
||||
return self.row
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
version_cursor = Cursor(("openGauss 6.0.5",))
|
||||
dialect = SimpleNamespace(
|
||||
_set_mariadb=lambda *_args: None,
|
||||
server_version_info=None,
|
||||
)
|
||||
connection = SimpleNamespace(connection=SimpleNamespace(cursor=lambda: version_cursor))
|
||||
assert _gauss_mysql_server_version_info(dialect, connection) == GAUSS_MYSQL_SQLALCHEMY_VERSION
|
||||
assert dialect.server_version_info == GAUSS_MYSQL_SQLALCHEMY_VERSION
|
||||
assert version_cursor.statement == "SELECT VERSION()"
|
||||
assert version_cursor.closed
|
||||
|
||||
isolation_cursor = Cursor(("read-committed",))
|
||||
dbapi = SimpleNamespace(cursor=lambda: isolation_cursor)
|
||||
assert _gauss_mysql_isolation_level(dialect, dbapi) == "READ COMMITTED"
|
||||
assert isolation_cursor.statement == "SELECT @@transaction_isolation"
|
||||
|
||||
class ScalarResult:
|
||||
def scalar(self):
|
||||
return b"deerflow"
|
||||
|
||||
class SchemaConnection:
|
||||
def exec_driver_sql(self, statement):
|
||||
assert statement == "SELECT current_schema()"
|
||||
return ScalarResult()
|
||||
|
||||
assert _gauss_mysql_default_schema_name(dialect, SchemaConnection()) == "deerflow"
|
||||
|
||||
|
||||
def test_has_table_uses_native_catalog_instead_of_describe() -> None:
|
||||
observed = {}
|
||||
|
||||
class Result:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args):
|
||||
return False
|
||||
|
||||
def fetchone(self):
|
||||
return (1,)
|
||||
|
||||
class Connection:
|
||||
def exec_driver_sql(self, statement, parameters, execution_options):
|
||||
observed.update(
|
||||
statement=statement,
|
||||
parameters=parameters,
|
||||
execution_options=execution_options,
|
||||
)
|
||||
return Result()
|
||||
|
||||
dialect = SimpleNamespace(
|
||||
default_schema_name="deerflow",
|
||||
_ensure_has_table_connection=lambda _connection: None,
|
||||
)
|
||||
assert _gauss_mysql_has_table(dialect, Connection(), "users")
|
||||
assert "pg_catalog.pg_class" in observed["statement"]
|
||||
assert "DESCRIBE" not in observed["statement"].upper()
|
||||
assert observed["parameters"] == ("deerflow", "users")
|
||||
|
||||
|
||||
def test_installer_is_driver_scoped_and_idempotent(monkeypatch) -> None:
|
||||
from sqlalchemy.dialects.mysql import asyncmy as asyncmy_module
|
||||
|
||||
class FakeDialect:
|
||||
calls = 0
|
||||
|
||||
def create_connect_args(self, _url):
|
||||
type(self).calls += 1
|
||||
return [], {"charset": "utf8mb4"}
|
||||
|
||||
monkeypatch.setattr(asyncmy_module, "MySQLDialect_asyncmy", FakeDialect)
|
||||
install_gauss_mysql_dialect_compatibility("asyncmy")
|
||||
first_original = FakeDialect._deerflow_gauss_mysql_original_create_connect_args
|
||||
install_gauss_mysql_dialect_compatibility("asyncmy")
|
||||
|
||||
_args, kwargs = FakeDialect().create_connect_args(object())
|
||||
assert kwargs["charset"] == "utf8mb4"
|
||||
assert kwargs["init_command"] == "SET standard_conforming_strings TO off"
|
||||
assert FakeDialect.calls == 1
|
||||
assert FakeDialect._deerflow_gauss_mysql_original_create_connect_args is first_original
|
||||
assert FakeDialect._deerflow_gauss_mysql_compat_installed is True
|
||||
|
||||
|
||||
def test_installer_rejects_conflicting_init_command(monkeypatch) -> None:
|
||||
from sqlalchemy.dialects.mysql import asyncmy as asyncmy_module
|
||||
|
||||
class FakeDialect:
|
||||
def create_connect_args(self, _url):
|
||||
return [], {"init_command": "SET time_zone = '+00:00'"}
|
||||
|
||||
monkeypatch.setattr(asyncmy_module, "MySQLDialect_asyncmy", FakeDialect)
|
||||
install_gauss_mysql_dialect_compatibility("asyncmy")
|
||||
|
||||
with pytest.raises(ValueError, match="standard_conforming_strings"):
|
||||
FakeDialect().create_connect_args(object())
|
||||
|
||||
|
||||
class _RowsResult:
|
||||
def __init__(self, *, scalar=None, rows=()):
|
||||
self._scalar = scalar
|
||||
self._rows = list(rows)
|
||||
|
||||
def scalar_one_or_none(self):
|
||||
return self._scalar
|
||||
|
||||
def fetchall(self):
|
||||
return list(self._rows)
|
||||
|
||||
|
||||
def test_schema_integrity_preflights_all_columns_before_ddl() -> None:
|
||||
metadata = MetaData()
|
||||
Table(
|
||||
"example",
|
||||
metadata,
|
||||
Column("id", Integer, primary_key=True),
|
||||
Column("safe_note", String(20), nullable=True),
|
||||
Column("unsafe_required", String(20), nullable=False),
|
||||
)
|
||||
|
||||
class Connection:
|
||||
engine = SimpleNamespace(url=SimpleNamespace(database="deerflow"))
|
||||
|
||||
def __init__(self):
|
||||
self.statements = []
|
||||
|
||||
def exec_driver_sql(self, statement, parameters=None):
|
||||
self.statements.append((statement, parameters))
|
||||
if statement == "SELECT current_schema()":
|
||||
return _RowsResult(scalar="deerflow")
|
||||
if "pg_catalog.pg_attribute" in statement:
|
||||
return _RowsResult(rows=[("example", "r", "id")])
|
||||
raise AssertionError(f"DDL must not run after unsafe preflight: {statement}")
|
||||
|
||||
connection = Connection()
|
||||
with pytest.raises(RuntimeError, match="NOT NULL column has no server_default"):
|
||||
ensure_gauss_schema_sync(connection, metadata)
|
||||
assert not any(statement.lstrip().startswith("ALTER TABLE") for statement, _ in connection.statements)
|
||||
|
||||
|
||||
def test_active_feature_models_are_registered_without_enterprise_research() -> None:
|
||||
import deerflow.persistence.models # noqa: F401
|
||||
from deerflow.persistence.base import Base
|
||||
|
||||
expected = {
|
||||
"ai_writing_sessions",
|
||||
"ai_writing_article_types",
|
||||
"scheduled_html_pages",
|
||||
"html_page_favorites",
|
||||
"task_analysis_tasks",
|
||||
"task_analysis_settings",
|
||||
}
|
||||
assert expected <= set(Base.metadata.tables)
|
||||
assert "enterprise_research_tasks" not in Base.metadata.tables
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("product", "expects_gauss"),
|
||||
[("mysql", False), ("gauss_mysql", True)],
|
||||
)
|
||||
async def test_engine_selects_dolphin_hooks_without_changing_mysql(
|
||||
monkeypatch,
|
||||
product: str,
|
||||
expects_gauss: bool,
|
||||
) -> None:
|
||||
import deerflow.persistence.engine as engine_module
|
||||
import deerflow.persistence.gauss_mysql_compat as compat_module
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
class Connection:
|
||||
async def run_sync(self, function, *_args):
|
||||
calls.append(function.__name__)
|
||||
|
||||
class Begin:
|
||||
async def __aenter__(self):
|
||||
return Connection()
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
class Engine:
|
||||
dialect = SimpleNamespace(name="mysql")
|
||||
|
||||
def begin(self):
|
||||
return Begin()
|
||||
|
||||
async def dispose(self):
|
||||
calls.append("dispose")
|
||||
|
||||
fake_engine = Engine()
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", product)
|
||||
monkeypatch.setattr(engine_module, "find_spec", lambda _name: object())
|
||||
monkeypatch.setattr(engine_module, "_add_runtime_vendor_path", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "create_async_engine", lambda *_args, **_kwargs: fake_engine)
|
||||
monkeypatch.setattr(engine_module, "_acquire_gauss_mysql_schema_bootstrap_lock", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "_release_gauss_mysql_schema_bootstrap_lock", lambda _handle: None)
|
||||
monkeypatch.setattr(
|
||||
compat_module,
|
||||
"install_gauss_mysql_dialect_compatibility",
|
||||
lambda driver: calls.append(f"install:{driver}"),
|
||||
)
|
||||
|
||||
await engine_module.close_engine()
|
||||
try:
|
||||
await engine_module.init_engine(
|
||||
"mysql",
|
||||
url="mysql+asyncmy://user:pass@db.example/deerflow",
|
||||
)
|
||||
finally:
|
||||
await engine_module.close_engine()
|
||||
|
||||
assert ("install:asyncmy" in calls) is expects_gauss
|
||||
assert ("ensure_gauss_schema_sync" in calls) is expects_gauss
|
||||
assert ("_ensure_orm_columns_sync" in calls) is (not expects_gauss)
|
||||
assert ("_backfill_thread_meta_task_projections_sync" in calls) is (not expects_gauss)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dolphin_unknown_schema_never_runs_mysql_create_database(monkeypatch) -> None:
|
||||
import deerflow.persistence.engine as engine_module
|
||||
import deerflow.persistence.gauss_mysql_compat as compat_module
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
class Connection:
|
||||
async def run_sync(self, function, *_args):
|
||||
if function.__name__ == "create_all":
|
||||
raise RuntimeError("1049 unknown database")
|
||||
|
||||
class Begin:
|
||||
async def __aenter__(self):
|
||||
return Connection()
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
class Engine:
|
||||
dialect = SimpleNamespace(name="mysql")
|
||||
|
||||
def begin(self):
|
||||
return Begin()
|
||||
|
||||
async def dispose(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", "gauss_mysql")
|
||||
monkeypatch.setattr(engine_module, "find_spec", lambda _name: object())
|
||||
monkeypatch.setattr(engine_module, "_add_runtime_vendor_path", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "create_async_engine", lambda *_args, **_kwargs: Engine())
|
||||
monkeypatch.setattr(engine_module, "_acquire_gauss_mysql_schema_bootstrap_lock", lambda: None)
|
||||
monkeypatch.setattr(engine_module, "_release_gauss_mysql_schema_bootstrap_lock", lambda _handle: None)
|
||||
monkeypatch.setattr(
|
||||
engine_module,
|
||||
"_auto_create_mysql_db",
|
||||
lambda _url: calls.append("mysql-create-database"),
|
||||
)
|
||||
monkeypatch.setattr(compat_module, "install_gauss_mysql_dialect_compatibility", lambda _driver: None)
|
||||
|
||||
await engine_module.close_engine()
|
||||
try:
|
||||
# Startup remains best-effort by repository invariant, but the MySQL
|
||||
# CREATE DATABASE retry must not be attempted against Dolphin.
|
||||
await engine_module.init_engine(
|
||||
"mysql",
|
||||
url="mysql+asyncmy://user:pass@db.example/deerflow",
|
||||
)
|
||||
finally:
|
||||
await engine_module.close_engine()
|
||||
|
||||
assert "mysql-create-database" not in calls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dolphin_analytics_skips_mysql_session_variables(monkeypatch) -> None:
|
||||
from app.gateway.routers.admin_users import _set_analytics_read_timeout
|
||||
|
||||
class Session:
|
||||
async def connection(self):
|
||||
raise AssertionError("Dolphin must return before touching MySQL session variables")
|
||||
|
||||
monkeypatch.setenv("DEERFLOW_DATABASE_PRODUCT", "gauss_mysql")
|
||||
await _set_analytics_read_timeout(Session())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skill_display_table_accepts_only_duplicate_create_race(monkeypatch) -> None:
|
||||
import app.gateway.routers.skills as skills_router
|
||||
|
||||
class DuplicateBegin:
|
||||
async def __aenter__(self):
|
||||
raise RuntimeError('relation "skill_display_adapters" already exists')
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
class DuplicateEngine:
|
||||
def begin(self):
|
||||
return DuplicateBegin()
|
||||
|
||||
duplicate_engine = DuplicateEngine()
|
||||
monkeypatch.setattr(skills_router, "_skill_display_table_engine", None)
|
||||
monkeypatch.setattr(skills_router, "_SKILL_DISPLAY_TABLE_LOCK", asyncio.Lock())
|
||||
monkeypatch.setattr(skills_router, "get_engine", lambda: duplicate_engine)
|
||||
monkeypatch.setattr(skills_router, "get_session_factory", lambda: object())
|
||||
|
||||
assert await skills_router._ensure_skill_display_table()
|
||||
assert skills_router._skill_display_table_engine is duplicate_engine
|
||||
assert skills_router._skill_display_table_already_exists(RuntimeError("error 1050"))
|
||||
assert not skills_router._skill_display_table_already_exists(RuntimeError("permission denied"))
|
||||
@@ -84,6 +84,8 @@ def test_missing_config_uses_the_built_in_default(monkeypatch: pytest.MonkeyPatc
|
||||
|
||||
def test_new_settings_leave_html_runtime_unset() -> None:
|
||||
assert SystemSettings().html_runtime == HtmlRuntimeSettings()
|
||||
assert SystemSettings().html_runtime.message_map_tile_min_zoom == 0
|
||||
assert SystemSettings().html_runtime.message_map_tile_max_zoom == 8
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -133,16 +135,46 @@ async def test_admin_can_save_html_runtime_addresses(
|
||||
system_settings_router.HtmlRuntimeSettingsUpdateRequest(
|
||||
base_url="https://users.example",
|
||||
map_tile_url="https://tiles.example/{z}/{x}/{y}.png",
|
||||
message_map_tile_min_zoom=1,
|
||||
message_map_tile_max_zoom=8,
|
||||
),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert response.base_url == "https://users.example/api/public/html-runtime"
|
||||
assert response.map_tile_url == "https://tiles.example/{z}/{x}/{y}.png"
|
||||
assert response.message_map_tile_min_zoom == 1
|
||||
assert response.message_map_tile_max_zoom == 8
|
||||
assert saved[0].html_runtime.base_url == response.base_url
|
||||
assert saved[0].html_runtime.message_map_tile_min_zoom == 1
|
||||
assert saved[0].html_runtime.message_map_tile_max_zoom == 8
|
||||
assert saved[0].prompt_prefix == current.prompt_prefix
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_map_tile_zoom_range_must_be_ordered(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
async def admin_user(_request):
|
||||
return SimpleNamespace(system_role="admin")
|
||||
|
||||
monkeypatch.setattr(system_settings_router, "get_optional_user_from_request", admin_user)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
await system_settings_router.update_html_runtime_settings(
|
||||
system_settings_router.HtmlRuntimeSettingsUpdateRequest(
|
||||
base_url="https://users.example",
|
||||
map_tile_url="https://tiles.example/{z}/{x}/{y}.png",
|
||||
message_map_tile_min_zoom=9,
|
||||
message_map_tile_max_zoom=8,
|
||||
),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 400
|
||||
assert "最小层级不能大于最大层级" in str(error.value.detail)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_html_runtime_address_is_rejected(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user