Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b1b9ef68c | ||
|
|
04cebdc504 |
No files matched your search
@@ -1,15 +1,15 @@
|
||||
---
|
||||
name: release
|
||||
description: Use when the user asks to release, bump version, update changelog/version files, or commit/push a repository release for the Planet repo. Determines version bump type from changes, updates all required version-bearing files, updates changelog and version-history, runs minimal validation, then commits, tags, and pushes.
|
||||
description: Use when the user asks to release, deploy, bump version, update changelog/version files, or commit/push a repository release (`发版`, `部署`, `发版部署`) for the Planet repo. Covers version bumps, validation, commit/tag/push, Gitea/OCI publication, production host script/config sync, and live deployment verification.
|
||||
---
|
||||
|
||||
# Release Workflow
|
||||
|
||||
Use this skill for release-oriented work in this repository.
|
||||
Use this skill for release and production deployment work in this repository.
|
||||
|
||||
## When To Use
|
||||
|
||||
- The user asks to `发版`
|
||||
- The user asks to `发版`, `部署`, `发版部署`, `上线`, or `deploy`
|
||||
- The user asks to bump a version
|
||||
- The user asks to update `CHANGELOG`, `version-history`, or version files as part of a release
|
||||
- The user asks to commit/push a release or a publishable bugfix/feature bundle
|
||||
@@ -213,6 +213,38 @@ attachment names and sizes before publishing. Verify the published Release URL
|
||||
and expected attachments through Gitea before reporting success. If Gitea is
|
||||
unreachable, report the tag and package state and why publication is incomplete.
|
||||
|
||||
### Step 9.5 — Production Host Sync & Live Deployment Verification (Required for `部署` / `发版部署` / `上线`)
|
||||
|
||||
Publishing images/manifests/Gitea assets in Step 9 does **not** deploy or update host-managed files (`发版 ≠ 已部署`). Whenever the user asks to `部署`, `发版部署`, or `上线`, run all four sub-checks before claiming deployment succeeded:
|
||||
|
||||
1. **Detect host-side file drift** against the previous release tag (`<prev_tag>`):
|
||||
|
||||
```bash
|
||||
git diff --name-only <prev_tag>..vx.x.x -- \
|
||||
scripts/production_deploy.py \
|
||||
scripts/production_registry.py \
|
||||
scripts/release_publish.py \
|
||||
deploy/ \
|
||||
docker-compose.deploy.yml
|
||||
```
|
||||
|
||||
2. **Sync changed host-managed files BEFORE rollout/retry** (using the operator's configured SSH access; never hardcode IPs or secrets in repo files):
|
||||
- If `scripts/production_deploy.py`, `scripts/production_registry.py`, or `scripts/release_publish.py` changed -> install onto the production host `/usr/local/lib/planet-release/` **before** triggering or retrying deployment so stale host checks (e.g. newly added `401` auth gates) cannot trigger a false-positive rollback.
|
||||
- If `deploy/systemd/planet-release-deploy.{service,timer}` changed -> install to `/etc/systemd/system/` and run `sudo systemctl daemon-reload`.
|
||||
- If `docker-compose.deploy.yml` or `deploy/nginx/*` changed -> sync env/compose additions into `/opt/planet/current/` or host Nginx sites and run `sudo nginx -t && sudo systemctl reload nginx`.
|
||||
|
||||
3. **Trigger or observe production rollout on host**:
|
||||
- Inspect service status and trigger/retry as needed:
|
||||
- Check logs: `journalctl -u planet-release-deploy.service -n 50 --no-pager`
|
||||
- Verify state / manifest match: `sudo python3 /usr/local/lib/planet-release/production_deploy.py --check`
|
||||
- If an earlier timer run failed (e.g. due to a host-script mismatch) and skipped `vx.x.x`, clear the skip after syncing host scripts by running `sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry` (or `sudo systemctl start planet-release-deploy.service`).
|
||||
- Confirm running containers (`backend`, `admin`, `aiprovider`) are `healthy` and their image digests match OCI `release-manifest:vx.x.x`.
|
||||
|
||||
4. **Verify live public endpoints reflect `vx.x.x`**:
|
||||
- Confirm `https://api.rclaw.top/health/ready` returns HTTP 200 and live version matches `x.x.x`.
|
||||
- When `client.mode != "none"`, confirm `https://rclaw.top/api/v1/client/update-manifest` returns `version == "x.x.x"` and the expected bundle SHA-256.
|
||||
- **Never claim `已部署` if host SSH is unavailable or live endpoints still show an older version**: report publication complete (`dev` / `vx.x.x` / Gitea / OCI) separately from the exact pending host sync / deploy commands.
|
||||
|
||||
### Step 10 — Completion summary
|
||||
|
||||
```
|
||||
@@ -225,6 +257,8 @@ unreachable, report the tag and package state and why publication is incomplete.
|
||||
✓ tag: v0.76.19
|
||||
✓ Pushed to origin/dev (or reported pending manual push)
|
||||
✓ Gitea Release and attachments verified (when publication was requested)
|
||||
✓ Host-side deploy scripts / Compose / Nginx drift checked & synced (when deployment was requested)
|
||||
✓ Production rollout & live endpoints verified at target version (or pending host steps listed explicitly)
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
@@ -90,6 +90,7 @@ the user's login interactive shell instead of assuming a specific dotfile.
|
||||
- `planet.sh` owns local lifecycle, ports, WSL/LAN behavior, and destructive
|
||||
`destroy` cleanup.
|
||||
- Frontend package management is Bun-only. Do not use npm, pnpm, or yarn.
|
||||
- **Local Frontend Dev Uses Vite, Not Static Nginx**: Local frontend/Admin development defaults to the host Vite HMR server (`./planet.sh start` / `./planet.sh restart -f`); do not run or rebuild the static Nginx `planet_admin` container (`./planet.sh admin ...`) unless the user explicitly asks to simulate production locally (`本地模拟线上`).
|
||||
- Frontend changes must satisfy `scripts/harness/frontend-rules-check.sh`; use
|
||||
rendered smoke evidence for public pages, auth guards, authenticated admin
|
||||
route/section availability, safe navigation/search/tab interactions, mobile
|
||||
@@ -131,6 +132,16 @@ the user's login interactive shell instead of assuming a specific dotfile.
|
||||
`release-manifest:<tag>` and must **not** create a Gitea Release; only
|
||||
`hotfix` or `full` client releases create a Gitea Release, and production
|
||||
`planet-release-deploy` reconciles from Git tags + OCI `release-manifest:<tag>`.
|
||||
- **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**:
|
||||
`scripts/release_publish.py` only publishes container images, OCI
|
||||
`release-manifest:<tag>`, and optional Gitea Releases; it never updates
|
||||
host-side files or verifies rollout. Whenever the user asks to `部署`,
|
||||
`发版部署`, or `上线`, follow `.codex/skills/release/SKILL.md` to diff
|
||||
host-managed files (`scripts/production_deploy.py`, `deploy/`,
|
||||
`docker-compose.deploy.yml`) against the prior tag, sync any changed host
|
||||
files before rollout/retry, inspect `planet-release-deploy.service`, and
|
||||
verify live public endpoints reflect the target version before claiming
|
||||
deployment succeeded.
|
||||
|
||||
### Conflict Policy
|
||||
|
||||
|
||||
@@ -13,42 +13,35 @@
|
||||
- **Admin 运维台**:支持通过 `PLANET_FRONTEND_TARGET=admin` 构建剔除 Earth 静态资源(约 110 MB)的轻量 Nginx 容器 `planet_admin`,也可保留在一体化 Web 开发服务中。
|
||||
- **后端与模型适配层**:FastAPI 数据与 AI 编排后端 + `aiprovider` 独立模型协议适配层。
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ 浏览器展示与运维层 │
|
||||
│ ┌──────────────────────────────┐ ┌──────────────────────────────┐ │
|
||||
│ │ Web Earth │ │ React 运维台 │ │
|
||||
│ │ frontend/public/earth │ │ frontend/src │ │
|
||||
│ │ Three.js 地球 / HUD / 新闻 │ │ 数据源 / 告警 / AI 设置 │ │
|
||||
│ │ 国界精度 / 品牌内容配置 │ │ 提示词配置 / 用户与系统配置 │ │
|
||||
│ └──────────────────────────────┘ └──────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
│ REST / WebSocket
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ FastAPI 业务与编排后端 │
|
||||
│ ┌────────────────────┐ ┌────────────────────┐ ┌─────────────────┐ │
|
||||
│ │ 数据 API 与认证 │ │ Earth 新闻增强 │ │ 告警与态势简报 │ │
|
||||
│ │ JWT / 权限 / 审计 │ │ 位置推断 / 本地化 │ │ BGP / 告警研判 │ │
|
||||
│ └────────────────────┘ └────────────────────┘ └─────────────────┘ │
|
||||
│ ┌────────────────────┐ ┌────────────────────┐ ┌─────────────────┐ │
|
||||
│ │ 系统运行配置 │ │ 默认提示词注册表 │ │ 未来 Agent Runtime│ │
|
||||
│ │ system_settings │ │ 代码发布 + DB 覆盖 │ │ 工具/证据/工作流 │ │
|
||||
│ └────────────────────┘ └────────────────────┘ └─────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
│ SQLAlchemy / Redis Stream │ 纯净 LLM 调用
|
||||
▼ ▼
|
||||
┌──────────────────────────────┐ ┌──────────────────────────────┐
|
||||
│ PostgreSQL / Redis │ │ aiprovider │
|
||||
│ 用户、配置、采集结果、新闻 │ │ provider + protocol adapter │
|
||||
│ Stream、缓存、运行状态 │ │ OpenAI / MiniMax / Ollama 等 │
|
||||
└──────────────────────────────┘ └──────────────────────────────┘
|
||||
▲
|
||||
│ 采集器 / 外部数据源
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ RSS 新闻、BGP 观测、公开数据源、后续 WebSearch/OCR/语音识别等工具 │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph UI["展示与运维端"]
|
||||
Earth["Web / Electron Earth (frontend/public/earth + client)"]
|
||||
Admin["React 运维台与 AI 参谋 (frontend/src/admin)"]
|
||||
end
|
||||
|
||||
subgraph Backend["FastAPI 业务与 AI 编排后端 (backend/)"]
|
||||
API["业务 API、认证与反爬网关"]
|
||||
DAG["DAG 多节点工作流引擎与工具白名单"]
|
||||
Evolve["三层工作流自进化与宪法校验内核"]
|
||||
Settings["系统配置与默认提示词 (system_settings / default_prompts)"]
|
||||
end
|
||||
|
||||
subgraph Infra["数据存储与模型协议层"]
|
||||
PG["PostgreSQL / Redis (数据、快照、运行轨迹与进化台账)"]
|
||||
AIP["aiprovider 独立协议网关 (OpenAI / MiniMax / Ollama 等)"]
|
||||
Sources["外部采集源 (RSS / BGP / PeeringDB / 海缆 / 卫星 / WebSearch)"]
|
||||
end
|
||||
|
||||
Earth -->|"REST / SSE / WebSocket"| API
|
||||
Admin -->|"REST / SSE"| API
|
||||
API --> DAG
|
||||
API --> Settings
|
||||
DAG -->|"运行遥测与灰度检查"| Evolve
|
||||
Evolve -->|"受宪法约束写回草稿 / 发布 / 回滚"| PG
|
||||
API --> PG
|
||||
DAG -->|"纯净模型请求"| AIP
|
||||
Sources -->|"采集与增强写入"| PG
|
||||
```
|
||||
|
||||
架构边界:
|
||||
@@ -57,7 +50,32 @@
|
||||
- `aiprovider` 只负责把纯净模型请求适配到不同供应商或协议,不内置具体业务提示词。
|
||||
- 默认提示词随代码发布并保存在 `backend/app/ai_tasks/default_prompts.json`,运维台可在数据库中保存覆盖值,重置时回到当前代码版本的默认提示词。
|
||||
- Earth 新闻保留英文原文,中文展示结果存入 `localizations`,前端默认展示 `zh-CN` 的 `display_title`、`display_summary` 和中文地域/状态文案。
|
||||
- Earth LLM 指令、语音识别、多角色态势研判属于后续 Agent Runtime 方向,计划见 [docs/plans/agents-earth-command-runtime-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-earth-command-runtime-plan.md)。
|
||||
- AI 工作流支持可视化编排、自进化调优与地球交互联动,规划与演进记录见 [AI 参谋工作流与自进化方案](docs/plans/ai-advisor-workflow-and-location-agent-plan.md) 与 [Earth 贴地影响范围与三维视觉升级方案](docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md)。
|
||||
|
||||
## AI 工作流自进化与元进化
|
||||
|
||||
为避免“人工写死工作流无法随新模型与真实运行退化持续迭代”,系统内置了 **零改表、三层有界自举架构**(详见 [workflow_evolver.py](backend/app/services/ai/workflow_evolver.py)):
|
||||
|
||||
- **Tier 0 · 不可变宪法内核(Python 硬约束)**:AI 永远无法修改底层校验代码。强制执行单层元递归锁(禁止自定义 `meta.*`)、冻结元引擎 `verify_output` 节点、限制单次自动改动半径(`<= 2` 个且 `<= 40%` 节点)、强制冷却期与每日自动预算上限,以及 **5 次运行灰度自动回滚**。
|
||||
- **Tier 1 · 业务工作流自优化与模型适配**:零成本采集 `WorkflowRun.budget_used` 中的模型名、耗时、版本号与 👍/👎 反馈;结合 0-Token 健康诊断、模型能力漂移检测、DGM 历史最佳父版本分支与 AFlow 正负经验生成最小节点补丁,并支持 Fixture A/B 对照与从高频问题孵化新工作流。可在管理台 `/advisor/workflows` 顶栏随时切换 `关闭(手动)` / `自动写草稿` / `自动发布 + 灰度回滚` 模式及单工作流锁定开关。
|
||||
- **Tier 2 · 元进化(`meta.workflow_evolver` 自举)**:内置三节点元工作流直接在工作流画布可见、可回滚;在独立开启元进化开关后,可依据历史台账验证/回滚客观结果迭代自身诊断与补丁合成策略,并受 7 天冷却与下游 3 次结果窗口自动回退保护。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Run["Playground / Earth 工作流运行 (记录 model_used / latency / 版本号)"] --> FB["管理员 👍 / 👎 反馈与失败轨迹"]
|
||||
FB --> Health["0-Token 健康与模型漂移诊断 (信号检测 + DGM 最佳父版本)"]
|
||||
Health -->|"手动触发或满足冷却/预算后异步触发"| Meta["Tier 2 元引擎 meta.workflow_evolver (diag_node -> patch_node -> verify_output)"]
|
||||
Ledger["进化台账 system_settings.ai_evolution_ledger (正负经验 / 已验证 / 已回滚)"] -->|"AFlow 经验注入"| Meta
|
||||
Meta -->|"生成最小节点 Diff 补丁"| Tier0{"Tier 0 不可变宪法内核:白名单 / 半径锁 / 禁清空提示词 / 禁 meta 递归"}
|
||||
Tier0 -->|"拦截"| Block["记入台账 blocked 并保留原版本"]
|
||||
Tier0 -->|"通过"| Mode{"策略模式 (off / draft / auto)"}
|
||||
Mode -->|"draft"| Draft["写入 draft_graph 待人工审核 / Fixture A-B 对照"]
|
||||
Mode -->|"auto (未锁定且未超日上限)"| Canary["自动发布新版本 + 开启 5 次运行灰度窗口"]
|
||||
Canary -->|"连续 2 次失败或差评率超阈"| Rollback["自动回滚上一稳定版本 & 记为 rolled_back"]
|
||||
Canary -->|"通过 5 次运行验证"| Verified["晋升为 verified 经验;积累 >=5 条后可触发元引擎自举"]
|
||||
Verified --> Ledger
|
||||
Rollback --> Ledger
|
||||
```
|
||||
|
||||
## 四大核心要素
|
||||
|
||||
@@ -239,7 +257,7 @@ bun run build
|
||||
|
||||
推荐按下面顺序排查和配置。
|
||||
|
||||
端口占用、`iphlpsvc` / portproxy、摄像头和依赖问题的集中排障入口见 [常见问题](/home/ray/dev/linkong/planet/docs/technical/zh/faq.md)。
|
||||
端口占用、`iphlpsvc` / portproxy、摄像头和依赖问题的集中排障入口见 [常见问题](docs/technical/zh/faq.md)。
|
||||
|
||||
### 1. 在 WSL 中启动服务
|
||||
|
||||
@@ -381,7 +399,7 @@ DATABASE_RETRY_INTERVAL=10 \
|
||||
|
||||
- 运维台 AI 设置可维护 provider、模型、协议、超时、token 等运行配置。
|
||||
- 运维台 AI 设置中的“提示词”页可选择不同功能入口,手动覆盖提示词,并一键重置到默认值。
|
||||
- 默认提示词随代码发布,位于 [backend/app/ai_tasks/default_prompts.json](/home/ray/dev/linkong/planet/backend/app/ai_tasks/default_prompts.json)。
|
||||
- 默认提示词随代码发布,位于 [backend/app/ai_tasks/default_prompts.json](backend/app/ai_tasks/default_prompts.json)。
|
||||
- 覆盖值保存在数据库运行配置中,升级代码后可继续保留现场配置,也可重置到新版本默认提示词。
|
||||
- 态势摘要、告警研判、新闻本地化等入口应使用各自任务提示词;调用 `aiprovider` 时只传递当前任务所需的 `prompt` / `system_prompt`。
|
||||
|
||||
@@ -427,8 +445,8 @@ AI_ANTHROPIC_VERSION=2023-06-01
|
||||
|
||||
如果你要本地直接起模型适配层,项目里已经补了模板:
|
||||
|
||||
- [aiprovider/.env.example](/home/ray/dev/linkong/planet/aiprovider/.env.example)
|
||||
- [docker-compose.local-model.yml](/home/ray/dev/linkong/planet/docker-compose.local-model.yml)
|
||||
- [aiprovider/.env.example](aiprovider/.env.example)
|
||||
- [docker-compose.local-model.yml](docker-compose.local-model.yml)
|
||||
|
||||
运行与调用补充:
|
||||
|
||||
@@ -439,13 +457,14 @@ AI_ANTHROPIC_VERSION=2023-06-01
|
||||
|
||||
详细文档:
|
||||
|
||||
- [docs/technical/zh/agents-aiprovider.md](/home/ray/dev/linkong/planet/docs/technical/zh/agents-aiprovider.md)
|
||||
- [docs/technical/en/agents-aiprovider.md](/home/ray/dev/linkong/planet/docs/technical/en/agents-aiprovider.md)
|
||||
- [aiprovider/README.md](/home/ray/dev/linkong/planet/aiprovider/README.md)
|
||||
- [docs/technical/frontend-layout-guidelines.md](/home/ray/dev/linkong/planet/docs/technical/frontend-layout-guidelines.md)
|
||||
- [docs/plans/frontend-ai-playground-development-plan.md](/home/ray/dev/linkong/planet/docs/plans/frontend-ai-playground-development-plan.md)
|
||||
- [docs/plans/agents-situational-awareness-foundation-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-situational-awareness-foundation-plan.md)
|
||||
- [docs/plans/agents-earth-command-runtime-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-earth-command-runtime-plan.md)
|
||||
- [docs/technical/zh/agents-aiprovider.md](docs/technical/zh/agents-aiprovider.md)
|
||||
- [docs/technical/en/agents-aiprovider.md](docs/technical/en/agents-aiprovider.md)
|
||||
- [aiprovider/README.md](aiprovider/README.md)
|
||||
- [docs/technical/zh/frontend-layout-guidelines.md](docs/technical/zh/frontend-layout-guidelines.md)
|
||||
- [docs/plans/ai-advisor-workflow-and-location-agent-plan.md](docs/plans/ai-advisor-workflow-and-location-agent-plan.md)
|
||||
- [docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md](docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md)
|
||||
- [docs/plans/agents-situational-awareness-foundation-plan.md](docs/plans/agents-situational-awareness-foundation-plan.md)
|
||||
- [docs/plans/agents-earth-command-runtime-plan.md](docs/plans/agents-earth-command-runtime-plan.md)
|
||||
|
||||
## 前端页面布局规范
|
||||
|
||||
@@ -458,8 +477,8 @@ AI_ANTHROPIC_VERSION=2023-06-01
|
||||
|
||||
当前推荐参考实现:
|
||||
|
||||
- [frontend/src/pages/BGP/BGP.tsx](/home/ray/dev/linkong/planet/frontend/src/pages/BGP/BGP.tsx)
|
||||
- [docs/technical/frontend-layout-guidelines.md](/home/ray/dev/linkong/planet/docs/technical/frontend-layout-guidelines.md)
|
||||
- [frontend/src/admin/pages/AdvisorWorkflows.tsx](frontend/src/admin/pages/AdvisorWorkflows.tsx)
|
||||
- [docs/technical/zh/frontend-layout-guidelines.md](docs/technical/zh/frontend-layout-guidelines.md)
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -124,6 +124,7 @@ class ProviderService:
|
||||
tool_choice = getattr(payload, "tool_choice", None)
|
||||
response_format = getattr(payload, "response_format", None)
|
||||
native_web_search = bool(getattr(payload, "native_web_search", False))
|
||||
images = self._normalize_images(getattr(payload, "images", None))
|
||||
tool_calls: list[ToolCallRecord] = []
|
||||
stop_reason: str | None = None
|
||||
|
||||
@@ -136,6 +137,7 @@ class ProviderService:
|
||||
tools=tools,
|
||||
tool_choice=tool_choice,
|
||||
response_format=response_format,
|
||||
images=images,
|
||||
)
|
||||
content = self._extract_openai_content(data)
|
||||
content_blocks = self._extract_openai_blocks(data)
|
||||
@@ -153,6 +155,7 @@ class ProviderService:
|
||||
tool_choice=tool_choice,
|
||||
response_format=response_format,
|
||||
native_web_search=native_web_search,
|
||||
images=images,
|
||||
)
|
||||
content_blocks = self._extract_responses_blocks(data)
|
||||
content = "".join(block.text for block in content_blocks if block.text)
|
||||
@@ -169,6 +172,7 @@ class ProviderService:
|
||||
tool_choice=tool_choice,
|
||||
response_format=response_format,
|
||||
native_web_search=native_web_search,
|
||||
images=images,
|
||||
)
|
||||
content = self._extract_anthropic_content(data)
|
||||
content_blocks = self._extract_anthropic_blocks(data)
|
||||
@@ -181,6 +185,7 @@ class ProviderService:
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
response_format=response_format,
|
||||
images=images,
|
||||
)
|
||||
content = self._extract_ollama_content(data)
|
||||
content_blocks = self._extract_ollama_blocks(data)
|
||||
@@ -230,6 +235,7 @@ class ProviderService:
|
||||
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
|
||||
|
||||
provider_api = self._resolve_model_provider_api(model)
|
||||
images = self._normalize_images(getattr(payload, "images", None))
|
||||
yield {"event": "start", "provider": self.provider, "model": model}
|
||||
|
||||
if provider_api == "anthropic-messages":
|
||||
@@ -239,24 +245,37 @@ class ProviderService:
|
||||
payload.thinking,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
images=images,
|
||||
):
|
||||
yield item
|
||||
return
|
||||
if provider_api == "openai-completions":
|
||||
async for item in self._stream_openai_compatible(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
model,
|
||||
prompt,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
images=images,
|
||||
):
|
||||
yield item
|
||||
return
|
||||
if provider_api == "openai-responses":
|
||||
async for item in self._stream_openai_responses(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
model,
|
||||
prompt,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
images=images,
|
||||
):
|
||||
yield item
|
||||
return
|
||||
if provider_api == "ollama-generate":
|
||||
async for item in self._stream_ollama(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
model,
|
||||
prompt,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
images=images,
|
||||
):
|
||||
yield item
|
||||
return
|
||||
@@ -308,6 +327,7 @@ class ProviderService:
|
||||
tool_choice: str | dict[str, Any] | None = None,
|
||||
response_format: dict[str, Any] | None = None,
|
||||
native_web_search: bool = False,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> tuple[str, dict[str, str], dict[str, Any]]:
|
||||
anthropic_messages: list[dict[str, Any]] = []
|
||||
source_messages = (
|
||||
@@ -357,6 +377,8 @@ class ProviderService:
|
||||
{"role": role or "user", "content": [{"type": "text", "text": str(msg.get("content") or "")}]}
|
||||
)
|
||||
|
||||
self._apply_images_to_messages(anthropic_messages, images or [], "anthropic")
|
||||
|
||||
resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(thinking, model)
|
||||
thinking_active = bool(
|
||||
resolved_thinking
|
||||
@@ -438,7 +460,8 @@ class ProviderService:
|
||||
thinking: dict[str, Any] | None = None,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
conversation_messages: list[dict[str, Any]] | None = None,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
path, headers, request_body = self._build_anthropic_request(
|
||||
model,
|
||||
@@ -447,6 +470,7 @@ class ProviderService:
|
||||
system_prompt,
|
||||
stream=True,
|
||||
conversation_messages=conversation_messages,
|
||||
images=images,
|
||||
)
|
||||
resolved_model = model
|
||||
usage: dict[str, Any] = {}
|
||||
@@ -509,16 +533,18 @@ class ProviderService:
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
conversation_messages: list[dict[str, Any]] | None = None,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
messages = []
|
||||
messages: list[dict[str, Any]] = []
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
messages.append({"role": "system", "content": resolved_system_prompt})
|
||||
if conversation_messages and len(conversation_messages) > 1:
|
||||
messages.extend(conversation_messages)
|
||||
messages.extend(dict(m) for m in conversation_messages)
|
||||
else:
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
self._apply_images_to_messages(messages, images or [], "openai-completions")
|
||||
request_body = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
@@ -577,13 +603,15 @@ class ProviderService:
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
conversation_messages: list[dict[str, Any]] | None = None,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
responses_input: Any = (
|
||||
[{"role": m["role"], "content": m["content"]} for m in conversation_messages]
|
||||
if (conversation_messages and len(conversation_messages) > 1)
|
||||
else prompt
|
||||
)
|
||||
responses_input = self._apply_images_to_responses_input(responses_input, images or [])
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"input": responses_input,
|
||||
@@ -639,7 +667,8 @@ class ProviderService:
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
conversation_messages: list[dict[str, Any]] | None = None,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
ollama_prompt = self._format_ollama_prompt(prompt, conversation_messages)
|
||||
request_body: dict[str, Any] = {
|
||||
@@ -648,6 +677,8 @@ class ProviderService:
|
||||
"prompt": ollama_prompt,
|
||||
"options": {"temperature": 0.2, "num_predict": self.max_tokens},
|
||||
}
|
||||
if images:
|
||||
request_body["images"] = [img["data_base64"] for img in images if img.get("data_base64")]
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
request_body["system"] = resolved_system_prompt
|
||||
@@ -796,6 +827,100 @@ class ProviderService:
|
||||
sections.append(f"附加上下文:\n{context_json}")
|
||||
return "\n\n".join(sections)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_images(images: list[Any] | None) -> list[dict[str, str]]:
|
||||
normalized: list[dict[str, str]] = []
|
||||
for raw in images or []:
|
||||
if isinstance(raw, dict):
|
||||
mime = str(raw.get("mime_type") or "").strip().lower()
|
||||
data = str(raw.get("data_base64") or "").strip()
|
||||
name = str(raw.get("name") or "").strip()
|
||||
else:
|
||||
mime = str(getattr(raw, "mime_type", "") or "").strip().lower()
|
||||
data = str(getattr(raw, "data_base64", "") or "").strip()
|
||||
name = str(getattr(raw, "name", "") or "").strip()
|
||||
if mime == "image/jpg":
|
||||
mime = "image/jpeg"
|
||||
if not mime.startswith("image/") or not data:
|
||||
continue
|
||||
normalized.append({"mime_type": mime, "data_base64": data, "name": name})
|
||||
if len(normalized) >= 8:
|
||||
break
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _apply_images_to_messages(
|
||||
messages: list[dict[str, Any]],
|
||||
images: list[dict[str, str]],
|
||||
api_style: str,
|
||||
) -> None:
|
||||
"""Attach base64 images onto the final user turn for Anthropic or OpenAI chat payloads."""
|
||||
if not images or not messages:
|
||||
return
|
||||
for idx in range(len(messages) - 1, -1, -1):
|
||||
if messages[idx].get("role") != "user":
|
||||
continue
|
||||
if api_style == "anthropic":
|
||||
content = messages[idx].get("content")
|
||||
blocks = list(content) if isinstance(content, list) else [{"type": "text", "text": str(content or "")}]
|
||||
for img in images:
|
||||
blocks.append(
|
||||
{
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": img["mime_type"],
|
||||
"data": img["data_base64"],
|
||||
},
|
||||
}
|
||||
)
|
||||
messages[idx]["content"] = blocks
|
||||
else:
|
||||
text = str(messages[idx].get("content") or "")
|
||||
blocks = [{"type": "text", "text": text}]
|
||||
for img in images:
|
||||
blocks.append(
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:{img['mime_type']};base64,{img['data_base64']}"},
|
||||
}
|
||||
)
|
||||
messages[idx]["content"] = blocks
|
||||
break
|
||||
|
||||
@staticmethod
|
||||
def _apply_images_to_responses_input(
|
||||
responses_input: Any,
|
||||
images: list[dict[str, str]],
|
||||
) -> Any:
|
||||
"""Attach base64 images onto OpenAI Responses API input items."""
|
||||
if not images:
|
||||
return responses_input
|
||||
image_blocks = [
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": f"data:{img['mime_type']};base64,{img['data_base64']}",
|
||||
}
|
||||
for img in images
|
||||
]
|
||||
if isinstance(responses_input, str):
|
||||
return [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [{"type": "input_text", "text": responses_input}, *image_blocks],
|
||||
}
|
||||
]
|
||||
if isinstance(responses_input, list):
|
||||
items = [dict(item) if isinstance(item, dict) else item for item in responses_input]
|
||||
for idx in range(len(items) - 1, -1, -1):
|
||||
item = items[idx]
|
||||
if isinstance(item, dict) and item.get("role") == "user":
|
||||
text = str(item.get("content") or "")
|
||||
item["content"] = [{"type": "input_text", "text": text}, *image_blocks]
|
||||
break
|
||||
return items
|
||||
return responses_input
|
||||
|
||||
def _resolve_system_prompt(self, system_prompt: str | None) -> str | None:
|
||||
resolved = str(system_prompt or "").strip()
|
||||
return resolved or None
|
||||
@@ -810,6 +935,7 @@ class ProviderService:
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
tool_choice: str | dict[str, Any] | None = None,
|
||||
response_format: dict[str, Any] | None = None,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
messages: list[dict[str, Any]] = []
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
@@ -857,6 +983,8 @@ class ProviderService:
|
||||
else:
|
||||
messages.append({"role": role, "content": str(msg.get("content") or "")})
|
||||
|
||||
self._apply_images_to_messages(messages, images or [], "openai-completions")
|
||||
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
@@ -912,6 +1040,7 @@ class ProviderService:
|
||||
tool_choice: str | dict[str, Any] | None = None,
|
||||
response_format: dict[str, Any] | None = None,
|
||||
native_web_search: bool = False,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
has_multi_or_tools = bool(
|
||||
conversation_messages
|
||||
@@ -955,6 +1084,8 @@ class ProviderService:
|
||||
else:
|
||||
responses_input = prompt
|
||||
|
||||
responses_input = self._apply_images_to_responses_input(responses_input, images or [])
|
||||
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"input": responses_input,
|
||||
@@ -1040,6 +1171,7 @@ class ProviderService:
|
||||
tool_choice: str | dict[str, Any] | None = None,
|
||||
response_format: dict[str, Any] | None = None,
|
||||
native_web_search: bool = False,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
path, headers, request_body = self._build_anthropic_request(
|
||||
model,
|
||||
@@ -1052,6 +1184,7 @@ class ProviderService:
|
||||
tool_choice=tool_choice,
|
||||
response_format=response_format,
|
||||
native_web_search=native_web_search,
|
||||
images=images,
|
||||
)
|
||||
return await self._post(
|
||||
path=path,
|
||||
@@ -1106,6 +1239,7 @@ class ProviderService:
|
||||
*,
|
||||
conversation_messages: list[dict[str, Any]] | None = None,
|
||||
response_format: dict[str, Any] | None = None,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
@@ -1116,6 +1250,8 @@ class ProviderService:
|
||||
"num_predict": self.max_tokens,
|
||||
},
|
||||
}
|
||||
if images:
|
||||
request_body["images"] = [img["data_base64"] for img in images if img.get("data_base64")]
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
request_body["system"] = resolved_system_prompt
|
||||
|
||||
@@ -17,6 +17,12 @@ class ToolCallRecord(BaseModel):
|
||||
arguments: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class ImageAttachment(BaseModel):
|
||||
mime_type: str = Field(..., pattern=r"^image/(png|jpeg|jpg|webp|gif)$")
|
||||
data_base64: str = Field(..., min_length=8, max_length=6_000_000)
|
||||
name: str = Field(default="", max_length=200)
|
||||
|
||||
|
||||
class AIContentBlock(BaseModel):
|
||||
type: str
|
||||
text: str | None = None
|
||||
@@ -39,6 +45,7 @@ class SituationalAnalysisRequest(BaseModel):
|
||||
tool_choice: str | dict[str, Any] | None = None
|
||||
response_format: dict[str, Any] | None = None
|
||||
native_web_search: bool = False
|
||||
images: list[ImageAttachment] = Field(default_factory=list, max_length=8)
|
||||
|
||||
|
||||
class SituationalAnalysisResponse(BaseModel):
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -20,17 +20,44 @@ from app.db.session import get_db
|
||||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.models.user import User
|
||||
from app.schemas.ai import ChatMessage, SituationalAnalysisRequest
|
||||
from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest
|
||||
from app.services.ai.dag_executor import run_workflow_dag_stream
|
||||
from app.services.ai.thinking_sanitizer import strip_thinking_text
|
||||
from app.services.ai.tool_registry import (
|
||||
SSRFBlockedError,
|
||||
isolate_untrusted_external_text,
|
||||
safe_web_fetch,
|
||||
)
|
||||
from app.services.ai.workflow_evolver import (
|
||||
FIXTURE_EXPECT_KEY,
|
||||
compute_workflow_health,
|
||||
dismiss_ledger_entry,
|
||||
get_evolution_ledger,
|
||||
get_evolution_policy,
|
||||
incubate_workflow_from_runs,
|
||||
normalize_fixture_expect,
|
||||
propose_meta_evolution,
|
||||
propose_workflow_evolution,
|
||||
record_run_feedback,
|
||||
run_fixture_ab_eval,
|
||||
schedule_post_run_evolution,
|
||||
update_evolution_policy,
|
||||
)
|
||||
from app.services.ai.workflow_registry import (
|
||||
clone_workflow,
|
||||
create_workflow,
|
||||
delete_workflow,
|
||||
discard_workflow_draft,
|
||||
ensure_builtin_workflows,
|
||||
generate_workflow_optimization_proposal,
|
||||
get_workflow_detail,
|
||||
list_public_workflow_bindings,
|
||||
list_workflows,
|
||||
publish_workflow,
|
||||
resolve_runtime_workflow_node,
|
||||
rollback_workflow,
|
||||
save_workflow_draft,
|
||||
update_workflow_metadata,
|
||||
)
|
||||
from app.services.ai_client import get_ai_provider_client
|
||||
from app.services.alert_ai_brief import build_alert_brief_request
|
||||
@@ -49,13 +76,56 @@ logger = get_logger(__name__, service="ai_workflows")
|
||||
|
||||
class WorkflowDraftUpdateRequest(BaseModel):
|
||||
graph: dict[str, Any]
|
||||
bindings: dict[str, Any] | None = None
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class WorkflowPublishRequest(BaseModel):
|
||||
graph: dict[str, Any] | None = None
|
||||
bindings: dict[str, Any] | None = None
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
change_summary: str = ""
|
||||
|
||||
|
||||
class WorkflowCreateRequest(BaseModel):
|
||||
workflow_id: str | None = Field(default=None, max_length=80)
|
||||
name: str = Field(..., min_length=1, max_length=160)
|
||||
name_en: str = Field(default="", max_length=160)
|
||||
category: str = Field(default="custom", max_length=60)
|
||||
description: str = Field(default="", max_length=2000)
|
||||
description_en: str = Field(default="", max_length=2000)
|
||||
graph: dict[str, Any] | None = None
|
||||
bindings: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class WorkflowCloneRequest(BaseModel):
|
||||
workflow_id: str | None = Field(default=None, max_length=80)
|
||||
name: str | None = Field(default=None, max_length=160)
|
||||
name_en: str | None = Field(default=None, max_length=160)
|
||||
|
||||
|
||||
class WorkflowMetadataUpdateRequest(BaseModel):
|
||||
name: str | None = Field(default=None, max_length=160)
|
||||
name_en: str | None = Field(default=None, max_length=160)
|
||||
category: str | None = Field(default=None, max_length=60)
|
||||
description: str | None = Field(default=None, max_length=2000)
|
||||
description_en: str | None = Field(default=None, max_length=2000)
|
||||
bindings: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class EarthTargetInput(BaseModel):
|
||||
entity_type: str = Field(..., min_length=1, max_length=64)
|
||||
entity_id: str | None = Field(default=None, max_length=160)
|
||||
label: str = Field(default="", max_length=200)
|
||||
latitude: float | None = None
|
||||
longitude: float | None = None
|
||||
layer: str | None = Field(default=None, max_length=80)
|
||||
kind: str | None = Field(default=None, max_length=80)
|
||||
properties: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class WorkflowRollbackRequest(BaseModel):
|
||||
revision: int = Field(..., ge=1)
|
||||
|
||||
@@ -65,12 +135,52 @@ class WorkflowOptimizeRequest(BaseModel):
|
||||
run_id: str | None = None
|
||||
|
||||
|
||||
class WorkflowRunFeedbackRequest(BaseModel):
|
||||
rating: Literal[-1, 0, 1]
|
||||
note: str = Field(default="", max_length=500)
|
||||
|
||||
|
||||
class EvolutionPolicyUpdateRequest(BaseModel):
|
||||
business_mode: Literal["off", "draft", "auto"] | None = None
|
||||
meta_mode: Literal["off", "draft", "auto"] | None = None
|
||||
daily_auto_budget: int | None = Field(default=None, ge=1, le=20)
|
||||
business_cooldown_hours: int | None = Field(default=None, ge=1, le=168)
|
||||
meta_cooldown_days: int | None = Field(default=None, ge=1, le=30)
|
||||
locked_workflows: list[str] | None = None
|
||||
auto_adapt_on_model_change: bool | None = None
|
||||
|
||||
|
||||
class EvolutionProposeRequest(BaseModel):
|
||||
mode: Literal["optimize", "model_adapt"] = "optimize"
|
||||
instruction: str = Field(default="", max_length=2000)
|
||||
run_id: str | None = None
|
||||
apply_mode: Literal["preview", "draft", "auto"] = "preview"
|
||||
branch_from_best: bool = False
|
||||
|
||||
|
||||
class EvolutionEvalRequest(BaseModel):
|
||||
proposed_graph: dict[str, Any]
|
||||
max_fixtures: int = Field(default=3, ge=1, le=5)
|
||||
|
||||
|
||||
class MetaEvolveRequest(BaseModel):
|
||||
instruction: str = Field(default="", max_length=2000)
|
||||
apply_mode: Literal["preview", "draft", "auto"] = "preview"
|
||||
|
||||
|
||||
class LedgerDismissRequest(BaseModel):
|
||||
reason: str = Field(default="", max_length=300)
|
||||
|
||||
|
||||
class WorkflowFixtureCreateRequest(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=160)
|
||||
description: str = ""
|
||||
earth_context: dict[str, Any] = Field(default_factory=dict)
|
||||
context_json: dict[str, Any] | None = None
|
||||
sample_question: str = ""
|
||||
# Gradable assertions: numbers / must_include / must_not_include /
|
||||
# require_uncertainty_without_evidence / min_evidence (stored in context_json["expect"]).
|
||||
expect: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class AdvisorChatMessageInput(BaseModel):
|
||||
@@ -78,12 +188,29 @@ class AdvisorChatMessageInput(BaseModel):
|
||||
content: str = Field(..., min_length=1, max_length=16000)
|
||||
|
||||
|
||||
class PlaygroundLinkParseRequest(BaseModel):
|
||||
url: str = Field(..., min_length=4, max_length=2000)
|
||||
|
||||
|
||||
class PlaygroundAttachmentInput(BaseModel):
|
||||
kind: Literal["image", "video", "link", "json", "text"]
|
||||
name: str = Field(default="", max_length=240)
|
||||
mime_type: str = Field(default="", max_length=120)
|
||||
url: str | None = Field(default=None, max_length=2000)
|
||||
text_content: str | None = Field(default=None, max_length=32000)
|
||||
json_data: Any = None
|
||||
images: list[ImageAttachment] = Field(default_factory=list, max_length=6)
|
||||
metadata: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class AdvisorPlaygroundChatRequest(BaseModel):
|
||||
workflow_id: str = "default.general"
|
||||
use_draft: bool = False
|
||||
message: str = Field(..., min_length=1, max_length=16000)
|
||||
message: str = Field(default="", max_length=16000)
|
||||
history: list[AdvisorChatMessageInput] = Field(default_factory=list)
|
||||
earth_context: dict[str, Any] | None = None
|
||||
attachments: list[PlaygroundAttachmentInput] = Field(default_factory=list, max_length=8)
|
||||
targets: list[EarthTargetInput] = Field(default_factory=list, max_length=8)
|
||||
model_override: str | None = None
|
||||
|
||||
|
||||
@@ -104,6 +231,81 @@ async def list_ai_workflows(
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
@router.get("/workflows/bindings")
|
||||
async def get_public_earth_workflow_bindings(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Public-safe list of enabled published workflows and their Earth interaction bindings."""
|
||||
items = await list_public_workflow_bindings(db)
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
@router.post("/workflows")
|
||||
async def create_ai_workflow(
|
||||
payload: WorkflowCreateRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await create_workflow(
|
||||
db,
|
||||
workflow_id=payload.workflow_id,
|
||||
name=payload.name,
|
||||
name_en=payload.name_en,
|
||||
category=payload.category,
|
||||
description=payload.description,
|
||||
description_en=payload.description_en,
|
||||
graph=payload.graph,
|
||||
bindings=payload.bindings,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/clone")
|
||||
async def clone_ai_workflow(
|
||||
workflow_id: str,
|
||||
payload: WorkflowCloneRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await clone_workflow(
|
||||
db,
|
||||
workflow_id,
|
||||
workflow_id=payload.workflow_id,
|
||||
name=payload.name,
|
||||
name_en=payload.name_en,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/workflows/{workflow_id}")
|
||||
async def patch_ai_workflow_metadata(
|
||||
workflow_id: str,
|
||||
payload: WorkflowMetadataUpdateRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await update_workflow_metadata(
|
||||
db,
|
||||
workflow_id,
|
||||
name=payload.name,
|
||||
name_en=payload.name_en,
|
||||
category=payload.category,
|
||||
description=payload.description,
|
||||
description_en=payload.description_en,
|
||||
bindings=payload.bindings,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/workflows/{workflow_id}")
|
||||
async def delete_ai_workflow(
|
||||
workflow_id: str,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await delete_workflow(db, workflow_id)
|
||||
|
||||
|
||||
@router.get("/workflows/{workflow_id}")
|
||||
async def get_ai_workflow_detail(
|
||||
workflow_id: str,
|
||||
@@ -124,6 +326,22 @@ async def update_ai_workflow_draft(
|
||||
db,
|
||||
workflow_id,
|
||||
payload.graph,
|
||||
bindings=payload.bindings,
|
||||
name=payload.name,
|
||||
description=payload.description,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/workflows/{workflow_id}/draft")
|
||||
async def discard_ai_workflow_draft(
|
||||
workflow_id: str,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await discard_workflow_draft(
|
||||
db,
|
||||
workflow_id,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
@@ -139,6 +357,9 @@ async def publish_ai_workflow(
|
||||
db,
|
||||
workflow_id,
|
||||
graph=payload.graph,
|
||||
bindings=payload.bindings,
|
||||
name=payload.name,
|
||||
description=payload.description,
|
||||
change_summary=payload.change_summary,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
@@ -205,6 +426,12 @@ async def create_ai_workflow_fixture(
|
||||
ctx_payload = dict(payload.context_json if payload.context_json is not None else payload.earth_context or {})
|
||||
if payload.description.strip() and "_description" not in ctx_payload:
|
||||
ctx_payload["_description"] = payload.description.strip()
|
||||
expect = normalize_fixture_expect(
|
||||
payload.expect if payload.expect is not None else ctx_payload.get(FIXTURE_EXPECT_KEY)
|
||||
)
|
||||
ctx_payload.pop(FIXTURE_EXPECT_KEY, None)
|
||||
if expect:
|
||||
ctx_payload[FIXTURE_EXPECT_KEY] = expect
|
||||
row = AIWorkflowFixture(
|
||||
workflow_id=workflow_id,
|
||||
name=payload.name.strip(),
|
||||
@@ -243,17 +470,31 @@ async def delete_ai_workflow_fixture(
|
||||
async def list_ai_workflow_runs(
|
||||
workflow_id: str | None = None,
|
||||
status: str | None = None,
|
||||
feedback: Literal["negative", "positive"] | None = None,
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
stmt = select(WorkflowRun).order_by(desc(WorkflowRun.started_at)).limit(limit)
|
||||
fetch_limit = min(400, limit * 3) if feedback else limit
|
||||
stmt = select(WorkflowRun).order_by(desc(WorkflowRun.started_at)).limit(fetch_limit)
|
||||
if workflow_id:
|
||||
stmt = stmt.where(WorkflowRun.workflow_id == workflow_id)
|
||||
if status:
|
||||
stmt = stmt.where(WorkflowRun.status == status)
|
||||
rows = (await db.execute(stmt)).scalars().all()
|
||||
items = [row.to_dict() for row in rows]
|
||||
if feedback == "negative":
|
||||
rows = [
|
||||
row
|
||||
for row in rows
|
||||
if row.status == "failed" or int((row.budget_used or {}).get("user_rating") or 0) == -1
|
||||
]
|
||||
elif feedback == "positive":
|
||||
rows = [
|
||||
row
|
||||
for row in rows
|
||||
if int((row.budget_used or {}).get("user_rating") or 0) == 1
|
||||
]
|
||||
items = [row.to_dict() for row in rows[:limit]]
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
@@ -271,6 +512,153 @@ async def get_ai_workflow_run_detail(
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
@router.post("/runs/{run_id}/feedback")
|
||||
async def submit_ai_workflow_run_feedback(
|
||||
run_id: str,
|
||||
payload: WorkflowRunFeedbackRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await record_run_feedback(
|
||||
db,
|
||||
run_id,
|
||||
rating=payload.rating,
|
||||
note=payload.note,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/evolution/policy")
|
||||
async def get_ai_evolution_policy(
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await get_evolution_policy(db)
|
||||
|
||||
|
||||
@router.put("/evolution/policy")
|
||||
async def update_ai_evolution_policy(
|
||||
payload: EvolutionPolicyUpdateRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await update_evolution_policy(db, payload.model_dump(exclude_none=True))
|
||||
|
||||
|
||||
@router.get("/evolution/ledger")
|
||||
async def list_ai_evolution_ledger(
|
||||
workflow_id: str | None = None,
|
||||
limit: int = Query(30, ge=1, le=50),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
items = await get_evolution_ledger(db, workflow_id=workflow_id, limit=limit)
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
@router.post("/evolution/ledger/{entry_id}/dismiss")
|
||||
async def dismiss_ai_evolution_ledger_entry(
|
||||
entry_id: str,
|
||||
payload: LedgerDismissRequest | None = None,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await dismiss_ledger_entry(
|
||||
db,
|
||||
entry_id,
|
||||
reason=(payload.reason if payload else ""),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/evolution/health/{workflow_id}")
|
||||
async def get_ai_workflow_evolution_health(
|
||||
workflow_id: str,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
ai_client = None
|
||||
try:
|
||||
ai_client = await get_ai_provider_client(db)
|
||||
except Exception:
|
||||
ai_client = None
|
||||
return await compute_workflow_health(db, workflow_id, ai_client=ai_client)
|
||||
|
||||
|
||||
@router.post("/evolution/propose/{workflow_id}")
|
||||
async def propose_ai_workflow_evolution(
|
||||
workflow_id: str,
|
||||
payload: EvolutionProposeRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
ai_client = None
|
||||
try:
|
||||
ai_client = await get_ai_provider_client(db)
|
||||
except Exception:
|
||||
ai_client = None
|
||||
return await propose_workflow_evolution(
|
||||
db,
|
||||
workflow_id,
|
||||
mode=payload.mode,
|
||||
instruction=payload.instruction,
|
||||
run_id=payload.run_id,
|
||||
apply_mode=payload.apply_mode,
|
||||
trigger="manual",
|
||||
branch_from_best=payload.branch_from_best,
|
||||
ai_client=ai_client,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/evolution/eval/{workflow_id}")
|
||||
async def evaluate_ai_workflow_fixtures(
|
||||
workflow_id: str,
|
||||
payload: EvolutionEvalRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await run_fixture_ab_eval(
|
||||
db,
|
||||
workflow_id,
|
||||
payload.proposed_graph,
|
||||
max_fixtures=payload.max_fixtures,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/evolution/incubate")
|
||||
async def incubate_ai_workflow_candidate(
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
ai_client = None
|
||||
try:
|
||||
ai_client = await get_ai_provider_client(db)
|
||||
except Exception:
|
||||
ai_client = None
|
||||
return await incubate_workflow_from_runs(db, ai_client=ai_client)
|
||||
|
||||
|
||||
@router.post("/evolution/meta-evolve")
|
||||
async def propose_ai_meta_evolution(
|
||||
payload: MetaEvolveRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
ai_client = None
|
||||
try:
|
||||
ai_client = await get_ai_provider_client(db)
|
||||
except Exception:
|
||||
ai_client = None
|
||||
return await propose_meta_evolution(
|
||||
db,
|
||||
instruction=payload.instruction,
|
||||
apply_mode=payload.apply_mode,
|
||||
trigger="meta_manual",
|
||||
ai_client=ai_client,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
async def _resolve_playground_slash_or_workflow(
|
||||
*,
|
||||
db: AsyncSession,
|
||||
@@ -286,7 +674,7 @@ async def _resolve_playground_slash_or_workflow(
|
||||
extra_meta: dict[str, Any] = {}
|
||||
|
||||
if trimmed.startswith("/bgp-brief"):
|
||||
active_wf = "ops.bgp_brief"
|
||||
active_wf = "brief.bgp"
|
||||
req, facts, ctx = await build_bgp_brief_request(db)
|
||||
tool_trace.extend(["query_bgp_incidents", "query_bgp_anomalies", "synthesize"])
|
||||
extra_meta["facts"] = facts
|
||||
@@ -294,7 +682,7 @@ async def _resolve_playground_slash_or_workflow(
|
||||
return active_wf, tool_trace, req, extra_meta
|
||||
|
||||
if trimmed.startswith("/alerts-brief"):
|
||||
active_wf = "ops.alerts_brief"
|
||||
active_wf = "brief.alerts"
|
||||
req, facts, ctx = await build_alert_brief_request(db)
|
||||
tool_trace.extend(["query_system_alerts", "synthesize"])
|
||||
extra_meta["facts"] = facts
|
||||
@@ -302,7 +690,7 @@ async def _resolve_playground_slash_or_workflow(
|
||||
return active_wf, tool_trace, req, extra_meta
|
||||
|
||||
if trimmed.startswith("/situational-brief"):
|
||||
active_wf = "ops.situational_alerts_brief"
|
||||
active_wf = "brief.alerts"
|
||||
req, facts, ctx = await build_situational_alert_brief_request(db)
|
||||
tool_trace.extend(["query_system_alerts", "query_bgp_incidents", "synthesize"])
|
||||
extra_meta["facts"] = facts
|
||||
@@ -348,6 +736,7 @@ async def _resolve_playground_slash_or_workflow(
|
||||
extra_meta["direct_reply"] = f"未能定位目标「{target_name}」:{res.failure_reason or '暂无可核验公开证据'}。"
|
||||
except Exception as exc:
|
||||
extra_meta["direct_reply"] = f"位置 Agent 调试执行失败:{exc}"
|
||||
extra_meta["direct_reply_error"] = str(exc)
|
||||
return active_wf, tool_trace, None, extra_meta
|
||||
|
||||
detail = await get_workflow_detail(db, active_wf)
|
||||
@@ -390,6 +779,78 @@ async def _resolve_playground_slash_or_workflow(
|
||||
return active_wf, tool_trace, req, extra_meta
|
||||
|
||||
|
||||
def _normalize_playground_attachments(
|
||||
attachments: list[PlaygroundAttachmentInput],
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
|
||||
"""Extract prompt-safe attachment summaries and capped multimodal image blocks."""
|
||||
structured: list[dict[str, Any]] = []
|
||||
images: list[dict[str, str]] = []
|
||||
for item in attachments[:8]:
|
||||
entry: dict[str, Any] = {
|
||||
"kind": item.kind,
|
||||
"name": item.name or item.url or item.kind,
|
||||
}
|
||||
if item.mime_type:
|
||||
entry["mime_type"] = item.mime_type
|
||||
if item.metadata:
|
||||
entry["metadata"] = item.metadata
|
||||
if item.kind == "link" and item.url:
|
||||
entry["url"] = item.url
|
||||
if item.text_content:
|
||||
entry["fetched_content"] = isolate_untrusted_external_text(
|
||||
item.url,
|
||||
item.name or item.url,
|
||||
item.text_content,
|
||||
max_chars=4000,
|
||||
)
|
||||
elif item.kind == "json" and item.json_data is not None:
|
||||
raw_json = json.dumps(item.json_data, ensure_ascii=False, default=str)
|
||||
entry["json_preview"] = raw_json[:8000]
|
||||
elif item.kind in {"text", "json"} and item.text_content:
|
||||
entry["text_preview"] = item.text_content[:8000]
|
||||
|
||||
for img in item.images or []:
|
||||
if len(images) >= 8:
|
||||
break
|
||||
images.append(
|
||||
{
|
||||
"mime_type": img.mime_type,
|
||||
"data_base64": img.data_base64,
|
||||
"name": img.name or item.name,
|
||||
}
|
||||
)
|
||||
if item.images:
|
||||
entry["image_frames_attached"] = len(item.images)
|
||||
structured.append(entry)
|
||||
return structured, images
|
||||
|
||||
|
||||
@router.post("/playground/parse-link")
|
||||
async def parse_playground_link(
|
||||
payload: PlaygroundLinkParseRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
):
|
||||
"""Fetch a public HTTP/HTTPS web page with SSRF validation and extract readable text."""
|
||||
try:
|
||||
fetched = await safe_web_fetch(payload.url.strip(), timeout_seconds=10)
|
||||
except SSRFBlockedError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Failed to fetch URL: {exc}") from exc
|
||||
|
||||
clean_text = (fetched.text or "")[:12000]
|
||||
excerpt = clean_text[:320].strip()
|
||||
return {
|
||||
"url": fetched.url,
|
||||
"final_url": fetched.final_url,
|
||||
"title": fetched.title or fetched.final_url,
|
||||
"text": clean_text,
|
||||
"excerpt": excerpt,
|
||||
"char_count": len(clean_text),
|
||||
"content_hash": fetched.content_hash,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/playground/chat/stream")
|
||||
async def stream_advisor_playground_chat(
|
||||
payload: AdvisorPlaygroundChatRequest,
|
||||
@@ -397,6 +858,12 @@ async def stream_advisor_playground_chat(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Stream AI Advisor Playground execution over SSE (`meta`, `node`, `reasoning`, `text`, `done`, `error`)."""
|
||||
raw_msg = payload.message.strip()
|
||||
if not raw_msg and not payload.attachments:
|
||||
raise HTTPException(status_code=422, detail="Message or attachment is required")
|
||||
effective_message = raw_msg or "请结合我上传的附件进行分析。"
|
||||
attachment_summaries, attachment_images = _normalize_playground_attachments(payload.attachments)
|
||||
|
||||
run_id = f"run_{uuid4().hex[:16]}"
|
||||
started_at = datetime.now(UTC)
|
||||
|
||||
@@ -405,74 +872,148 @@ async def stream_advisor_playground_chat(
|
||||
tool_trace: list[str] = []
|
||||
status_value = "completed"
|
||||
error_text = ""
|
||||
resolved_model = str(payload.model_override or "").strip()
|
||||
resolved_provider = ""
|
||||
verification: dict[str, Any] = {}
|
||||
workflow_revision = 1
|
||||
is_slash_cmd = effective_message.strip().startswith(
|
||||
("/bgp-brief", "/alerts-brief", "/situational-brief", "/locate")
|
||||
)
|
||||
try:
|
||||
active_wf, tool_trace, req, extra_meta = await _resolve_playground_slash_or_workflow(
|
||||
db=db,
|
||||
workflow_id=active_wf,
|
||||
message=payload.message,
|
||||
use_draft=payload.use_draft,
|
||||
earth_context=payload.earth_context,
|
||||
)
|
||||
yield _sse_frame(
|
||||
"meta",
|
||||
{
|
||||
"run_id": run_id,
|
||||
"workflow_id": active_wf,
|
||||
"use_draft": payload.use_draft,
|
||||
"nodes": tool_trace,
|
||||
**{k: v for k, v in extra_meta.items() if k != "direct_reply"},
|
||||
},
|
||||
)
|
||||
for node_id in tool_trace:
|
||||
yield _sse_frame("node", {"node_id": node_id, "status": "completed"})
|
||||
|
||||
if "direct_reply" in extra_meta:
|
||||
reply = str(extra_meta["direct_reply"])
|
||||
yield _sse_frame("text", {"delta": reply})
|
||||
yield _sse_frame("done", {"run_id": run_id, "workflow_id": active_wf, "nodes": tool_trace})
|
||||
return
|
||||
|
||||
if req is not None:
|
||||
if payload.model_override:
|
||||
req.preferred_model = payload.model_override.strip()
|
||||
if payload.history:
|
||||
req.messages = [
|
||||
ChatMessage(role=m.role, content=m.content) # type: ignore[arg-type]
|
||||
for m in payload.history[-12:]
|
||||
]
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
ready, _, active_model = await provider_client.is_ready()
|
||||
if not ready:
|
||||
status_value = "failed"
|
||||
error_text = "AI Provider 尚未配置可用密钥或服务地址,请前往「运维与配置 → AI 基础设施」检查。"
|
||||
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
|
||||
return
|
||||
|
||||
full_text_parts: list[str] = []
|
||||
async for item in provider_client.stream_analyze(req, request_id=run_id):
|
||||
ev = str(item.get("event") or "")
|
||||
if ev == "reasoning" and item.get("delta"):
|
||||
yield _sse_frame("reasoning", {"delta": str(item["delta"])})
|
||||
elif ev == "text" and item.get("delta"):
|
||||
delta = str(item["delta"])
|
||||
full_text_parts.append(delta)
|
||||
yield _sse_frame("text", {"delta": delta})
|
||||
elif ev == "error":
|
||||
status_value = "failed"
|
||||
error_text = str(item.get("message") or "Streaming error")
|
||||
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
|
||||
return
|
||||
cleaned, _ = strip_thinking_text("".join(full_text_parts))
|
||||
if is_slash_cmd:
|
||||
active_wf, tool_trace, req, extra_meta = await _resolve_playground_slash_or_workflow(
|
||||
db=db,
|
||||
workflow_id=active_wf,
|
||||
message=effective_message,
|
||||
use_draft=payload.use_draft,
|
||||
earth_context=payload.earth_context,
|
||||
)
|
||||
yield _sse_frame(
|
||||
"done",
|
||||
"meta",
|
||||
{
|
||||
"run_id": run_id,
|
||||
"workflow_id": active_wf,
|
||||
"model": payload.model_override or active_model,
|
||||
"use_draft": payload.use_draft,
|
||||
"nodes": tool_trace,
|
||||
"text_length": len(cleaned),
|
||||
**{
|
||||
k: v
|
||||
for k, v in extra_meta.items()
|
||||
if k not in {"direct_reply", "direct_reply_error"}
|
||||
},
|
||||
},
|
||||
)
|
||||
for node_id in tool_trace:
|
||||
yield _sse_frame("node", {"node_id": node_id, "status": "completed"})
|
||||
|
||||
if "direct_reply" in extra_meta:
|
||||
reply = str(extra_meta["direct_reply"])
|
||||
if extra_meta.get("direct_reply_error"):
|
||||
status_value = "failed"
|
||||
error_text = str(extra_meta["direct_reply_error"])
|
||||
yield _sse_frame("text", {"delta": reply})
|
||||
yield _sse_frame("done", {"run_id": run_id, "workflow_id": active_wf, "nodes": tool_trace})
|
||||
return
|
||||
|
||||
if req is not None:
|
||||
if attachment_summaries:
|
||||
req.context = {**(req.context or {}), "attachments": attachment_summaries}
|
||||
if attachment_images:
|
||||
req.images = [
|
||||
ImageAttachment.model_validate(img) for img in attachment_images[:8]
|
||||
]
|
||||
if payload.model_override:
|
||||
req.preferred_model = payload.model_override.strip()
|
||||
if payload.history:
|
||||
req.messages = [
|
||||
ChatMessage(role=m.role, content=m.content) # type: ignore[arg-type]
|
||||
for m in payload.history[-12:]
|
||||
]
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
ready, active_provider, active_model = await provider_client.is_ready()
|
||||
resolved_provider = resolved_provider or str(active_provider or "")
|
||||
resolved_model = resolved_model or str(active_model or "")
|
||||
if not ready:
|
||||
status_value = "failed"
|
||||
error_text = "AI Provider 尚未配置可用密钥或服务地址,请前往「运维与配置 → AI」检查。"
|
||||
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
|
||||
return
|
||||
|
||||
full_text_parts: list[str] = []
|
||||
async for item in provider_client.stream_analyze(req, request_id=run_id):
|
||||
ev = str(item.get("event") or "")
|
||||
if ev == "reasoning" and item.get("delta"):
|
||||
yield _sse_frame("reasoning", {"delta": str(item["delta"])})
|
||||
elif ev == "text" and item.get("delta"):
|
||||
delta = str(item["delta"])
|
||||
full_text_parts.append(delta)
|
||||
yield _sse_frame("text", {"delta": delta})
|
||||
elif ev == "error":
|
||||
status_value = "failed"
|
||||
error_text = str(item.get("message") or "Streaming error")
|
||||
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
|
||||
return
|
||||
cleaned, _ = strip_thinking_text("".join(full_text_parts))
|
||||
yield _sse_frame(
|
||||
"done",
|
||||
{
|
||||
"run_id": run_id,
|
||||
"workflow_id": active_wf,
|
||||
"model": payload.model_override or active_model,
|
||||
"nodes": tool_trace,
|
||||
"text_length": len(cleaned),
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
detail = await get_workflow_detail(db, active_wf)
|
||||
wf_obj = detail["workflow"]
|
||||
workflow_revision = int(wf_obj.get("active_revision") or 1)
|
||||
provider_client = None
|
||||
try:
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
except Exception:
|
||||
provider_client = None
|
||||
|
||||
targets_list = [t.model_dump() for t in payload.targets]
|
||||
history_list = [{"role": m.role, "content": m.content} for m in payload.history[-12:]]
|
||||
async for item in run_workflow_dag_stream(
|
||||
db=db,
|
||||
workflow=wf_obj,
|
||||
question=effective_message,
|
||||
use_draft=payload.use_draft,
|
||||
targets=targets_list,
|
||||
earth_context=payload.earth_context,
|
||||
attachments=attachment_summaries,
|
||||
images=attachment_images,
|
||||
history=history_list,
|
||||
ai_client=provider_client,
|
||||
run_id=run_id,
|
||||
model_override=payload.model_override,
|
||||
allow_external_tools=True,
|
||||
extra_meta={
|
||||
"earth_context_attached": bool(payload.earth_context),
|
||||
"attachments_count": len(attachment_summaries),
|
||||
},
|
||||
):
|
||||
ev_name = str(item.get("event") or "")
|
||||
ev_data = dict(item.get("data") or {})
|
||||
if ev_name == "node" and ev_data.get("status") == "completed":
|
||||
nid = str(ev_data.get("node_id") or "")
|
||||
if nid and nid not in tool_trace:
|
||||
tool_trace.append(nid)
|
||||
elif ev_name == "done":
|
||||
if isinstance(ev_data.get("nodes"), list):
|
||||
tool_trace = [str(n) for n in ev_data["nodes"] if n]
|
||||
if ev_data.get("model"):
|
||||
resolved_model = str(ev_data["model"])
|
||||
if ev_data.get("provider"):
|
||||
resolved_provider = str(ev_data["provider"])
|
||||
if isinstance(ev_data.get("verification"), dict):
|
||||
verification = ev_data["verification"]
|
||||
elif ev_name == "error":
|
||||
status_value = "failed"
|
||||
error_text = str(ev_data.get("message") or "Workflow execution failed")
|
||||
yield _sse_frame(ev_name, ev_data)
|
||||
except Exception as exc:
|
||||
status_value = "failed"
|
||||
error_text = str(exc)
|
||||
@@ -484,6 +1025,8 @@ async def stream_advisor_playground_chat(
|
||||
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
|
||||
finally:
|
||||
try:
|
||||
completed_at = datetime.now(UTC)
|
||||
latency_ms = max(0, int((completed_at - started_at).total_seconds() * 1000))
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=run_id,
|
||||
@@ -491,20 +1034,38 @@ async def stream_advisor_playground_chat(
|
||||
status=status_value,
|
||||
access_tier="admin",
|
||||
actor_key=_actor_label(admin),
|
||||
question=payload.message[:500],
|
||||
question=effective_message[:500],
|
||||
input_params={
|
||||
"use_draft": payload.use_draft,
|
||||
"model_override": payload.model_override,
|
||||
"has_earth_context": bool(payload.earth_context),
|
||||
"attachments_count": len(attachment_summaries),
|
||||
"targets_count": len(payload.targets),
|
||||
},
|
||||
tool_trace=tool_trace,
|
||||
budget_used={"steps": len(tool_trace)},
|
||||
budget_used={
|
||||
"steps": len(tool_trace),
|
||||
"model_used": resolved_model,
|
||||
"provider": resolved_provider,
|
||||
"latency_ms": latency_ms,
|
||||
"workflow_revision": workflow_revision,
|
||||
**(
|
||||
{
|
||||
"verification_passed": bool(verification.get("passed", True)),
|
||||
"verification_warnings": list(verification.get("warnings") or [])[:6],
|
||||
}
|
||||
if verification
|
||||
else {}
|
||||
),
|
||||
},
|
||||
error_message=error_text[:500],
|
||||
started_at=started_at,
|
||||
completed_at=datetime.now(UTC),
|
||||
completed_at=completed_at,
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
if not payload.use_draft:
|
||||
schedule_post_run_evolution(active_wf, run_id)
|
||||
except Exception:
|
||||
try:
|
||||
await db.rollback()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Compute observations, administrator configuration and independent facility samples."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Literal
|
||||
|
||||
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression
|
||||
from app.api.v1.visualization import convert_compute_centers_to_geojson
|
||||
|
||||
@@ -44,7 +44,7 @@ from app.services.custom_datasource_runtime import (
|
||||
)
|
||||
from app.services.datasource_connectivity import (
|
||||
_resolve_aisstream_api_key,
|
||||
_resolve_spacetrack_credentials_with_override,
|
||||
resolve_spacetrack_credentials,
|
||||
get_builtin_connection_status,
|
||||
save_connectivity_success,
|
||||
strip_connectivity_validation,
|
||||
@@ -123,7 +123,10 @@ class DataSourceConfigCreate(BaseModel):
|
||||
description: Optional[str] = None
|
||||
source_type: str = Field(..., description="rest, websocket, http, api, database")
|
||||
endpoint: str = Field(..., max_length=500)
|
||||
auth_type: AuthType = Field(default=AuthType.NONE, description="none, bearer, api_key, basic")
|
||||
auth_type: AuthType = Field(
|
||||
default=AuthType.NONE,
|
||||
description="none, bearer, api_key, basic, oauth_client",
|
||||
)
|
||||
auth_config: dict = Field(default={})
|
||||
headers: dict = Field(default={})
|
||||
config: dict = Field(default={"timeout": 30, "retry": 3})
|
||||
@@ -162,28 +165,6 @@ def _is_builtin_config_name(name: str | None) -> bool:
|
||||
return bool(name and name in DEFAULT_DATASOURCES)
|
||||
|
||||
|
||||
async def _ensure_builtin_connection_verified(
|
||||
db: AsyncSession,
|
||||
config_data: DataSourceConfigCreate,
|
||||
) -> None:
|
||||
if not _is_builtin_config_name(config_data.name):
|
||||
return
|
||||
|
||||
status_result = await get_builtin_connection_status(
|
||||
db,
|
||||
config_data.name,
|
||||
config_data.endpoint,
|
||||
config_data.auth_type,
|
||||
config_data.headers,
|
||||
config_data.config,
|
||||
)
|
||||
if not status_result.get("connected"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=status_result.get("message") or "请先完成连接验证,再保存内置采集器配置。",
|
||||
)
|
||||
|
||||
|
||||
class CustomSampleRequest(BaseModel):
|
||||
datasource_config_id: Optional[int] = None
|
||||
config: Optional[DataSourceConfigCreate] = None
|
||||
@@ -543,12 +524,7 @@ async def reveal_builtin_config_secrets(
|
||||
payload.update({"api_key": api_key, "api_key_source": api_key_source})
|
||||
details.update({"api_key_configured": bool(api_key), "api_key_source": api_key_source})
|
||||
elif provider == "spacetrack":
|
||||
if auth_config.get("username") or auth_config.get("password"):
|
||||
username = str(auth_config.get("username") or "")
|
||||
password = str(auth_config.get("password") or "")
|
||||
credential_source = "datasource_config"
|
||||
else:
|
||||
username, password, credential_source = _resolve_spacetrack_credentials_with_override()
|
||||
username, password, credential_source = await resolve_spacetrack_credentials(db)
|
||||
payload.update(
|
||||
{
|
||||
"username": username,
|
||||
@@ -606,6 +582,32 @@ async def get_config(
|
||||
}
|
||||
|
||||
|
||||
_SECRET_AUTH_KEYS = frozenset(
|
||||
{"api_key", "client_secret", "password", "token", "access_token", "bearer_token"}
|
||||
)
|
||||
|
||||
|
||||
def _is_masked_secret(value: Any) -> bool:
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
stripped = value.strip()
|
||||
return bool(stripped) and set(stripped) <= {"•", "*"}
|
||||
|
||||
|
||||
def _merge_auth_config(existing: dict[str, Any] | None, incoming: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""Merge partial `auth_config` updates while preserving omitted or masked secrets."""
|
||||
merged = dict(existing or {})
|
||||
if not isinstance(incoming, dict):
|
||||
return merged
|
||||
for key, raw in incoming.items():
|
||||
if key in _SECRET_AUTH_KEYS:
|
||||
cleaned = str(raw or "").strip() if isinstance(raw, str) else raw
|
||||
if not cleaned or _is_masked_secret(cleaned):
|
||||
continue
|
||||
merged[key] = raw
|
||||
return merged
|
||||
|
||||
|
||||
@router.post("/configs")
|
||||
async def create_config(
|
||||
config_data: DataSourceConfigCreate,
|
||||
@@ -619,7 +621,7 @@ async def create_config(
|
||||
source_type=config_data.source_type,
|
||||
endpoint=config_data.endpoint,
|
||||
auth_type=config_data.auth_type,
|
||||
auth_config=config_data.auth_config,
|
||||
auth_config=_merge_auth_config({}, config_data.auth_config),
|
||||
headers=config_data.headers,
|
||||
config=strip_connectivity_validation(config_data.config),
|
||||
)
|
||||
@@ -655,8 +657,8 @@ async def update_config(
|
||||
for field, value in update_data.items():
|
||||
if field == "config":
|
||||
value = strip_connectivity_validation(value)
|
||||
if field == "auth_config" and value == {} and (config.auth_config or {}):
|
||||
continue
|
||||
if field == "auth_config":
|
||||
value = _merge_auth_config(config.auth_config or {}, value)
|
||||
setattr(config, field, value)
|
||||
|
||||
await db.commit()
|
||||
|
||||
@@ -2,7 +2,7 @@ from copy import deepcopy
|
||||
from datetime import UTC, datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Literal, Optional
|
||||
from typing import Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
@@ -70,7 +70,6 @@ from app.services.llm_model_catalog import (
|
||||
LLMProviderCatalogConfigError,
|
||||
can_refresh_catalog_without_api_key,
|
||||
catalog_error_message,
|
||||
catalog_requires_api_key,
|
||||
fetch_model_catalog,
|
||||
)
|
||||
from app.services.scheduler import sync_datasource_job
|
||||
@@ -759,24 +758,6 @@ def _runtime_config_from_ai_payload(ai_payload: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _ai_provider_runtime_fingerprint(ai_payload: dict) -> dict:
|
||||
runtime_config = _runtime_config_from_ai_payload(ai_payload)
|
||||
llm_config = runtime_config.get("llm_config") or {}
|
||||
return {
|
||||
"service_url": runtime_config.get("service_url") or "",
|
||||
"service_token": runtime_config.get("service_token") or "",
|
||||
"timeout_seconds": int(runtime_config.get("timeout_seconds") or 0),
|
||||
"retry_attempts": int(runtime_config.get("retry_attempts") or 0),
|
||||
"provider": llm_config.get("provider") or "",
|
||||
"provider_api": llm_config.get("provider_api") or "",
|
||||
"base_url": llm_config.get("base_url") or "",
|
||||
"model": llm_config.get("model") or "",
|
||||
"api_key": llm_config.get("api_key") or "",
|
||||
"max_tokens": int(llm_config.get("max_tokens") or 0),
|
||||
"anthropic_version": llm_config.get("anthropic_version") or "",
|
||||
}
|
||||
|
||||
|
||||
async def _validate_ai_provider_full_connection(ai_payload: dict) -> dict:
|
||||
runtime_config = _runtime_config_from_ai_payload(ai_payload)
|
||||
client = AIProviderClient(
|
||||
|
||||
@@ -89,10 +89,25 @@ class HistoryMessageItem(BaseModel):
|
||||
content: str = Field(min_length=1, max_length=6000)
|
||||
|
||||
|
||||
class EarthTargetItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
entity_type: str = Field(min_length=1, max_length=64)
|
||||
entity_id: str | None = Field(default=None, max_length=160)
|
||||
label: str = Field(default="", max_length=200)
|
||||
latitude: float | None = None
|
||||
longitude: float | None = None
|
||||
layer: str | None = Field(default=None, max_length=80)
|
||||
kind: str | None = Field(default=None, max_length=80)
|
||||
properties: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class SessionTurnRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
question: str = Field(min_length=2, max_length=1000)
|
||||
workflow_id: str | None = Field(default=None, max_length=80, pattern=r"^[A-Za-z0-9_.-]+$")
|
||||
targets: list[EarthTargetItem] = Field(default_factory=list, max_length=8)
|
||||
domain: WorkbenchDomain | None = None
|
||||
selected_codes: list[str] | None = Field(default=None, max_length=12)
|
||||
mode: ComputeSeriesMode | None = None
|
||||
@@ -407,6 +422,8 @@ async def stream_investigation_session_turn(
|
||||
conversation_summary=payload.conversation_summary,
|
||||
memory_notes=payload.memory_notes,
|
||||
pinned_summaries=payload.pinned_summaries,
|
||||
workflow_id=payload.workflow_id,
|
||||
targets=[t.model_dump() for t in payload.targets],
|
||||
access=effective_access,
|
||||
ai_client=ai_client,
|
||||
client_run_id=payload.run_id,
|
||||
|
||||
@@ -14,10 +14,10 @@ fao:
|
||||
landing_point_url: "https://data.apps.fao.org/catalog/dataset/1b75ff21-92f2-4b96-9b7b-98e8aa65ad5d/resource/b6071077-d1d4-4e97-aa00-42e902847c87/download/landing-point-geo.csv"
|
||||
|
||||
telegeography:
|
||||
# TeleGeography 海缆/系统主数据源,当前使用 GitHub 镜像 JSON
|
||||
cable_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/cable.json"
|
||||
# TeleGeography 登陆点主数据源,当前使用 GitHub 镜像 JSON
|
||||
landing_point_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/landing_point.json"
|
||||
# TeleGeography 官方海缆/系统 JSON 接口
|
||||
cable_url: "https://www.submarinecablemap.com/api/v3/cable/all.json"
|
||||
# TeleGeography 官方登陆点 GeoJSON 接口
|
||||
landing_point_url: "https://www.submarinecablemap.com/api/v3/landing-point/landing-point-geo.json"
|
||||
# TeleGeography 历史 API 存档,用于 cable collector 的 fallback
|
||||
archived_cable_url: "https://web.archive.org/web/2024/https://www.submarinecablemap.com/api/v3/cable"
|
||||
# TeleGeography 官网页面,用于 cable collector 的最终 HTML 抓取 fallback
|
||||
|
||||
@@ -161,7 +161,7 @@ DEFAULT_DATASOURCES = {
|
||||
"is_free": True,
|
||||
"requires_credentials": True,
|
||||
"credential_provider": "spacetrack",
|
||||
"credential_status": "planned",
|
||||
"credential_status": "supported",
|
||||
},
|
||||
"celestrak_tle": {
|
||||
"id": 20,
|
||||
|
||||
@@ -217,6 +217,7 @@ class AuthType(StrEnum):
|
||||
BEARER = "bearer"
|
||||
API_KEY = "api_key"
|
||||
BASIC = "basic"
|
||||
OAUTH_CLIENT = "oauth_client"
|
||||
|
||||
|
||||
class TVSourceType(StrEnum):
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Add bindings JSON/JSONB column to ai_workflows for Earth interaction bindings."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0006"
|
||||
NAME = "add_ai_workflow_bindings"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Add bindings column to ai_workflows idempotently across PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
ALTER TABLE ai_workflows
|
||||
ADD COLUMN IF NOT EXISTS bindings JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
"""
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
res = await conn.execute(text("PRAGMA table_info(ai_workflows)"))
|
||||
columns = {str(row[1]) for row in res.fetchall()}
|
||||
if columns and "bindings" not in columns:
|
||||
await conn.execute(
|
||||
text("ALTER TABLE ai_workflows ADD COLUMN bindings JSON NOT NULL DEFAULT '{}'")
|
||||
)
|
||||
@@ -911,6 +911,14 @@ async def _init_db_ddl_and_seed():
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
ALTER TABLE ai_workflows
|
||||
ADD COLUMN IF NOT EXISTS bindings JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
|
||||
@@ -25,7 +25,8 @@ class AIWorkflow(Base):
|
||||
is_builtin = Column(Boolean, nullable=False, default=True)
|
||||
active_revision = Column(Integer, nullable=False, default=1)
|
||||
published_graph = Column(JSON, nullable=False, default=dict)
|
||||
draft_graph = Column(JSON, nullable=True)
|
||||
draft_graph = Column(JSON(none_as_null=True), nullable=True)
|
||||
bindings = Column(JSON, nullable=False, default=dict)
|
||||
updated_by = Column(String(120), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(
|
||||
@@ -50,6 +51,10 @@ class AIWorkflow(Base):
|
||||
"has_draft": self.draft_graph is not None,
|
||||
"published_graph": self.published_graph or {},
|
||||
"draft_graph": self.draft_graph,
|
||||
"bindings": self.bindings or {},
|
||||
"draft_bindings": (
|
||||
self.draft_graph.get("bindings") if isinstance(self.draft_graph, dict) else None
|
||||
),
|
||||
"updated_by": self.updated_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
"updated_at": to_iso8601_utc(self.updated_at),
|
||||
|
||||
@@ -19,6 +19,12 @@ class ToolCallRecord(BaseModel):
|
||||
arguments: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class ImageAttachment(BaseModel):
|
||||
mime_type: str = Field(..., pattern=r"^image/(png|jpeg|jpg|webp|gif)$")
|
||||
data_base64: str = Field(..., min_length=8, max_length=6_000_000)
|
||||
name: str = Field(default="", max_length=200)
|
||||
|
||||
|
||||
class AIContentBlock(BaseModel):
|
||||
type: str
|
||||
text: str | None = None
|
||||
@@ -41,6 +47,7 @@ class SituationalAnalysisRequest(BaseModel):
|
||||
tool_choice: str | dict[str, Any] | None = None
|
||||
response_format: dict[str, Any] | None = None
|
||||
native_web_search: bool = False
|
||||
images: list[ImageAttachment] = Field(default_factory=list, max_length=8)
|
||||
|
||||
|
||||
class BGPBriefRequest(BaseModel):
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,150 @@
|
||||
"""Shared `<planet_scene>` prompt guidance and streaming extraction for Earth Influence Zones."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.services.ai.workflow_runtime import validate_influence_zones
|
||||
|
||||
logger = get_logger(__name__, service="ai_scene")
|
||||
|
||||
PLANET_SCENE_TAG_OPEN = "<planet_scene>"
|
||||
PLANET_SCENE_RE = re.compile(r"<planet_scene>\s*(.*?)\s*</planet_scene>", re.DOTALL | re.IGNORECASE)
|
||||
PLANET_SCENE_OPEN_RE = re.compile(r"<\s*planet_scene\b", re.IGNORECASE)
|
||||
_CODE_FENCE_OPEN_RE = re.compile(r"^\s*```[a-zA-Z0-9_-]*\s*\n?")
|
||||
_CODE_FENCE_CLOSE_RE = re.compile(r"\n?\s*```\s*$")
|
||||
_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")
|
||||
|
||||
INFLUENCE_ZONE_GUIDANCE = (
|
||||
"【地球影响范围联动指令】正文仍用自然 Markdown 输出(绝不在正文解释本标签);"
|
||||
"只要分析涉及明确地理国家、地区、消费/市场辐射域、基础设施影响区、海域/海峡走廊、峰会/组织或用户询问“影响范围/影响地区/覆盖区域”,"
|
||||
"就必须在回答**最末尾另起一行**附带一个纯 JSON(禁用 markdown 代码围栏)的系统隐藏标签:\n"
|
||||
"<planet_scene>{...}</planet_scene>\n"
|
||||
"分层输出规范(严格遵循):\n"
|
||||
"- 第一层(必需,直接当事国/核心对象):shape.mode=\"countries\",color=\"#ef4444\",opacity=0.54,edge.style=\"sharp\";必须填全所有直接核心国家且严格使用标准 ISO-3 代码(如朝鲜必须写 \"PRK\",禁用 \"DPRK\";中国 \"CHN\"、韩国 \"KOR\"、日本 \"JPN\"、俄罗斯 \"RUS\"、英国 \"GBR\")。\n"
|
||||
"- 第二层(若事件存在跨国/区域外溢则必填;纯单一国内消费/内部新闻则不填第二、三层):次级邻近/区域辐射,shape.mode=\"countries\" 或已支持的 \"region_preset\",color=\"#f59e0b\",opacity=0.32,edge.style=\"soft\"。\n"
|
||||
"- 第三层(仅当明确涉及海峡、海域航道或边境辐射带时可选):shape.mode=\"circle\"(center:[lat,lon], radius_km),color=\"#38bdf8\",opacity=0.28,edge.style=\"soft\"。\n"
|
||||
"完整单国示例:\n"
|
||||
"<planet_scene>{\"influence_zones\":[{\"id\":\"chn-core\",\"label\":\"直接影响:中国\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\"]}}],\"camera_hint\":{\"lat\":35.0,\"lon\":104.0}}</planet_scene>\n"
|
||||
"双国核心+区域外溢+海域辐射示例:\n"
|
||||
"<planet_scene>{\"influence_zones\":[{\"id\":\"core\",\"label\":\"核心国家\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\",\"PRK\"]}},{\"id\":\"spill\",\"label\":\"东北亚周边外溢\",\"color\":\"#f59e0b\",\"opacity\":0.32,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"fade\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"KOR\",\"JPN\",\"RUS\"]}},{\"id\":\"sea\",\"label\":\"黄海—朝鲜海峡航道辐射\",\"color\":\"#38bdf8\",\"opacity\":0.28,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"radial\"},\"shape\":{\"mode\":\"circle\",\"center\":[36.5,124.5],\"radius_km\":850}}],\"camera_hint\":{\"lat\":38.0,\"lon\":122.0}}</planet_scene>\n"
|
||||
"可选 region_preset 枚举(仅限此列表,勿自造名称):"
|
||||
"APEC, ASIA_PACIFIC, NORTHEAST_ASIA, EAST_ASIA, KOREAN_PENINSULA, SOUTHEAST_ASIA, SOUTH_ASIA, CENTRAL_ASIA, ASEAN, INDO_PACIFIC, "
|
||||
"EU, EUROPE, EASTERN_EUROPE, NORTHERN_EUROPE, WESTERN_EUROPE, G7, BRICS, NATO, MIDDLE_EAST, MENA, AMERICAS, NORTH_AMERICA, SOUTH_AMERICA, AFRICA;"
|
||||
"animation.type 选 \"sweep\"、\"radial\" 或 \"fade\"。"
|
||||
)
|
||||
|
||||
|
||||
def sanitize_camera_hint(raw: Any) -> dict[str, float] | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
cleaned: dict[str, float] = {}
|
||||
for key in ("lat", "lon", "altitude", "zoom"):
|
||||
val = raw.get(key)
|
||||
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
||||
cleaned[key] = float(val)
|
||||
return cleaned if ("lat" in cleaned and "lon" in cleaned) else None
|
||||
|
||||
|
||||
def _parse_scene_json_candidate(raw_json: str) -> dict[str, Any] | None:
|
||||
"""Parse JSON inside `<planet_scene>` even if wrapped in code fences or containing trailing commas."""
|
||||
text = str(raw_json or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
text = _CODE_FENCE_OPEN_RE.sub("", text)
|
||||
text = _CODE_FENCE_CLOSE_RE.sub("", text).strip()
|
||||
candidates = [text]
|
||||
first_brace = text.find("{")
|
||||
last_brace = text.rfind("}")
|
||||
if first_brace != -1 and last_brace > first_brace:
|
||||
sliced = text[first_brace : last_brace + 1]
|
||||
if sliced != text:
|
||||
candidates.append(sliced)
|
||||
for cand in candidates:
|
||||
for attempt in (cand, _TRAILING_COMMA_RE.sub(r"\1", cand)):
|
||||
try:
|
||||
parsed = json.loads(attempt)
|
||||
except Exception:
|
||||
continue
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
return None
|
||||
|
||||
|
||||
def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | None]:
|
||||
"""Strip `<planet_scene>...</planet_scene>` blocks and return validated scene spec fields."""
|
||||
if not text:
|
||||
return "", None
|
||||
parsed_scene: dict[str, Any] | None = None
|
||||
matches = PLANET_SCENE_RE.findall(text)
|
||||
for raw_json in matches:
|
||||
payload = _parse_scene_json_candidate(raw_json)
|
||||
if payload is None:
|
||||
continue
|
||||
zones = [z.model_dump(mode="json") for z in validate_influence_zones(payload.get("influence_zones"))]
|
||||
camera_hint = sanitize_camera_hint(payload.get("camera_hint"))
|
||||
if zones or camera_hint:
|
||||
parsed_scene = {}
|
||||
if zones:
|
||||
parsed_scene["influence_zones"] = zones
|
||||
if camera_hint:
|
||||
parsed_scene["camera_hint"] = camera_hint
|
||||
|
||||
if matches and parsed_scene is not None:
|
||||
extracted_zones = parsed_scene.get("influence_zones") or []
|
||||
logger.info_event(
|
||||
"Extracted planet scene directives",
|
||||
event="ai_scene.directive.extracted",
|
||||
context={
|
||||
"zones_count": len(extracted_zones),
|
||||
"zone_ids": [z.get("id") for z in extracted_zones if isinstance(z, dict)],
|
||||
"has_camera_hint": "camera_hint" in parsed_scene,
|
||||
},
|
||||
)
|
||||
elif matches:
|
||||
logger.warning_event(
|
||||
"Planet scene directive ignored after parse/validation failure",
|
||||
event="ai_scene.directive.dropped",
|
||||
context={"snippet": str(matches[-1])[:300]},
|
||||
)
|
||||
|
||||
cleaned = PLANET_SCENE_RE.sub("", text)
|
||||
open_match = PLANET_SCENE_OPEN_RE.search(cleaned)
|
||||
if open_match:
|
||||
cleaned = cleaned[: open_match.start()]
|
||||
return cleaned.rstrip(), parsed_scene
|
||||
|
||||
|
||||
def consume_text_holding_scene_tag(buffer: str, *, flush_all: bool = False) -> tuple[str, str]:
|
||||
"""Yield visible text before `<planet_scene` while holding back partial tag prefixes."""
|
||||
stripped_blocks = PLANET_SCENE_RE.sub("", buffer)
|
||||
open_match = PLANET_SCENE_OPEN_RE.search(stripped_blocks)
|
||||
if open_match:
|
||||
return stripped_blocks[: open_match.start()], stripped_blocks[open_match.start() :]
|
||||
if flush_all:
|
||||
return stripped_blocks, ""
|
||||
last_lt = stripped_blocks.rfind("<")
|
||||
if last_lt != -1:
|
||||
tail = stripped_blocks[last_lt:]
|
||||
if len(tail) < len(PLANET_SCENE_TAG_OPEN) and PLANET_SCENE_TAG_OPEN.startswith(tail.lower()):
|
||||
return stripped_blocks[:last_lt], tail
|
||||
return stripped_blocks, ""
|
||||
|
||||
|
||||
def merge_scene_specs(
|
||||
base_scene: dict[str, Any] | None,
|
||||
parsed_scene: dict[str, Any] | None,
|
||||
*,
|
||||
domain: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
if not parsed_scene and not isinstance(base_scene, dict):
|
||||
return None
|
||||
merged: dict[str, Any] = dict(base_scene) if isinstance(base_scene, dict) else {}
|
||||
if parsed_scene:
|
||||
merged.update(parsed_scene)
|
||||
if domain and not merged.get("domain"):
|
||||
merged["domain"] = domain
|
||||
return merged
|
||||
@@ -12,10 +12,12 @@ from typing import Any
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.situational_assessment import InvestigationSession
|
||||
from app.models.ai_workflow import AIWorkflow
|
||||
from app.models.situational_assessment import InvestigationSession, WorkflowRun
|
||||
from app.schemas.ai import ChatMessage, SituationalAnalysisRequest
|
||||
from app.services.ai.access_policy import AccessContext
|
||||
from app.services.ai.conversation_memory import (
|
||||
@@ -23,13 +25,27 @@ from app.services.ai.conversation_memory import (
|
||||
sanitize_memory_notes,
|
||||
sanitize_pinned_summaries,
|
||||
)
|
||||
from app.services.ai.dag_executor import run_workflow_dag_stream
|
||||
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
|
||||
from app.services.ai.tool_registry import (
|
||||
TimeBasis,
|
||||
query_global_situational_tool,
|
||||
query_recent_earth_news_tool,
|
||||
)
|
||||
from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn
|
||||
from app.services.ai.scene_directives import (
|
||||
INFLUENCE_ZONE_GUIDANCE as _INFLUENCE_ZONE_GUIDANCE,
|
||||
consume_text_holding_scene_tag as _consume_text_holding_scene_tag,
|
||||
extract_planet_scene_from_text,
|
||||
)
|
||||
from app.services.ai.workflow_evolver import schedule_post_run_evolution
|
||||
from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows
|
||||
from app.services.ai.workflow_runtime import (
|
||||
ActiveRunHandle,
|
||||
classify_turn_intent,
|
||||
execute_session_turn,
|
||||
register_active_run_handle,
|
||||
unregister_active_run_handle,
|
||||
)
|
||||
from app.services.ai_client import AIProviderClient
|
||||
|
||||
logger = get_logger(__name__, service="ai_stream")
|
||||
@@ -181,6 +197,7 @@ def _build_news_analysis_request(
|
||||
context["user_memory_notes"] = memory_notes
|
||||
if pinned_summaries:
|
||||
context["pinned_comparisons"] = pinned_summaries
|
||||
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
|
||||
return SituationalAnalysisRequest(
|
||||
title="Planet 全球新闻与国际局势研判",
|
||||
objective=(
|
||||
@@ -189,16 +206,17 @@ def _build_news_analysis_request(
|
||||
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
|
||||
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
|
||||
"3. **后续重点观察信号与不确定边界**。\n"
|
||||
"请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。"
|
||||
"正文直接输出面向用户的 Markdown,不要把正文包在 JSON 里;若存在任何明确的地理国家、地区或海域影响范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
|
||||
),
|
||||
system_prompt=(
|
||||
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
|
||||
"如有前序对话与用户备忘录,请保持指代与口径延续。"
|
||||
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。"
|
||||
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。\n\n"
|
||||
f"{_INFLUENCE_ZONE_GUIDANCE}"
|
||||
),
|
||||
context=context,
|
||||
constraints=[
|
||||
"Output clean user-facing Markdown directly (not JSON).",
|
||||
"Output clean user-facing Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
|
||||
"Distinguish reported facts from analytical outlook.",
|
||||
],
|
||||
thinking=thinking_cfg,
|
||||
@@ -234,20 +252,23 @@ def _build_telemetry_stream_request(
|
||||
context["user_memory_notes"] = memory_notes
|
||||
if pinned_summaries:
|
||||
context["pinned_comparisons"] = pinned_summaries
|
||||
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
|
||||
return SituationalAnalysisRequest(
|
||||
title=f"Planet 态势参谋分析({domain})",
|
||||
objective=(
|
||||
f"用户问题:{question}\n\n"
|
||||
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
|
||||
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。"
|
||||
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要把正文包在 JSON 对象里;"
|
||||
"若涉及明确国家、地区或海域范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
|
||||
),
|
||||
system_prompt=(
|
||||
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
|
||||
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。"
|
||||
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。\n\n"
|
||||
f"{_INFLUENCE_ZONE_GUIDANCE}"
|
||||
),
|
||||
context=context,
|
||||
constraints=[
|
||||
"Output clean Markdown directly (not JSON).",
|
||||
"Output clean Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
|
||||
"Do not invent telemetry counts or unverified outages outside context.",
|
||||
],
|
||||
thinking=thinking_cfg,
|
||||
@@ -271,6 +292,8 @@ async def stream_session_turn(
|
||||
conversation_summary: str | None = None,
|
||||
memory_notes: list[str] | None = None,
|
||||
pinned_summaries: list[str] | None = None,
|
||||
workflow_id: str | None = None,
|
||||
targets: list[dict[str, Any]] | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline."""
|
||||
check_stream_quota(access)
|
||||
@@ -335,6 +358,193 @@ async def stream_session_turn(
|
||||
compacted_flag = bool(compaction.get("compacted"))
|
||||
memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries)
|
||||
|
||||
if workflow_id:
|
||||
wf_dict: dict[str, Any] | None = None
|
||||
try:
|
||||
await ensure_builtin_workflows(db)
|
||||
wf_row = (
|
||||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
|
||||
).scalar_one_or_none()
|
||||
if wf_row is not None:
|
||||
wf_dict = wf_row.to_dict()
|
||||
except Exception:
|
||||
wf_dict = None
|
||||
if wf_dict is None:
|
||||
wf_dict = _fallback_workflow_dict(workflow_id)
|
||||
|
||||
if wf_dict is not None:
|
||||
wf_started_at = datetime.now(UTC)
|
||||
wf_trace: list[str] = []
|
||||
wf_status = "completed"
|
||||
wf_error = ""
|
||||
wf_answer = ""
|
||||
wf_model = str(model_name or "")
|
||||
wf_provider = str(provider_name or "")
|
||||
wf_revision = int(wf_dict.get("active_revision") or 1)
|
||||
wf_scene_zones_count = 0
|
||||
run_handle = register_active_run_handle(
|
||||
ActiveRunHandle(
|
||||
run_id=run_id,
|
||||
session_id=session_id_val if session is not None else None,
|
||||
actor_key=getattr(access, "actor_key", "anonymous"),
|
||||
workflow_id=workflow_id,
|
||||
access_tier=getattr(access, "access_tier", "public_zero_cost"),
|
||||
question=question[:500],
|
||||
started_at=wf_started_at,
|
||||
)
|
||||
)
|
||||
try:
|
||||
wf_earth_ctx: dict[str, Any] = {
|
||||
**merged_ctx,
|
||||
"domain": domain,
|
||||
"selected_codes": codes,
|
||||
"visible_layers": visible_layers,
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at,
|
||||
}
|
||||
if news_context:
|
||||
wf_earth_ctx["news_context"] = news_context
|
||||
if clean_memory_notes:
|
||||
wf_earth_ctx["user_memory_notes"] = clean_memory_notes
|
||||
|
||||
effective_client = ai_client
|
||||
if ai_ready and ai_client is not None and type(ai_client) is AIProviderClient and ai_client.llm_config:
|
||||
cur_max = int(ai_client.llm_config.get("max_tokens") or 0)
|
||||
if cur_max < 3200:
|
||||
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
|
||||
|
||||
allow_external = getattr(access, "access_tier", "public_zero_cost") == "admin"
|
||||
async for item in run_workflow_dag_stream(
|
||||
db=db,
|
||||
workflow=wf_dict,
|
||||
question=question,
|
||||
use_draft=False,
|
||||
targets=targets,
|
||||
earth_context=wf_earth_ctx,
|
||||
history=recent_history,
|
||||
ai_client=effective_client,
|
||||
request=request,
|
||||
run_id=run_id,
|
||||
allow_external_tools=allow_external,
|
||||
cancel_event=run_handle.cancel_event,
|
||||
extra_meta={
|
||||
"session_id": session_id_val,
|
||||
"domain": domain,
|
||||
"ai_enabled": ai_ready,
|
||||
"provider": provider_name if ai_ready else None,
|
||||
"model": model_name if ai_ready else None,
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"context_state": {**merged_ctx, "domain": domain},
|
||||
**({"session_token": issued_session_token} if issued_session_token else {}),
|
||||
},
|
||||
):
|
||||
if run_handle.cancel_event.is_set() or (
|
||||
request is not None and await request.is_disconnected()
|
||||
):
|
||||
wf_status = "cancelled"
|
||||
break
|
||||
ev_name = str(item.get("event") or "")
|
||||
ev_data = dict(item.get("data") or {})
|
||||
if ev_name == "node" and ev_data.get("status") == "completed":
|
||||
nid = str(ev_data.get("node_id") or "")
|
||||
if nid and nid not in wf_trace:
|
||||
wf_trace.append(nid)
|
||||
elif ev_name == "scene":
|
||||
s_spec = ev_data.get("scene_spec")
|
||||
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
|
||||
wf_scene_zones_count = len(s_spec["influence_zones"])
|
||||
elif ev_name == "done":
|
||||
if run_handle.cancel_event.is_set():
|
||||
wf_status = "cancelled"
|
||||
break
|
||||
if isinstance(ev_data.get("nodes"), list):
|
||||
wf_trace = [str(n) for n in ev_data["nodes"] if n]
|
||||
if ev_data.get("model"):
|
||||
wf_model = str(ev_data["model"])
|
||||
if ev_data.get("provider"):
|
||||
wf_provider = str(ev_data["provider"])
|
||||
s_spec = ev_data.get("scene_spec")
|
||||
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
|
||||
wf_scene_zones_count = len(s_spec["influence_zones"])
|
||||
wf_answer = str(ev_data.get("answer_markdown") or "")
|
||||
ev_data.setdefault("usage", {})
|
||||
ev_data["compacted"] = compacted_flag
|
||||
ev_data["conversation_summary"] = compacted_summary
|
||||
ev_data["memory_used"] = memory_used_flag
|
||||
if session is not None and isinstance(session.context_state, dict):
|
||||
base_recent = list(session.context_state.get("recent_messages") or recent_history)
|
||||
updated_recent = [*base_recent, {"role": "user", "content": question}]
|
||||
if wf_answer:
|
||||
updated_recent.append({"role": "assistant", "content": wf_answer[:1800]})
|
||||
session.context_state = {
|
||||
**session.context_state,
|
||||
"conversation_summary": compacted_summary,
|
||||
"recent_messages": updated_recent[-8:],
|
||||
}
|
||||
elif ev_name == "error":
|
||||
wf_status = "failed"
|
||||
wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error")
|
||||
yield _format_sse(ev_name, ev_data)
|
||||
if run_handle.cancel_event.is_set():
|
||||
wf_status = "cancelled"
|
||||
except asyncio.CancelledError:
|
||||
wf_status = "cancelled"
|
||||
raise
|
||||
except Exception as exc:
|
||||
wf_status = "failed"
|
||||
wf_error = str(exc)
|
||||
logger.warning_event(
|
||||
"Bound Earth workflow DAG stream failed",
|
||||
event="ai_stream.workflow_dag.failed",
|
||||
context={"workflow_id": workflow_id, "run_id": run_id, "error": wf_error},
|
||||
)
|
||||
yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)})
|
||||
finally:
|
||||
unregister_active_run_handle(run_id)
|
||||
try:
|
||||
wf_completed_at = datetime.now(UTC)
|
||||
wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000))
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=run_id,
|
||||
session_id=session.id if session is not None else None,
|
||||
workflow_id=workflow_id,
|
||||
status=wf_status,
|
||||
access_tier=getattr(access, "access_tier", "public_zero_cost"),
|
||||
actor_key=getattr(access, "actor_key", "anonymous"),
|
||||
question=question[:500],
|
||||
input_params={
|
||||
"domain": domain,
|
||||
"targets_count": len(targets or []),
|
||||
"source": "earth_copilot",
|
||||
},
|
||||
tool_trace=wf_trace,
|
||||
budget_used={
|
||||
"steps": len(wf_trace),
|
||||
"model_used": wf_model,
|
||||
"provider": wf_provider,
|
||||
"latency_ms": wf_latency_ms,
|
||||
"workflow_revision": wf_revision,
|
||||
"scene_zones_count": wf_scene_zones_count,
|
||||
},
|
||||
error_message=wf_error[:500],
|
||||
started_at=wf_started_at,
|
||||
completed_at=wf_completed_at,
|
||||
)
|
||||
)
|
||||
if hasattr(db, "commit"):
|
||||
await db.commit()
|
||||
schedule_post_run_evolution(workflow_id, run_id)
|
||||
except Exception:
|
||||
if hasattr(db, "rollback"):
|
||||
try:
|
||||
await db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
|
||||
view_spec: dict[str, Any] | None = None
|
||||
scene_spec: dict[str, Any] | None = None
|
||||
evidence: dict[str, Any] = {}
|
||||
@@ -429,7 +639,8 @@ async def stream_session_turn(
|
||||
def _persist_session_memory(answer_text: str) -> None:
|
||||
if session is None or not isinstance(session.context_state, dict):
|
||||
return
|
||||
updated_recent = [*recent_history, {"role": "user", "content": question}]
|
||||
base_recent = list(session.context_state.get("recent_messages") or recent_history)
|
||||
updated_recent = [*base_recent, {"role": "user", "content": question}]
|
||||
if answer_text:
|
||||
updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
|
||||
session.context_state = {
|
||||
@@ -504,13 +715,27 @@ async def stream_session_turn(
|
||||
|
||||
text_chunks: list[str] = []
|
||||
reasoning_chunks: list[str] = []
|
||||
pending_scene_tail = ""
|
||||
resolved_provider = provider_name
|
||||
resolved_model = model_name
|
||||
final_usage: dict[str, Any] = {}
|
||||
direct_run_handle = register_active_run_handle(
|
||||
ActiveRunHandle(
|
||||
run_id=run_id,
|
||||
session_id=session_id_val if session is not None else None,
|
||||
actor_key=getattr(access, "actor_key", "anonymous"),
|
||||
workflow_id=f"stream.{domain}",
|
||||
access_tier=getattr(access, "access_tier", "public_zero_cost"),
|
||||
question=question[:500],
|
||||
started_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
|
||||
if request is not None and await request.is_disconnected():
|
||||
if direct_run_handle.cancel_event.is_set() or (
|
||||
request is not None and await request.is_disconnected()
|
||||
):
|
||||
return
|
||||
ev_type = str(ev.get("event") or "")
|
||||
if ev_type == "start":
|
||||
@@ -527,7 +752,10 @@ async def stream_session_turn(
|
||||
delta = ev.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
text_chunks.append(delta)
|
||||
yield _format_sse("text", {"delta": delta})
|
||||
combined_buf = pending_scene_tail + delta
|
||||
emit_chunk, pending_scene_tail = _consume_text_holding_scene_tag(combined_buf)
|
||||
if emit_chunk:
|
||||
yield _format_sse("text", {"delta": emit_chunk})
|
||||
elif ev_type == "done":
|
||||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||||
resolved_provider = ev["provider"]
|
||||
@@ -538,17 +766,30 @@ async def stream_session_turn(
|
||||
elif ev_type == "error":
|
||||
raise RuntimeError(str(ev.get("detail") or "AI stream error"))
|
||||
|
||||
if direct_run_handle.cancel_event.is_set():
|
||||
return
|
||||
|
||||
if pending_scene_tail:
|
||||
cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail)
|
||||
if cleaned_tail:
|
||||
yield _format_sse("text", {"delta": cleaned_tail})
|
||||
|
||||
combined_text = "".join(text_chunks).strip()
|
||||
if not combined_text:
|
||||
raise RuntimeError("AI provider stream returned empty response")
|
||||
|
||||
clean_text, inline_thoughts = strip_thinking_text(combined_text)
|
||||
clean_text, parsed_scene = extract_planet_scene_from_text(clean_text or combined_text)
|
||||
combined_reasoning = "".join(reasoning_chunks).strip()
|
||||
if inline_thoughts:
|
||||
extra_thought = "\n\n".join(inline_thoughts)
|
||||
combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
|
||||
|
||||
final_answer_md = clean_text or combined_text
|
||||
merged_scene_spec: dict[str, Any] | None = dict(scene_spec) if isinstance(scene_spec, dict) else None
|
||||
if parsed_scene:
|
||||
merged_scene_spec = {**(merged_scene_spec or {}), "domain": (merged_scene_spec or {}).get("domain") or domain, **parsed_scene}
|
||||
|
||||
_persist_session_memory(final_answer_md)
|
||||
if hasattr(db, "commit"):
|
||||
try:
|
||||
@@ -556,22 +797,26 @@ async def stream_session_turn(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
yield _format_sse(
|
||||
"done",
|
||||
{
|
||||
"status": "completed",
|
||||
"generation_mode": "llm_verified",
|
||||
"zero_token": False,
|
||||
"provider": resolved_provider,
|
||||
"model": resolved_model,
|
||||
"usage": final_usage,
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"answer_markdown": final_answer_md,
|
||||
"reasoning_markdown": combined_reasoning,
|
||||
},
|
||||
)
|
||||
if merged_scene_spec is not None and (merged_scene_spec.get("influence_zones") or parsed_scene):
|
||||
yield _format_sse("scene", {"scene_spec": merged_scene_spec})
|
||||
|
||||
done_payload: dict[str, Any] = {
|
||||
"status": "completed",
|
||||
"generation_mode": "llm_verified",
|
||||
"zero_token": False,
|
||||
"provider": resolved_provider,
|
||||
"model": resolved_model,
|
||||
"usage": final_usage,
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"answer_markdown": final_answer_md,
|
||||
"reasoning_markdown": combined_reasoning,
|
||||
}
|
||||
if merged_scene_spec is not None:
|
||||
done_payload["scene_spec"] = merged_scene_spec
|
||||
|
||||
yield _format_sse("done", done_payload)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
@@ -611,3 +856,5 @@ async def stream_session_turn(
|
||||
"fallback_reason": str(exc),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
unregister_active_run_handle(run_id)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -94,6 +94,17 @@ def get_active_run_handle(run_id: str) -> ActiveRunHandle | None:
|
||||
return _ACTIVE_RUNS.get(run_id)
|
||||
|
||||
|
||||
def register_active_run_handle(handle: ActiveRunHandle) -> ActiveRunHandle:
|
||||
"""Register an active streaming/execution run handle for explicit cooperative cancellation."""
|
||||
_ACTIVE_RUNS[handle.run_id] = handle
|
||||
return handle
|
||||
|
||||
|
||||
def unregister_active_run_handle(run_id: str) -> None:
|
||||
"""Remove an active run handle once execution finishes or aborts."""
|
||||
_ACTIVE_RUNS.pop(run_id, None)
|
||||
|
||||
|
||||
def cancel_active_run_handle(run_id: str) -> bool:
|
||||
"""Signal cancellation event and abort in-flight asyncio task if active."""
|
||||
handle = _ACTIVE_RUNS.get(run_id)
|
||||
@@ -136,6 +147,481 @@ class WorkbenchBlockSpec(BaseModel):
|
||||
data: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class InfluenceZoneEdgeSpec(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
style: Literal["soft", "sharp"] = "soft"
|
||||
feather_px: float = Field(default=22.0, ge=0.0, le=48.0)
|
||||
border_width: float = Field(default=1.5, ge=0.0, le=6.0)
|
||||
|
||||
|
||||
class InfluenceZoneAnimationSpec(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["sweep", "radial", "fade"] = "sweep"
|
||||
direction: str = Field(default="west_to_east", max_length=32)
|
||||
duration_ms: int = Field(default=1800, ge=150, le=8000)
|
||||
delay_ms: int = Field(default=0, ge=0, le=5000)
|
||||
|
||||
|
||||
class InfluenceZoneShapeSpec(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
mode: Literal["countries", "region_preset", "circle", "polygon"]
|
||||
countries: list[str] = Field(default_factory=list, max_length=64)
|
||||
region_preset: str | None = Field(default=None, max_length=32)
|
||||
center: list[float] | None = Field(default=None, min_length=2, max_length=2)
|
||||
radius_km: float | None = Field(default=None, ge=20.0, le=15000.0)
|
||||
coordinates: list[list[list[float]]] = Field(default_factory=list, max_length=16)
|
||||
|
||||
|
||||
class InfluenceZoneSpec(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str = Field(..., min_length=1, max_length=64)
|
||||
label: str = Field(default="", max_length=80)
|
||||
color: str = Field(default="#38bdf8", pattern=r"^#[0-9a-fA-F]{6}$")
|
||||
opacity: float = Field(default=0.42, ge=0.05, le=0.9)
|
||||
z_index: int = Field(default=0, ge=-50, le=50)
|
||||
edge: InfluenceZoneEdgeSpec = Field(default_factory=InfluenceZoneEdgeSpec)
|
||||
animation: InfluenceZoneAnimationSpec = Field(default_factory=InfluenceZoneAnimationSpec)
|
||||
shape: InfluenceZoneShapeSpec
|
||||
|
||||
|
||||
_SCENE_COLOR_NAMES: dict[str, str] = {
|
||||
"red": "#ef4444",
|
||||
"crimson": "#dc2626",
|
||||
"orange": "#f97316",
|
||||
"amber": "#f59e0b",
|
||||
"yellow": "#eab308",
|
||||
"green": "#22c55e",
|
||||
"emerald": "#10b981",
|
||||
"teal": "#14b8a6",
|
||||
"cyan": "#06b6d4",
|
||||
"blue": "#38bdf8",
|
||||
"indigo": "#6366f1",
|
||||
"purple": "#a855f7",
|
||||
"violet": "#8b5cf6",
|
||||
"pink": "#ec4899",
|
||||
"white": "#f8fafc",
|
||||
}
|
||||
|
||||
SUPPORTED_REGION_PRESETS: frozenset[str] = frozenset(
|
||||
{
|
||||
"APEC",
|
||||
"ASIA_PACIFIC",
|
||||
"NORTHEAST_ASIA",
|
||||
"EAST_ASIA",
|
||||
"KOREAN_PENINSULA",
|
||||
"SOUTHEAST_ASIA",
|
||||
"SOUTH_ASIA",
|
||||
"CENTRAL_ASIA",
|
||||
"INDO_PACIFIC",
|
||||
"ASEAN",
|
||||
"EU",
|
||||
"EUROPE",
|
||||
"EASTERN_EUROPE",
|
||||
"NORTHERN_EUROPE",
|
||||
"WESTERN_EUROPE",
|
||||
"G7",
|
||||
"BRICS",
|
||||
"NATO",
|
||||
"MIDDLE_EAST",
|
||||
"MENA",
|
||||
"AMERICAS",
|
||||
"NORTH_AMERICA",
|
||||
"SOUTH_AMERICA",
|
||||
"AFRICA",
|
||||
}
|
||||
)
|
||||
|
||||
_REGION_PRESET_ALIASES: dict[str, str] = {
|
||||
"东北亚": "NORTHEAST_ASIA",
|
||||
"NE_ASIA": "NORTHEAST_ASIA",
|
||||
"东亚": "EAST_ASIA",
|
||||
"朝鲜半岛": "KOREAN_PENINSULA",
|
||||
"PENINSULA": "KOREAN_PENINSULA",
|
||||
"东南": "SOUTHEAST_ASIA",
|
||||
"东南亚": "SOUTHEAST_ASIA",
|
||||
"SE_ASIA": "SOUTHEAST_ASIA",
|
||||
"南亚": "SOUTH_ASIA",
|
||||
"中亚": "CENTRAL_ASIA",
|
||||
"亚太": "ASIA_PACIFIC",
|
||||
"印太": "INDO_PACIFIC",
|
||||
"欧洲": "EUROPE",
|
||||
"东欧": "EASTERN_EUROPE",
|
||||
"北欧": "NORTHERN_EUROPE",
|
||||
"NORDIC": "NORTHERN_EUROPE",
|
||||
"BALTIC": "NORTHERN_EUROPE",
|
||||
"波罗的海": "NORTHERN_EUROPE",
|
||||
"西欧": "WESTERN_EUROPE",
|
||||
"欧盟": "EU",
|
||||
"北约": "NATO",
|
||||
"东盟": "ASEAN",
|
||||
"中东": "MIDDLE_EAST",
|
||||
"中东北非": "MENA",
|
||||
"MIDDLE_EAST_NORTH_AFRICA": "MENA",
|
||||
"美洲": "AMERICAS",
|
||||
"北美": "NORTH_AMERICA",
|
||||
"南美": "SOUTH_AMERICA",
|
||||
"拉美": "SOUTH_AMERICA",
|
||||
"LATIN_AMERICA": "SOUTH_AMERICA",
|
||||
"非洲": "AFRICA",
|
||||
}
|
||||
|
||||
_COUNTRY_ALIAS_MAP: dict[str, str] = {
|
||||
"CN": "CHN",
|
||||
"CHN": "CHN",
|
||||
"CHINA": "CHN",
|
||||
"PRC": "CHN",
|
||||
"中国": "CHN",
|
||||
"HK": "CHN",
|
||||
"HKG": "CHN",
|
||||
"香港": "CHN",
|
||||
"MO": "CHN",
|
||||
"MAC": "CHN",
|
||||
"澳门": "CHN",
|
||||
"TW": "CHN",
|
||||
"TWN": "CHN",
|
||||
"台湾": "CHN",
|
||||
"KP": "PRK",
|
||||
"PRK": "PRK",
|
||||
"DPRK": "PRK",
|
||||
"NK": "PRK",
|
||||
"NKR": "PRK",
|
||||
"NORTH KOREA": "PRK",
|
||||
"NORTH_KOREA": "PRK",
|
||||
"朝鲜": "PRK",
|
||||
"北朝鲜": "PRK",
|
||||
"朝鲜民主主义人民共和国": "PRK",
|
||||
"KR": "KOR",
|
||||
"KOR": "KOR",
|
||||
"ROK": "KOR",
|
||||
"KOREA": "KOR",
|
||||
"SOUTH KOREA": "KOR",
|
||||
"SOUTH_KOREA": "KOR",
|
||||
"韩国": "KOR",
|
||||
"南韩": "KOR",
|
||||
"大韩民国": "KOR",
|
||||
"US": "USA",
|
||||
"USA": "USA",
|
||||
"AMERICA": "USA",
|
||||
"美国": "USA",
|
||||
"RU": "RUS",
|
||||
"RUS": "RUS",
|
||||
"RUSSIA": "RUS",
|
||||
"俄罗斯": "RUS",
|
||||
"俄国": "RUS",
|
||||
"JP": "JPN",
|
||||
"JPN": "JPN",
|
||||
"JAPAN": "JPN",
|
||||
"日本": "JPN",
|
||||
"UK": "GBR",
|
||||
"GB": "GBR",
|
||||
"GBR": "GBR",
|
||||
"BRITAIN": "GBR",
|
||||
"英国": "GBR",
|
||||
"FR": "FRA",
|
||||
"FRA": "FRA",
|
||||
"FRANCE": "FRA",
|
||||
"法国": "FRA",
|
||||
"DE": "DEU",
|
||||
"DEU": "DEU",
|
||||
"GERMANY": "DEU",
|
||||
"德国": "DEU",
|
||||
"IN": "IND",
|
||||
"IND": "IND",
|
||||
"INDIA": "IND",
|
||||
"印度": "IND",
|
||||
"AU": "AUS",
|
||||
"AUS": "AUS",
|
||||
"AUSTRALIA": "AUS",
|
||||
"澳大利亚": "AUS",
|
||||
"CA": "CAN",
|
||||
"CAN": "CAN",
|
||||
"CANADA": "CAN",
|
||||
"加拿大": "CAN",
|
||||
"BR": "BRA",
|
||||
"BRA": "BRA",
|
||||
"BRAZIL": "BRA",
|
||||
"巴西": "BRA",
|
||||
"SG": "SGP",
|
||||
"SGP": "SGP",
|
||||
"SINGAPORE": "SGP",
|
||||
"新加坡": "SGP",
|
||||
"ID": "IDN",
|
||||
"IDN": "IDN",
|
||||
"INDONESIA": "IDN",
|
||||
"印尼": "IDN",
|
||||
"VN": "VNM",
|
||||
"VNM": "VNM",
|
||||
"VIETNAM": "VNM",
|
||||
"越南": "VNM",
|
||||
"TH": "THA",
|
||||
"THA": "THA",
|
||||
"THAILAND": "THA",
|
||||
"泰国": "THA",
|
||||
"MY": "MYS",
|
||||
"MYS": "MYS",
|
||||
"MALAYSIA": "MYS",
|
||||
"马来西亚": "MYS",
|
||||
"PH": "PHL",
|
||||
"PHL": "PHL",
|
||||
"PHILIPPINES": "PHL",
|
||||
"菲律宾": "PHL",
|
||||
"UA": "UKR",
|
||||
"UKR": "UKR",
|
||||
"UKRAINE": "UKR",
|
||||
"乌克兰": "UKR",
|
||||
"IR": "IRN",
|
||||
"IRN": "IRN",
|
||||
"IRAN": "IRN",
|
||||
"伊朗": "IRN",
|
||||
"SA": "SAU",
|
||||
"SAU": "SAU",
|
||||
"沙特": "SAU",
|
||||
"TR": "TUR",
|
||||
"TUR": "TUR",
|
||||
"TURKEY": "TUR",
|
||||
"土耳其": "TUR",
|
||||
"IL": "ISR",
|
||||
"ISR": "ISR",
|
||||
"ISRAEL": "ISR",
|
||||
"以色列": "ISR",
|
||||
"EG": "EGY",
|
||||
"EGY": "EGY",
|
||||
"EGYPT": "EGY",
|
||||
"埃及": "EGY",
|
||||
"SO": "SOM",
|
||||
"SOM": "SOM",
|
||||
"SOMALIA": "SOM",
|
||||
"索马里": "SOM",
|
||||
"YE": "YEM",
|
||||
"YEM": "YEM",
|
||||
"YEMEN": "YEM",
|
||||
"也门": "YEM",
|
||||
"AE": "ARE",
|
||||
"ARE": "ARE",
|
||||
"UAE": "ARE",
|
||||
"阿联酋": "ARE",
|
||||
"MN": "MNG",
|
||||
"MNG": "MNG",
|
||||
"MONGOLIA": "MNG",
|
||||
"蒙古": "MNG",
|
||||
"PL": "POL",
|
||||
"POL": "POL",
|
||||
"POLAND": "POL",
|
||||
"波兰": "POL",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_country_code(raw: Any) -> str:
|
||||
text = str(raw or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
upper = text.upper()
|
||||
return _COUNTRY_ALIAS_MAP.get(text) or _COUNTRY_ALIAS_MAP.get(upper) or upper
|
||||
|
||||
|
||||
def _normalize_region_preset(raw: Any) -> str | None:
|
||||
text = str(raw or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
normalized = re.sub(r"[\s-]+", "_", text.upper())
|
||||
canonical = _REGION_PRESET_ALIASES.get(text) or _REGION_PRESET_ALIASES.get(normalized) or normalized
|
||||
return canonical[:32] if canonical in SUPPORTED_REGION_PRESETS else None
|
||||
|
||||
|
||||
def _coerce_bounded_float(value: Any, low: float, high: float, default: float) -> float:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
|
||||
return default
|
||||
try:
|
||||
num = float(value)
|
||||
except Exception:
|
||||
return default
|
||||
return max(low, min(high, num))
|
||||
|
||||
|
||||
def _coerce_bounded_int(value: Any, low: int, high: int, default: int) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
|
||||
return default
|
||||
try:
|
||||
num = int(float(value))
|
||||
except Exception:
|
||||
return default
|
||||
return max(low, min(high, num))
|
||||
|
||||
|
||||
def _normalize_zone_color(raw: Any) -> str:
|
||||
text = str(raw or "").strip().lower()
|
||||
if re.fullmatch(r"#[0-9a-f]{6}", text):
|
||||
return text
|
||||
if re.fullmatch(r"#[0-9a-f]{3}", text):
|
||||
return "#" + "".join(ch * 2 for ch in text[1:])
|
||||
return _SCENE_COLOR_NAMES.get(text, "#38bdf8")
|
||||
|
||||
|
||||
def _normalize_influence_zone_candidate(item: dict[str, Any], idx: int) -> dict[str, Any]:
|
||||
"""Sanitize tolerant LLM-authored influence zone fields before strict Pydantic validation."""
|
||||
raw_edge = item.get("edge")
|
||||
edge_dict: dict[str, Any] = {}
|
||||
hoisted_opacity = None
|
||||
if isinstance(raw_edge, str):
|
||||
style = raw_edge.strip().lower()
|
||||
edge_dict["style"] = style if style in {"soft", "sharp"} else "soft"
|
||||
elif isinstance(raw_edge, dict):
|
||||
if "opacity" in raw_edge:
|
||||
hoisted_opacity = raw_edge.get("opacity")
|
||||
style = str(raw_edge.get("style") or "soft").strip().lower()
|
||||
edge_dict["style"] = style if style in {"soft", "sharp"} else "soft"
|
||||
if "feather_px" in raw_edge:
|
||||
edge_dict["feather_px"] = _coerce_bounded_float(raw_edge.get("feather_px"), 0.0, 48.0, 22.0)
|
||||
if "border_width" in raw_edge:
|
||||
edge_dict["border_width"] = _coerce_bounded_float(raw_edge.get("border_width"), 0.0, 6.0, 1.5)
|
||||
|
||||
raw_anim = item.get("animation")
|
||||
anim_dict: dict[str, Any] = {}
|
||||
if isinstance(raw_anim, str):
|
||||
atype = raw_anim.strip().lower()
|
||||
anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep"
|
||||
elif isinstance(raw_anim, dict):
|
||||
atype = str(raw_anim.get("type") or "sweep").strip().lower()
|
||||
anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep"
|
||||
if raw_anim.get("direction"):
|
||||
anim_dict["direction"] = str(raw_anim["direction"])[:32]
|
||||
if "duration_ms" in raw_anim:
|
||||
anim_dict["duration_ms"] = _coerce_bounded_int(raw_anim.get("duration_ms"), 150, 8000, 1800)
|
||||
if "delay_ms" in raw_anim:
|
||||
anim_dict["delay_ms"] = _coerce_bounded_int(raw_anim.get("delay_ms"), 0, 5000, 0)
|
||||
|
||||
raw_shape = item.get("shape")
|
||||
shape_src = dict(raw_shape) if isinstance(raw_shape, dict) else {
|
||||
k: item[k]
|
||||
for k in ("mode", "countries", "country", "iso_codes", "region_preset", "region", "center", "radius_km", "coordinates")
|
||||
if k in item
|
||||
}
|
||||
raw_countries = shape_src.get("countries") if "countries" in shape_src else (shape_src.get("country") or shape_src.get("iso_codes"))
|
||||
if isinstance(raw_countries, str):
|
||||
raw_country_items = [raw_countries]
|
||||
elif isinstance(raw_countries, list):
|
||||
raw_country_items = raw_countries[:64]
|
||||
else:
|
||||
raw_country_items = []
|
||||
countries_list: list[str] = []
|
||||
seen_countries: set[str] = set()
|
||||
for raw_c in raw_country_items:
|
||||
norm_c = _normalize_country_code(raw_c)
|
||||
if norm_c and norm_c not in seen_countries:
|
||||
seen_countries.add(norm_c)
|
||||
countries_list.append(norm_c)
|
||||
|
||||
region_preset = shape_src.get("region_preset") or shape_src.get("region")
|
||||
region_preset_val = _normalize_region_preset(region_preset)
|
||||
|
||||
raw_center = shape_src.get("center")
|
||||
center_val: list[float] | None = None
|
||||
if isinstance(raw_center, dict) and "lat" in raw_center and "lon" in raw_center:
|
||||
center_val = [
|
||||
_coerce_bounded_float(raw_center.get("lat"), -90.0, 90.0, 0.0),
|
||||
_coerce_bounded_float(raw_center.get("lon"), -180.0, 180.0, 0.0),
|
||||
]
|
||||
elif isinstance(raw_center, (list, tuple)) and len(raw_center) >= 2:
|
||||
center_val = [
|
||||
_coerce_bounded_float(raw_center[0], -90.0, 90.0, 0.0),
|
||||
_coerce_bounded_float(raw_center[1], -180.0, 180.0, 0.0),
|
||||
]
|
||||
|
||||
raw_coords = shape_src.get("coordinates")
|
||||
coords_val: list[list[list[float]]] = []
|
||||
if isinstance(raw_coords, list) and raw_coords:
|
||||
first_coord = raw_coords[0]
|
||||
# Auto-wrap 2D polygon rings ([[lon, lat], ...]) to MultiPolygon ring list ([[[lon, lat], ...]]).
|
||||
if (
|
||||
isinstance(first_coord, (list, tuple))
|
||||
and first_coord
|
||||
and isinstance(first_coord[0], (int, float))
|
||||
):
|
||||
coords_val = [raw_coords] # type: ignore[list-item]
|
||||
else:
|
||||
coords_val = raw_coords[:16]
|
||||
|
||||
mode = str(shape_src.get("mode") or "").strip().lower()
|
||||
if mode not in {"countries", "region_preset", "circle", "polygon"}:
|
||||
if countries_list:
|
||||
mode = "countries"
|
||||
elif region_preset_val:
|
||||
mode = "region_preset"
|
||||
elif center_val is not None:
|
||||
mode = "circle"
|
||||
elif coords_val:
|
||||
mode = "polygon"
|
||||
elif mode == "region_preset" and region_preset_val is None and countries_list:
|
||||
mode = "countries"
|
||||
|
||||
shape_clean: dict[str, Any] = {"mode": mode}
|
||||
if countries_list:
|
||||
shape_clean["countries"] = countries_list
|
||||
if region_preset_val:
|
||||
shape_clean["region_preset"] = region_preset_val
|
||||
if center_val is not None:
|
||||
shape_clean["center"] = center_val
|
||||
if shape_src.get("radius_km") is not None:
|
||||
shape_clean["radius_km"] = _coerce_bounded_float(shape_src.get("radius_km"), 20.0, 15000.0, 600.0)
|
||||
if coords_val:
|
||||
shape_clean["coordinates"] = coords_val
|
||||
|
||||
opacity_raw = item.get("opacity", hoisted_opacity)
|
||||
candidate: dict[str, Any] = {
|
||||
"id": str(item.get("id") or f"zone-{idx + 1}").strip()[:64] or f"zone-{idx + 1}",
|
||||
"label": str(item.get("label") or item.get("name") or item.get("title") or "")[:80],
|
||||
"color": _normalize_zone_color(item.get("color")),
|
||||
"opacity": _coerce_bounded_float(opacity_raw, 0.05, 0.9, 0.42),
|
||||
"z_index": _coerce_bounded_int(item.get("z_index"), -50, 50, 0),
|
||||
"shape": shape_clean,
|
||||
}
|
||||
if edge_dict:
|
||||
candidate["edge"] = edge_dict
|
||||
if anim_dict:
|
||||
candidate["animation"] = anim_dict
|
||||
return candidate
|
||||
|
||||
|
||||
def validate_influence_zones(raw: Any) -> list[InfluenceZoneSpec]:
|
||||
"""Validate and bound LLM-proposed influence zones without failing the response."""
|
||||
if not isinstance(raw, list):
|
||||
return []
|
||||
validated: list[InfluenceZoneSpec] = []
|
||||
for idx, item in enumerate(raw[:12]):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
candidate = _normalize_influence_zone_candidate(item, idx)
|
||||
shape = candidate.get("shape") or {}
|
||||
mode = shape.get("mode")
|
||||
has_renderable_shape = (
|
||||
(mode == "countries" and bool(shape.get("countries")))
|
||||
or (mode == "region_preset" and bool(shape.get("region_preset")))
|
||||
or (mode == "circle" and shape.get("center") is not None)
|
||||
or (mode == "polygon" and bool(shape.get("coordinates")))
|
||||
)
|
||||
if not has_renderable_shape:
|
||||
logger.warning_event(
|
||||
"Influence zone candidate rejected due to empty/unrenderable shape",
|
||||
event="ai_scene.zone.rejected",
|
||||
context={"index": idx, "mode": mode, "id": candidate.get("id")},
|
||||
)
|
||||
continue
|
||||
try:
|
||||
validated.append(InfluenceZoneSpec.model_validate(candidate))
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Influence zone candidate rejected",
|
||||
event="ai_scene.zone.rejected",
|
||||
context={"index": idx, "error": str(exc)},
|
||||
)
|
||||
continue
|
||||
return validated
|
||||
|
||||
|
||||
class SceneSpec(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
@@ -147,6 +633,7 @@ class SceneSpec(BaseModel):
|
||||
camera_hint: dict[str, float] | None = None
|
||||
presentation_key: str | None = None
|
||||
auto_play_presentation: bool = False
|
||||
influence_zones: list[InfluenceZoneSpec] = Field(default_factory=list, max_length=12)
|
||||
|
||||
|
||||
class ViewSpec(BaseModel):
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.alert import Alert, AlertSeverity, AlertStatus
|
||||
from app.schemas.ai import AlertBriefRequest, SituationalAnalysisRequest
|
||||
from app.models.alert import Alert, AlertStatus
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.task import CollectionTask
|
||||
from app.schemas.ai import SituationalAnalysisRequest
|
||||
from app.ai_tasks.prompts import get_effective_prompt
|
||||
|
||||
ALERT_BRIEF_PROMPT_KEY = "alerts.brief"
|
||||
@@ -19,6 +22,50 @@ def _format_counter(counter: Counter[str], empty_text: str = "无") -> str:
|
||||
return ",".join(f"{key} {value}" for key, value in counter.items())
|
||||
|
||||
|
||||
async def _collect_operational_health(db: AsyncSession) -> dict[str, Any]:
|
||||
"""Query failed collection tasks and unhealthy data sources, degrading safely."""
|
||||
summary: dict[str, Any] = {
|
||||
"failed_tasks_24h": 0,
|
||||
"recent_failed_tasks": [],
|
||||
"failed_datasources": [],
|
||||
}
|
||||
try:
|
||||
cutoff = datetime.now(UTC) - timedelta(hours=24)
|
||||
failed_24h_count = await db.execute(
|
||||
select(func.count(CollectionTask.id))
|
||||
.where(CollectionTask.status == "failed")
|
||||
.where(CollectionTask.created_at >= cutoff)
|
||||
)
|
||||
failed_tasks_rows = await db.execute(
|
||||
select(CollectionTask)
|
||||
.where(CollectionTask.status == "failed")
|
||||
.order_by(CollectionTask.created_at.desc(), CollectionTask.id.desc())
|
||||
.limit(6)
|
||||
)
|
||||
failed_sources_rows = await db.execute(
|
||||
select(DataSource)
|
||||
.where(DataSource.is_active.is_(True))
|
||||
.where(DataSource.last_status.in_(["failed", "error"]))
|
||||
)
|
||||
summary["failed_tasks_24h"] = int(failed_24h_count.scalar() or 0)
|
||||
summary["recent_failed_tasks"] = [
|
||||
{
|
||||
"source": task.source or f"datasource:{task.datasource_id}",
|
||||
"task_type": task.task_type,
|
||||
"error": (task.error_message or "")[:160],
|
||||
}
|
||||
for task in failed_tasks_rows.scalars().all()
|
||||
]
|
||||
summary["failed_datasources"] = [
|
||||
{"source": ds.source, "name": ds.name, "status": ds.last_status}
|
||||
for ds in failed_sources_rows.scalars().all()
|
||||
]
|
||||
except Exception:
|
||||
# Keep brief generation resilient even in minimal test DB fixtures.
|
||||
pass
|
||||
return summary
|
||||
|
||||
|
||||
async def build_alert_brief_request(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
@@ -76,6 +123,28 @@ async def build_alert_brief_request(
|
||||
)
|
||||
)
|
||||
|
||||
health = await _collect_operational_health(db)
|
||||
failed_sources = health["failed_datasources"]
|
||||
failed_tasks = health["recent_failed_tasks"]
|
||||
facts.append(
|
||||
f"近 24 小时采集任务失败 {health['failed_tasks_24h']} 次,"
|
||||
f"当前处于异常/失败状态的活跃数据源 {len(failed_sources)} 个。"
|
||||
)
|
||||
if failed_sources:
|
||||
facts.append(
|
||||
"异常数据源:"
|
||||
+ "、".join(f"{item['name']} ({item['source']})" for item in failed_sources[:6])
|
||||
+ "。"
|
||||
)
|
||||
if failed_tasks:
|
||||
facts.append(
|
||||
"最近失败任务摘录:"
|
||||
+ ";".join(
|
||||
f"{item['source']} [{item['task_type']}] {item['error'] or 'failed'}"
|
||||
for item in failed_tasks[:4]
|
||||
)
|
||||
)
|
||||
|
||||
context = {
|
||||
"source": "alerts",
|
||||
"total_alerts": total_alerts,
|
||||
@@ -86,6 +155,9 @@ async def build_alert_brief_request(
|
||||
"status_distribution": dict(status_counts),
|
||||
"top_datasources": dict(datasource_counts.most_common(6)),
|
||||
"top_active_datasources": dict(active_datasource_counts.most_common(5)),
|
||||
"failed_tasks_24h": health["failed_tasks_24h"],
|
||||
"recent_failed_tasks": failed_tasks,
|
||||
"failed_datasources": failed_sources,
|
||||
}
|
||||
prompt = await get_effective_prompt(db, ALERT_BRIEF_PROMPT_KEY)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from datetime import UTC, datetime
|
||||
from time import perf_counter
|
||||
from urllib.parse import urlparse
|
||||
import httpx
|
||||
from sqlalchemy import delete, insert, select, text, update
|
||||
from sqlalchemy import delete, insert, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.collected_data_fields import build_dynamic_metadata, get_record_field
|
||||
@@ -66,6 +66,15 @@ class BaseCollector(ABC):
|
||||
self._fetch_is_complete: bool = False
|
||||
self._fetch_is_sample_fallback: bool = False
|
||||
self._sample_fallback_reason: Optional[str] = None
|
||||
self._db_commit_lock: Optional[asyncio.Lock] = asyncio.Lock()
|
||||
|
||||
def _get_db_commit_lock(self) -> asyncio.Lock:
|
||||
"""Return the per-collector lock used to serialize DB session commits."""
|
||||
lock = getattr(self, "_db_commit_lock", None)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
self._db_commit_lock = lock
|
||||
return lock
|
||||
|
||||
def _mark_fetch_complete(self, complete: bool = True) -> None:
|
||||
"""Mark the current fetch payload as a verified full-universe snapshot."""
|
||||
@@ -157,7 +166,9 @@ class BaseCollector(ABC):
|
||||
|
||||
async def update_progress(self, records_processed: int, *, commit: bool = False, force: bool = False):
|
||||
"""Update task progress - call this during data processing"""
|
||||
if self._current_task and self._db_session:
|
||||
if not self._current_task or not self._db_session:
|
||||
return
|
||||
async with self._get_db_commit_lock():
|
||||
self._current_task.records_processed = records_processed
|
||||
if self._current_task.total_records and self._current_task.total_records > 0:
|
||||
self._current_task.progress = (
|
||||
@@ -172,7 +183,9 @@ class BaseCollector(ABC):
|
||||
await self._publish_task_update(force=force)
|
||||
|
||||
async def set_phase(self, phase: str, *, message: str | None = None, reset_progress: bool = True):
|
||||
if self._current_task and self._db_session:
|
||||
if not self._current_task or not self._db_session:
|
||||
return
|
||||
async with self._get_db_commit_lock():
|
||||
self._current_task.phase = phase
|
||||
self._current_task.phase_message = message
|
||||
if reset_progress:
|
||||
@@ -198,24 +211,25 @@ class BaseCollector(ABC):
|
||||
if not self._current_task or not self._db_session:
|
||||
return
|
||||
|
||||
if progress is None and current is not None and total and total > 0:
|
||||
progress = (current / total) * 100
|
||||
async with self._get_db_commit_lock():
|
||||
if progress is None and current is not None and total and total > 0:
|
||||
progress = (current / total) * 100
|
||||
|
||||
if progress is not None:
|
||||
self._current_task.phase_progress = max(0.0, min(float(progress), 100.0))
|
||||
if current is not None:
|
||||
self._current_task.phase_current = max(0, int(current))
|
||||
if total is not None:
|
||||
self._current_task.phase_total = max(0, int(total))
|
||||
if unit is not None:
|
||||
self._current_task.phase_unit = unit
|
||||
if message is not None:
|
||||
self._current_task.phase_message = message
|
||||
if progress is not None:
|
||||
self._current_task.phase_progress = max(0.0, min(float(progress), 100.0))
|
||||
if current is not None:
|
||||
self._current_task.phase_current = max(0, int(current))
|
||||
if total is not None:
|
||||
self._current_task.phase_total = max(0, int(total))
|
||||
if unit is not None:
|
||||
self._current_task.phase_unit = unit
|
||||
if message is not None:
|
||||
self._current_task.phase_message = message
|
||||
|
||||
if commit:
|
||||
await self._db_session.commit()
|
||||
if commit:
|
||||
await self._db_session.commit()
|
||||
|
||||
await self._publish_task_update(force=force)
|
||||
await self._publish_task_update(force=force)
|
||||
|
||||
@abstractmethod
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
|
||||
@@ -116,16 +116,17 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
]
|
||||
total_expected = sum(expected_sizes) if expected_sizes else 0
|
||||
if total_expected > 0 and self._current_task and self._db_session:
|
||||
self._current_task.total_records = total_expected
|
||||
self._current_task.records_processed = 0
|
||||
self._current_task.progress = 0.0
|
||||
self._current_task.phase_progress = 0.0
|
||||
self._current_task.phase_message = "正在下载 IPtoASN 数据"
|
||||
self._current_task.phase_current = 0
|
||||
self._current_task.phase_total = total_expected
|
||||
self._current_task.phase_unit = "bytes"
|
||||
await self._db_session.commit()
|
||||
await self._publish_task_update(force=True)
|
||||
async with self._get_db_commit_lock():
|
||||
self._current_task.total_records = total_expected
|
||||
self._current_task.records_processed = 0
|
||||
self._current_task.progress = 0.0
|
||||
self._current_task.phase_progress = 0.0
|
||||
self._current_task.phase_message = "正在下载 IPtoASN 数据"
|
||||
self._current_task.phase_current = 0
|
||||
self._current_task.phase_total = total_expected
|
||||
self._current_task.phase_unit = "bytes"
|
||||
await self._db_session.commit()
|
||||
await self._publish_task_update(force=True)
|
||||
|
||||
url_progress: dict[str, int] = {url: 0 for url in dataset_urls}
|
||||
progress_lock = asyncio.Lock()
|
||||
@@ -136,29 +137,29 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
if total_expected <= 0:
|
||||
return
|
||||
async with progress_lock:
|
||||
current = max(0, downloaded_bytes)
|
||||
if current < url_progress[url]:
|
||||
url_downloaded = max(0, downloaded_bytes)
|
||||
if url_downloaded < url_progress[url]:
|
||||
return
|
||||
url_progress[url] = current
|
||||
url_progress[url] = url_downloaded
|
||||
aggregated = sum(url_progress.values())
|
||||
now = time.monotonic()
|
||||
current = min(aggregated, total_expected)
|
||||
should_emit = (
|
||||
aggregated >= total_expected
|
||||
or aggregated - last_emit["value"] >= min_emit_bytes
|
||||
or now - last_emit["t"] >= 2.0
|
||||
(current >= total_expected and last_emit["value"] < total_expected)
|
||||
or current - last_emit["value"] >= min_emit_bytes
|
||||
or (current > last_emit["value"] and now - last_emit["t"] >= 2.0)
|
||||
)
|
||||
if not should_emit:
|
||||
return
|
||||
last_emit["value"] = aggregated
|
||||
last_emit["value"] = current
|
||||
last_emit["t"] = now
|
||||
current = min(aggregated, total_expected)
|
||||
await self.update_phase_progress(
|
||||
current=current,
|
||||
total=total_expected,
|
||||
unit="bytes",
|
||||
message="正在下载 IPtoASN 数据",
|
||||
)
|
||||
await self.update_progress(current, commit=True)
|
||||
await self.update_phase_progress(
|
||||
current=current,
|
||||
total=total_expected,
|
||||
unit="bytes",
|
||||
message="正在下载 IPtoASN 数据",
|
||||
)
|
||||
await self.update_progress(current, commit=True)
|
||||
|
||||
dataset_paths = await asyncio.gather(
|
||||
*(
|
||||
|
||||
@@ -52,9 +52,11 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
from app.core.config import settings
|
||||
from app.services.datasource_connectivity import resolve_spacetrack_credentials
|
||||
|
||||
username = settings.SPACETRACK_USERNAME
|
||||
password = settings.SPACETRACK_PASSWORD
|
||||
username, password, _ = await resolve_spacetrack_credentials(self._db_session)
|
||||
username = username or settings.SPACETRACK_USERNAME
|
||||
password = password or settings.SPACETRACK_PASSWORD
|
||||
|
||||
if not username or not password:
|
||||
logger.warning_event(
|
||||
|
||||
@@ -131,9 +131,36 @@ AISSTREAM_DEFAULT_GUIDE = CredentialGuideDefault(
|
||||
)
|
||||
|
||||
|
||||
SPACETRACK_DEFAULT_GUIDE = CredentialGuideDefault(
|
||||
provider="spacetrack",
|
||||
title="Space-Track TLE 凭证获取教程",
|
||||
prompt=(
|
||||
"请生成一份中文教程,指导开发者注册并获取 Space-Track.org 的账号凭证并配置到 Planet。"
|
||||
"包含注册登录、遵循查询频率限制(如 GP 查询间隔)、在 Planet 采集器配置页填写用户名与密码、"
|
||||
"测试连通性与常见失败排查。请以 Space-Track 当前官网文档为准。"
|
||||
),
|
||||
markdown="""## Space-Track TLE 凭证获取
|
||||
|
||||
官方入口:https://www.space-track.org/
|
||||
|
||||
1. 前往 Space-Track.org 注册或登录账号。
|
||||
2. 确认账号已完成邮箱激活且可正常通过网站登录。
|
||||
3. 回到 Planet 的「采集管理 -> 采集器配置 -> `spacetrack_tle`」。
|
||||
4. 填写 `用户名` 与 `密码`(或通过环境变量 `SPACETRACK_USERNAME` / `SPACETRACK_PASSWORD` 注入)。
|
||||
5. 点击「连接测试」验证登录态与 TLE 查询接口后点击「保存」。
|
||||
|
||||
### 注意事项
|
||||
|
||||
- Space-Track 对 GP 数据接口有严格的限频策略,请避免高频手动重复抓取。
|
||||
- 本源使用表单会话登录(`/ajaxauth/login`),不要将账号密码当作普通 HTTP Basic Header 暴露。
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_CREDENTIAL_GUIDES = {
|
||||
BARENTSWATCH_DEFAULT_GUIDE.provider: BARENTSWATCH_DEFAULT_GUIDE,
|
||||
AISSTREAM_DEFAULT_GUIDE.provider: AISSTREAM_DEFAULT_GUIDE,
|
||||
SPACETRACK_DEFAULT_GUIDE.provider: SPACETRACK_DEFAULT_GUIDE,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -3,10 +3,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import func, select
|
||||
@@ -17,6 +20,7 @@ from app.core.enums import JobStatus
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.barentswatch import (
|
||||
BarentsWatchConfig,
|
||||
@@ -29,6 +33,26 @@ from app.services.barentswatch import (
|
||||
CONNECTIVITY_VALIDATION_KEY = "connectivity_validation"
|
||||
CONNECTIVITY_STORE_CATEGORY = "datasource_connectivity_validations"
|
||||
SUPPORTED_CREDENTIAL_PROVIDERS = {"barentswatch", "spacetrack", "aisstream"}
|
||||
_ARCGIS_SOURCES = frozenset(
|
||||
{"arcgis_cables", "arcgis_landing_points", "arcgis_cable_landing_relation"}
|
||||
)
|
||||
_EPOCH_CSV_URL = "https://epoch.ai/data/gpu_clusters.csv"
|
||||
|
||||
|
||||
def _is_masked_secret(value: Any) -> bool:
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
stripped = value.strip()
|
||||
return bool(stripped) and set(stripped) <= {"•", "*"}
|
||||
|
||||
|
||||
def _clean_override_value(override: dict[str, str] | None, key: str, *, secret: bool = False) -> str:
|
||||
if not isinstance(override, dict):
|
||||
return ""
|
||||
raw = str(override.get(key) or "").strip()
|
||||
if not raw or (secret and _is_masked_secret(raw)):
|
||||
return ""
|
||||
return raw
|
||||
|
||||
|
||||
def _sha256_json(payload: Any) -> str:
|
||||
@@ -46,26 +70,68 @@ def _resolve_spacetrack_credentials() -> tuple[str, str, str]:
|
||||
return username, password, source or "missing"
|
||||
|
||||
|
||||
def _resolve_spacetrack_credentials_with_override(
|
||||
async def resolve_spacetrack_credentials(
|
||||
db=None,
|
||||
credential_override: dict[str, str] | None = None,
|
||||
) -> tuple[str, str, str]:
|
||||
if credential_override and (
|
||||
credential_override.get("username") or credential_override.get("password")
|
||||
):
|
||||
return (
|
||||
str(credential_override.get("username") or ""),
|
||||
str(credential_override.get("password") or ""),
|
||||
"draft",
|
||||
)
|
||||
return _resolve_spacetrack_credentials()
|
||||
"""Resolve Space-Track credentials (`draft override -> DataSourceConfig -> env -> ~/.zshrc`)."""
|
||||
db_user = ""
|
||||
db_pass = ""
|
||||
if db is not None and hasattr(db, "execute"):
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(DataSourceConfig.name == "spacetrack_tle")
|
||||
.where(DataSourceConfig.is_active.is_(True))
|
||||
)
|
||||
record = result.scalar_one_or_none()
|
||||
if record is not None:
|
||||
auth_cfg = record.auth_config or {}
|
||||
runtime_cfg = record.config or {}
|
||||
db_user = str(auth_cfg.get("username") or runtime_cfg.get("username") or "").strip()
|
||||
db_pass = str(auth_cfg.get("password") or runtime_cfg.get("password") or "").strip()
|
||||
except Exception:
|
||||
db_user = ""
|
||||
db_pass = ""
|
||||
|
||||
env_user, env_pass, env_source = _resolve_spacetrack_credentials()
|
||||
username = db_user or env_user
|
||||
password = db_pass or env_pass
|
||||
source = "datasource_config" if (db_user or db_pass) else env_source
|
||||
|
||||
ov_user = _clean_override_value(credential_override, "username")
|
||||
ov_pass = _clean_override_value(credential_override, "password", secret=True)
|
||||
if ov_user or ov_pass:
|
||||
return ov_user or username, ov_pass or password, "draft"
|
||||
return username, password, source or "missing"
|
||||
|
||||
|
||||
async def _resolve_barentswatch_with_override(
|
||||
db,
|
||||
endpoint: str,
|
||||
credential_override: dict[str, str] | None = None,
|
||||
) -> BarentsWatchConfig:
|
||||
"""Resolve BarentsWatch credentials merging partial draft overrides with saved config."""
|
||||
saved = await resolve_barentswatch_config(db)
|
||||
ov_id = _clean_override_value(credential_override, "client_id")
|
||||
ov_secret = _clean_override_value(credential_override, "client_secret", secret=True)
|
||||
has_override = bool(ov_id or ov_secret)
|
||||
return BarentsWatchConfig(
|
||||
endpoint=str(endpoint or "").strip() or saved.endpoint,
|
||||
client_id=ov_id or saved.client_id,
|
||||
client_secret=ov_secret or saved.client_secret,
|
||||
credential_source="draft" if has_override else saved.credential_source,
|
||||
endpoint_source="draft" if str(endpoint or "").strip() else saved.endpoint_source,
|
||||
)
|
||||
|
||||
|
||||
async def _resolve_aisstream_api_key(
|
||||
db=None,
|
||||
credential_override: dict[str, str] | None = None,
|
||||
) -> tuple[str, str]:
|
||||
if credential_override and credential_override.get("api_key"):
|
||||
return str(credential_override["api_key"]), "draft"
|
||||
ov_key = _clean_override_value(credential_override, "api_key", secret=True)
|
||||
if ov_key:
|
||||
return ov_key, "draft"
|
||||
|
||||
env_key = os.getenv("AISSTREAM_API_KEY")
|
||||
zshrc_key = _read_zshrc_env().get("AISSTREAM_API_KEY")
|
||||
@@ -125,15 +191,12 @@ async def build_builtin_connectivity_checksum(
|
||||
has_credentials = not defaults.get("requires_credentials", False)
|
||||
|
||||
if credential_provider == "barentswatch":
|
||||
if credential_override:
|
||||
client_id = credential_override.get("client_id", "")
|
||||
client_secret = credential_override.get("client_secret", "")
|
||||
credential_source = "draft"
|
||||
else:
|
||||
barentswatch_config = await resolve_barentswatch_config(db)
|
||||
client_id = barentswatch_config.client_id
|
||||
client_secret = barentswatch_config.client_secret
|
||||
credential_source = barentswatch_config.credential_source
|
||||
barentswatch_config = await _resolve_barentswatch_with_override(
|
||||
db, endpoint, credential_override
|
||||
)
|
||||
client_id = barentswatch_config.client_id
|
||||
client_secret = barentswatch_config.client_secret
|
||||
credential_source = barentswatch_config.credential_source
|
||||
has_credentials = bool(client_id and client_secret)
|
||||
credential_fingerprint = _sha256_json(
|
||||
{
|
||||
@@ -142,8 +205,8 @@ async def build_builtin_connectivity_checksum(
|
||||
}
|
||||
)
|
||||
elif credential_provider == "spacetrack":
|
||||
username, password, credential_source = _resolve_spacetrack_credentials_with_override(
|
||||
credential_override
|
||||
username, password, credential_source = await resolve_spacetrack_credentials(
|
||||
db, credential_override
|
||||
)
|
||||
has_credentials = bool(username and password)
|
||||
credential_fingerprint = _sha256_json(
|
||||
@@ -176,6 +239,113 @@ async def build_builtin_connectivity_checksum(
|
||||
}
|
||||
|
||||
|
||||
def _prepare_builtin_http_probe(
|
||||
source: str,
|
||||
endpoint: str,
|
||||
headers: dict[str, str],
|
||||
) -> tuple[str, Any, dict[str, str]]:
|
||||
"""Build lightweight protocol-accurate probe URL, params, and headers for a built-in source."""
|
||||
probe_url = str(endpoint or "").strip()
|
||||
probe_params: Any = None
|
||||
probe_headers = dict(headers)
|
||||
|
||||
if source == "bgpstream_bgp":
|
||||
base = probe_url.rstrip("/")
|
||||
probe_url = base if base.endswith("/data") else f"{base}/data"
|
||||
end = int(datetime.now(UTC).timestamp()) - 3600
|
||||
start = end - 3600
|
||||
probe_params = [
|
||||
("projects[]", "routeviews"),
|
||||
("collectors[]", "route-views2"),
|
||||
("types[]", "updates"),
|
||||
("intervals[]", f"{start},{end}"),
|
||||
]
|
||||
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
|
||||
elif source == "celestrak_tle":
|
||||
if "?" not in probe_url:
|
||||
probe_params = {"CATNR": "25544", "FORMAT": "json"}
|
||||
elif source in _ARCGIS_SOURCES:
|
||||
if probe_url.rstrip("/").endswith("/query") and "f=" not in probe_url:
|
||||
probe_params = {"where": "1=1", "returnCountOnly": "true", "f": "json"}
|
||||
elif source == "epoch_ai_gpu":
|
||||
parsed = urlparse(probe_url)
|
||||
if parsed.hostname == "epoch.ai" and not parsed.path.endswith(".csv"):
|
||||
probe_url = _EPOCH_CSV_URL
|
||||
elif source == "ris_live_bgp":
|
||||
probe_headers.setdefault(
|
||||
"X-RIS-Subscribe",
|
||||
json.dumps({"host": "rrc00", "type": "UPDATE", "require": "announcements"}),
|
||||
)
|
||||
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
|
||||
return probe_url, probe_params, probe_headers
|
||||
|
||||
|
||||
async def _read_bounded_probe_bytes(response: httpx.Response, limit: int = 65536) -> bytes:
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
async for chunk in response.aiter_bytes():
|
||||
chunks.append(chunk)
|
||||
size += len(chunk)
|
||||
if size >= limit:
|
||||
break
|
||||
return b"".join(chunks)[:limit]
|
||||
|
||||
|
||||
async def _validate_builtin_probe_response(source: str, response: httpx.Response) -> str | None:
|
||||
"""Validate response content for sources that return HTTP 200 even on invalid queries."""
|
||||
if source == "ris_live_bgp":
|
||||
first_line = ""
|
||||
async for line in response.aiter_lines():
|
||||
stripped = line.strip()
|
||||
if stripped:
|
||||
first_line = stripped
|
||||
break
|
||||
if not first_line:
|
||||
return "RIS Live 流未返回任何有效消息。"
|
||||
try:
|
||||
payload = json.loads(first_line)
|
||||
except json.JSONDecodeError:
|
||||
return "RIS Live 返回非 JSON 响应。"
|
||||
return None if isinstance(payload, dict) else "RIS Live 响应结构异常。"
|
||||
|
||||
if source not in _ARCGIS_SOURCES | {"bgpstream_bgp", "celestrak_tle", "epoch_ai_gpu"}:
|
||||
return None
|
||||
|
||||
limit = 4096 if source == "epoch_ai_gpu" else 65536
|
||||
raw = await _read_bounded_probe_bytes(response, limit=limit)
|
||||
text = raw.decode(response.encoding or "utf-8", errors="replace").lstrip("\ufeff").strip()
|
||||
|
||||
if source == "epoch_ai_gpu":
|
||||
if text.lower().startswith(("<!doctype", "<html")):
|
||||
return "Epoch AI 返回了 HTML 页面而非 CSV 数据集。"
|
||||
first_line = next((line for line in text.splitlines() if line.strip()), "")
|
||||
headers_row = next(csv.reader(io.StringIO(first_line)), [])
|
||||
if not {"Name", "Country"}.issubset(set(headers_row)):
|
||||
return "Epoch AI CSV 表头校验失败(缺少 Name / Country)。"
|
||||
return None
|
||||
|
||||
if source == "celestrak_tle":
|
||||
if text.lower().startswith("invalid query"):
|
||||
return f"CelesTrak 参数校验失败:{text[:120]}"
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return "CelesTrak 未返回有效 JSON。"
|
||||
return None if isinstance(parsed, list) else "CelesTrak 返回格式不是 JSON 数组。"
|
||||
|
||||
try:
|
||||
parsed_obj = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return "接口返回了非 JSON 内容(可能是 HTML 错误页)。"
|
||||
if not isinstance(parsed_obj, dict):
|
||||
return "接口返回的 JSON 结构无效。"
|
||||
if parsed_obj.get("error"):
|
||||
return f"上游接口报错:{str(parsed_obj['error'])[:120]}"
|
||||
if source == "bgpstream_bgp" and "data" not in parsed_obj:
|
||||
return "BGPStream Broker 响应缺少 data 字段。"
|
||||
return None
|
||||
|
||||
|
||||
async def test_builtin_connectivity(
|
||||
source: str,
|
||||
endpoint: str,
|
||||
@@ -223,6 +393,27 @@ async def test_builtin_connectivity(
|
||||
**credential_context,
|
||||
}
|
||||
|
||||
if source == "media_news_archive":
|
||||
if db is not None and hasattr(db, "execute"):
|
||||
try:
|
||||
await db.execute(select(func.count(EarthNewsItem.id)))
|
||||
except Exception as exc:
|
||||
return {
|
||||
"success": False,
|
||||
"checksum": checksum,
|
||||
"stage": "internal",
|
||||
"message": f"本地新闻归档表检查失败:{exc.__class__.__name__}",
|
||||
"error": str(exc),
|
||||
**credential_context,
|
||||
}
|
||||
return {
|
||||
"success": True,
|
||||
"checksum": checksum,
|
||||
"stage": "internal",
|
||||
"message": "内部新闻归档采集器无需外部连接,本地数据源正常。",
|
||||
**credential_context,
|
||||
}
|
||||
|
||||
request_headers = {str(key): str(value) for key, value in (headers or {}).items()}
|
||||
request_config = strip_connectivity_validation(config)
|
||||
timeout = float(request_config.get("timeout") or 30)
|
||||
@@ -245,19 +436,15 @@ async def test_builtin_connectivity(
|
||||
**credential_context,
|
||||
}
|
||||
|
||||
probe_url, probe_params, request_headers = _prepare_builtin_http_probe(
|
||||
source, request_endpoint, request_headers
|
||||
)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
|
||||
if credential_context["credential_provider"] == "barentswatch":
|
||||
if credential_override:
|
||||
barentswatch_config = BarentsWatchConfig(
|
||||
endpoint=str(request_endpoint or ""),
|
||||
client_id=str(credential_override.get("client_id") or ""),
|
||||
client_secret=str(credential_override.get("client_secret") or ""),
|
||||
credential_source="draft",
|
||||
endpoint_source="draft",
|
||||
)
|
||||
else:
|
||||
barentswatch_config = await resolve_barentswatch_config(db)
|
||||
barentswatch_config = await _resolve_barentswatch_with_override(
|
||||
db, request_endpoint, credential_override
|
||||
)
|
||||
token = await fetch_barentswatch_access_token(client, barentswatch_config)
|
||||
if not token:
|
||||
return {
|
||||
@@ -270,8 +457,8 @@ async def test_builtin_connectivity(
|
||||
}
|
||||
request_headers["Authorization"] = f"Bearer {token}"
|
||||
elif credential_context["credential_provider"] == "spacetrack":
|
||||
username, password, _source = _resolve_spacetrack_credentials_with_override(
|
||||
credential_override
|
||||
username, password, _source = await resolve_spacetrack_credentials(
|
||||
db, credential_override
|
||||
)
|
||||
login_url = "https://www.space-track.org/ajaxauth/login"
|
||||
login_response = await client.post(
|
||||
@@ -284,10 +471,26 @@ async def test_builtin_connectivity(
|
||||
login_response.raise_for_status()
|
||||
|
||||
started = datetime.now(UTC)
|
||||
async with client.stream("GET", request_endpoint, headers=request_headers) as response:
|
||||
async with client.stream(
|
||||
"GET",
|
||||
probe_url,
|
||||
params=probe_params,
|
||||
headers=request_headers,
|
||||
) as response:
|
||||
response.raise_for_status()
|
||||
status_code = response.status_code
|
||||
body_error = await _validate_builtin_probe_response(source, response)
|
||||
elapsed_ms = (datetime.now(UTC) - started).total_seconds() * 1000
|
||||
if body_error:
|
||||
return {
|
||||
"success": False,
|
||||
"checksum": checksum,
|
||||
"stage": "endpoint",
|
||||
"message": body_error,
|
||||
"error": body_error,
|
||||
"status_code": status_code,
|
||||
**credential_context,
|
||||
}
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
|
||||
@@ -413,8 +413,21 @@ async def run_controlled_location_agent(
|
||||
place_q = coerce_str(args.get("place_query"))
|
||||
expected_c = normalize_country_text(args.get("country") or query.country)
|
||||
agent_attempts.append(f"geocode_verify:{place_q}")
|
||||
geo_res = await asyncio.to_thread(_agent_geocoder, place_q)
|
||||
if not isinstance(geo_res, dict):
|
||||
try:
|
||||
geo_res = await asyncio.to_thread(_agent_geocoder, place_q)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Location agent geocode_verify failed",
|
||||
event="location_agent.geocode_verify.failed",
|
||||
context={"place_query": place_q, "error": str(exc)},
|
||||
)
|
||||
geo_res = None
|
||||
geocode_error = f"geocoder request failed: {exc}"
|
||||
else:
|
||||
geocode_error = ""
|
||||
if geocode_error:
|
||||
tool_output = {"found": False, "error": geocode_error, "retryable": True}
|
||||
elif not isinstance(geo_res, dict):
|
||||
tool_output = {"found": False, "reason": "No geocoder match"}
|
||||
else:
|
||||
lat = parse_float(geo_res.get("lat") if geo_res.get("lat") is not None else geo_res.get("latitude"))
|
||||
|
||||
@@ -14,12 +14,15 @@ can swap the geocoder behavior without touching pipeline construction.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
import time
|
||||
from functools import lru_cache
|
||||
from typing import Any, Callable
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.logging import get_logger
|
||||
|
||||
from ..models import LocationCandidate, LocationQuery, ResolverOutput
|
||||
from ..text import (
|
||||
coerce_str,
|
||||
@@ -28,6 +31,9 @@ from ..text import (
|
||||
parse_float,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__, service="location_geocoder")
|
||||
_RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({429, 502, 503, 504})
|
||||
|
||||
NOMINATIM_SEARCH_URL = "https://nominatim.openstreetmap.org/search"
|
||||
DEFAULT_USER_AGENT = "planet-earth-location-resolver/1.0"
|
||||
DEFAULT_MIN_INTERVAL_SECONDS = 1.1
|
||||
@@ -40,8 +46,10 @@ def build_default_nominatim_geocoder(
|
||||
min_interval_seconds: float = DEFAULT_MIN_INTERVAL_SECONDS,
|
||||
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
||||
cache_size: int = 512,
|
||||
max_retries: int = 2,
|
||||
retry_backoff_seconds: float = 0.6,
|
||||
) -> Callable[[str], dict[str, Any] | None]:
|
||||
"""Return a cached, rate-limited Nominatim geocoder."""
|
||||
"""Return a cached, rate-limited Nominatim geocoder with transient retry."""
|
||||
|
||||
last_request_at = [0.0]
|
||||
|
||||
@@ -49,29 +57,52 @@ def build_default_nominatim_geocoder(
|
||||
def geocode(query: str) -> dict[str, Any] | None:
|
||||
if not query:
|
||||
return None
|
||||
elapsed = time.monotonic() - last_request_at[0]
|
||||
if elapsed < min_interval_seconds:
|
||||
time.sleep(min_interval_seconds - elapsed)
|
||||
last_request_at[0] = time.monotonic()
|
||||
response = httpx.get(
|
||||
NOMINATIM_SEARCH_URL,
|
||||
params={
|
||||
"q": query,
|
||||
"format": "jsonv2",
|
||||
"limit": 1,
|
||||
"addressdetails": 1,
|
||||
},
|
||||
headers={"User-Agent": user_agent},
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
if not isinstance(payload, list) or not payload:
|
||||
return None
|
||||
result = payload[0]
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
return result
|
||||
attempts = max(0, int(max_retries)) + 1
|
||||
for attempt in range(attempts):
|
||||
elapsed = time.monotonic() - last_request_at[0]
|
||||
if elapsed < min_interval_seconds:
|
||||
time.sleep(min_interval_seconds - elapsed)
|
||||
last_request_at[0] = time.monotonic()
|
||||
try:
|
||||
response = httpx.get(
|
||||
NOMINATIM_SEARCH_URL,
|
||||
params={
|
||||
"q": query,
|
||||
"format": "jsonv2",
|
||||
"limit": 1,
|
||||
"addressdetails": 1,
|
||||
},
|
||||
headers={"User-Agent": user_agent},
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
if not isinstance(payload, list) or not payload:
|
||||
return None
|
||||
result = payload[0]
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
return result
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code if exc.response is not None else 0
|
||||
if status_code not in _RETRYABLE_STATUS_CODES or attempt >= attempts - 1:
|
||||
raise
|
||||
logger.warning_event(
|
||||
"Nominatim HTTP status transient failure, retrying",
|
||||
event="location.nominatim.retry",
|
||||
context={"attempt": attempt + 1, "max_attempts": attempts, "status_code": status_code, "error": str(exc)},
|
||||
)
|
||||
except (httpx.TransportError, ssl.SSLError, OSError) as exc:
|
||||
if attempt >= attempts - 1:
|
||||
raise
|
||||
logger.warning_event(
|
||||
"Nominatim transport/SSL transient failure, retrying",
|
||||
event="location.nominatim.retry",
|
||||
context={"attempt": attempt + 1, "max_attempts": attempts, "error": str(exc)},
|
||||
)
|
||||
if retry_backoff_seconds > 0:
|
||||
time.sleep(retry_backoff_seconds * (attempt + 1))
|
||||
return None
|
||||
|
||||
return geocode
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..models import LocationCandidate, LocationQuery, ResolverOutput
|
||||
|
||||
@@ -277,3 +277,330 @@ async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
|
||||
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
|
||||
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
|
||||
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_turn_extracts_planet_scene_and_emits_scene_event(monkeypatch):
|
||||
from app.services.ai.workflow_runtime import SceneSpec
|
||||
|
||||
reset_stream_quota_ledger()
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "global",
|
||||
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
||||
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
||||
}
|
||||
|
||||
async def fake_recent_news(*_args, **_kwargs):
|
||||
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
|
||||
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
||||
|
||||
class _SceneStreamingClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "secret-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
},
|
||||
)
|
||||
|
||||
async def stream_analyze(self, payload, request_id=None):
|
||||
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
yield {"event": "text", "delta": "APEC 峰会影响聚焦中美俄及亚太经济体。"}
|
||||
yield {"event": "text", "delta": "\n<planet_"}
|
||||
yield {
|
||||
"event": "text",
|
||||
"delta": (
|
||||
'scene>{"camera_hint":{"lat":28.0,"lon":128.0},'
|
||||
'"influence_zones":[{"id":"apec-core","label":"核心与会国","color":"#ef4444",'
|
||||
'"opacity":0.62,"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"west_to_east"},'
|
||||
'"shape":{"mode":"countries","countries":["CHN","USA","RUS"]}}]}</planet_scene>'
|
||||
),
|
||||
}
|
||||
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 64}}
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
||||
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _SceneStreamingClient()
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
res = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "请分析这条国际新闻:「APEC 中美俄元首会晤」在地缘上的影响范围",
|
||||
"domain": "news",
|
||||
"news_context": {
|
||||
"id": "apec-1",
|
||||
"title": "APEC 中美俄元首会晤",
|
||||
"summary": "中美俄三方会晤与亚太经济体协同",
|
||||
"source": "Reuters",
|
||||
"region": "亚太",
|
||||
},
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
events = _parse_sse_text(res.text)
|
||||
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
|
||||
assert "<planet_scene>" not in text_deltas
|
||||
assert "APEC 峰会影响聚焦中美俄及亚太经济体" in text_deltas
|
||||
|
||||
scene_events = [data for name, data in events if name == "scene"]
|
||||
assert len(scene_events) == 1
|
||||
zones = scene_events[0]["scene_spec"]["influence_zones"]
|
||||
assert len(zones) == 1
|
||||
assert zones[0]["id"] == "apec-core"
|
||||
assert zones[0]["shape"]["countries"] == ["CHN", "USA", "RUS"]
|
||||
|
||||
done_ev = events[-1][1]
|
||||
assert "<planet_scene>" not in done_ev["answer_markdown"]
|
||||
assert done_ev["scene_spec"]["camera_hint"]["lat"] == 28.0
|
||||
|
||||
validated = SceneSpec.model_validate({
|
||||
"domain": "global",
|
||||
"influence_zones": zones,
|
||||
})
|
||||
assert validated.influence_zones[0].edge.style == "sharp"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_workflow_dag_stream_emits_influence_zones_for_red_sea_news(monkeypatch):
|
||||
reset_stream_quota_ledger()
|
||||
|
||||
class _EmptyScalarResult:
|
||||
def scalar_one_or_none(self):
|
||||
return None
|
||||
|
||||
class _DagStubDb(_StubDb):
|
||||
async def execute(self, *_args, **_kwargs):
|
||||
return _EmptyScalarResult()
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {"domain": "global", "domain_summaries": [], "evidence": {}}
|
||||
|
||||
async def fake_recent_news(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "news",
|
||||
"available": True,
|
||||
"count": 1,
|
||||
"items": [{"id": "n-redsea", "title": "红海安全成为埃及与索马里军方会谈重点"}],
|
||||
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Red Sea News"}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr("app.services.ai.dag_executor.query_global_situational_tool", fake_global_tool)
|
||||
monkeypatch.setattr("app.services.ai.dag_executor.query_recent_earth_news_tool", fake_recent_news)
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
||||
|
||||
captured_requests = []
|
||||
|
||||
class _DagSceneClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "secret-key",
|
||||
"model": "MiniMax-M3.1-Flash",
|
||||
},
|
||||
)
|
||||
|
||||
async def stream_analyze(self, payload, request_id=None):
|
||||
captured_requests.append(payload)
|
||||
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
|
||||
yield {"event": "text", "delta": "红海安全会谈核心涉及埃及与索马里及曼德海峡航道。\n<planet_sce"}
|
||||
yield {
|
||||
"event": "text",
|
||||
"delta": (
|
||||
'ne>{"camera_hint":{"lat":18.0,"lon":39.0},"influence_zones":['
|
||||
'{"id":"redsea-corridor","label":"红海—曼德海峡走廊","color":"#38bdf8","opacity":0.28,'
|
||||
'"edge":{"style":"soft"},"animation":{"type":"radial"},'
|
||||
'"shape":{"mode":"circle","center":[15.5,42.5],"radius_km":950}},'
|
||||
'{"id":"egy-som","label":"埃及与索马里","color":"#f59e0b","opacity":0.55,'
|
||||
'"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"north_to_south"},'
|
||||
'"shape":{"mode":"countries","countries":["EGY","SOM"]}}]}</planet_scene>'
|
||||
),
|
||||
}
|
||||
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
||||
app.dependency_overrides[situational_awareness.get_db] = lambda: _DagStubDb()
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _DagSceneClient()
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
res = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "该事件影响范围?",
|
||||
"domain": "news",
|
||||
"workflow_id": "earth.news.analysis",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
events = _parse_sse_text(res.text)
|
||||
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
|
||||
assert "<planet_scene>" not in text_deltas
|
||||
assert "红海安全会谈核心涉及埃及与索马里" in text_deltas
|
||||
|
||||
scene_events = [data for name, data in events if name == "scene"]
|
||||
assert len(scene_events) == 1
|
||||
zones = scene_events[0]["scene_spec"]["influence_zones"]
|
||||
assert [z["id"] for z in zones] == ["redsea-corridor", "egy-som"]
|
||||
|
||||
done_ev = events[-1][1]
|
||||
assert "<planet_scene>" not in done_ev["answer_markdown"]
|
||||
assert len(done_ev["scene_spec"]["influence_zones"]) == 2
|
||||
assert captured_requests and "scene_overlay_guidance" in captured_requests[0].context
|
||||
assert "<planet_scene>" in (captured_requests[0].system_prompt or "")
|
||||
|
||||
|
||||
def test_scene_directives_tolerate_code_fences_and_llm_field_quirks():
|
||||
from app.services.ai.scene_directives import extract_planet_scene_from_text
|
||||
from app.services.ai.workflow_runtime import validate_influence_zones
|
||||
|
||||
raw = (
|
||||
"直接影响地区为中国市场。\n"
|
||||
"<planet_scene>\n"
|
||||
"```json\n"
|
||||
"{\n"
|
||||
' "influence_zones": [\n'
|
||||
" {\n"
|
||||
' "name": "直接影响:中国",\n'
|
||||
' "color": "red",\n'
|
||||
' "edge": {"style": "sharp", "opacity": 0.55, "extra_ignored": true},\n'
|
||||
' "animation": "sweep",\n'
|
||||
' "countries": "CHN",\n'
|
||||
' "extra_note": "ignore me",\n'
|
||||
" },\n"
|
||||
" {\n"
|
||||
' "id": "corridor",\n'
|
||||
' "color": "#38b",\n'
|
||||
' "opacity": 1.4,\n'
|
||||
' "shape": {"mode": "circle", "center": {"lat": 15.5, "lon": 42.5}, "radius_km": 5}\n'
|
||||
" },\n"
|
||||
" ],\n"
|
||||
' "camera_hint": {"lat": 35.0, "lon": 104.0}\n'
|
||||
"}\n"
|
||||
"```\n"
|
||||
"</planet_scene>"
|
||||
)
|
||||
cleaned, parsed = extract_planet_scene_from_text(raw)
|
||||
assert cleaned == "直接影响地区为中国市场。"
|
||||
assert parsed is not None
|
||||
assert parsed["camera_hint"] == {"lat": 35.0, "lon": 104.0}
|
||||
zones = parsed["influence_zones"]
|
||||
assert len(zones) == 2
|
||||
assert zones[0]["label"] == "直接影响:中国"
|
||||
assert zones[0]["color"] == "#ef4444"
|
||||
assert zones[0]["opacity"] == pytest.approx(0.55)
|
||||
assert zones[0]["edge"]["style"] == "sharp"
|
||||
assert zones[0]["animation"]["type"] == "sweep"
|
||||
assert zones[0]["shape"]["mode"] == "countries"
|
||||
assert zones[0]["shape"]["countries"] == ["CHN"]
|
||||
|
||||
assert zones[1]["color"] == "#3388bb"
|
||||
assert zones[1]["opacity"] == pytest.approx(0.9)
|
||||
assert zones[1]["shape"]["center"] == [15.5, 42.5]
|
||||
assert zones[1]["shape"]["radius_km"] == pytest.approx(20.0)
|
||||
|
||||
# Also test validate_influence_zones directly with edge string + flat region_preset
|
||||
direct = validate_influence_zones(
|
||||
[{"id": "apec", "color": "#f59e0b", "edge": "soft", "region_preset": "APEC"}]
|
||||
)
|
||||
assert len(direct) == 1
|
||||
assert direct[0].edge.style == "soft"
|
||||
assert direct[0].shape.mode == "region_preset"
|
||||
assert direct[0].shape.region_preset == "APEC"
|
||||
|
||||
|
||||
def test_validate_influence_zones_normalizes_dprk_presets_polygons_and_rejects_empty():
|
||||
from app.services.ai.workflow_runtime import validate_influence_zones
|
||||
|
||||
zones = validate_influence_zones(
|
||||
[
|
||||
{"id": "core", "color": "red", "countries": ["CHN", "DPRK", "朝鲜", "KP"]},
|
||||
{"id": "ne-asia", "color": "amber", "region_preset": "东北亚"},
|
||||
{"id": "ne-asia-en", "color": "amber", "shape": {"mode": "region_preset", "region_preset": "northeast-asia"}},
|
||||
{"id": "poly2d", "color": "#38bdf8", "coordinates": [[120.0, 35.0], [126.0, 35.0], [126.0, 40.0]]},
|
||||
{"id": "unknown-preset", "color": "#38bdf8", "shape": {"mode": "region_preset", "region_preset": "MARS_BELT"}},
|
||||
{"id": "empty-countries", "color": "#ef4444", "shape": {"mode": "countries", "countries": []}},
|
||||
]
|
||||
)
|
||||
assert [z.id for z in zones] == ["core", "ne-asia", "ne-asia-en", "poly2d"]
|
||||
assert zones[0].shape.countries == ["CHN", "PRK"]
|
||||
assert zones[1].shape.mode == "region_preset"
|
||||
assert zones[1].shape.region_preset == "NORTHEAST_ASIA"
|
||||
assert zones[2].shape.region_preset == "NORTHEAST_ASIA"
|
||||
assert zones[3].shape.mode == "polygon"
|
||||
assert len(zones[3].shape.coordinates) == 1
|
||||
assert len(zones[3].shape.coordinates[0]) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_turn_cooperative_cancel_stops_stream_and_preserves_session_memory(monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
import app.services.ai.stream_turn as st_mod
|
||||
from app.services.ai.workflow_runtime import cancel_active_run_handle
|
||||
from app.services.ai.access_policy import AccessContext
|
||||
|
||||
async def _fake_recent_news(*_args, **_kwargs):
|
||||
return {"items": [], "evidence": {}}
|
||||
|
||||
async def _fake_global_tool(*_args, **_kwargs):
|
||||
return {"domain_summaries": [], "evidence": {}}
|
||||
|
||||
monkeypatch.setattr(st_mod, "query_recent_earth_news_tool", _fake_recent_news)
|
||||
monkeypatch.setattr(st_mod, "query_global_situational_tool", _fake_global_tool)
|
||||
|
||||
class FakeSlowClient:
|
||||
llm_config = {"provider": "minimax", "model": "MiniMax-M3.1-Flash", "max_tokens": 4096}
|
||||
|
||||
async def is_ready(self):
|
||||
return True, "minimax", "MiniMax-M3.1-Flash"
|
||||
|
||||
async def stream_analyze(self, req, request_id=None):
|
||||
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
|
||||
yield {"event": "text", "delta": "first chunk "}
|
||||
# Simulate cooperative cancel triggered by overlapping turn before finishing
|
||||
assert cancel_active_run_handle(request_id) is True
|
||||
yield {"event": "text", "delta": "should not appear"}
|
||||
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash", "usage": {}}
|
||||
|
||||
class DummyDb:
|
||||
async def commit(self):
|
||||
return None
|
||||
|
||||
session = SimpleNamespace(
|
||||
id="sess-cancel-test",
|
||||
context_state={"recent_messages": [{"role": "user", "content": "keep me"}], "domain": "news"},
|
||||
pinned_items=[],
|
||||
)
|
||||
access = AccessContext(tier="public_zero_cost", actor_key="test-actor", hourly_paid_quota=100)
|
||||
events = []
|
||||
async for raw_ev in st_mod.stream_session_turn(
|
||||
DummyDb(),
|
||||
request=None,
|
||||
session=session,
|
||||
question="旧提问",
|
||||
context_override={"domain": "news"},
|
||||
news_context={"id": "n1", "title": "中朝关系", "source": "BBC World"},
|
||||
access=access,
|
||||
ai_client=FakeSlowClient(),
|
||||
client_run_id="run-cancel-1",
|
||||
):
|
||||
events.append(raw_ev)
|
||||
|
||||
joined = "".join(events)
|
||||
assert "should not appear" not in joined
|
||||
assert "event: done" not in joined
|
||||
assert session.context_state["recent_messages"] == [{"role": "user", "content": "keep me"}]
|
||||
@@ -17,7 +17,11 @@ from app.main import app
|
||||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS
|
||||
from app.services.ai.workflow_registry import (
|
||||
BUILTIN_WORKFLOWS,
|
||||
_LEGACY_BUILTIN_POSITIONS,
|
||||
ensure_builtin_workflows,
|
||||
)
|
||||
|
||||
|
||||
class _SyncAsAsyncSession:
|
||||
@@ -53,7 +57,14 @@ class _SyncAsAsyncSession:
|
||||
|
||||
|
||||
async def _make_sqlite_session():
|
||||
from sqlalchemy import event
|
||||
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
event.listen(
|
||||
engine,
|
||||
"connect",
|
||||
lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v),
|
||||
)
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
@@ -171,7 +182,6 @@ async def test_ai_workflows_seed_draft_publish_rollback_and_fixtures(monkeypatch
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_workflow_optimize_whitelist_and_playground_sse_runs(monkeypatch):
|
||||
engine, factory = await _make_sqlite_session()
|
||||
@@ -271,3 +281,417 @@ async def test_ai_workflow_optimize_whitelist_and_playground_sse_runs(monkeypatc
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
def test_builtin_workflows_have_spacious_left_to_right_layout():
|
||||
for spec in BUILTIN_WORKFLOWS:
|
||||
wf_id = spec["workflow_id"]
|
||||
nodes_by_id = {n["id"]: n for n in spec["graph"]["nodes"]}
|
||||
for edge in spec["graph"]["edges"]:
|
||||
src = nodes_by_id[edge["source"]]["position"]
|
||||
tgt = nodes_by_id[edge["target"]]["position"]
|
||||
dx = tgt["x"] - src["x"]
|
||||
assert dx >= 320, (
|
||||
f"{wf_id} edge {edge['id']} ({edge['source']} -> {edge['target']}) "
|
||||
f"has cramped or backwards dx={dx}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only():
|
||||
import copy
|
||||
|
||||
engine, factory = await _make_sqlite_session()
|
||||
try:
|
||||
async with factory() as session:
|
||||
loc_spec = next(
|
||||
item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "location.resolve_unknown"
|
||||
)
|
||||
legacy_loc_graph = copy.deepcopy(loc_spec["graph"])
|
||||
for node in legacy_loc_graph["nodes"]:
|
||||
lx, ly = _LEGACY_BUILTIN_POSITIONS["location.resolve_unknown"][node["id"]]
|
||||
node["position"] = {"x": lx, "y": ly}
|
||||
|
||||
gen_spec = next(
|
||||
item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "default.general"
|
||||
)
|
||||
custom_gen_graph = copy.deepcopy(gen_spec["graph"])
|
||||
custom_gen_graph["nodes"][0]["position"] = {"x": 99, "y": 222}
|
||||
|
||||
session.add(
|
||||
AIWorkflow(
|
||||
workflow_id="location.resolve_unknown",
|
||||
name=loc_spec["name"],
|
||||
name_en=loc_spec["name_en"],
|
||||
category=loc_spec["category"],
|
||||
description=loc_spec["description"],
|
||||
description_en=loc_spec["description_en"],
|
||||
is_default=False,
|
||||
is_builtin=True,
|
||||
active_revision=1,
|
||||
published_graph=legacy_loc_graph,
|
||||
draft_graph=None,
|
||||
updated_by="system",
|
||||
)
|
||||
)
|
||||
session.add(
|
||||
AIWorkflow(
|
||||
workflow_id="default.general",
|
||||
name=gen_spec["name"],
|
||||
name_en=gen_spec["name_en"],
|
||||
category=gen_spec["category"],
|
||||
description=gen_spec["description"],
|
||||
description_en=gen_spec["description_en"],
|
||||
is_default=True,
|
||||
is_builtin=True,
|
||||
active_revision=1,
|
||||
published_graph=custom_gen_graph,
|
||||
draft_graph=None,
|
||||
updated_by="admin",
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
await ensure_builtin_workflows(session)
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
upgraded_loc = (
|
||||
await session.execute(
|
||||
select(AIWorkflow).where(AIWorkflow.workflow_id == "location.resolve_unknown")
|
||||
)
|
||||
).scalar_one()
|
||||
l1 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l1_knowledge")
|
||||
l2 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l2_agent_research")
|
||||
assert l2["position"]["x"] > l1["position"]["x"]
|
||||
|
||||
untouched_gen = (
|
||||
await session.execute(
|
||||
select(AIWorkflow).where(AIWorkflow.workflow_id == "default.general")
|
||||
)
|
||||
).scalar_one()
|
||||
assert untouched_gen.published_graph["nodes"][0]["position"] == {"x": 99, "y": 222}
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_playground_slash_briefs_map_to_registered_workflow_ids():
|
||||
from app.api.v1.ai_workflows import _resolve_playground_slash_or_workflow
|
||||
from app.models.alert import Alert
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.task import CollectionTask
|
||||
|
||||
from sqlalchemy import event
|
||||
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
event.listen(
|
||||
engine,
|
||||
"connect",
|
||||
lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v),
|
||||
)
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
AIWorkflow.__table__,
|
||||
AIWorkflowRevision.__table__,
|
||||
AIWorkflowFixture.__table__,
|
||||
WorkflowRun.__table__,
|
||||
SystemSetting.__table__,
|
||||
Alert.__table__,
|
||||
BGPIncident.__table__,
|
||||
BGPAnomaly.__table__,
|
||||
BGPObservation.__table__,
|
||||
DataSource.__table__,
|
||||
CollectionTask.__table__,
|
||||
],
|
||||
)
|
||||
sync_factory = sessionmaker(engine, expire_on_commit=False)
|
||||
registered_ids = {spec["workflow_id"] for spec in BUILTIN_WORKFLOWS}
|
||||
try:
|
||||
sess = _SyncAsAsyncSession(sync_factory())
|
||||
sess.add(
|
||||
DataSource(
|
||||
name="Test Unhealthy Source",
|
||||
source="unhealthy_test",
|
||||
module="L1",
|
||||
collector_class="TestCollector",
|
||||
is_active=True,
|
||||
last_status="failed",
|
||||
)
|
||||
)
|
||||
sess.add(
|
||||
CollectionTask(
|
||||
datasource_id=1,
|
||||
source="unhealthy_test",
|
||||
task_type="collect",
|
||||
status="failed",
|
||||
error_message="connection timeout",
|
||||
)
|
||||
)
|
||||
await sess.commit()
|
||||
|
||||
wf_bgp, _, _, _ = await _resolve_playground_slash_or_workflow(
|
||||
db=sess,
|
||||
workflow_id="default.general",
|
||||
message="/bgp-brief",
|
||||
use_draft=False,
|
||||
earth_context=None,
|
||||
)
|
||||
assert wf_bgp == "brief.bgp"
|
||||
assert wf_bgp in registered_ids
|
||||
|
||||
wf_alerts, _, req_alerts, _ = await _resolve_playground_slash_or_workflow(
|
||||
db=sess,
|
||||
workflow_id="default.general",
|
||||
message="/alerts-brief",
|
||||
use_draft=False,
|
||||
earth_context=None,
|
||||
)
|
||||
assert wf_alerts == "brief.alerts"
|
||||
assert wf_alerts in registered_ids
|
||||
assert req_alerts is not None
|
||||
assert req_alerts.context["failed_tasks_24h"] == 1
|
||||
assert len(req_alerts.context["failed_datasources"]) == 1
|
||||
|
||||
wf_sit, _, _, _ = await _resolve_playground_slash_or_workflow(
|
||||
db=sess,
|
||||
workflow_id="default.general",
|
||||
message="/situational-brief",
|
||||
use_draft=False,
|
||||
earth_context=None,
|
||||
)
|
||||
assert wf_sit == "brief.alerts"
|
||||
assert wf_sit in registered_ids
|
||||
await sess.close()
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_workflow_crud_clone_cycle_guard_and_public_bindings():
|
||||
engine, factory = await _make_sqlite_session()
|
||||
|
||||
async def override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
def override_admin():
|
||||
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
app.dependency_overrides[require_admin_user] = override_admin
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# 1. Create custom workflow with Earth bindings
|
||||
create_resp = await client.post(
|
||||
"/api/v1/ai/workflows",
|
||||
json={
|
||||
"workflow_id": "custom.cable_vessel_check",
|
||||
"name": "海缆与近邻船舶排查",
|
||||
"description": "排查断缆周边船舶与路由异动",
|
||||
"bindings": {
|
||||
"enabled": True,
|
||||
"surfaces": ["info_card", "multi_select"],
|
||||
"entity_types": ["cable", "vessel"],
|
||||
"action_label": "断缆与船舶联动",
|
||||
"icon": "troubleshoot",
|
||||
"priority": 40,
|
||||
"prompt_template": "排查 {{targets_summary}} 风险",
|
||||
},
|
||||
},
|
||||
)
|
||||
assert create_resp.status_code == 200
|
||||
created = create_resp.json()
|
||||
assert created["workflow_id"] == "custom.cable_vessel_check"
|
||||
assert created["is_builtin"] is False
|
||||
assert created["bindings"]["enabled"] is True
|
||||
|
||||
# 2. Reject deleting built-in workflow (400)
|
||||
del_builtin = await client.delete("/api/v1/ai/workflows/default.general")
|
||||
assert del_builtin.status_code == 400
|
||||
|
||||
# 3. Clone built-in workflow and verify prompt_key is stripped on cloned nodes
|
||||
clone_resp = await client.post(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/clone",
|
||||
json={"workflow_id": "custom.my_news", "name": "我的新闻研判"},
|
||||
)
|
||||
assert clone_resp.status_code == 200
|
||||
cloned = clone_resp.json()
|
||||
assert cloned["is_builtin"] is False
|
||||
for node in cloned["published_graph"]["nodes"]:
|
||||
assert node.get("prompt_key") is None
|
||||
|
||||
# 4. PATCH metadata + bindings
|
||||
patch_resp = await client.patch(
|
||||
"/api/v1/ai/workflows/custom.my_news",
|
||||
json={
|
||||
"name": "我的新闻研判 V2",
|
||||
"bindings": {
|
||||
"enabled": True,
|
||||
"surfaces": ["news_card"],
|
||||
"entity_types": ["news"],
|
||||
"action_label": "定制新闻研判",
|
||||
},
|
||||
},
|
||||
)
|
||||
assert patch_resp.status_code == 200
|
||||
assert patch_resp.json()["name"] == "我的新闻研判 V2"
|
||||
|
||||
# 5. Reject cyclic graph (422)
|
||||
cyclic_graph = {
|
||||
"nodes": [
|
||||
{"id": "a", "node_type": "trigger", "title": "A", "position": {"x": 0, "y": 0}},
|
||||
{"id": "b", "node_type": "llm_agent", "title": "B", "position": {"x": 300, "y": 0}},
|
||||
],
|
||||
"edges": [
|
||||
{"id": "e1", "source": "a", "target": "b"},
|
||||
{"id": "e2", "source": "b", "target": "a"},
|
||||
],
|
||||
}
|
||||
cycle_resp = await client.put(
|
||||
"/api/v1/ai/workflows/custom.my_news/draft",
|
||||
json={"graph": cyclic_graph},
|
||||
)
|
||||
assert cycle_resp.status_code == 422
|
||||
|
||||
# 6. Reject >12 nodes (422)
|
||||
too_many = {
|
||||
"nodes": [
|
||||
{"id": f"n{i}", "node_type": "llm_agent", "title": f"N{i}", "position": {"x": i * 100, "y": 0}}
|
||||
for i in range(13)
|
||||
],
|
||||
"edges": [],
|
||||
}
|
||||
max_resp = await client.put(
|
||||
"/api/v1/ai/workflows/custom.my_news/draft",
|
||||
json={"graph": too_many},
|
||||
)
|
||||
assert max_resp.status_code == 422
|
||||
|
||||
# 7. Public /workflows/bindings must work WITHOUT admin auth & leak ZERO prompts/graphs
|
||||
app.dependency_overrides.pop(require_admin_user, None)
|
||||
bindings_resp = await client.get("/api/v1/ai/workflows/bindings")
|
||||
assert bindings_resp.status_code == 200
|
||||
b_items = bindings_resp.json()["items"]
|
||||
assert any(item["workflow_id"] == "custom.cable_vessel_check" for item in b_items)
|
||||
for item in b_items:
|
||||
assert "published_graph" not in item
|
||||
assert "draft_graph" not in item
|
||||
assert "system_prompt" not in item
|
||||
assert "updated_by" not in item
|
||||
|
||||
# 7b. Re-enable admin and test discard draft restores published workflow cleanly
|
||||
app.dependency_overrides[require_admin_user] = override_admin
|
||||
discard_draft_graph = {
|
||||
"nodes": [
|
||||
{"id": "only_trigger", "node_type": "trigger", "title": "Draft Trigger", "position": {"x": 0, "y": 0}},
|
||||
],
|
||||
"edges": [],
|
||||
}
|
||||
draft_put = await client.put(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/draft",
|
||||
json={"graph": discard_draft_graph},
|
||||
)
|
||||
assert draft_put.status_code == 200
|
||||
assert draft_put.json()["has_draft"] is True
|
||||
|
||||
discard_resp = await client.delete("/api/v1/ai/workflows/earth.news.analysis/draft")
|
||||
assert discard_resp.status_code == 200
|
||||
discarded = discard_resp.json()
|
||||
assert discarded["has_draft"] is False
|
||||
assert discarded["draft_graph"] is None
|
||||
assert len(discarded["published_graph"]["nodes"]) == 4
|
||||
|
||||
# 8. Delete custom workflow
|
||||
del_custom = await client.delete("/api/v1/ai/workflows/custom.my_news")
|
||||
assert del_custom.status_code == 200
|
||||
assert del_custom.json()["deleted"] is True
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_playground_link_parser_ssrf_guard_and_multimodal_attachments(monkeypatch):
|
||||
from app.api.v1 import ai_workflows as ai_wf_api
|
||||
from app.services.ai.tool_registry import FetchedEvidence
|
||||
|
||||
app.dependency_overrides[require_admin_user] = lambda: SimpleNamespace(
|
||||
id=1, username="admin", role="admin"
|
||||
)
|
||||
try:
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
blocked = await client.post(
|
||||
"/api/v1/ai/playground/parse-link",
|
||||
json={"url": "http://127.0.0.1:8000/secret"},
|
||||
)
|
||||
assert blocked.status_code == 400
|
||||
|
||||
async def fake_fetch(url: str, *, timeout_seconds: int = 10):
|
||||
return FetchedEvidence(
|
||||
url=url,
|
||||
final_url="https://example.com/article",
|
||||
title="Example Report",
|
||||
text="Subsea cable resilience analysis text body.",
|
||||
content_hash="abc123",
|
||||
extractor="ssrf_guarded_html",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(ai_wf_api, "safe_web_fetch", fake_fetch)
|
||||
ok = await client.post(
|
||||
"/api/v1/ai/playground/parse-link",
|
||||
json={"url": "https://example.com/article"},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
body = ok.json()
|
||||
assert body["title"] == "Example Report"
|
||||
assert "Subsea cable resilience" in body["text"]
|
||||
assert body["char_count"] == len("Subsea cable resilience analysis text body.")
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
structured, images = ai_wf_api._normalize_playground_attachments(
|
||||
[
|
||||
ai_wf_api.PlaygroundAttachmentInput(
|
||||
kind="video",
|
||||
name="clip.mp4",
|
||||
mime_type="video/mp4",
|
||||
metadata={"duration_seconds": 12.4},
|
||||
images=[
|
||||
ai_wf_api.ImageAttachment(
|
||||
mime_type="image/jpeg",
|
||||
data_base64="dGVzdGltYWdlZGF0YQ==",
|
||||
name="frame-1.jpg",
|
||||
)
|
||||
],
|
||||
),
|
||||
ai_wf_api.PlaygroundAttachmentInput(
|
||||
kind="link",
|
||||
name="Example Report",
|
||||
url="https://example.com/article",
|
||||
text_content="Summary text",
|
||||
),
|
||||
]
|
||||
)
|
||||
assert len(structured) == 2
|
||||
assert structured[0]["image_frames_attached"] == 1
|
||||
assert "fetched_content" in structured[1]
|
||||
assert len(images) == 1
|
||||
assert images[0]["mime_type"] == "image/jpeg"
|
||||
|
||||
from aiprovider.provider_service import ProviderService
|
||||
|
||||
openai_msgs = [{"role": "user", "content": "Inspect this frame"}]
|
||||
ProviderService._apply_images_to_messages(openai_msgs, images, "openai-completions")
|
||||
assert isinstance(openai_msgs[0]["content"], list)
|
||||
assert openai_msgs[0]["content"][1]["type"] == "image_url"
|
||||
|
||||
anthropic_msgs = [{"role": "user", "content": [{"type": "text", "text": "Inspect"}]}]
|
||||
ProviderService._apply_images_to_messages(anthropic_msgs, images, "anthropic")
|
||||
assert anthropic_msgs[0]["content"][1]["type"] == "image"
|
||||
assert anthropic_msgs[0]["content"][1]["source"]["media_type"] == "image/jpeg"
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Tests for topological DAG workflow execution, edge branching, and Earth stateless routing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.db.session import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.situational_assessment import InvestigationSession, WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.ai.dag_executor import render_workflow_template, run_workflow_dag_stream
|
||||
|
||||
|
||||
class _SyncAsAsyncSession:
|
||||
def __init__(self, sync_session):
|
||||
self._s = sync_session
|
||||
|
||||
def add(self, obj):
|
||||
return self._s.add(obj)
|
||||
|
||||
async def execute(self, stmt, *args, **kwargs):
|
||||
return self._s.execute(stmt, *args, **kwargs)
|
||||
|
||||
async def scalar(self, stmt, *args, **kwargs):
|
||||
return self._s.scalar(stmt, *args, **kwargs)
|
||||
|
||||
async def get(self, model, ident):
|
||||
return self._s.get(model, ident)
|
||||
|
||||
async def delete(self, obj):
|
||||
return self._s.delete(obj)
|
||||
|
||||
async def commit(self):
|
||||
return self._s.commit()
|
||||
|
||||
async def rollback(self):
|
||||
return self._s.rollback()
|
||||
|
||||
async def refresh(self, obj):
|
||||
return self._s.refresh(obj)
|
||||
|
||||
async def close(self):
|
||||
return self._s.close()
|
||||
|
||||
|
||||
def _make_db_factory():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
event.listen(
|
||||
engine,
|
||||
"connect",
|
||||
lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v),
|
||||
)
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
AIWorkflow.__table__,
|
||||
AIWorkflowRevision.__table__,
|
||||
AIWorkflowFixture.__table__,
|
||||
WorkflowRun.__table__,
|
||||
InvestigationSession.__table__,
|
||||
SystemSetting.__table__,
|
||||
BGPIncident.__table__,
|
||||
CollectedData.__table__,
|
||||
EarthNewsItem.__table__,
|
||||
],
|
||||
)
|
||||
sync_factory = sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
class _Ctx:
|
||||
def __call__(self):
|
||||
return self
|
||||
|
||||
async def __aenter__(self):
|
||||
self._sess = _SyncAsAsyncSession(sync_factory())
|
||||
return self._sess
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
await self._sess.close()
|
||||
|
||||
return engine, _Ctx()
|
||||
|
||||
|
||||
def test_render_workflow_template_safely_interpolates_targets_and_nodes():
|
||||
rendered = render_workflow_template(
|
||||
"检查 {{target.label}} ({{target.lat}}, {{target.lon}});前序={{node.step1}};全部={{targets_summary}};未知={{evil.__class__}}",
|
||||
question="有什么异常",
|
||||
targets=[
|
||||
{
|
||||
"entity_type": "cable",
|
||||
"entity_id": "cable-peace",
|
||||
"label": "PEACE Cable",
|
||||
"latitude": 12.3456,
|
||||
"longitude": 43.21,
|
||||
}
|
||||
],
|
||||
node_outputs={"step1": "周边发现2艘锚泊船"},
|
||||
)
|
||||
assert "PEACE Cable" in rendered
|
||||
assert "12.3456" in rendered
|
||||
assert "周边发现2艘锚泊船" in rendered
|
||||
assert "unknown" not in rendered and "__class__" not in rendered
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dag_executor_multi_llm_chain_edge_conditions_and_fly_to():
|
||||
engine, factory = _make_db_factory()
|
||||
calls: list[dict] = []
|
||||
|
||||
class _FakeMultiAIClient:
|
||||
async def is_ready(self):
|
||||
return True, "openai", "gpt-test"
|
||||
|
||||
async def analyze(self, req):
|
||||
calls.append({"mode": "analyze", "objective": req.objective})
|
||||
return SimpleNamespace(
|
||||
content="初筛摘要:已提取海缆坐标与船舶轨迹要点",
|
||||
provider="openai",
|
||||
model="gpt-fast",
|
||||
)
|
||||
|
||||
async def stream_analyze(self, req, request_id=None):
|
||||
calls.append({"mode": "stream", "objective": req.objective, "context": req.context})
|
||||
yield {"event": "reasoning", "delta": "正在交叉比对阶段一结论…"}
|
||||
yield {"event": "text", "delta": "最终研判:海缆周边态势稳定。"}
|
||||
|
||||
workflow = {
|
||||
"workflow_id": "custom.multi_stage",
|
||||
"name": "多阶段研判",
|
||||
"active_revision": 1,
|
||||
"bindings": {"prompt_template": "围绕 {{targets_summary}} 分析"},
|
||||
"published_graph": {
|
||||
"nodes": [
|
||||
{"id": "trig", "node_type": "trigger", "title": "触发"},
|
||||
{
|
||||
"id": "det_bgp",
|
||||
"node_type": "deterministic",
|
||||
"title": "BGP 快照",
|
||||
"tools": ["query_bgp_incidents"],
|
||||
},
|
||||
{
|
||||
"id": "branch_cable_only",
|
||||
"node_type": "deterministic",
|
||||
"title": "海缆分支",
|
||||
"tools": ["query_cable_posture"],
|
||||
},
|
||||
{
|
||||
"id": "branch_sat_skip",
|
||||
"node_type": "deterministic",
|
||||
"title": "卫星分支(应跳过)",
|
||||
"tools": ["query_satellite_posture"],
|
||||
},
|
||||
{
|
||||
"id": "llm_stage1",
|
||||
"node_type": "llm_agent",
|
||||
"title": "阶段一摘要",
|
||||
"system_prompt": "做初步梳理",
|
||||
"prompt": "梳理 {{target.label}}",
|
||||
},
|
||||
{
|
||||
"id": "llm_final",
|
||||
"node_type": "llm_agent",
|
||||
"title": "阶段二定论",
|
||||
"system_prompt": "综合定论",
|
||||
"prompt": "依据阶段一结论:{{node.llm_stage1}}",
|
||||
},
|
||||
{
|
||||
"id": "guard",
|
||||
"node_type": "guardrail",
|
||||
"title": "核验声明",
|
||||
"guardrails": {"append_disclaimer": "以上结论基于内置遥测实时快照。"},
|
||||
},
|
||||
{
|
||||
"id": "out",
|
||||
"node_type": "output",
|
||||
"title": "输出联动",
|
||||
"params": {"fly_to_target": True, "fly_zoom": 1.6},
|
||||
},
|
||||
],
|
||||
"edges": [
|
||||
{"id": "e1", "source": "trig", "target": "det_bgp", "condition": "always"},
|
||||
{
|
||||
"id": "e2",
|
||||
"source": "det_bgp",
|
||||
"target": "branch_cable_only",
|
||||
"condition": "on_entity_type",
|
||||
"condition_value": "cable",
|
||||
},
|
||||
{
|
||||
"id": "e3",
|
||||
"source": "det_bgp",
|
||||
"target": "branch_sat_skip",
|
||||
"condition": "on_entity_type",
|
||||
"condition_value": "satellite",
|
||||
},
|
||||
{"id": "e4", "source": "branch_cable_only", "target": "llm_stage1", "condition": "always"},
|
||||
{"id": "e5", "source": "llm_stage1", "target": "llm_final", "condition": "always"},
|
||||
{"id": "e6", "source": "llm_final", "target": "guard", "condition": "always"},
|
||||
{"id": "e7", "source": "guard", "target": "out", "condition": "always"},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
async with factory() as db:
|
||||
events: list[dict] = []
|
||||
async for ev in run_workflow_dag_stream(
|
||||
db=db,
|
||||
workflow=workflow,
|
||||
question="",
|
||||
targets=[
|
||||
{
|
||||
"entity_type": "cable",
|
||||
"entity_id": "cable-2",
|
||||
"label": "2Africa",
|
||||
"latitude": 15.5,
|
||||
"longitude": 41.2,
|
||||
}
|
||||
],
|
||||
ai_client=_FakeMultiAIClient(),
|
||||
run_id="run-dag-test",
|
||||
allow_external_tools=False,
|
||||
):
|
||||
events.append(ev)
|
||||
|
||||
skipped_nodes = [
|
||||
e["data"]["node_id"]
|
||||
for e in events
|
||||
if e["event"] == "node" and e["data"].get("status") == "skipped"
|
||||
]
|
||||
assert "branch_sat_skip" in skipped_nodes
|
||||
assert "branch_cable_only" not in skipped_nodes
|
||||
|
||||
# Verify multi-LLM chaining: stage1 used analyze(), stage2 received stage1 output and used stream_analyze()
|
||||
assert len(calls) == 2
|
||||
assert calls[0]["mode"] == "analyze"
|
||||
assert calls[1]["mode"] == "stream"
|
||||
assert "初筛摘要:已提取海缆坐标与船舶轨迹要点" in calls[1]["objective"]
|
||||
|
||||
done_ev = next(e["data"] for e in events if e["event"] == "done")
|
||||
assert "最终研判:海缆周边态势稳定。" in done_ev["answer_markdown"]
|
||||
assert "以上结论基于内置遥测实时快照。" in done_ev["answer_markdown"]
|
||||
assert done_ev["scene_spec"] == {
|
||||
"fly_to": {"lat": 15.5, "lon": 41.2, "zoom": 1.6},
|
||||
"highlight_entities": ["cable-2"],
|
||||
}
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_earth_stateless_stream_executes_published_custom_workflow_and_blocks_external_tools(monkeypatch):
|
||||
engine, factory = _make_db_factory()
|
||||
|
||||
class _FakePublicAIClient:
|
||||
llm_config = {"provider": "openai", "model": "gpt-test", "max_tokens": 4096}
|
||||
|
||||
async def is_ready(self):
|
||||
return True, "openai", "gpt-test"
|
||||
|
||||
async def stream_analyze(self, req, request_id=None):
|
||||
yield {"event": "text", "delta": f"已用已发布图回答(外部搜索跳过={req.context.get('tool_results', {}).get('web_search', {}).get('skipped')})"}
|
||||
|
||||
from app.services.ai_client import get_ai_provider_client
|
||||
|
||||
async def override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
async def fake_client():
|
||||
return _FakePublicAIClient()
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
app.dependency_overrides[get_ai_provider_client] = fake_client
|
||||
|
||||
try:
|
||||
async with factory() as session:
|
||||
session.add(
|
||||
AIWorkflow(
|
||||
workflow_id="custom.earth_pub_only",
|
||||
name="公开海缆研判",
|
||||
name_en="Public Cable Check",
|
||||
category="custom",
|
||||
is_default=False,
|
||||
is_builtin=False,
|
||||
active_revision=1,
|
||||
published_graph={
|
||||
"nodes": [
|
||||
{"id": "t", "node_type": "trigger", "title": "Trigger"},
|
||||
{
|
||||
"id": "d",
|
||||
"node_type": "deterministic",
|
||||
"title": "Tools",
|
||||
"tools": ["web_search"],
|
||||
},
|
||||
{
|
||||
"id": "l",
|
||||
"node_type": "llm_agent",
|
||||
"title": "Published LLM",
|
||||
"system_prompt": "Published prompt",
|
||||
"prompt": "{{target.label}} {{question}}",
|
||||
},
|
||||
],
|
||||
"edges": [
|
||||
{"id": "e1", "source": "t", "target": "d"},
|
||||
{"id": "e2", "source": "d", "target": "l"},
|
||||
],
|
||||
},
|
||||
draft_graph={
|
||||
"nodes": [
|
||||
{
|
||||
"id": "l_draft",
|
||||
"node_type": "llm_agent",
|
||||
"title": "Draft Secret",
|
||||
"system_prompt": "SHOULD NOT RUN FOR PUBLIC CALLER",
|
||||
"prompt": "Draft",
|
||||
}
|
||||
],
|
||||
"edges": [],
|
||||
},
|
||||
bindings={
|
||||
"enabled": True,
|
||||
"surfaces": ["info_card"],
|
||||
"entity_types": ["cable"],
|
||||
"action_label": "海缆排查",
|
||||
},
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
resp = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "分析周边风险",
|
||||
"workflow_id": "custom.earth_pub_only",
|
||||
"targets": [
|
||||
{
|
||||
"entity_type": "cable",
|
||||
"entity_id": "cable-1",
|
||||
"label": "FLAG Cable",
|
||||
"latitude": 30.0,
|
||||
"longitude": 32.0,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.text
|
||||
assert "external_web_search_admin_only" in body
|
||||
assert "l_draft" not in body
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,414 @@
|
||||
"""Regression tests for collector auth_type, secret persistence, Space-Track config, and probes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.core.enums import AuthType
|
||||
from app.core.security import get_current_user
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.db.session import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services import datasource_connectivity
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector
|
||||
from app.services.collectors.spacetrack import SpaceTrackTLECollector
|
||||
|
||||
|
||||
class _SyncAsAsyncSession:
|
||||
def __init__(self, sync_session):
|
||||
self._s = sync_session
|
||||
|
||||
def add(self, obj):
|
||||
return self._s.add(obj)
|
||||
|
||||
async def execute(self, stmt, *args, **kwargs):
|
||||
return self._s.execute(stmt, *args, **kwargs)
|
||||
|
||||
async def scalar(self, stmt, *args, **kwargs):
|
||||
return self._s.scalar(stmt, *args, **kwargs)
|
||||
|
||||
async def get(self, model, ident):
|
||||
return self._s.get(model, ident)
|
||||
|
||||
async def delete(self, obj):
|
||||
return self._s.delete(obj)
|
||||
|
||||
async def commit(self):
|
||||
return self._s.commit()
|
||||
|
||||
async def rollback(self):
|
||||
return self._s.rollback()
|
||||
|
||||
async def refresh(self, obj):
|
||||
return self._s.refresh(obj)
|
||||
|
||||
async def close(self):
|
||||
return self._s.close()
|
||||
|
||||
|
||||
def _make_db():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
DataSourceConfig.__table__,
|
||||
DataSource.__table__,
|
||||
CollectedData.__table__,
|
||||
SystemSetting.__table__,
|
||||
EarthNewsItem.__table__,
|
||||
],
|
||||
)
|
||||
sync_factory = sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
class _Ctx:
|
||||
def __call__(self):
|
||||
return self
|
||||
|
||||
async def __aenter__(self):
|
||||
self._sess = _SyncAsAsyncSession(sync_factory())
|
||||
return self._sess
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
await self._sess.close()
|
||||
|
||||
return engine, _Ctx()
|
||||
|
||||
|
||||
def _mock_httpx_factory(handler):
|
||||
real_async_client = httpx.AsyncClient
|
||||
transport = httpx.MockTransport(handler)
|
||||
|
||||
def _factory(*_args, **kwargs):
|
||||
kwargs.pop("follow_redirects", None)
|
||||
kwargs["transport"] = transport
|
||||
return real_async_client(**kwargs)
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_barentswatch_oauth_client_accepted_and_partial_update_preserves_secret(monkeypatch):
|
||||
assert AuthType.OAUTH_CLIENT.value == "oauth_client"
|
||||
engine, factory = _make_db()
|
||||
captured: dict = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
captured["urls"] = [*captured.get("urls", []), str(request.url)]
|
||||
if "barentswatch.no/connect/token" in str(request.url):
|
||||
captured["token_body"] = request.content.decode()
|
||||
return httpx.Response(200, json={"access_token": "tok_test_123"})
|
||||
captured["auth_header"] = request.headers.get("Authorization")
|
||||
return httpx.Response(200, json=[])
|
||||
|
||||
monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler))
|
||||
|
||||
async def override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
def override_user():
|
||||
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
app.dependency_overrides[get_current_user] = override_user
|
||||
try:
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
# 1. Create BarentsWatch config with auth_type=oauth_client (previously 422)
|
||||
create_resp = await client.post(
|
||||
"/api/v1/datasources/configs",
|
||||
json={
|
||||
"name": "barentswatch_vessels",
|
||||
"source_type": "api",
|
||||
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
|
||||
"auth_type": "oauth_client",
|
||||
"auth_config": {"client_id": "id-1", "client_secret": "real-secret-1"},
|
||||
},
|
||||
)
|
||||
assert create_resp.status_code == 200, create_resp.text
|
||||
cfg_id = create_resp.json()["id"]
|
||||
|
||||
# 2. Partial PUT updating client_id (omitting masked client_secret) preserves real-secret-1
|
||||
put_resp = await client.put(
|
||||
f"/api/v1/datasources/configs/{cfg_id}",
|
||||
json={
|
||||
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
|
||||
"auth_type": "oauth_client",
|
||||
"auth_config": {"client_id": "id-2", "client_secret": "••••••••"},
|
||||
},
|
||||
)
|
||||
assert put_resp.status_code == 200, put_resp.text
|
||||
|
||||
async with factory() as db:
|
||||
row = (await db.execute(select(DataSourceConfig).where(DataSourceConfig.id == cfg_id))).scalar_one()
|
||||
assert row.auth_config["client_id"] == "id-2"
|
||||
assert row.auth_config["client_secret"] == "real-secret-1"
|
||||
|
||||
# 3. Builtin connect with partial auth_config uses merged saved secret
|
||||
conn_resp = await client.post(
|
||||
"/api/v1/datasources/configs/builtin/connect",
|
||||
json={
|
||||
"name": "barentswatch_vessels",
|
||||
"source_type": "api",
|
||||
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
|
||||
"auth_type": "oauth_client",
|
||||
"auth_config": {"client_id": "id-2"},
|
||||
},
|
||||
)
|
||||
assert conn_resp.status_code == 200, conn_resp.text
|
||||
assert conn_resp.json()["success"] is True
|
||||
assert "client_secret=real-secret-1" in captured["token_body"]
|
||||
assert captured["auth_header"] == "Bearer tok_test_123"
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spacetrack_collector_uses_saved_database_credentials(monkeypatch):
|
||||
engine, factory = _make_db()
|
||||
monkeypatch.delenv("SPACETRACK_USERNAME", raising=False)
|
||||
monkeypatch.delenv("SPACETRACK_PASSWORD", raising=False)
|
||||
monkeypatch.setattr(datasource_connectivity, "_read_zshrc_env", lambda: {})
|
||||
posted: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.method == "POST" and "ajaxauth/login" in str(request.url):
|
||||
posted.append(request.content.decode())
|
||||
return httpx.Response(200, text="{}")
|
||||
if request.method == "GET" and str(request.url).rstrip("/").endswith("space-track.org"):
|
||||
return httpx.Response(200, text="ok")
|
||||
return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}])
|
||||
|
||||
monkeypatch.setattr("app.services.collectors.spacetrack.httpx.AsyncClient", _mock_httpx_factory(handler))
|
||||
|
||||
try:
|
||||
async with factory() as db:
|
||||
db.add(
|
||||
DataSourceConfig(
|
||||
name="spacetrack_tle",
|
||||
source_type="api",
|
||||
endpoint="https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json",
|
||||
auth_type="basic",
|
||||
auth_config={"username": "db-user", "password": "db-password"},
|
||||
is_active=True,
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
collector = SpaceTrackTLECollector()
|
||||
collector._db_session = db
|
||||
collector._resolved_url = "https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json"
|
||||
rows = await collector.fetch()
|
||||
assert rows == [{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}]
|
||||
assert posted and "identity=db-user" in posted[0] and "password=db-password" in posted[0]
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_builtin_connectivity_probes_match_collector_protocols(monkeypatch):
|
||||
seen_requests: list[tuple[str, dict[str, str]]] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
url = str(request.url)
|
||||
seen_requests.append((url, dict(request.headers)))
|
||||
if "broker.bgpstream.caida.org" in url:
|
||||
if url.endswith("/v2"):
|
||||
return httpx.Response(404)
|
||||
return httpx.Response(200, json={"error": None, "data": {"resources": []}})
|
||||
if "celestrak.org" in url:
|
||||
if "CATNR=25544" not in url:
|
||||
return httpx.Response(200, text='Invalid query: ""')
|
||||
return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544}])
|
||||
if "services.arcgis.com" in url:
|
||||
if "f=json" not in url:
|
||||
return httpx.Response(200, text="<html>ArcGIS HTML</html>")
|
||||
return httpx.Response(200, json={"count": 42})
|
||||
if "epoch.ai" in url:
|
||||
if url.endswith("gpu-clusters"):
|
||||
return httpx.Response(200, text="<!doctype html><html></html>", headers={"content-type": "text/html"})
|
||||
return httpx.Response(200, text="Name,Country,Status\nFrontier,USA,Active\n", headers={"content-type": "text/csv"})
|
||||
if "ris-live.ripe.net" in url:
|
||||
assert "x-ris-subscribe" in request.headers
|
||||
return httpx.Response(200, text='{"type":"ris_message","data":{}}\n', headers={"content-type": "application/x-ndjson"})
|
||||
return httpx.Response(404)
|
||||
|
||||
monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler))
|
||||
|
||||
engine, factory = _make_db()
|
||||
try:
|
||||
async with factory() as db:
|
||||
for source, endpoint in [
|
||||
("bgpstream_bgp", "https://broker.bgpstream.caida.org/v2"),
|
||||
("celestrak_tle", "https://celestrak.org/NORAD/elements/gp.php"),
|
||||
("arcgis_cables", "https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query"),
|
||||
("epoch_ai_gpu", "https://epoch.ai/data/gpu-clusters"),
|
||||
("ris_live_bgp", "https://ris-live.ripe.net/v1/stream/?format=json&client=planet-ris-live"),
|
||||
("media_news_archive", ""),
|
||||
]:
|
||||
res = await datasource_connectivity.test_builtin_connectivity(
|
||||
source, endpoint, "none", {}, {"timeout": 10}, db=db
|
||||
)
|
||||
assert res["success"] is True, (source, res)
|
||||
|
||||
assert any("/v2/data?" in url and "intervals%5B%5D=" in url for url, _ in seen_requests)
|
||||
|
||||
# Reject fake HTTP 200 responses when content fails validation (e.g., ArcGIS/CelesTrak bad params)
|
||||
bad_arcgis = await datasource_connectivity.test_builtin_connectivity(
|
||||
"arcgis_cables",
|
||||
"https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query?f=html",
|
||||
"none",
|
||||
{},
|
||||
{"timeout": 10},
|
||||
)
|
||||
assert bad_arcgis["success"] is False
|
||||
|
||||
bad_celestrak = await datasource_connectivity.test_builtin_connectivity(
|
||||
"celestrak_tle",
|
||||
"https://celestrak.org/NORAD/elements/gp.php?BAD=1",
|
||||
"none",
|
||||
{},
|
||||
{"timeout": 10},
|
||||
)
|
||||
assert bad_celestrak["success"] is False
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
class _StrictNonConcurrentSession:
|
||||
"""Fake AsyncSession that fails immediately if commit() is entered concurrently."""
|
||||
|
||||
def __init__(self, task: SimpleNamespace) -> None:
|
||||
self.task = task
|
||||
self._in_commit = False
|
||||
self.active_commits = 0
|
||||
self.max_concurrent_commits = 0
|
||||
self.commit_count = 0
|
||||
self.committed_progress: list[int] = []
|
||||
|
||||
async def commit(self) -> None:
|
||||
if self._in_commit:
|
||||
raise RuntimeError("concurrent operations are not permitted")
|
||||
self._in_commit = True
|
||||
self.active_commits += 1
|
||||
self.max_concurrent_commits = max(self.max_concurrent_commits, self.active_commits)
|
||||
try:
|
||||
self.committed_progress.append(int(self.task.records_processed or 0))
|
||||
await asyncio.sleep(0.01)
|
||||
self.commit_count += 1
|
||||
finally:
|
||||
self.active_commits -= 1
|
||||
self._in_commit = False
|
||||
|
||||
|
||||
def _make_task_stub(task_id: int = 29) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
id=task_id,
|
||||
status="running",
|
||||
phase="downloading",
|
||||
phase_progress=0.0,
|
||||
phase_message="",
|
||||
phase_current=0,
|
||||
phase_total=0,
|
||||
phase_unit="bytes",
|
||||
progress=0.0,
|
||||
records_processed=0,
|
||||
total_records=0,
|
||||
started_at=None,
|
||||
completed_at=None,
|
||||
error_message=None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_iptoasn_parallel_download_progress_serializes_db_commits(tmp_path, monkeypatch):
|
||||
v4_path = tmp_path / "ip2asn-v4.tsv.gz"
|
||||
v6_path = tmp_path / "ip2asn-v6.tsv.gz"
|
||||
with gzip.open(v4_path, "wt", encoding="utf-8") as f:
|
||||
f.write("1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET\n")
|
||||
with gzip.open(v6_path, "wt", encoding="utf-8") as f:
|
||||
f.write("2606:4700::\t2606:4700::ffff\t13335\tUS\tCLOUDFLARENET\n")
|
||||
|
||||
async def _noop_broadcast(_payload):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast)
|
||||
|
||||
collector = IPtoASNPrefixGeoCollector()
|
||||
task = _make_task_stub(task_id=29)
|
||||
strict_session = _StrictNonConcurrentSession(task)
|
||||
collector._resolved_url = "https://iptoasn.com/data/ip2asn-combined.tsv.gz"
|
||||
collector._db_session = strict_session
|
||||
collector._current_task = task
|
||||
|
||||
async def _fake_fetch_remote_info(_client, _url):
|
||||
return {"content_length": 10_000_000}
|
||||
|
||||
async def _fake_download_dataset_file(_client, url, *, progress_callback=None):
|
||||
for step in (2_500_000, 5_000_000, 7_500_000, 10_000_000, 10_000_000):
|
||||
if progress_callback:
|
||||
await progress_callback(step, 10_000_000)
|
||||
await asyncio.sleep(0)
|
||||
return v4_path if "v4" in url else v6_path
|
||||
|
||||
async def _no_short_circuit(_db, *, file_sha256):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(collector._downloader, "fetch_remote_info", _fake_fetch_remote_info)
|
||||
monkeypatch.setattr(collector, "_download_dataset_file", _fake_download_dataset_file)
|
||||
monkeypatch.setattr(collector, "_can_short_circuit_unchanged_file", _no_short_circuit)
|
||||
|
||||
rows = await collector.fetch()
|
||||
|
||||
assert len(rows) == 2
|
||||
assert {row["asn"] for row in rows} == {"13335"}
|
||||
assert strict_session.max_concurrent_commits == 1
|
||||
assert strict_session.commit_count >= 2
|
||||
assert strict_session.committed_progress == sorted(strict_session.committed_progress)
|
||||
assert collector._current_task.records_processed == 20_000_000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_base_collector_serializes_concurrent_progress_and_phase_commits(monkeypatch):
|
||||
class _DummyCollector(BaseCollector):
|
||||
name = "dummy_concurrent_collector"
|
||||
|
||||
async def fetch(self):
|
||||
return []
|
||||
|
||||
async def _noop_broadcast(_payload):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast)
|
||||
|
||||
collector = _DummyCollector()
|
||||
task = _make_task_stub(task_id=30)
|
||||
task.total_records = 10
|
||||
strict_session = _StrictNonConcurrentSession(task)
|
||||
collector._current_task = task
|
||||
collector._db_session = strict_session
|
||||
|
||||
await asyncio.gather(
|
||||
collector.update_progress(1, commit=True, force=True),
|
||||
collector.update_phase_progress(current=2, total=10, unit="rows", message="step 2", commit=True, force=True),
|
||||
collector.set_phase("downloading", message="step 3"),
|
||||
collector.update_progress(4, commit=True, force=True),
|
||||
collector.update_phase_progress(current=5, total=10, unit="rows", message="step 5", commit=True, force=True),
|
||||
collector.set_phase("parsing", message="step 6"),
|
||||
)
|
||||
|
||||
assert strict_session.max_concurrent_commits == 1
|
||||
assert strict_session.commit_count == 6
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import ssl
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -363,3 +364,144 @@ async def test_tool_calling_agent_rejects_unobserved_citations_and_persists_term
|
||||
assert saved.verification_status == "undisclosed"
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_nominatim_geocoder_retries_transient_ssl_eof(monkeypatch):
|
||||
from app.services.location.resolvers import nominatim
|
||||
|
||||
calls = {"count": 0}
|
||||
|
||||
class _FakeResp:
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return [{"lat": "35.1495", "lon": "-90.0490", "display_name": "Memphis, TN", "address": {"city": "Memphis", "country": "United States"}}]
|
||||
|
||||
def _fake_get(*_args, **_kwargs):
|
||||
calls["count"] += 1
|
||||
if calls["count"] == 1:
|
||||
raise ssl.SSLError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1081)")
|
||||
return _FakeResp()
|
||||
|
||||
monkeypatch.setattr(nominatim.httpx, "get", _fake_get)
|
||||
geocoder = nominatim.build_default_nominatim_geocoder(
|
||||
min_interval_seconds=0.0,
|
||||
retry_backoff_seconds=0.0,
|
||||
max_retries=2,
|
||||
)
|
||||
res = geocoder("Memphis, United States")
|
||||
assert res is not None
|
||||
assert res["lat"] == "35.1495"
|
||||
assert calls["count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_location_agent_recovers_from_geocode_verify_exception(monkeypatch):
|
||||
from app.services.location import agent_resolver
|
||||
|
||||
geo_calls = {"count": 0}
|
||||
|
||||
def _flaky_geocoder(place_query: str):
|
||||
geo_calls["count"] += 1
|
||||
if geo_calls["count"] == 1:
|
||||
raise ssl.SSLError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1081)")
|
||||
return {
|
||||
"lat": "35.1495",
|
||||
"lon": "-90.0490",
|
||||
"display_name": place_query,
|
||||
"city": "Memphis",
|
||||
"region": "Tennessee",
|
||||
"country": "United States",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(agent_resolver, "_agent_geocoder", _flaky_geocoder)
|
||||
monkeypatch.setattr(
|
||||
agent_resolver,
|
||||
"safe_web_fetch",
|
||||
lambda url, **_kwargs: _async_val(
|
||||
SimpleNamespace(url=url, final_url=url, title="Colossus", text="3231 Paul R Lowry Road, Memphis, Tennessee")
|
||||
),
|
||||
)
|
||||
|
||||
class _RecoveringProvider:
|
||||
def __init__(self):
|
||||
self.turn = 0
|
||||
self.saw_retryable_error = False
|
||||
|
||||
async def analyze(self, req):
|
||||
self.turn += 1
|
||||
if self.turn == 1:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="c1",
|
||||
name="fetch_source_url",
|
||||
arguments=json.dumps({"url": "https://example.com/colossus"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
if self.turn == 2:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="c2",
|
||||
name="geocode_verify",
|
||||
arguments=json.dumps({"place_query": "3231 Paul R Lowry Road, Memphis", "country": "United States"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
if self.turn == 3:
|
||||
last_msg = req.messages[-1].content if req.messages else ""
|
||||
if "geocoder request failed" in str(last_msg):
|
||||
self.saw_retryable_error = True
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="c3",
|
||||
name="geocode_verify",
|
||||
arguments=json.dumps({"place_query": "Memphis, Tennessee", "country": "United States"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="c4",
|
||||
name="submit_location_result",
|
||||
arguments=json.dumps(
|
||||
{
|
||||
"status": "located",
|
||||
"facility_name": "Colossus Memphis",
|
||||
"city": "Memphis",
|
||||
"region": "Tennessee",
|
||||
"country": "United States",
|
||||
"precision": "city",
|
||||
"geocode_candidate_id": "geo_1",
|
||||
"citations": ["https://example.com/colossus"],
|
||||
"confidence": 0.9,
|
||||
"reasoning": "Recovered after geocode retry",
|
||||
}
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
provider = _RecoveringProvider()
|
||||
res, term = await run_controlled_location_agent(
|
||||
provider_client=provider,
|
||||
web_search_client=None,
|
||||
query=LocationQuery(name="Colossus Memphis", country="United States"),
|
||||
)
|
||||
assert provider.saw_retryable_error is True
|
||||
assert term is None
|
||||
assert len(res.candidates) == 1
|
||||
assert res.candidates[0].city == "Memphis"
|
||||
|
||||
|
||||
async def _async_val(val):
|
||||
return val
|
||||
@@ -0,0 +1,690 @@
|
||||
"""Tests for 3-tier AI workflow self-evolution, constitution kernel, canary rollback, and meta-evolution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.core.access_gate import require_admin_user
|
||||
from app.db.session import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.ai.workflow_evolver import (
|
||||
META_WORKFLOW_ID,
|
||||
append_ledger_entry,
|
||||
evaluate_canary_and_maybe_rollback,
|
||||
validate_evolution_patch,
|
||||
)
|
||||
from app.services.ai.workflow_registry import (
|
||||
create_workflow,
|
||||
ensure_builtin_workflows,
|
||||
list_public_workflow_bindings,
|
||||
)
|
||||
|
||||
|
||||
class _SyncAsAsyncSession:
|
||||
def __init__(self, sync_session):
|
||||
self._s = sync_session
|
||||
|
||||
def add(self, obj):
|
||||
return self._s.add(obj)
|
||||
|
||||
async def execute(self, stmt, *args, **kwargs):
|
||||
return self._s.execute(stmt, *args, **kwargs)
|
||||
|
||||
async def scalar(self, stmt, *args, **kwargs):
|
||||
return self._s.scalar(stmt, *args, **kwargs)
|
||||
|
||||
async def get(self, model, ident):
|
||||
return self._s.get(model, ident)
|
||||
|
||||
async def delete(self, obj):
|
||||
return self._s.delete(obj)
|
||||
|
||||
async def commit(self):
|
||||
return self._s.commit()
|
||||
|
||||
async def rollback(self):
|
||||
return self._s.rollback()
|
||||
|
||||
async def refresh(self, obj):
|
||||
return self._s.refresh(obj)
|
||||
|
||||
async def close(self):
|
||||
return self._s.close()
|
||||
|
||||
|
||||
async def _make_sqlite_session():
|
||||
from sqlalchemy import event
|
||||
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
event.listen(
|
||||
engine,
|
||||
"connect",
|
||||
lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v),
|
||||
)
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
AIWorkflow.__table__,
|
||||
AIWorkflowRevision.__table__,
|
||||
AIWorkflowFixture.__table__,
|
||||
WorkflowRun.__table__,
|
||||
SystemSetting.__table__,
|
||||
BGPIncident.__table__,
|
||||
CollectedData.__table__,
|
||||
EarthNewsItem.__table__,
|
||||
],
|
||||
)
|
||||
sync_factory = sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
class _Ctx:
|
||||
def __call__(self):
|
||||
return self
|
||||
|
||||
async def __aenter__(self):
|
||||
self._sess = _SyncAsAsyncSession(sync_factory())
|
||||
return self._sess
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
await self._sess.close()
|
||||
|
||||
return engine, _Ctx()
|
||||
|
||||
|
||||
async def _add_graded_fixture(client, workflow_id: str) -> None:
|
||||
"""Graded fixture that the deterministic (no-AI) fallback answer satisfies on both A/B sides."""
|
||||
resp = await client.post(
|
||||
f"/api/v1/ai/workflows/{workflow_id}/fixtures",
|
||||
json={
|
||||
"name": "Graded baseline",
|
||||
"sample_question": "全球态势摘要",
|
||||
"context_json": {"domain": "global"},
|
||||
"expect": {"must_include": ["全球态势摘要"]},
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["context_json"]["expect"] == {"must_include": ["全球态势摘要"]}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_meta_workflow_seeded_excluded_from_public_and_single_level_recursion_locked():
|
||||
engine, factory = await _make_sqlite_session()
|
||||
try:
|
||||
async with factory() as db:
|
||||
await ensure_builtin_workflows(db)
|
||||
meta_row = (
|
||||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID))
|
||||
).scalar_one_or_none()
|
||||
assert meta_row is not None
|
||||
assert meta_row.category == "meta"
|
||||
node_ids = [n["id"] for n in meta_row.published_graph["nodes"]]
|
||||
assert node_ids == ["diag_node", "patch_node", "verify_output"]
|
||||
|
||||
public_items = await list_public_workflow_bindings(db)
|
||||
assert all(item["workflow_id"] != META_WORKFLOW_ID for item in public_items)
|
||||
|
||||
# Single-level recursion lock: custom `meta.*` workflows are forbidden
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await create_workflow(db, workflow_id="meta.nested_evolver", name="Nested Meta")
|
||||
assert getattr(exc_info.value, "status_code", None) == 400
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_tier0_constitution_validator_enforces_meta_freeze_and_blast_radius():
|
||||
base_meta_graph = {
|
||||
"nodes": [
|
||||
{
|
||||
"id": "diag_node",
|
||||
"node_type": "llm_agent",
|
||||
"title": "Diag",
|
||||
"position": {"x": 80, "y": 140},
|
||||
"enabled": True,
|
||||
"system_prompt": "Diagnose traces cleanly.",
|
||||
"prompt": "Check traces.",
|
||||
"tools": [],
|
||||
"thinking_enabled": True,
|
||||
"max_steps": 1,
|
||||
"timeout_seconds": 60,
|
||||
},
|
||||
{
|
||||
"id": "patch_node",
|
||||
"node_type": "llm_agent",
|
||||
"title": "Patch",
|
||||
"position": {"x": 460, "y": 140},
|
||||
"enabled": True,
|
||||
"system_prompt": "Output strict JSON with node_patches.",
|
||||
"prompt": "Produce JSON.",
|
||||
"tools": [],
|
||||
"thinking_enabled": True,
|
||||
"max_steps": 1,
|
||||
"timeout_seconds": 60,
|
||||
},
|
||||
{
|
||||
"id": "verify_output",
|
||||
"node_type": "guardrail",
|
||||
"title": "Constitution",
|
||||
"position": {"x": 840, "y": 140},
|
||||
"enabled": True,
|
||||
"system_prompt": "",
|
||||
"prompt": "",
|
||||
"tools": [],
|
||||
"thinking_enabled": False,
|
||||
"max_steps": 1,
|
||||
"timeout_seconds": 60,
|
||||
"guardrails": {"immutable_tier0": True},
|
||||
},
|
||||
],
|
||||
"edges": [
|
||||
{"id": "e1", "source": "diag_node", "target": "patch_node"},
|
||||
{"id": "e2", "source": "patch_node", "target": "verify_output"},
|
||||
],
|
||||
}
|
||||
|
||||
# 1. Touching frozen `verify_output` is blocked
|
||||
bad_meta = {**base_meta_graph, "nodes": list(base_meta_graph["nodes"])}
|
||||
ok, violations = validate_evolution_patch(
|
||||
base_meta_graph,
|
||||
bad_meta,
|
||||
[{"node_id": "verify_output", "field": "enabled", "before": True, "after": False}],
|
||||
is_meta=True,
|
||||
is_auto=True,
|
||||
)
|
||||
assert not ok
|
||||
assert any("verify_output" in v for v in violations)
|
||||
|
||||
# 2. Removing JSON output constraint from `patch_node` is blocked
|
||||
bad_json_meta = {
|
||||
"nodes": [
|
||||
base_meta_graph["nodes"][0],
|
||||
{**base_meta_graph["nodes"][1], "system_prompt": "Just talk freely", "prompt": "Write prose"},
|
||||
base_meta_graph["nodes"][2],
|
||||
],
|
||||
"edges": base_meta_graph["edges"],
|
||||
}
|
||||
ok2, violations2 = validate_evolution_patch(
|
||||
base_meta_graph,
|
||||
bad_json_meta,
|
||||
[{"node_id": "patch_node", "field": "system_prompt"}],
|
||||
is_meta=True,
|
||||
is_auto=True,
|
||||
)
|
||||
assert not ok2
|
||||
assert any("node_patches" in v for v in violations2)
|
||||
|
||||
# 3. Auto-mode blast radius (> 1 node on meta) is blocked
|
||||
ok3, violations3 = validate_evolution_patch(
|
||||
base_meta_graph,
|
||||
base_meta_graph,
|
||||
[
|
||||
{"node_id": "diag_node", "field": "prompt"},
|
||||
{"node_id": "patch_node", "field": "prompt"},
|
||||
],
|
||||
is_meta=True,
|
||||
is_auto=True,
|
||||
)
|
||||
assert not ok3
|
||||
assert any("半径" in v for v in violations3)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_evolution_policy_feedback_health_model_drift_and_dgm_archive(monkeypatch):
|
||||
engine, factory = await _make_sqlite_session()
|
||||
|
||||
class _FakeAI:
|
||||
async def is_ready(self):
|
||||
return True, "gemini", "gemini-2.5-flash"
|
||||
|
||||
async def analyze(self, req):
|
||||
return SimpleNamespace(
|
||||
content='{"summary": "Mocked proposal", "node_patches": []}'
|
||||
)
|
||||
|
||||
async def fake_get_ai_client(_db):
|
||||
return _FakeAI()
|
||||
|
||||
monkeypatch.setattr("app.api.v1.ai_workflows.get_ai_provider_client", fake_get_ai_client)
|
||||
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client)
|
||||
|
||||
async def override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
def override_admin():
|
||||
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
app.dependency_overrides[require_admin_user] = override_admin
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with factory() as db:
|
||||
await ensure_builtin_workflows(db)
|
||||
# Seed runs: 5 runs under older model at v1, plus 1 failure
|
||||
now = datetime.now(UTC)
|
||||
for idx in range(5):
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"run_seed_{idx}",
|
||||
workflow_id="default.general",
|
||||
status="failed" if idx == 4 else "completed",
|
||||
access_tier="admin",
|
||||
actor_key="admin",
|
||||
question=f"BGP AS4837 路由异常查询 #{idx}",
|
||||
input_params={},
|
||||
tool_trace=["intent_router", "advisor_agent"],
|
||||
budget_used={
|
||||
"steps": 2,
|
||||
"model_used": "MiniMax-M3.1-Flash",
|
||||
"latency_ms": 620 + idx * 50,
|
||||
"workflow_revision": 1,
|
||||
},
|
||||
error_message="missing citation URL" if idx == 4 else "",
|
||||
started_at=now - timedelta(minutes=20 - idx),
|
||||
completed_at=now - timedelta(minutes=19 - idx),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# 1. Submit negative & positive feedback
|
||||
fb_resp = await client.post(
|
||||
"/api/v1/ai/runs/run_seed_1/feedback",
|
||||
json={"rating": -1, "note": "缺少一手链接取证"},
|
||||
)
|
||||
assert fb_resp.status_code == 200
|
||||
assert fb_resp.json()["budget_used"]["user_rating"] == -1
|
||||
assert fb_resp.json()["budget_used"]["feedback_note"] == "缺少一手链接取证"
|
||||
|
||||
neg_runs = await client.get("/api/v1/ai/runs", params={"feedback": "negative"})
|
||||
assert neg_runs.status_code == 200
|
||||
neg_ids = {item["id"] for item in neg_runs.json()["items"]}
|
||||
assert "run_seed_1" in neg_ids
|
||||
assert "run_seed_4" in neg_ids
|
||||
|
||||
# 2. Policy get/update
|
||||
pol_resp = await client.put(
|
||||
"/api/v1/ai/evolution/policy",
|
||||
json={"business_mode": "auto", "meta_mode": "draft", "daily_auto_budget": 5},
|
||||
)
|
||||
assert pol_resp.status_code == 200
|
||||
assert pol_resp.json()["business_mode"] == "auto"
|
||||
assert pol_resp.json()["meta_mode"] == "draft"
|
||||
assert pol_resp.json()["daily_auto_budget"] == 5
|
||||
|
||||
# 3. 0-Token Health Check: detects model drift + unused tool + signals
|
||||
health_resp = await client.get("/api/v1/ai/evolution/health/default.general")
|
||||
assert health_resp.status_code == 200
|
||||
health = health_resp.json()
|
||||
assert health["total_runs"] == 5
|
||||
assert health["downvotes"] == 1
|
||||
assert health["model_drift_detected"] is True
|
||||
assert "query_global_situational" in health["unused_tools"]
|
||||
|
||||
# 4. Model explicitly returns an empty patch -> the engine must accept "no change"
|
||||
prop_resp = await client.post(
|
||||
"/api/v1/ai/evolution/propose/default.general",
|
||||
json={"mode": "model_adapt", "apply_mode": "preview"},
|
||||
)
|
||||
assert prop_resp.status_code == 200
|
||||
prop = prop_resp.json()
|
||||
assert prop["applied_status"] == "no_change"
|
||||
assert prop["changes"] == []
|
||||
|
||||
# 5. Incubate new custom workflow from `default.general` BGP runs
|
||||
inc_resp = await client.post("/api/v1/ai/evolution/incubate")
|
||||
assert inc_resp.status_code == 200
|
||||
inc = inc_resp.json()
|
||||
assert inc["suggested_workflow_id"].startswith("custom.")
|
||||
assert "bgp" in inc["suggested_workflow_id"]
|
||||
assert len(inc["graph"]["nodes"]) == 3
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_canary_auto_rollback_and_meta_canary_rollback(monkeypatch):
|
||||
engine, factory = await _make_sqlite_session()
|
||||
|
||||
class _NoAIClient:
|
||||
async def is_ready(self):
|
||||
return False, "unconfigured", ""
|
||||
|
||||
async def fake_get_ai_client(_db):
|
||||
return _NoAIClient()
|
||||
|
||||
monkeypatch.setattr("app.api.v1.ai_workflows.get_ai_provider_client", fake_get_ai_client)
|
||||
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client)
|
||||
|
||||
async def override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
def override_admin():
|
||||
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
app.dependency_overrides[require_admin_user] = override_admin
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# First run a meta-evolution in `auto` mode so meta v2 enters canary window
|
||||
await client.put(
|
||||
"/api/v1/ai/evolution/policy",
|
||||
json={"business_mode": "auto", "meta_mode": "auto"},
|
||||
)
|
||||
meta_pub = await client.post(
|
||||
"/api/v1/ai/evolution/meta-evolve",
|
||||
json={"instruction": "Prefer minimal single-node changes.", "apply_mode": "auto"},
|
||||
)
|
||||
assert meta_pub.status_code == 200
|
||||
assert meta_pub.json()["applied_status"] == "auto_published"
|
||||
assert meta_pub.json()["new_revision"] == 2
|
||||
|
||||
# Auto-publish requires a graded fixture A/B gate
|
||||
await _add_graded_fixture(client, "default.general")
|
||||
# Auto-publish default.general v2 (uses live meta v2)
|
||||
evo_pub = await client.post(
|
||||
"/api/v1/ai/evolution/propose/default.general",
|
||||
json={
|
||||
"mode": "optimize",
|
||||
"instruction": "Require primary search verification",
|
||||
"apply_mode": "auto",
|
||||
},
|
||||
)
|
||||
assert evo_pub.status_code == 200
|
||||
assert evo_pub.json()["applied_status"] == "auto_published"
|
||||
assert evo_pub.json()["new_revision"] == 2
|
||||
|
||||
# Simulate 2 consecutive failed runs on v2 -> canary triggers rollback to v1
|
||||
async with factory() as db:
|
||||
now = datetime.now(UTC) + timedelta(seconds=2)
|
||||
for idx in range(2):
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"run_canary_fail_{idx}",
|
||||
workflow_id="default.general",
|
||||
status="failed",
|
||||
access_tier="admin",
|
||||
actor_key="admin",
|
||||
question="fail test",
|
||||
input_params={},
|
||||
tool_trace=["intent_router"],
|
||||
budget_used={"workflow_revision": 2},
|
||||
error_message="boom",
|
||||
started_at=now + timedelta(seconds=idx),
|
||||
completed_at=now + timedelta(seconds=idx + 1),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
res = await evaluate_canary_and_maybe_rollback(db, "default.general")
|
||||
assert res is not None and res["action"] == "rolled_back"
|
||||
|
||||
wf_row = (
|
||||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == "default.general"))
|
||||
).scalar_one()
|
||||
# Rollback publishes a new revision v3 carrying v1 graph
|
||||
assert wf_row.active_revision == 3
|
||||
|
||||
# Add a 2nd rolled_back downstream outcome in ledger -> meta-canary rolls back meta v2!
|
||||
await append_ledger_entry(
|
||||
db,
|
||||
{
|
||||
"workflow_id": "brief.bgp",
|
||||
"mode": "optimize",
|
||||
"trigger": "auto_post_run",
|
||||
"status": "rolled_back",
|
||||
"base_revision": 1,
|
||||
"target_revision": 2,
|
||||
"summary": "second failure under meta v2",
|
||||
"created_at": (now + timedelta(seconds=5)).isoformat(),
|
||||
},
|
||||
)
|
||||
# Re-run meta canary check via another canary evaluation
|
||||
from app.services.ai.workflow_evolver import _evaluate_meta_canary
|
||||
|
||||
await _evaluate_meta_canary(db)
|
||||
meta_row = (
|
||||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID))
|
||||
).scalar_one()
|
||||
assert meta_row.active_revision == 3
|
||||
|
||||
# Cooldown / ledger inspectable & dismissible
|
||||
led_resp = await client.get("/api/v1/ai/evolution/ledger")
|
||||
assert led_resp.status_code == 200
|
||||
entries = led_resp.json()["items"]
|
||||
assert any(e["workflow_id"] == META_WORKFLOW_ID and e["status"] == "rolled_back" for e in entries)
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fixture_ab_eval_endpoint(monkeypatch):
|
||||
engine, factory = await _make_sqlite_session()
|
||||
|
||||
class _FakeStreamAI:
|
||||
async def is_ready(self):
|
||||
return True, "minimax", "MiniMax-M3.1-Flash"
|
||||
|
||||
async def stream_analyze(self, _req, request_id=None):
|
||||
yield {"event": "text", "delta": "全球态势核心节点运行稳定。"}
|
||||
|
||||
async def fake_get_ai_client(_db):
|
||||
return _FakeStreamAI()
|
||||
|
||||
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client)
|
||||
|
||||
async def override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
def override_admin():
|
||||
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
app.dependency_overrides[require_admin_user] = override_admin
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
fix = await client.post(
|
||||
"/api/v1/ai/workflows/default.general/fixtures",
|
||||
json={"name": "Sample Global", "sample_question": "全球态势摘要", "context_json": {"domain": "global"}},
|
||||
)
|
||||
assert fix.status_code == 200
|
||||
detail = (await client.get("/api/v1/ai/workflows/default.general")).json()
|
||||
graph = detail["workflow"]["published_graph"]
|
||||
|
||||
eval_resp = await client.post(
|
||||
"/api/v1/ai/evolution/eval/default.general",
|
||||
json={"proposed_graph": graph, "max_fixtures": 2},
|
||||
)
|
||||
assert eval_resp.status_code == 200
|
||||
ev = eval_resp.json()
|
||||
assert ev["fixture_count"] == 1
|
||||
assert ev["base_passed"] == 1
|
||||
assert ev["proposed_passed"] == 1
|
||||
assert ev["verdict"] in {"neutral", "improved", "slower"}
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lock_quota_cooldown_dgm_branching_canary_verify_and_ledger_dismiss(monkeypatch):
|
||||
engine, factory = await _make_sqlite_session()
|
||||
|
||||
class _NoAIClient:
|
||||
async def is_ready(self):
|
||||
return False, "unconfigured", ""
|
||||
|
||||
async def fake_get_ai_client(_db):
|
||||
return _NoAIClient()
|
||||
|
||||
monkeypatch.setattr("app.api.v1.ai_workflows.get_ai_provider_client", fake_get_ai_client)
|
||||
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client)
|
||||
|
||||
async def override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
def override_admin():
|
||||
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
app.dependency_overrides[require_admin_user] = override_admin
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# 1. Locked workflow blocks `apply_mode="auto"`
|
||||
await client.put(
|
||||
"/api/v1/ai/evolution/policy",
|
||||
json={"business_mode": "auto", "locked_workflows": ["default.general"], "daily_auto_budget": 2},
|
||||
)
|
||||
locked_resp = await client.post(
|
||||
"/api/v1/ai/evolution/propose/default.general",
|
||||
json={"mode": "optimize", "instruction": "Tighten citations", "apply_mode": "auto"},
|
||||
)
|
||||
assert locked_resp.status_code == 200
|
||||
assert locked_resp.json()["applied_status"] == "blocked"
|
||||
assert "锁定" in locked_resp.json()["blocked_reason"]
|
||||
|
||||
# Unlock and set daily_auto_budget=1 so 2nd auto run hits budget cap
|
||||
await client.put(
|
||||
"/api/v1/ai/evolution/policy",
|
||||
json={"locked_workflows": [], "daily_auto_budget": 2},
|
||||
)
|
||||
await _add_graded_fixture(client, "default.general")
|
||||
pub1 = await client.post(
|
||||
"/api/v1/ai/evolution/propose/default.general",
|
||||
json={"mode": "optimize", "instruction": "Always cite verified telemetry", "apply_mode": "auto"},
|
||||
)
|
||||
assert pub1.status_code == 200
|
||||
assert pub1.json()["applied_status"] == "auto_published"
|
||||
rev_v2 = pub1.json()["new_revision"]
|
||||
assert rev_v2 == 2
|
||||
|
||||
# Seed 5 good runs on v2 -> Canary verifies cleanly
|
||||
async with factory() as db:
|
||||
now = datetime.now(UTC) + timedelta(seconds=2)
|
||||
for idx in range(5):
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"run_ok_v2_{idx}",
|
||||
workflow_id="default.general",
|
||||
status="completed",
|
||||
access_tier="admin",
|
||||
actor_key="admin",
|
||||
question=f"Verified query {idx}",
|
||||
input_params={},
|
||||
tool_trace=["intent_router", "advisor_agent"],
|
||||
budget_used={"workflow_revision": rev_v2, "user_rating": 1},
|
||||
error_message="",
|
||||
started_at=now + timedelta(seconds=idx),
|
||||
completed_at=now + timedelta(seconds=idx + 1),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
canary_ok = await evaluate_canary_and_maybe_rollback(db, "default.general")
|
||||
assert canary_ok is not None and canary_ok["action"] == "verified"
|
||||
|
||||
# Now seed 4 good runs on v1 and 3 failed runs on a degraded v3 to trigger DGM parent recommendation
|
||||
v1_rev = (
|
||||
await db.execute(
|
||||
select(AIWorkflowRevision)
|
||||
.where(AIWorkflowRevision.workflow_id == "default.general")
|
||||
.where(AIWorkflowRevision.revision == 1)
|
||||
)
|
||||
).scalar_one()
|
||||
from app.services.ai.workflow_registry import publish_workflow
|
||||
|
||||
await publish_workflow(
|
||||
db,
|
||||
"default.general",
|
||||
graph=v1_rev.graph_json,
|
||||
change_summary="manual degraded v3",
|
||||
actor="admin",
|
||||
)
|
||||
for idx in range(4):
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"run_v1_best_{idx}",
|
||||
workflow_id="default.general",
|
||||
status="completed",
|
||||
access_tier="admin",
|
||||
actor_key="admin",
|
||||
question="v1 baseline",
|
||||
input_params={},
|
||||
tool_trace=["intent_router"],
|
||||
budget_used={"workflow_revision": 1, "user_rating": 1},
|
||||
error_message="",
|
||||
started_at=now + timedelta(seconds=10 + idx),
|
||||
completed_at=now + timedelta(seconds=11 + idx),
|
||||
)
|
||||
)
|
||||
for idx in range(3):
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"run_v3_bad_{idx}",
|
||||
workflow_id="default.general",
|
||||
status="failed",
|
||||
access_tier="admin",
|
||||
actor_key="admin",
|
||||
question="v3 degraded",
|
||||
input_params={},
|
||||
tool_trace=["intent_router"],
|
||||
budget_used={"workflow_revision": 3, "user_rating": -1},
|
||||
error_message="degraded",
|
||||
started_at=now + timedelta(seconds=20 + idx),
|
||||
completed_at=now + timedelta(seconds=21 + idx),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
# Health recommends parent v2 (or v1) over degraded v3, and branch_from_best picks it
|
||||
h = (await client.get("/api/v1/ai/evolution/health/default.general")).json()
|
||||
assert h["recommended_parent_revision"] in {1, 2}
|
||||
branch_prop = (
|
||||
await client.post(
|
||||
"/api/v1/ai/evolution/propose/default.general",
|
||||
json={"mode": "optimize", "instruction": "Recovery patch", "apply_mode": "preview", "branch_from_best": True},
|
||||
)
|
||||
).json()
|
||||
assert branch_prop["base_revision"] == h["recommended_parent_revision"]
|
||||
|
||||
# Cooldown blocks immediate 2nd `auto` propose while recent ledger entry is active
|
||||
cd_resp = (
|
||||
await client.post(
|
||||
"/api/v1/ai/evolution/propose/default.general",
|
||||
json={"mode": "optimize", "instruction": "Another auto change", "apply_mode": "auto"},
|
||||
)
|
||||
).json()
|
||||
assert cd_resp["applied_status"] == "blocked"
|
||||
assert "冷却" in cd_resp["blocked_reason"]
|
||||
|
||||
# Check ledger & dismiss an entry
|
||||
ledger_items = (await client.get("/api/v1/ai/evolution/ledger")).json()["items"]
|
||||
target_entry = next(
|
||||
e for e in ledger_items if e["workflow_id"] == "default.general" and e["status"] == "verified"
|
||||
)
|
||||
dis = await client.post(
|
||||
f"/api/v1/ai/evolution/ledger/{target_entry['id']}/dismiss",
|
||||
json={"reason": "Not needed right now"},
|
||||
)
|
||||
assert dis.status_code == 200
|
||||
assert dis.json()["status"] == "dismissed"
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
"""Regression tests for the v0.82.0 workflow review: Earth DAG data/evidence/card output and evolver safety."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, event, select
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.db.session import Base
|
||||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.ai import dag_executor
|
||||
from app.services.ai.dag_executor import _execute_tool, run_workflow_dag_stream
|
||||
from app.services.ai.workflow_evolver import (
|
||||
META_WORKFLOW_ID,
|
||||
_load_ledger_entries,
|
||||
append_ledger_entry,
|
||||
build_business_evolution_request,
|
||||
evaluate_canary_and_maybe_rollback,
|
||||
grade_fixture_result,
|
||||
propose_meta_evolution,
|
||||
propose_workflow_evolution,
|
||||
run_fixture_ab_eval,
|
||||
update_evolution_policy,
|
||||
)
|
||||
from app.services.ai.workflow_registry import (
|
||||
_fallback_workflow_dict,
|
||||
create_workflow,
|
||||
discard_workflow_draft,
|
||||
ensure_builtin_workflows,
|
||||
list_public_workflow_bindings,
|
||||
publish_workflow,
|
||||
rollback_workflow,
|
||||
save_workflow_draft,
|
||||
)
|
||||
|
||||
|
||||
class _SyncAsAsyncSession:
|
||||
def __init__(self, sync_session):
|
||||
self._s = sync_session
|
||||
|
||||
def add(self, obj):
|
||||
return self._s.add(obj)
|
||||
|
||||
async def execute(self, stmt, *args, **kwargs):
|
||||
return self._s.execute(stmt, *args, **kwargs)
|
||||
|
||||
async def scalar(self, stmt, *args, **kwargs):
|
||||
return self._s.scalar(stmt, *args, **kwargs)
|
||||
|
||||
async def get(self, model, ident):
|
||||
return self._s.get(model, ident)
|
||||
|
||||
async def delete(self, obj):
|
||||
return self._s.delete(obj)
|
||||
|
||||
async def flush(self):
|
||||
return self._s.flush()
|
||||
|
||||
async def commit(self):
|
||||
return self._s.commit()
|
||||
|
||||
async def rollback(self):
|
||||
return self._s.rollback()
|
||||
|
||||
async def refresh(self, obj):
|
||||
return self._s.refresh(obj)
|
||||
|
||||
async def close(self):
|
||||
return self._s.close()
|
||||
|
||||
|
||||
def _make_db():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
event.listen(
|
||||
engine,
|
||||
"connect",
|
||||
lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v),
|
||||
)
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
AIWorkflow.__table__,
|
||||
AIWorkflowRevision.__table__,
|
||||
AIWorkflowFixture.__table__,
|
||||
WorkflowRun.__table__,
|
||||
SystemSetting.__table__,
|
||||
BGPIncident.__table__,
|
||||
CollectedData.__table__,
|
||||
EarthNewsItem.__table__,
|
||||
],
|
||||
)
|
||||
return engine, _SyncAsAsyncSession(sessionmaker(engine, expire_on_commit=False)())
|
||||
|
||||
|
||||
async def _collect(stream) -> list[dict]:
|
||||
return [ev async for ev in stream]
|
||||
|
||||
|
||||
def _done(events: list[dict]) -> dict:
|
||||
return next(ev["data"] for ev in events if ev["event"] == "done")
|
||||
|
||||
|
||||
def _text(events: list[dict]) -> str:
|
||||
return "".join(ev["data"]["delta"] for ev in events if ev["event"] == "text")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Cross-layer evidence: each source must query its own object regardless of click order
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multi_select_targets_route_each_source_to_its_own_object(monkeypatch):
|
||||
seen: dict[str, list] = {"bgp": [], "cable": [], "vessel": []}
|
||||
|
||||
async def fake_bgp(_db, *, incident_key=None, **_kw):
|
||||
seen["bgp"].append(incident_key)
|
||||
return []
|
||||
|
||||
async def fake_cable(_db, *, entity_id=None, **_kw):
|
||||
seen["cable"].append(entity_id)
|
||||
return {}
|
||||
|
||||
async def fake_vessel(_db, *, entity_id=None, **_kw):
|
||||
seen["vessel"].append(entity_id)
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(dag_executor, "query_bgp_incidents_tool", fake_bgp)
|
||||
monkeypatch.setattr(dag_executor, "query_cable_posture_tool", fake_cable)
|
||||
monkeypatch.setattr(dag_executor, "query_vessel_posture_tool", fake_vessel)
|
||||
|
||||
cable = {"entity_type": "cable", "entity_id": "cable-peace"}
|
||||
vessel = {"entity_type": "vessel", "entity_id": "mmsi-413000000"}
|
||||
bgp = {"entity_type": "bgp", "entity_id": "bgp-incident-77"}
|
||||
for order in ([cable, vessel, bgp], [bgp, vessel, cable], [vessel, bgp, cable]):
|
||||
for tool in ("query_bgp_incidents", "query_cable_posture", "query_vessel_posture"):
|
||||
await _execute_tool(
|
||||
None, tool, question="q", targets=order, earth_context={}, allow_external_tools=False
|
||||
)
|
||||
assert set(seen["bgp"]) == {"bgp-incident-77"}
|
||||
assert set(seen["cable"]) == {"cable-peace"}
|
||||
assert set(seen["vessel"]) == {"mmsi-413000000"}
|
||||
|
||||
# A source with no matching target gets no ID (never another layer's ID).
|
||||
seen["vessel"].clear()
|
||||
await _execute_tool(None, "query_vessel_posture", question="q", targets=[cable, bgp], earth_context={}, allow_external_tools=False)
|
||||
assert seen["vessel"] == [None]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Compute comparison workflow must hand a ViewSpec workbench to the Earth copilot
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SERIES = {
|
||||
"years": (2023, 2024),
|
||||
"compute": [
|
||||
{"year": 2023, "values": {"CN": 30.0, "US": 52.0}, "evidence_id": "ev-top500-2023"},
|
||||
{"year": 2024, "values": {"CN": 37.0, "US": 50.0}, "evidence_id": "ev-top500-2024"},
|
||||
],
|
||||
"unit": "%",
|
||||
"evidence": {
|
||||
"ev-top500-2023": {"id": "ev-top500-2023", "title": "TOP500 2023", "publisher": "TOP500", "url": "https://top500.org/2023"},
|
||||
"ev-top500-2024": {"id": "ev-top500-2024", "title": "TOP500 2024", "publisher": "TOP500", "url": "https://top500.org/2024"},
|
||||
},
|
||||
"time_basis": "retrospective",
|
||||
}
|
||||
|
||||
|
||||
class _ComputeBriefAI:
|
||||
def __init__(self, content: str):
|
||||
self.content = content
|
||||
self.stream_calls = 0
|
||||
|
||||
async def is_ready(self):
|
||||
return True, "fake", "fake-model"
|
||||
|
||||
async def analyze(self, req):
|
||||
return SimpleNamespace(content=self.content, provider="fake", model="fake-model")
|
||||
|
||||
async def stream_analyze(self, req, request_id=None):
|
||||
self.stream_calls += 1
|
||||
yield {"event": "text", "delta": "should not stream"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("valid_brief", [True, False])
|
||||
async def test_compute_comparison_workflow_emits_view_spec_and_no_raw_json(monkeypatch, valid_brief):
|
||||
async def fake_compute(_db, countries, mode="global_share", **_kw):
|
||||
return copy.deepcopy(_SERIES)
|
||||
|
||||
monkeypatch.setattr(dag_executor, "query_compute_posture_tool", fake_compute)
|
||||
brief = {
|
||||
"headline": "中国算力份额升至 37%",
|
||||
"headline_en": "China share rises to 37%",
|
||||
"executive_assertion": "2024 年中国全球算力份额为 37%。",
|
||||
"executive_assertion_en": "China held 37% in 2024.",
|
||||
"causes": [
|
||||
{"label": "装机增长", "detail": "新增超算集中投运", "evidence_ids": ["ev-top500-2024" if valid_brief else "ev-made-up"]}
|
||||
],
|
||||
"breakthrough_levers": [],
|
||||
"blind_spots": ["未覆盖商业云内部集群"],
|
||||
"evidence_ids": ["ev-top500-2024"],
|
||||
}
|
||||
ai = _ComputeBriefAI(json.dumps(brief, ensure_ascii=False))
|
||||
workflow = _fallback_workflow_dict("compute.comparison")
|
||||
events = await _collect(
|
||||
run_workflow_dag_stream(
|
||||
db=None,
|
||||
workflow=workflow,
|
||||
question="对比中美算力",
|
||||
earth_context={"selected_codes": ["CN", "US"], "mode": "global_share"},
|
||||
ai_client=ai,
|
||||
)
|
||||
)
|
||||
done = _done(events)
|
||||
text = _text(events)
|
||||
assert ai.stream_calls == 0
|
||||
assert not text.lstrip().startswith("{") and '"headline"' not in text
|
||||
assert isinstance(done["view_spec"], dict) and done["view_spec"].get("blocks")
|
||||
late_meta = [ev["data"] for ev in events if ev["event"] == "meta" and ev["data"].get("view_spec")]
|
||||
assert late_meta and late_meta[-1]["domain"] == "compute"
|
||||
if valid_brief:
|
||||
assert "中国算力份额升至 37%" in text
|
||||
else:
|
||||
assert "确定性研判" in text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Evidence guardrail failures must reach the user and the evaluator
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _guarded_graph(system_prompt: str = "研判 BGP 成因") -> dict:
|
||||
return {
|
||||
"nodes": [
|
||||
{"id": "t", "node_type": "trigger", "title": "入口"},
|
||||
{"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": system_prompt},
|
||||
{"id": "gr", "node_type": "guardrail", "title": "证据校验", "guardrails": {"require_evidence": True}},
|
||||
{"id": "out", "node_type": "output", "title": "输出"},
|
||||
],
|
||||
"edges": [
|
||||
{"id": "e1", "source": "t", "target": "llm"},
|
||||
{"id": "e2", "source": "llm", "target": "gr"},
|
||||
{"id": "e3", "source": "gr", "target": "out"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class _StreamAI:
|
||||
"""Streams an answer chosen by the node system prompt (lets A/B graphs answer differently)."""
|
||||
|
||||
def __init__(self, answers: dict[str, str], default: str = "研判完成"):
|
||||
self.answers = answers
|
||||
self.default = default
|
||||
|
||||
async def is_ready(self):
|
||||
return True, "fake", "fake-model"
|
||||
|
||||
async def analyze(self, req):
|
||||
return SimpleNamespace(content=self._pick(req), provider="fake", model="fake-model")
|
||||
|
||||
async def stream_analyze(self, req, request_id=None):
|
||||
yield {"event": "text", "delta": self._pick(req)}
|
||||
|
||||
def _pick(self, req) -> str:
|
||||
for key, answer in self.answers.items():
|
||||
if key in (req.system_prompt or ""):
|
||||
return answer
|
||||
return self.default
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_evidence_marks_run_unverified_and_delivers_pending_cause():
|
||||
workflow = {"workflow_id": "custom.bgp_cause", "name": "BGP 成因", "published_graph": _guarded_graph()}
|
||||
events = await _collect(
|
||||
run_workflow_dag_stream(
|
||||
db=None, workflow=workflow, question="AS4837 为什么异常", ai_client=_StreamAI({}, "成因是上游劫持。")
|
||||
)
|
||||
)
|
||||
done = _done(events)
|
||||
assert done["status"] == "unverified"
|
||||
assert done["verification"]["passed"] is False
|
||||
assert "原因待核实" in done["answer_markdown"] and "待查项" in done["answer_markdown"]
|
||||
failures = grade_fixture_result(
|
||||
{"answer": done["answer_markdown"], "error": "", "verification_passed": False, "verification_warnings": done["verification"]["warnings"]},
|
||||
{},
|
||||
)
|
||||
assert any("护栏" in f for f in failures)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. News: one click runs only the interactive branch
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_news_analysis_runs_only_the_branch_matching_the_trigger(monkeypatch):
|
||||
async def fake_news(_db, region=None, limit=10):
|
||||
return {"items": [{"title": "headline"}], "evidence": {}}
|
||||
|
||||
async def fake_global(_db, **_kw):
|
||||
return {"items": [], "evidence": {}}
|
||||
|
||||
monkeypatch.setattr(dag_executor, "query_recent_earth_news_tool", fake_news)
|
||||
monkeypatch.setattr(dag_executor, "query_global_situational_tool", fake_global)
|
||||
calls: list[str] = []
|
||||
|
||||
class _AI:
|
||||
async def is_ready(self):
|
||||
return True, "fake", "fake-model"
|
||||
|
||||
async def analyze(self, req):
|
||||
calls.append("analyze")
|
||||
return SimpleNamespace(content='{"location": {}, "localizations": {}}', provider="fake", model="m")
|
||||
|
||||
async def stream_analyze(self, req, request_id=None):
|
||||
calls.append("stream")
|
||||
yield {"event": "text", "delta": "研判正文"}
|
||||
|
||||
workflow = _fallback_workflow_dict("earth.news.analysis")
|
||||
events = await _collect(run_workflow_dag_stream(db=None, workflow=workflow, question="分析这条新闻", ai_client=_AI()))
|
||||
skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"}
|
||||
assert "news_enrich_node" in skipped
|
||||
assert calls == ["stream"]
|
||||
assert _text(events) == "研判正文"
|
||||
|
||||
calls.clear()
|
||||
events = await _collect(
|
||||
run_workflow_dag_stream(db=None, workflow=workflow, question="enrich", ai_client=_AI(), trigger_source="ingest")
|
||||
)
|
||||
skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"}
|
||||
assert "news_analyst_node" in skipped
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Draft bindings stay out of the public Earth entry until publish; rollback restores them
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_draft_bindings_do_not_touch_public_entry_and_roll_back_with_graph():
|
||||
engine, db = _make_db()
|
||||
try:
|
||||
await ensure_builtin_workflows(db)
|
||||
wf_id = "earth.news.analysis"
|
||||
|
||||
async def public_ids() -> set[str]:
|
||||
return {item["workflow_id"] for item in await list_public_workflow_bindings(db)}
|
||||
|
||||
assert wf_id in await public_ids()
|
||||
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
||||
graph = copy.deepcopy(row.published_graph)
|
||||
live_bindings = copy.deepcopy(row.bindings)
|
||||
disabled = {**live_bindings, "enabled": False}
|
||||
|
||||
saved = await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin")
|
||||
assert wf_id in await public_ids()
|
||||
assert saved["draft_bindings"]["enabled"] is False
|
||||
await discard_workflow_draft(db, wf_id)
|
||||
assert wf_id in await public_ids()
|
||||
|
||||
enabled_rev = (await publish_workflow(db, wf_id, graph=graph, bindings=live_bindings))["active_revision"]
|
||||
await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin")
|
||||
await publish_workflow(db, wf_id)
|
||||
assert wf_id not in await public_ids()
|
||||
await rollback_workflow(db, wf_id, enabled_rev)
|
||||
assert wf_id in await public_ids()
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Canary rollback must not overwrite a newer manual publish
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_canary_rollback_is_superseded_by_manual_publish():
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
engine, db = _make_db()
|
||||
try:
|
||||
await ensure_builtin_workflows(db)
|
||||
wf_id = "default.general"
|
||||
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
||||
graph = copy.deepcopy(row.published_graph)
|
||||
await publish_workflow(db, wf_id, graph=graph, actor="system:auto_evolver") # v2 canary
|
||||
await append_ledger_entry(
|
||||
db,
|
||||
{"workflow_id": wf_id, "status": "canary", "base_revision": 1, "target_revision": 2, "canary_runs_target": 5},
|
||||
)
|
||||
manual = copy.deepcopy(graph)
|
||||
manual["nodes"][0]["description"] = "manual v3"
|
||||
await publish_workflow(db, wf_id, graph=manual, actor="admin") # v3 manual
|
||||
now = datetime.now(UTC) + timedelta(seconds=2)
|
||||
for idx in range(2):
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"v2_fail_{idx}", workflow_id=wf_id, status="failed", access_tier="admin", actor_key="admin",
|
||||
question="q", input_params={}, tool_trace=[], budget_used={"workflow_revision": 2},
|
||||
error_message="boom", started_at=now + timedelta(seconds=idx), completed_at=now + timedelta(seconds=idx + 1),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
res = await evaluate_canary_and_maybe_rollback(db, wf_id)
|
||||
assert res["action"] == "superseded"
|
||||
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
||||
assert row.active_revision == 3
|
||||
assert row.published_graph["nodes"][0]["description"] == "manual v3"
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. Evolver can conclude "no change" (business + meta)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _EmptyPatchAI:
|
||||
async def is_ready(self):
|
||||
return True, "fake", "fake-model"
|
||||
|
||||
async def analyze(self, req):
|
||||
return SimpleNamespace(content='{"summary": "无需修改", "node_patches": []}')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_explicit_empty_patch_ends_round_without_new_version():
|
||||
engine, db = _make_db()
|
||||
try:
|
||||
await ensure_builtin_workflows(db)
|
||||
await update_evolution_policy(db, {"business_mode": "auto", "meta_mode": "auto"})
|
||||
for wf_id in ("compute.comparison", "default.general"):
|
||||
for apply_mode in ("preview", "draft", "auto"):
|
||||
res = await propose_workflow_evolution(
|
||||
db, wf_id, apply_mode=apply_mode, ai_client=_EmptyPatchAI(), trigger="manual"
|
||||
)
|
||||
assert res["applied_status"] == "no_change", (wf_id, apply_mode)
|
||||
meta_res = await propose_meta_evolution(db, apply_mode="auto", ai_client=_EmptyPatchAI())
|
||||
assert meta_res["applied_status"] == "no_change"
|
||||
|
||||
class _NoAI:
|
||||
async def is_ready(self):
|
||||
return False, "", ""
|
||||
|
||||
# No AI, no ledger outcomes, no instruction -> nothing to base a meta rule on.
|
||||
meta_fallback = await propose_meta_evolution(db, apply_mode="auto", ai_client=_NoAI())
|
||||
assert meta_fallback["applied_status"] == "no_change"
|
||||
rows = (await db.execute(select(AIWorkflow))).scalars().all()
|
||||
assert all(r.active_revision == 1 and r.draft_graph is None for r in rows)
|
||||
assert await _load_ledger_entries(db) == []
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 8. Graded A/B: 37 vs 73 must be a regression, and auto-publish requires the gate
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_graded_fixture_ab_detects_wrong_number_and_gates_auto_publish(monkeypatch):
|
||||
engine, db = _make_db()
|
||||
try:
|
||||
await ensure_builtin_workflows(db)
|
||||
base_graph = {
|
||||
"nodes": [
|
||||
{"id": "t", "node_type": "trigger", "title": "入口"},
|
||||
{"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": "PROMPT_BASE"},
|
||||
{"id": "out", "node_type": "output", "title": "输出"},
|
||||
],
|
||||
"edges": [{"id": "e1", "source": "t", "target": "llm"}, {"id": "e2", "source": "llm", "target": "out"}],
|
||||
}
|
||||
await create_workflow(db, workflow_id="custom.metric", name="指标研判", graph=base_graph)
|
||||
proposed = copy.deepcopy(base_graph)
|
||||
proposed["nodes"][1]["system_prompt"] = "PROMPT_NEW"
|
||||
ai = _StreamAI({"PROMPT_BASE": "观测值为 37。", "PROMPT_NEW": "观测值为 73。"})
|
||||
|
||||
async def fake_client(_db):
|
||||
return ai
|
||||
|
||||
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client)
|
||||
db.add(
|
||||
AIWorkflowFixture(
|
||||
workflow_id="custom.metric", name="观测值 37", sample_question="当前观测值是多少?",
|
||||
context_json={"expect": {"numbers": [37]}},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
ab = await run_fixture_ab_eval(db, "custom.metric", proposed)
|
||||
assert (ab["base_passed"], ab["proposed_passed"]) == (1, 0)
|
||||
assert ab["verdict"] == "regressed" and ab["regressions"] == ["观测值 37"]
|
||||
assert ab["graded_fixture_count"] == 1
|
||||
|
||||
# Auto-publish of that regressing candidate is blocked by the A/B gate.
|
||||
await update_evolution_policy(db, {"business_mode": "auto"})
|
||||
|
||||
class _PatchAI(_StreamAI):
|
||||
async def analyze(self, req):
|
||||
return SimpleNamespace(
|
||||
content=json.dumps(
|
||||
{"summary": "调整提示词", "node_patches": [{"node_id": "llm", "field": "system_prompt", "after": "PROMPT_NEW", "reason": "test"}]}
|
||||
)
|
||||
)
|
||||
|
||||
res = await propose_workflow_evolution(
|
||||
db, "custom.metric", apply_mode="auto", ai_client=_PatchAI(ai.answers), trigger="manual"
|
||||
)
|
||||
assert res["applied_status"] == "blocked"
|
||||
assert "A/B" in res["blocked_reason"]
|
||||
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == "custom.metric"))).scalar_one()
|
||||
assert row.active_revision == 1
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 9. Auto evolution builds from the live revision and never ships human drafts
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_evolution_ignores_unpublished_human_draft(monkeypatch):
|
||||
engine, db = _make_db()
|
||||
try:
|
||||
await ensure_builtin_workflows(db)
|
||||
wf_id = "default.general"
|
||||
stream_ai = _StreamAI({}, "研判完成:态势稳定。")
|
||||
|
||||
async def fake_client(_db):
|
||||
return stream_ai
|
||||
|
||||
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client)
|
||||
db.add(
|
||||
AIWorkflowFixture(
|
||||
workflow_id=wf_id, name="稳定性", sample_question="全球态势",
|
||||
context_json={"expect": {"must_include": ["研判完成"]}},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
||||
human_draft = copy.deepcopy(row.published_graph)
|
||||
for node in human_draft["nodes"][:3]:
|
||||
node["description"] = "HUMAN EDIT"
|
||||
await save_workflow_draft(db, wf_id, human_draft, actor="admin")
|
||||
await update_evolution_policy(db, {"business_mode": "auto"})
|
||||
|
||||
class _PatchAI(_StreamAI):
|
||||
async def analyze(self, req):
|
||||
return SimpleNamespace(
|
||||
content=json.dumps(
|
||||
{"summary": "增加一步", "node_patches": [{"node_id": "advisor_agent", "field": "max_steps", "after": 4, "reason": "test"}]}
|
||||
)
|
||||
)
|
||||
|
||||
res = await propose_workflow_evolution(
|
||||
db, wf_id, apply_mode="auto", trigger="auto_post_run", ai_client=_PatchAI({}, "研判完成:态势稳定。")
|
||||
)
|
||||
assert res["applied_status"] == "auto_published", res["blocked_reason"]
|
||||
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
||||
assert all(n.get("description") != "HUMAN EDIT" for n in row.published_graph["nodes"])
|
||||
assert row.draft_graph is not None
|
||||
assert sum(1 for n in row.draft_graph["nodes"] if n.get("description") == "HUMAN EDIT") == 3
|
||||
assert [(c["node_id"], c["field"]) for c in res["changes_vs_live"]] == [("advisor_agent", "max_steps")]
|
||||
ledger = await _load_ledger_entries(db)
|
||||
assert ledger[0]["changes_vs_live"] == res["changes_vs_live"]
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 10. Every meta-evolvable field changes the downstream business request
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_meta_evolvable_fields_change_business_request():
|
||||
base_diag = {"system_prompt": "诊断系统", "prompt": "诊断任务 A", "thinking_enabled": True}
|
||||
base_patch = {"system_prompt": "输出 JSON node_patches", "prompt": "补丁任务", "thinking_enabled": True}
|
||||
|
||||
def build(diag, patch):
|
||||
req = build_business_evolution_request(
|
||||
workflow_id="default.general", mode="optimize", instruction="", diag_node=diag, patch_node=patch,
|
||||
schema={"type": "object"}, context={},
|
||||
)
|
||||
return req.model_dump()
|
||||
|
||||
baseline = build(base_diag, base_patch)
|
||||
variants = {
|
||||
("diag_node", "system_prompt"): build({**base_diag, "system_prompt": "诊断系统 v2"}, base_patch),
|
||||
("diag_node", "prompt"): build({**base_diag, "prompt": "诊断任务 B"}, base_patch),
|
||||
("patch_node", "system_prompt"): build(base_diag, {**base_patch, "system_prompt": "输出 JSON node_patches v2"}),
|
||||
("patch_node", "prompt"): build(base_diag, {**base_patch, "prompt": "补丁任务 v2"}),
|
||||
("patch_node", "thinking_enabled"): build(base_diag, {**base_patch, "thinking_enabled": False}),
|
||||
}
|
||||
from app.services.ai.workflow_evolver import META_EVOLVABLE_FIELDS
|
||||
|
||||
assert set(variants) == set(META_EVOLVABLE_FIELDS)
|
||||
for key, req in variants.items():
|
||||
assert req != baseline, key
|
||||
assert META_WORKFLOW_ID == "meta.workflow_evolver"
|
||||
+2
-2
@@ -16,7 +16,7 @@
|
||||
"pmtiles": "4.4.1",
|
||||
"satellite.js": "5.0.0",
|
||||
"simplex-noise": "4.0.1",
|
||||
"three": "0.128.0",
|
||||
"three": "0.160.1",
|
||||
"typescript": "5.9.3",
|
||||
},
|
||||
},
|
||||
@@ -595,7 +595,7 @@
|
||||
|
||||
"temp-file": ["temp-file@3.4.0", "https://registry.npmmirror.com/temp-file/-/temp-file-3.4.0.tgz", { "dependencies": { "async-exit-hook": "^2.0.1", "fs-extra": "^10.0.0" } }, "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg=="],
|
||||
|
||||
"three": ["three@0.128.0", "https://registry.npmmirror.com/three/-/three-0.128.0.tgz", {}, "sha512-i0ap/E+OaSfzw7bD1TtYnPo3VEplkl70WX5fZqZnfZsE3k3aSFudqrrC9ldFZfYFkn1zwDmBcdGfiIm/hnbyZA=="],
|
||||
"three": ["three@0.160.1", "", {}, "sha512-Bgl2wPJypDOZ1stAxwfWAcJ0WQf7QzlptsxkjYiURPz+n5k4RBDLsq+6f9Y75TYxn6aHLcWz+JNmwTOXWrQTBQ=="],
|
||||
|
||||
"tiny-async-pool": ["tiny-async-pool@1.3.0", "https://registry.npmmirror.com/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz", { "dependencies": { "semver": "^5.5.0" } }, "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA=="],
|
||||
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.81.0",
|
||||
"version": "0.83.0",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
@@ -26,7 +26,7 @@
|
||||
"pmtiles": "4.4.1",
|
||||
"satellite.js": "5.0.0",
|
||||
"simplex-noise": "4.0.1",
|
||||
"three": "0.128.0",
|
||||
"three": "0.160.1",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -15,7 +15,7 @@ const bundleEarthDir = join(desktopRoot, '.earth-bundle/earth')
|
||||
const require = createRequire(join(desktopRoot, 'package.json'))
|
||||
|
||||
const VENDOR_PACKAGES = [
|
||||
{ id: 'three', outFile: 'three.mjs', resolvePath: 'three/build/three.module.js' },
|
||||
{ id: 'three', outFile: 'three.mjs' },
|
||||
{ id: 'pmtiles', outFile: 'pmtiles.mjs' },
|
||||
{ id: '@mapbox/vector-tile', outFile: 'mapbox-vector-tile.mjs' },
|
||||
{ id: 'pbf', outFile: 'pbf.mjs' },
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type StartupGpuDecision,
|
||||
type StartupGpuDecisionReason,
|
||||
} from './gpu-policy'
|
||||
import { tClient } from './i18n'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -296,14 +297,20 @@ export function createAdaptiveGpuMonitor(options: {
|
||||
}
|
||||
if (record.reason === 'low-fps-low-vram') {
|
||||
return record.target === 'software'
|
||||
? { message: '独显显存不足且帧率偏低,已自动切换至 CPU 软渲染', type: 'info' }
|
||||
? {
|
||||
message: tClient('独显显存不足且帧率偏低,已自动切换至软件兼容渲染', 'Low VRAM and FPS; switched to software rendering'),
|
||||
type: 'info',
|
||||
}
|
||||
: {
|
||||
message: '独显显存不足且帧率偏低,已自动切换至集成核显渲染(保留全部特效)',
|
||||
message: tClient('独显显存不足且帧率偏低,已自动切换至节能核显', 'Low VRAM and FPS; switched to integrated GPU'),
|
||||
type: 'info',
|
||||
}
|
||||
}
|
||||
if (record.reason === 'vram-recovered') {
|
||||
return { message: '独显显存已充足,已自动切回独立显卡渲染', type: 'success' }
|
||||
return {
|
||||
message: tClient('独显显存已充足,已自动切回高性能显卡', 'VRAM recovered; switched back to high-performance GPU'),
|
||||
type: 'success',
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
shouldSuppressUpdatePrompt,
|
||||
type ClientUpdateManifest,
|
||||
} from './hot-update-core'
|
||||
import { tClient } from './i18n'
|
||||
|
||||
export interface HotUpdateVersionInfo {
|
||||
shellVersion: string
|
||||
@@ -129,7 +130,10 @@ export function createHotUpdateController(options: {
|
||||
pendingVerification = false
|
||||
markHotfixVerified(options.userDataDir)
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
notifyStatus(`热更新已生效 / Hotfix v${activeBundleVersion} active`, 'success')
|
||||
notifyStatus(
|
||||
tClient(`更新已生效 (v${activeBundleVersion})`, `Update v${activeBundleVersion} active`),
|
||||
'success',
|
||||
)
|
||||
}
|
||||
|
||||
const handleRendererCrash = () => {
|
||||
@@ -146,7 +150,10 @@ export function createHotUpdateController(options: {
|
||||
}
|
||||
|
||||
const applyHotfixBundle = async (bundleUrl: string, version: string, expectedSha256: string) => {
|
||||
notifyStatus(`正在下载热更新 v${version}… / Downloading hotfix v${version}…`, 'info')
|
||||
notifyStatus(
|
||||
tClient(`正在下载更新 v${version}…`, `Downloading update v${version}…`),
|
||||
'info',
|
||||
)
|
||||
const response = await fetchWithTimeout(fetchImpl, bundleUrl, DOWNLOAD_TIMEOUT_MS, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
@@ -198,10 +205,10 @@ export function createHotUpdateController(options: {
|
||||
if (manual) {
|
||||
await showBox({
|
||||
type: 'warning',
|
||||
title: '检查更新失败 / Update Check Failed',
|
||||
message: '无法获取版本清单,请确认服务端连接正常。',
|
||||
title: tClient('检查更新失败', 'Update Check Failed'),
|
||||
message: tClient('无法获取版本清单,请确认网络连接正常。', 'Unable to fetch update manifest. Please check your connection.'),
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
buttons: [tClient('确定', 'OK')],
|
||||
})
|
||||
} else {
|
||||
console.warn('[planet-client] Startup update check skipped:', detail)
|
||||
@@ -221,10 +228,13 @@ export function createHotUpdateController(options: {
|
||||
if (manual) {
|
||||
await showBox({
|
||||
type: 'info',
|
||||
title: '当前已是最新版本 / Up to Date',
|
||||
message: 'Planet Earth 客户端已是最新版本。',
|
||||
detail: `外壳版本 / Shell: v${options.shellVersion}\n地球业务包 / Earth Bundle: v${activeBundleVersion}`,
|
||||
buttons: ['确定 / OK'],
|
||||
title: tClient('当前已是最新版本', 'Up to Date'),
|
||||
message: tClient('智能星球客户端已是最新版本。', 'Intelligent Planet is up to date.'),
|
||||
detail: tClient(
|
||||
`当前版本:v${activeBundleVersion}`,
|
||||
`Version: v${activeBundleVersion}`,
|
||||
),
|
||||
buttons: [tClient('确定', 'OK')],
|
||||
})
|
||||
}
|
||||
return
|
||||
@@ -238,13 +248,18 @@ export function createHotUpdateController(options: {
|
||||
|
||||
if (decision.kind === 'hotfix-update') {
|
||||
const { bundle } = decision
|
||||
const notes = bundle.releaseNotes?.trim() ? `\n\n更新内容:\n${bundle.releaseNotes.trim()}` : ''
|
||||
const rawNotes = bundle.releaseNotes?.trim() || ''
|
||||
const notesZh = rawNotes ? `\n\n更新内容:\n${rawNotes}` : ''
|
||||
const notesEn = rawNotes ? `\n\nRelease notes:\n${rawNotes}` : ''
|
||||
const { response } = await showBox({
|
||||
type: 'info',
|
||||
title: '发现新版本 / Update Available',
|
||||
message: `发现 Planet Earth 增量热更新 v${bundle.version}`,
|
||||
detail: `当前地球版本 v${activeBundleVersion} → 最新版本 v${bundle.version}\n更新方式:轻量热更新(无需重新安装,应用后自动生效)${notes}`,
|
||||
buttons: ['立即更新 / Update Now', '稍后提醒 / Later'],
|
||||
title: tClient('发现新版本', 'Update Available'),
|
||||
message: tClient(`发现新版本更新 v${bundle.version}`, `Update v${bundle.version} available`),
|
||||
detail: tClient(
|
||||
`当前版本 v${activeBundleVersion} → 最新版本 v${bundle.version}\n支持在线更新,无需重新安装。${notesZh}`,
|
||||
`Current v${activeBundleVersion} → Latest v${bundle.version}\nOnline update ready, no reinstall required.${notesEn}`,
|
||||
),
|
||||
buttons: [tClient('立即更新', 'Update Now'), tClient('稍后提醒', 'Later')],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
@@ -261,25 +276,33 @@ export function createHotUpdateController(options: {
|
||||
console.error('[planet-client] Hotfix installation failed:', detail)
|
||||
await showBox({
|
||||
type: 'error',
|
||||
title: '热更新失败 / Hotfix Failed',
|
||||
message: `热更新包 v${bundle.version} 下载或校验失败,已保留当前版本运行。`,
|
||||
title: tClient('更新失败', 'Update Failed'),
|
||||
message: tClient(
|
||||
`更新包 v${bundle.version} 下载或校验失败,将继续使用当前版本。`,
|
||||
`Failed to download or verify update v${bundle.version}. Keeping current version.`,
|
||||
),
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
buttons: [tClient('确定', 'OK')],
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const { shell: shellInfo, mandatory } = decision
|
||||
const notes = shellInfo.releaseNotes?.trim() ? `\n\n更新说明:\n${shellInfo.releaseNotes.trim()}` : ''
|
||||
const rawNotes = shellInfo.releaseNotes?.trim() || ''
|
||||
const notesZh = rawNotes ? `\n\n更新说明:\n${rawNotes}` : ''
|
||||
const notesEn = rawNotes ? `\n\nRelease notes:\n${rawNotes}` : ''
|
||||
const { response } = await showBox({
|
||||
type: mandatory ? 'warning' : 'info',
|
||||
title: '发现客户端大版本更新 / Major Client Update',
|
||||
title: tClient('发现客户端重要更新', 'Major Update Available'),
|
||||
message: mandatory
|
||||
? `当前客户端版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}`
|
||||
: `发现客户端新版本 v${shellInfo.version}`,
|
||||
detail: `当前客户端外壳:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n该版本包含底层架构或原生壳变更,需下载安装包覆盖更新。${notes}`,
|
||||
buttons: ['前往下载 / Download', '稍后提醒 / Later'],
|
||||
? tClient(`当前版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}`, `Current version v${options.shellVersion} requires upgrading to v${shellInfo.version}`)
|
||||
: tClient(`发现客户端新版本 v${shellInfo.version}`, `New version v${shellInfo.version} available`),
|
||||
detail: tClient(
|
||||
`当前版本:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n请下载新版安装包完成升级。${notesZh}`,
|
||||
`Current version: v${options.shellVersion}\nLatest version: v${shellInfo.version}\nPlease download the installer to upgrade.${notesEn}`,
|
||||
),
|
||||
buttons: [tClient('前往下载', 'Download'), tClient('稍后提醒', 'Later')],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
export type ClientLocale = 'zh-CN' | 'en-US'
|
||||
|
||||
let overrideLocale: ClientLocale | null = null
|
||||
|
||||
/**
|
||||
* Normalize any Electron / BCP-47 locale tag to our two supported UI locales.
|
||||
*/
|
||||
export function normalizeClientLocale(raw: unknown): ClientLocale {
|
||||
if (typeof raw !== 'string') return 'zh-CN'
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized.startsWith('en')) return 'en-US'
|
||||
return 'zh-CN'
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the active Electron desktop UI locale from explicit override,
|
||||
* environment hint, or Electron app locale when running inside the main process.
|
||||
*/
|
||||
export function getClientLocale(): ClientLocale {
|
||||
if (overrideLocale) return overrideLocale
|
||||
const envLocale = process.env.PLANET_LOCALE || process.env.LANG
|
||||
if (envLocale && envLocale.trim().toLowerCase().startsWith('en')) {
|
||||
return 'en-US'
|
||||
}
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const electronMod = require('electron') as { app?: { getLocale?: () => string; isReady?: () => boolean } }
|
||||
const appLocale = electronMod?.app?.getLocale?.()
|
||||
if (appLocale) return normalizeClientLocale(appLocale)
|
||||
} catch {
|
||||
// Allow importing in pure Bun unit tests outside Electron runtime.
|
||||
}
|
||||
return 'zh-CN'
|
||||
}
|
||||
|
||||
export function setClientLocale(raw: unknown): ClientLocale {
|
||||
overrideLocale = normalizeClientLocale(raw)
|
||||
return overrideLocale
|
||||
}
|
||||
|
||||
/**
|
||||
* Select pure Chinese or pure English copy for Electron native chrome and dialogs.
|
||||
*/
|
||||
export function tClient(zh: string, en: string): string {
|
||||
return getClientLocale() === 'en-US' ? en : zh
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-
|
||||
import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy'
|
||||
import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core'
|
||||
import { createHotUpdateController } from './hot-updater'
|
||||
import { tClient } from './i18n'
|
||||
import { buildApplicationMenu } from './menu'
|
||||
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
|
||||
import { createScreenRecorderController } from './screen-recorder'
|
||||
@@ -250,10 +251,10 @@ if (!singleInstanceLock) {
|
||||
const targetWin = mainWindow && !mainWindow.isDestroyed() ? mainWindow : undefined
|
||||
const boxOptions = {
|
||||
type: 'info' as const,
|
||||
title: '渲染设备设置 / GPU Mode',
|
||||
message: '渲染设备模式已更新,需重启客户端生效',
|
||||
detail: '是否立即重启 Planet Earth?(重启约需 1-2 秒,将保留全部视觉特效)',
|
||||
buttons: ['立即重启 / Restart Now', '稍后手动重启 / Later'],
|
||||
title: tClient('渲染模式设置', 'Graphics Mode'),
|
||||
message: tClient('渲染模式已更改,需重启应用生效', 'Graphics mode updated. Restart to apply.'),
|
||||
detail: tClient('是否立即重启?重启约需 1-2 秒。', 'Restart now? This takes about 1–2 seconds.'),
|
||||
buttons: [tClient('立即重启', 'Restart Now'), tClient('稍后重启', 'Later')],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
}
|
||||
|
||||
+49
-40
@@ -3,23 +3,27 @@ import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions }
|
||||
import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config'
|
||||
import type { GpuRuntimeSummary } from './gpu-monitor'
|
||||
import type { HotUpdateVersionInfo } from './hot-updater'
|
||||
import { tClient } from './i18n'
|
||||
import type { RecordingStatusSnapshot } from './recording-core'
|
||||
import { openServerSettingsDialog, toggleWindowOrientation } from './window'
|
||||
|
||||
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
|
||||
const targetLabel =
|
||||
summary.activeTarget === 'low-power'
|
||||
? '集成核显'
|
||||
? tClient('节能核显', 'Integrated GPU')
|
||||
: summary.activeTarget === 'software'
|
||||
? 'CPU 软渲染'
|
||||
? tClient('软件兼容渲染', 'Software Rendering')
|
||||
: summary.activeTarget === 'high-performance' || summary.latestVramSample
|
||||
? '独立显卡'
|
||||
: '硬件 GPU'
|
||||
const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动'
|
||||
? tClient('高性能显卡', 'High-Performance GPU')
|
||||
: tClient('硬件加速', 'Hardware GPU')
|
||||
const modeTag = summary.requestedMode === 'auto' ? tClient('自动', 'Auto') : tClient('手动', 'Manual')
|
||||
const vramTag = summary.latestVramSample
|
||||
? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`
|
||||
? tClient(
|
||||
` · 可用显存 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`,
|
||||
` · ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB free`,
|
||||
)
|
||||
: ''
|
||||
return `当前生效: ${targetLabel} (${modeTag}${vramTag})`
|
||||
return tClient(`当前运行: ${targetLabel} (${modeTag}${vramTag})`, `Active: ${targetLabel} (${modeTag}${vramTag})`)
|
||||
}
|
||||
|
||||
export function buildApplicationMenu(options: {
|
||||
@@ -89,15 +93,15 @@ export function buildApplicationMenu(options: {
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: 'Planet Earth',
|
||||
label: tClient('智能星球', 'Intelligent Planet'),
|
||||
submenu: [
|
||||
{
|
||||
label: '重新加载数据 / Reload Data',
|
||||
label: tClient('重新加载数据', 'Reload Data'),
|
||||
accelerator: 'CmdOrCtrl+R',
|
||||
click: () => sendAction('reload-data'),
|
||||
},
|
||||
{
|
||||
label: '服务端连接设置 / Server Settings...',
|
||||
label: tClient('服务器连接设置...', 'Server Settings...'),
|
||||
click: () => {
|
||||
openServerSettingsDialog(options.mainWindow, options.configStore, () => {
|
||||
if (!options.mainWindow.isDestroyed()) {
|
||||
@@ -107,24 +111,24 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '启动画面 / Splash Screen',
|
||||
label: tClient('启动动画', 'Splash Screen'),
|
||||
submenu: [
|
||||
{
|
||||
label: '启用启动画面 / Enable Splash Screen',
|
||||
label: tClient('启用启动动画', 'Enable Splash Screen'),
|
||||
type: 'checkbox',
|
||||
checked: currentSplashTheme !== 'off',
|
||||
click: () => selectSplashTheme(currentSplashTheme === 'off' ? 'singularity' : 'off'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '立即重播启动画面 / Replay Splash Screen',
|
||||
label: tClient('立即重播启动动画', 'Replay Splash Screen'),
|
||||
accelerator: 'CmdOrCtrl+Shift+S',
|
||||
click: replayActiveSplash,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '渲染设备 / GPU Mode',
|
||||
label: tClient('渲染模式', 'Graphics Mode'),
|
||||
submenu: [
|
||||
...(gpuSummary
|
||||
? [
|
||||
@@ -136,7 +140,7 @@ export function buildApplicationMenu(options: {
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto',
|
||||
label: tClient('自动切换(推荐)', 'Automatic (Recommended)'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'auto',
|
||||
click: () => {
|
||||
@@ -144,7 +148,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '独立显卡(高性能) / Discrete GPU',
|
||||
label: tClient('高性能显卡', 'High-Performance GPU'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'high-performance',
|
||||
click: () => {
|
||||
@@ -152,7 +156,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '集成核显(不占独显显存) / Integrated GPU',
|
||||
label: tClient('节能核显', 'Integrated GPU'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'low-power',
|
||||
click: () => {
|
||||
@@ -160,7 +164,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '纯 CPU 软渲染 / Software GL',
|
||||
label: tClient('软件兼容渲染', 'Software Rendering'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'software',
|
||||
click: () => {
|
||||
@@ -170,14 +174,14 @@ export function buildApplicationMenu(options: {
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '录屏 / Screen Recording',
|
||||
label: tClient('录屏', 'Screen Recording'),
|
||||
submenu: [
|
||||
{
|
||||
label: isRecordingOrStopping
|
||||
? '停止录屏 / Stop Recording'
|
||||
? tClient('停止录屏', 'Stop Recording')
|
||||
: recordingState === 'starting'
|
||||
? '正在启动录屏… / Starting…'
|
||||
: '开始录屏 / Start Recording',
|
||||
? tClient('正在启动录屏…', 'Starting Recording…')
|
||||
: tClient('开始录屏', 'Start Recording'),
|
||||
accelerator: 'CmdOrCtrl+Shift+F9',
|
||||
enabled: recordingState === 'idle' || recordingState === 'recording',
|
||||
click: () => {
|
||||
@@ -185,7 +189,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '录制声音 / Include Audio',
|
||||
label: tClient('录制音频', 'Include Audio'),
|
||||
type: 'checkbox',
|
||||
checked: currentRecordAudio,
|
||||
enabled: recordingState === 'idle',
|
||||
@@ -194,7 +198,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '隐藏光标 / Hide Cursor',
|
||||
label: tClient('隐藏光标', 'Hide Cursor'),
|
||||
type: 'checkbox',
|
||||
checked: currentRecordHideCursor,
|
||||
enabled: recordingState === 'idle',
|
||||
@@ -204,7 +208,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '打开录屏目录 / Open Recordings Folder',
|
||||
label: tClient('打开录屏目录', 'Open Recordings Folder'),
|
||||
click: () => {
|
||||
options.onOpenRecordingsFolder?.()
|
||||
},
|
||||
@@ -213,59 +217,62 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '打开运维控制台 / Open Admin Console',
|
||||
label: tClient('打开管理控制台', 'Open Admin Console'),
|
||||
click: () => openAdminPath('/admin'),
|
||||
},
|
||||
{
|
||||
label: '打开操作文档 / Open Documentation',
|
||||
label: tClient('打开帮助文档', 'Open Documentation'),
|
||||
click: () => openAdminPath('/docs/manual'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '检查更新 / Check for Updates...',
|
||||
label: tClient('检查更新...', 'Check for Updates...'),
|
||||
click: () => options.onCheckForUpdates?.(),
|
||||
},
|
||||
...(options.getVersionInfo
|
||||
? [
|
||||
(() => {
|
||||
const info = options.getVersionInfo!()
|
||||
const suffix = info.usingHotfix ? ' (热更 / Hotfix)' : ''
|
||||
const suffix = info.usingHotfix ? tClient('(已更新)', ' (Updated)') : ''
|
||||
return {
|
||||
label: `当前版本: Shell v${info.shellVersion} · Earth v${info.activeBundleVersion}${suffix}`,
|
||||
label: tClient(
|
||||
`当前版本: v${info.activeBundleVersion}${suffix}`,
|
||||
`Version: v${info.activeBundleVersion}${suffix}`,
|
||||
),
|
||||
enabled: false,
|
||||
}
|
||||
})(),
|
||||
]
|
||||
: []),
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit', label: '退出 / Quit' },
|
||||
{ role: 'quit', label: tClient('退出', 'Quit') },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '视图 / View',
|
||||
label: tClient('视图', 'View'),
|
||||
submenu: [
|
||||
{
|
||||
label: '放大视角 / Zoom In',
|
||||
label: tClient('放大视角', 'Zoom In'),
|
||||
accelerator: 'CmdOrCtrl+=',
|
||||
click: () => sendAction('zoom-in'),
|
||||
},
|
||||
{
|
||||
label: '缩小视角 / Zoom Out',
|
||||
label: tClient('缩小视角', 'Zoom Out'),
|
||||
accelerator: 'CmdOrCtrl+-',
|
||||
click: () => sendAction('zoom-out'),
|
||||
},
|
||||
{
|
||||
label: '重置缩放 / Reset Zoom (100%)',
|
||||
label: tClient('重置缩放 (100%)', 'Reset Zoom (100%)'),
|
||||
accelerator: 'CmdOrCtrl+0',
|
||||
click: () => sendAction('zoom-reset'),
|
||||
},
|
||||
{
|
||||
label: '重置地球视角 / Reset View',
|
||||
label: tClient('重置地球视角', 'Reset View'),
|
||||
click: () => sendAction('reset-view'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '切换横竖屏 / Toggle Portrait & Landscape',
|
||||
label: tClient('切换横竖屏', 'Toggle Portrait & Landscape'),
|
||||
accelerator: 'CmdOrCtrl+Shift+M',
|
||||
click: () => {
|
||||
if (!options.mainWindow.isDestroyed()) {
|
||||
@@ -274,7 +281,9 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '切换全屏 / Toggle Fullscreen (F11)',
|
||||
label: process.platform === 'darwin'
|
||||
? tClient('切换全屏', 'Toggle Fullscreen')
|
||||
: tClient('切换全屏 (F11)', 'Toggle Fullscreen (F11)'),
|
||||
// Keep accelerator unregistered on Win/Linux so controls.js F11 shortcut never double-toggles.
|
||||
...(process.platform === 'darwin' ? { accelerator: 'Ctrl+Command+F' } : {}),
|
||||
click: () => {
|
||||
@@ -284,12 +293,12 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '显示/隐藏帧率 / Toggle FPS',
|
||||
label: tClient('显示或隐藏帧率', 'Toggle FPS'),
|
||||
click: () => sendAction('toggle-fps'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '开发者工具 / Toggle DevTools',
|
||||
label: tClient('开发者工具', 'Toggle DevTools'),
|
||||
accelerator: 'F12',
|
||||
click: () => {
|
||||
if (!options.mainWindow.isDestroyed()) {
|
||||
|
||||
@@ -119,9 +119,13 @@ export function computeIndicatorBounds(options: {
|
||||
/**
|
||||
* Render self-contained HTML for the transparent floating recording indicator pill.
|
||||
*/
|
||||
export function buildRecordingIndicatorHtml(): string {
|
||||
export function buildRecordingIndicatorHtml(locale: 'zh-CN' | 'en-US' = 'zh-CN'): string {
|
||||
const isEn = locale === 'en-US'
|
||||
const shortcut = process.platform === 'darwin' ? 'Cmd+Shift+F9' : 'Ctrl+Shift+F9'
|
||||
const stopTitle = isEn ? `Stop recording (${shortcut})` : `点击停止录屏 (${shortcut})`
|
||||
const stopAria = isEn ? 'Stop recording' : '停止录屏'
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<html lang="${locale}">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
@@ -214,7 +218,7 @@ export function buildRecordingIndicatorHtml(): string {
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<button id="rec-stop-btn" class="rec-pill" type="button" title="点击停止录屏 (Ctrl+Shift+F9)" aria-label="停止录屏">
|
||||
<button id="rec-stop-btn" class="rec-pill" type="button" title="${stopTitle}" aria-label="${stopAria}">
|
||||
<span class="rec-glyph-wrap" aria-hidden="true"><span class="rec-glyph"></span></span>
|
||||
<span id="rec-timer" class="rec-time">00:00</span>
|
||||
</button>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
import { BrowserWindow, screen } from 'electron'
|
||||
|
||||
import { getClientLocale } from './i18n'
|
||||
import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core'
|
||||
|
||||
export interface RecordingIndicatorController {
|
||||
@@ -162,7 +163,9 @@ export function createRecordingIndicatorController(options: {
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
})
|
||||
void indicatorWin.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(buildRecordingIndicatorHtml())}`)
|
||||
void indicatorWin.loadURL(
|
||||
`data:text/html;charset=utf-8,${encodeURIComponent(buildRecordingIndicatorHtml(getClientLocale()))}`,
|
||||
)
|
||||
return indicatorWin
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from 'electron'
|
||||
|
||||
import type { DesktopConfigStore } from './config'
|
||||
import { tClient } from './i18n'
|
||||
import {
|
||||
buildRecordingFilename,
|
||||
resolveRecordingExtension,
|
||||
@@ -230,7 +231,7 @@ export function createScreenRecorderController(options: {
|
||||
writeChain = Promise.resolve()
|
||||
writeStream = fs.createWriteStream(filePath)
|
||||
writeStream.on('error', (err) => {
|
||||
notifyStatus(`录屏写入失败:${err.message}`, 'error')
|
||||
notifyStatus(tClient(`录屏写入失败:${err.message}`, `Recording write failed: ${err.message}`), 'error')
|
||||
})
|
||||
|
||||
startedAtMs = Date.now()
|
||||
@@ -298,15 +299,15 @@ export function createScreenRecorderController(options: {
|
||||
if (result.savedPath && result.savedName && result.hadData) {
|
||||
lastSavedFilePath = result.savedPath
|
||||
notifyStatus({
|
||||
message: `已保存录屏:${result.savedPath}`,
|
||||
message: tClient(`已保存录屏:${result.savedPath}`, `Recording saved: ${result.savedPath}`),
|
||||
type: 'success',
|
||||
fullText: true,
|
||||
durationMs: 6000,
|
||||
actionLabel: '打开目录',
|
||||
actionLabel: tClient('打开目录', 'Open Folder'),
|
||||
action: 'open-recordings-folder',
|
||||
})
|
||||
} else if (state !== 'idle') {
|
||||
notifyStatus('录屏已停止(未采集到有效画面帧)', 'info')
|
||||
notifyStatus(tClient('录屏已停止(未采集到有效画面帧)', 'Recording stopped (no valid frames captured)'), 'info')
|
||||
}
|
||||
resetToIdle()
|
||||
return result
|
||||
@@ -315,14 +316,14 @@ export function createScreenRecorderController(options: {
|
||||
const onAbort = async (_event: Electron.IpcMainInvokeEvent, payload?: { error?: string }) => {
|
||||
await closeWriteStream()
|
||||
if (payload?.error) {
|
||||
notifyStatus(`启动录屏失败:${payload.error}`, 'error')
|
||||
notifyStatus(tClient(`启动录屏失败:${payload.error}`, `Failed to start recording: ${payload.error}`), 'error')
|
||||
}
|
||||
resetToIdle()
|
||||
}
|
||||
|
||||
const onAudioFallback = () => {
|
||||
includeAudio = false
|
||||
notifyStatus('当前设备不支持内录音频,已切换为静音录屏', 'info')
|
||||
notifyStatus(tClient('当前设备不支持音频录制,已切换为静音录屏', 'System audio capture unavailable; recording muted'), 'info')
|
||||
}
|
||||
|
||||
const onIndicatorStop = () => {
|
||||
|
||||
+11
-10
@@ -6,6 +6,7 @@ import { BrowserWindow, ipcMain, nativeTheme, screen, shell, type Display } from
|
||||
import { createSoloAltMenuTracker } from './alt-menu'
|
||||
import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig } from './config'
|
||||
import { resolveExternalTargetUrl } from './external-links'
|
||||
import { getClientLocale, tClient } from './i18n'
|
||||
import { createWindowShowGate } from './show-gate'
|
||||
import {
|
||||
clampBoundsToWorkArea,
|
||||
@@ -496,7 +497,7 @@ export function openServerSettingsDialog(
|
||||
maximizable: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: '#091522',
|
||||
title: 'Planet Earth — Server Connection',
|
||||
title: tClient('服务器连接设置', 'Server Connection Settings'),
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
@@ -509,7 +510,7 @@ export function openServerSettingsDialog(
|
||||
value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<html lang="${getClientLocale()}">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
@@ -528,23 +529,23 @@ export function openServerSettingsDialog(
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>服务端连接配置 / Server Connection</h2>
|
||||
<h2>${tClient('服务器连接设置', 'Server Connection Settings')}</h2>
|
||||
<form id="cfg">
|
||||
<label>后端服务地址 (Backend API URL)
|
||||
<label>${tClient('服务器地址', 'Backend API URL')}
|
||||
<input name="backendUrl" type="url" required value="${escapeAttr(current.backendUrl)}">
|
||||
</label>
|
||||
<label>运维控制台地址 (Admin Console URL)
|
||||
<label>${tClient('管理控制台地址', 'Admin Console URL')}
|
||||
<input name="adminUrl" type="url" required value="${escapeAttr(current.adminUrl)}">
|
||||
</label>
|
||||
<label>本地动捕 WebSocket (Motion Agent WS URL)
|
||||
<label>${tClient('动捕服务地址', 'Motion Service WS URL')}
|
||||
<input name="motionWsUrl" type="text" required value="${escapeAttr(current.motionWsUrl)}">
|
||||
</label>
|
||||
<div id="err" class="error" aria-live="polite"></div>
|
||||
<div class="actions">
|
||||
<button type="button" id="defaults">恢复默认 / Defaults</button>
|
||||
<button type="button" id="defaults">${tClient('恢复默认', 'Reset Defaults')}</button>
|
||||
<div class="actions-right">
|
||||
<button type="button" id="cancel">取消 / Cancel</button>
|
||||
<button type="submit" class="primary">保存并重连 / Save</button>
|
||||
<button type="button" id="cancel">${tClient('取消', 'Cancel')}</button>
|
||||
<button type="submit" class="primary">${tClient('保存并重连', 'Save & Reconnect')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -578,7 +579,7 @@ export function openServerSettingsDialog(
|
||||
!isValidUrl(adminUrl, ['http:', 'https:']) ||
|
||||
!isValidUrl(motionWsUrl, ['ws:', 'wss:'])
|
||||
) {
|
||||
errEl.textContent = '请输入有效地址 (http/https 与 ws/wss) / Enter valid URLs.';
|
||||
errEl.textContent = ${JSON.stringify(tClient('请输入有效的服务器地址(支持 http/https 与 ws/wss)。', 'Enter valid URLs (http/https and ws/wss).'))};
|
||||
return;
|
||||
}
|
||||
const q = new URLSearchParams({ backendUrl, adminUrl, motionWsUrl });
|
||||
|
||||
@@ -7,8 +7,7 @@ interface GlobePoint {
|
||||
lat: number
|
||||
lon: number
|
||||
kind: 0 | 1 | 2
|
||||
shardAngle: number
|
||||
shardSpeed: number
|
||||
dissolveOrder: number
|
||||
phase: number
|
||||
}
|
||||
|
||||
@@ -201,8 +200,7 @@ function buildGlobePoints(): GlobePoint[] {
|
||||
lat,
|
||||
lon: (lonDeg * Math.PI) / 180,
|
||||
kind: 2,
|
||||
shardAngle: rand() * Math.PI * 2,
|
||||
shardSpeed: 0.65 + rand() * 1.15,
|
||||
dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35),
|
||||
phase: rand() * Math.PI * 2,
|
||||
})
|
||||
} else if (kind === 1 && y % 2 === 0 && x % interiorStep === 0) {
|
||||
@@ -211,8 +209,7 @@ function buildGlobePoints(): GlobePoint[] {
|
||||
lat,
|
||||
lon: (lonDeg * Math.PI) / 180,
|
||||
kind: 1,
|
||||
shardAngle: rand() * Math.PI * 2,
|
||||
shardSpeed: 0.5 + rand() * 0.9,
|
||||
dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35),
|
||||
phase: rand() * Math.PI * 2,
|
||||
})
|
||||
} else if (kind === 0 && y % 5 === 0 && x % oceanStep === 0) {
|
||||
@@ -221,8 +218,7 @@ function buildGlobePoints(): GlobePoint[] {
|
||||
lat,
|
||||
lon: (lonDeg * Math.PI) / 180,
|
||||
kind: 0,
|
||||
shardAngle: rand() * Math.PI * 2,
|
||||
shardSpeed: 0.4 + rand() * 0.7,
|
||||
dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35),
|
||||
phase: rand() * Math.PI * 2,
|
||||
})
|
||||
}
|
||||
@@ -752,6 +748,7 @@ export function createDesktopSplashController(options: {
|
||||
const styleEl = document.createElement('style')
|
||||
styleEl.textContent = SPLASH_CSS
|
||||
|
||||
const isEn = getLocaleIsEn()
|
||||
const root = document.createElement('div')
|
||||
root.className = 'splash-root'
|
||||
root.dataset.theme = activeTheme
|
||||
@@ -760,16 +757,16 @@ export function createDesktopSplashController(options: {
|
||||
<header class="splash-topbar">
|
||||
<div class="splash-telemetry-tag">
|
||||
<span class="splash-telemetry-dot"></span>
|
||||
<span>PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL</span>
|
||||
<span>${isEn ? 'INTELLIGENT PLANET // 3D EARTH KERNEL' : '智能星球 // 三维地球核心'}</span>
|
||||
</div>
|
||||
<div class="splash-controls">
|
||||
<button type="button" class="splash-skip" data-splash-skip title="跳过启动动画 (Esc)">ESC 跳过</button>
|
||||
<button type="button" class="splash-skip" data-splash-skip title="${isEn ? 'Skip splash screen (Esc)' : '跳过启动动画 (Esc)'}">${isEn ? 'ESC SKIP' : 'ESC 跳过'}</button>
|
||||
</div>
|
||||
</header>
|
||||
<footer class="splash-footer">
|
||||
<div class="splash-brand-head">
|
||||
<h1 class="splash-title">智能星球计划</h1>
|
||||
<div class="splash-subtitle">INTELLIGENT PLANET PROGRAM</div>
|
||||
<h1 class="splash-title">${isEn ? 'INTELLIGENT PLANET' : '智能星球计划'}</h1>
|
||||
${isEn ? '' : '<div class="splash-subtitle">全球基础设施与空间态势引擎</div>'}
|
||||
</div>
|
||||
<div class="splash-progress-box">
|
||||
<div class="splash-progress-meta">
|
||||
@@ -781,12 +778,11 @@ export function createDesktopSplashController(options: {
|
||||
</div>
|
||||
</div>
|
||||
<div class="splash-presenter">
|
||||
<img class="splash-zju-emblem" src="planet://earth/earth/assets/brand/zju-emblem.png" alt="浙江大学">
|
||||
<img class="splash-zju-emblem" src="planet://earth/earth/assets/brand/zju-emblem.png" alt="${isEn ? 'Zhejiang University' : '浙江大学'}">
|
||||
<div class="splash-presenter-divider" aria-hidden="true"></div>
|
||||
<div class="splash-presenter-copy">
|
||||
<span class="splash-presenter-kicker">PRESENTED BY</span>
|
||||
<span class="splash-presenter-zh">临空智能媒体研究院</span>
|
||||
<span class="splash-presenter-en">Intelligent Media Institute</span>
|
||||
<span class="splash-presenter-kicker">${isEn ? 'PRESENTED BY' : '联合研制'}</span>
|
||||
<span class="${isEn ? 'splash-presenter-en' : 'splash-presenter-zh'}">${isEn ? 'Linkong Intelligent Media Institute' : '临空智能媒体研究院'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
@@ -921,31 +917,19 @@ export function createDesktopSplashController(options: {
|
||||
cx: number,
|
||||
cy: number,
|
||||
) => {
|
||||
const warp = exitRatio > 0 ? exitRatio * exitRatio : 0
|
||||
const dolly = exitRatio > 0 ? 1 + exitRatio * exitRatio * 0.06 : 1
|
||||
const exitFade = exitRatio > 0 ? 1 - smoothstep(0.12, 0.88, exitRatio) : 1
|
||||
for (const star of stars) {
|
||||
const sx = star.x * w
|
||||
const sy = star.y * h
|
||||
const sx = cx + (star.x * w - cx) * dolly
|
||||
const sy = cy + (star.y * h - cy) * dolly
|
||||
const twinkle = 0.55 + 0.45 * Math.sin(elapsed * star.twinkleSpeed + star.phase)
|
||||
const alpha = star.alpha * twinkle * (1 - exitRatio * 0.75)
|
||||
const alpha = star.alpha * twinkle * exitFade
|
||||
if (alpha <= 0.01) continue
|
||||
|
||||
ctx.fillStyle = `rgba(210, 232, 255, ${alpha.toFixed(3)})`
|
||||
if (warp > 0.02) {
|
||||
const dx = sx - cx
|
||||
const dy = sy - cy
|
||||
const len = Math.max(1, Math.hypot(dx, dy))
|
||||
const streak = warp * 44
|
||||
ctx.strokeStyle = `rgba(176, 224, 255, ${(alpha * 0.85).toFixed(3)})`
|
||||
ctx.lineWidth = star.size * 0.85
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(sx, sy)
|
||||
ctx.lineTo(sx + (dx / len) * streak, sy + (dy / len) * streak)
|
||||
ctx.stroke()
|
||||
} else {
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, star.size, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, star.size, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -967,7 +951,7 @@ export function createDesktopSplashController(options: {
|
||||
const perspK = 3.25
|
||||
const tiltX = -0.25
|
||||
const rollZ = -0.11
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 2.1)
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 0.32)
|
||||
const eclipseR = radius * 0.955
|
||||
const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45
|
||||
|
||||
@@ -976,26 +960,26 @@ export function createDesktopSplashController(options: {
|
||||
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const coronaAlpha = dawnIntensity * fade
|
||||
const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 1.4))
|
||||
const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 0.55))
|
||||
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.9 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.5 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.15 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
|
||||
ctx.fillStyle = corona
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, eclipseR * (1.95 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.arc(cx, cy, eclipseR * (1.95 + burst * 0.55), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
|
||||
if (coreReveal > 0.01) {
|
||||
const haloAlpha = coreReveal * fade
|
||||
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
|
||||
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 0.55))
|
||||
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`)
|
||||
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * haloAlpha).toFixed(3)})`)
|
||||
glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
|
||||
ctx.fillStyle = glow
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.arc(cx, cy, radius * (1.85 + burst * 0.55), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
|
||||
@@ -1027,24 +1011,26 @@ export function createDesktopSplashController(options: {
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Act 2: Three tilted orbital rings drawing into full orbits, expanding on Act 3 burst
|
||||
// Act 2: Three tilted orbital rings drawing into full orbits, smoothly expanding & fading on Act 3 iris
|
||||
if (orbitReveal > 0.01) {
|
||||
const ringEase = exitRatio > 0 ? 1 - Math.pow(1 - exitRatio, 2.6) : 0
|
||||
const ringFade = fade * (1 - smoothstep(0.08, 0.82, exitRatio))
|
||||
const ringConfigs = [
|
||||
{ rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
|
||||
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
|
||||
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
|
||||
{ rx: radius * (1.36 + ringEase * 0.72), ry: radius * (0.4 + ringEase * 0.22), rot: -0.34, color: '116, 206, 255' },
|
||||
{ rx: radius * (1.56 + ringEase * 0.72), ry: radius * (0.5 + ringEase * 0.22), rot: 0.42, color: '146, 184, 255' },
|
||||
{ rx: radius * (1.18 + ringEase * 0.72), ry: radius * (0.34 + ringEase * 0.22), rot: 0.08, color: '214, 240, 255' },
|
||||
]
|
||||
for (let i = 0; i < ringConfigs.length; i += 1) {
|
||||
const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8)
|
||||
if (ringReveal <= 0.005) continue
|
||||
if (ringReveal <= 0.005 || ringFade <= 0.005) continue
|
||||
const ring = ringConfigs[i]
|
||||
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(cx, cy)
|
||||
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
|
||||
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.15
|
||||
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * ringFade).toFixed(3)})`
|
||||
ctx.lineWidth = Math.max(0.65, 1.05 * (1 - exitRatio * 0.35))
|
||||
ctx.beginPath()
|
||||
if (ringReveal >= 0.995) {
|
||||
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
|
||||
@@ -1055,31 +1041,26 @@ export function createDesktopSplashController(options: {
|
||||
|
||||
const sx = Math.cos(a) * ring.rx
|
||||
const sy = Math.sin(a) * ring.ry
|
||||
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * fade).toFixed(3)})`
|
||||
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * ringFade).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
|
||||
ctx.arc(sx, sy, Math.max(0.8, 2.4 * (1 - exitRatio * 0.55)), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
}
|
||||
|
||||
// Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> radial scatter
|
||||
// Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> coherent iris dissolve
|
||||
const oceanReveal = clamp01((coreReveal - 0.25) / 0.75)
|
||||
const sphereScale = 1 + smoothstep(0, 1, exitRatio) * 0.22
|
||||
const dotSizeFactor = 1 - exitRatio * 0.35
|
||||
for (const pt of globePoints) {
|
||||
const p = projectSpherePoint(pt.lat, pt.lon, yaw, tiltX, rollZ)
|
||||
if (burst === 0 && p.nz < -0.22) continue
|
||||
if (exitRatio === 0 && p.nz < -0.22) continue
|
||||
|
||||
const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8)
|
||||
const jitterX = Math.cos(pt.shardAngle) * burst * 0.28
|
||||
const jitterY = Math.sin(pt.shardAngle) * burst * 0.28
|
||||
const px = p.nx * radialBoost + jitterX
|
||||
const py = p.ny * radialBoost + jitterY
|
||||
const pz = p.nz + burst * pt.shardSpeed * 1.1
|
||||
|
||||
const depth = Math.max(0.25, perspD - pz)
|
||||
const screenScale = (radius * perspK) / depth
|
||||
const sx = cx + px * screenScale
|
||||
const sy = cy + py * screenScale
|
||||
const depth = Math.max(0.25, perspD - p.nz)
|
||||
const screenScale = (radius * perspK * sphereScale) / depth
|
||||
const sx = cx + p.nx * screenScale
|
||||
const sy = cy + p.ny * screenScale
|
||||
if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) continue
|
||||
|
||||
const depthFade = p.nz >= 0 ? 1 : Math.max(0.14, 1 + p.nz * 2.2)
|
||||
@@ -1102,31 +1083,20 @@ export function createDesktopSplashController(options: {
|
||||
pointGain = oceanReveal * 0.28 * depthFade
|
||||
}
|
||||
|
||||
const alpha = pointGain * polarFade * fade
|
||||
const exitPointFade =
|
||||
exitRatio > 0 ? 1 - smoothstep(pt.dissolveOrder * 0.32, pt.dissolveOrder * 0.32 + 0.44, exitRatio) : 1
|
||||
const alpha = pointGain * polarFade * fade * exitPointFade
|
||||
if (alpha <= 0.015) continue
|
||||
|
||||
if (burst > 0.03) {
|
||||
const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst)
|
||||
const prevScale = (radius * perspK) / Math.max(0.3, perspD - p.nz)
|
||||
const ox = cx + p.nx * prevBoost * prevScale
|
||||
const oy = cy + p.ny * prevBoost * prevScale
|
||||
ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})`
|
||||
ctx.lineWidth = dotR
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(ox, oy)
|
||||
ctx.lineTo(sx, sy)
|
||||
ctx.stroke()
|
||||
} else {
|
||||
ctx.fillStyle = `rgba(${color}, ${alpha.toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, dotR, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
ctx.fillStyle = `rgba(${color}, ${alpha.toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, Math.max(0.55, dotR * dotSizeFactor), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
|
||||
// Intercontinental telemetry arcs across front hemisphere
|
||||
if (arcReveal > 0.01 && burst < 0.55) {
|
||||
const arcAlpha = arcReveal * fade * Math.max(0, 1 - burst * 1.6)
|
||||
if (arcReveal > 0.01 && exitRatio < 0.45) {
|
||||
const arcAlpha = arcReveal * fade * (1 - smoothstep(0.0, 0.45, exitRatio))
|
||||
for (const arc of ARC_DEFINITIONS) {
|
||||
const p1 = projectSpherePoint((arc.lat1 * Math.PI) / 180, (arc.lon1 * Math.PI) / 180, yaw, tiltX, rollZ)
|
||||
const p2 = projectSpherePoint((arc.lat2 * Math.PI) / 180, (arc.lon2 * Math.PI) / 180, yaw, tiltX, rollZ)
|
||||
@@ -1138,7 +1108,7 @@ export function createDesktopSplashController(options: {
|
||||
const y2 = cy + p2.ny * radius * 1.02
|
||||
const mx = (p1.nx + p2.nx) * 0.5
|
||||
const my = (p1.ny + p2.ny) * 0.5
|
||||
const lift = 1.24 + burst * 0.9
|
||||
const lift = 1.24 + burst * 0.18
|
||||
const cpx = cx + mx * radius * lift
|
||||
const cpy = cy + my * radius * lift
|
||||
|
||||
@@ -1160,14 +1130,25 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
}
|
||||
|
||||
// Act 3: Climax shockwave ring on scatter burst
|
||||
if (burst > 0.005) {
|
||||
const shockR = radius * (0.88 + exitRatio * 5.2)
|
||||
ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})`
|
||||
ctx.lineWidth = Math.max(1, 3.2 * (1 - exitRatio))
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, shockR, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
// Act 3: Dual-layer refined optical aperture iris reveal
|
||||
if (exitRatio > 0.005) {
|
||||
const iris = 1 - Math.pow(1 - exitRatio, 3)
|
||||
const irisFade = smoothstep(0.0, 0.12, exitRatio) * (1 - smoothstep(0.18, 0.82, exitRatio))
|
||||
if (irisFade > 0.005) {
|
||||
const outerR = radius * (1.02 + iris * 1.55)
|
||||
ctx.strokeStyle = `rgba(162, 218, 255, ${(0.36 * irisFade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.0
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, outerR, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
|
||||
const companionR = radius * (0.98 + iris * 1.22)
|
||||
ctx.strokeStyle = `rgba(98, 184, 255, ${(0.14 * irisFade).toFixed(3)})`
|
||||
ctx.lineWidth = 2.6
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, companionR, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1217,13 +1198,13 @@ export function createDesktopSplashController(options: {
|
||||
if (reducedMotion) {
|
||||
rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(exitRatio, 1.35)).toFixed(3)}`
|
||||
} else {
|
||||
// Portal cutout expands from center while particle bursts continue radiating over edges
|
||||
const holePct = Math.pow(exitRatio, 1.45) * 135
|
||||
const edgePct = holePct + 18
|
||||
// Wide feathered optical iris handoff into the live 3D Earth
|
||||
const holePct = Math.pow(exitRatio, 1.35) * 115
|
||||
const edgePct = holePct + 36
|
||||
const maskValue = `radial-gradient(circle at ${cx.toFixed(1)}px ${cy.toFixed(1)}px, transparent ${holePct.toFixed(1)}%, #000 ${edgePct.toFixed(1)}%)`
|
||||
rootEl.style.webkitMaskImage = maskValue
|
||||
rootEl.style.maskImage = maskValue
|
||||
rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(Math.max(0, exitRatio - 0.55) / 0.45, 1.5)).toFixed(3)}`
|
||||
rootEl.style.opacity = `${Math.max(0, 1 - smoothstep(0.28, 1, exitRatio)).toFixed(3)}`
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
@@ -275,4 +275,20 @@ describe('splash theme configuration and landmask', () => {
|
||||
})
|
||||
expect(capHit).toEqual({ targetProgress: 1, readyToExit: true })
|
||||
})
|
||||
|
||||
test('splash exit choreography uses calm coherent optical dissolve without outward radial streaks', () => {
|
||||
const splashSrc = readFileSync(new URL('../src/preload/splash.ts', import.meta.url), 'utf8')
|
||||
expect(splashSrc).not.toContain('shardSpeed')
|
||||
expect(splashSrc).not.toContain('shardAngle')
|
||||
expect(splashSrc).not.toContain('radialBoost')
|
||||
expect(splashSrc).not.toContain('warp * 44')
|
||||
|
||||
let prevFade = 1
|
||||
for (const ratio of [0, 0.25, 0.5, 0.75, 1]) {
|
||||
const phase = computeSplashMorphPhases(1, ratio)
|
||||
expect(phase.fade).toBeLessThanOrEqual(prevFade + 1e-9)
|
||||
prevFade = phase.fade
|
||||
}
|
||||
expect(computeSplashMorphPhases(1, 1).fade).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,45 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [0.83.0] — 2026-12-02
|
||||
|
||||
Released: 2026-12-02
|
||||
|
||||
### Highlights
|
||||
|
||||
- **Earth Phase 1–4 贴地影响范围与三维视觉升级**: 上线贴地影响范围着色器引擎(`influence-zones.js` + `scene_directives.py`,单次离屏模糊合成与层级叠序 `renderOrderBase = 0.965`)、本地云图 `earth_clouds_2048.png` 瑞利晨昏散射与地面云影、`surface-ribbon.js` 屏幕空间抗锯齿发光丝带(国界/雷达/弧线/海缆/航迹/轨道)及 GPU 投影 Iridium 足迹。
|
||||
- **Earth 聚合徽标视觉统一与优先一折连线**: 聚合徽标统一为 `28px` 深色玻璃内核 + `2.5px` 纯色 / `conic-gradient` 比例分段环及子类别明细提示;卡片引导线升级为“能一折优先一折、最多一折”策略,短距与紧凑胶囊平滑退化。
|
||||
- **AI 参谋自进化约束加固与数据源连通性修复**: 加固 `workflow_evolver.py` / `dag_executor.py` / `stream_turn.py` 的无变更结果、可判对错 A/B 样本、草稿隔离与灰度防覆盖机制;修复 Space-Track/ArcGIS/Epoch 等数据源连通性校验与凭据引导。
|
||||
- **Electron 客户端启动动效、打包构建与双语统一**: 更新桌面端 `splash.ts` 启动页配置与 Earth 热更包构建,并完成控制台、登录、文档页品牌图标及中英文纯净度统一;清理近 3 日冗余死代码并同步规划与技术文档。
|
||||
|
||||
### Added / Changed
|
||||
|
||||
- Earth & Frontend: `influence-zones.js`、`surface-ribbon.js`、`earth-surface-material.js`、`cluster-presentation.js`、`callout-connector.js`、`admin-write-auth.js`、`datasourceConfigHelpers.ts`
|
||||
- Backend: `scene_directives.py`、`dag_executor.py`、`workflow_evolver.py`、`workflow_runtime.py`、`stream_turn.py`、`datasource_connectivity.py`
|
||||
- Desktop Client: `client/src/preload/splash.ts`、`client/scripts/build-earth-bundle.mjs`、`client/bun.lock`
|
||||
|
||||
---
|
||||
|
||||
## [0.82.0] — 2026-12-01
|
||||
|
||||
Released: 2026-12-01
|
||||
|
||||
### Highlights
|
||||
|
||||
- **AI 参谋 3 层工作流自进化与元进化系统**: 引入 Tier-0 不可变宪法安全内核(`validate_evolution_patch`)、可自举元工作流 `meta.workflow_evolver`(单层递归锁防止无限自改)、Playground 👍/👎 用户反馈与模型/耗时遥测采集、5 次运行金丝雀自动回滚、Fixture A/B 离线评测与运行反刍孵化;支持在工作流画布通过 `自进化策略` 与 `调优` 面板管理自动/半自动优化。
|
||||
- **多模态 Playground 与工作流绑定**: 新增 Playground 附件上传与运行时上下文注入、DAG 执行器与 `ai_workflows.bindings` 地球交互绑定。
|
||||
- **Electron 客户端增强与国际化**: 升级桌面端无边框 `mainFrame` 录屏与指示浮窗、GPU 监控、热更新检查及主进程中英文国际化(`client/src/main/i18n.ts`)。
|
||||
- **AI Provider 模型目录与全量 UI / 文档升级**: AI Provider 支持模型聚合目录排序/折叠/刷新,升级地球界面与管理台中英文 UI,归档近期计划至 `docs/plans/` 并为 `README.md` 增加可渲染 Mermaid 架构图与自进化架构说明。
|
||||
|
||||
### Added / Changed
|
||||
|
||||
- Backend: `workflow_registry.py`、`workflow_evolver.py`、`dag_executor.py`、`stream_turn.py`、`ai_workflows.py`、`0006_add_ai_workflow_bindings.py`
|
||||
- Admin & Earth: `AdvisorPlayground.tsx`、`AdvisorRuns.tsx`、`AdvisorWorkflows.tsx`、`workflow-bindings.js`、地球面板与全量 i18n 审计修复
|
||||
- Desktop Client: `recording-core.ts`、`screen-recorder.ts`、`gpu-monitor.ts`、`hot-updater.ts`、`window.ts`、`i18n.ts`
|
||||
- Docs: 更新 `README.md` Mermaid 架构图、`docs/plans/` 与中英文技术文档
|
||||
|
||||
---
|
||||
|
||||
## [0.81.0] — 2026-11-30
|
||||
|
||||
Released: 2026-11-30
|
||||
|
||||
+3
-2
@@ -65,10 +65,10 @@ git diff --unified=0 HEAD -- <path>
|
||||
| Purpose | Command |
|
||||
| --- | --- |
|
||||
| First setup | `./planet.sh init` |
|
||||
| Start local stack | `./planet.sh start` |
|
||||
| Start local stack | `./planet.sh start` (Vite HMR frontend on `:3000`) |
|
||||
| Start with LAN access | `./planet.sh start --allow-lan` |
|
||||
| Restart all services | `./planet.sh restart` |
|
||||
| Restart one area | `./planet.sh restart -b`, `-f`, `-a`, or `-d` |
|
||||
| Restart one area | `./planet.sh restart -b`, `-f` (Vite HMR), `-a`, or `-d` |
|
||||
| Health check | `./planet.sh health` |
|
||||
| Logs | `./planet.sh log`, `./planet.sh log -b`, `-f`, `-a`, or `-m` |
|
||||
| Create local user | `./planet.sh createuser` |
|
||||
@@ -272,6 +272,7 @@ modify the host Docker environment.
|
||||
- Do not replace Bun with npm, pnpm, or yarn.
|
||||
- Do not migrate CI from `.gitea/workflows/` to `.github/workflows/`.
|
||||
- Do not rewrite `planet.sh` lifecycle behavior as a parallel script.
|
||||
- Do not start or rebuild the static Nginx `planet_admin` container (`./planet.sh admin ...`) for routine local development; use the Vite HMR dev server (`./planet.sh start` / `./planet.sh restart -f`) unless the user explicitly asks to simulate production locally.
|
||||
- Do not run `./planet.sh destroy` unless explicitly requested.
|
||||
- Do not commit `.env`, secrets, private keys, logs, or generated build output.
|
||||
- Do not add external integrations, hooks, or new dependency managers just to
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
当前重点入口:
|
||||
|
||||
- [开发 Agent 模型分配与 Token 控制计划](development-agent-model-allocation-plan.md)
|
||||
- [Earth 贴地影响范围与电影级三维视觉升级方案](earth-influence-zones-and-vfx-upgrade-plan.md)
|
||||
- [AI 参谋工作流可视化编排、客户端上下文与受控位置 Agent 方案](ai-advisor-workflow-and-location-agent-plan.md)
|
||||
- [Earth 地理资源、空间浮动卡片与性能实施计划](earth-spatial-presentation-and-geographic-assets-plan.md)
|
||||
- [算力与资源态势:展示、采集与 AI 迭代实施计划](compute-resource-intelligence-plan.md)
|
||||
- [控制台 i18n 接入计划](/home/ray/dev/linkong/planet/docs/plans/admin-console-i18n-plan.md)
|
||||
|
||||
@@ -30,3 +30,17 @@
|
||||
4. **L0–L4 未知设施位置解析管线与 `aiprovider` 纯协议扩展**:
|
||||
- `aiprovider` 保持纯协议适配器,新增 `tools`、`tool_choice`、`response_format`、`native_web_search` 与多轮 `tool`/`tool_calls` 透传以及结构化 `context` JSON 序列化。
|
||||
- 后端位置管线:`BuildsUponComputeCenterResolver` + ROR 商业云超大规模数据中心过滤 → L1 异步 `wikidata_lookup`(P625/P276)与 `peeringdb_fac_lookup`(`/api/fac`) → L2 最多 4 步受控 Tool-Calling Agent(`fetch_source_url`、`web_search`、`geocode_verify`、`submit_location_result`) → L3 硬护栏(强校验观测 URL 引用、Nominatim 国家/范围校核与市级降级) → L4 终态(`undisclosed` / `multi_site` / `anonymous`)持久化与短路。
|
||||
|
||||
---
|
||||
|
||||
## 2. Phase 2 & Phase 3 演进落地摘要(随 `v0.82.0` 发布)
|
||||
|
||||
1. **多节点 DAG 运行时与地球交互动态绑定**:
|
||||
- 新增 `backend/app/services/ai/dag_executor.py` 支持任意 `trigger -> deterministic -> llm_agent -> guardrail -> output` 有向无环图流式执行与条件路由。
|
||||
- 通过 `0006_add_ai_workflow_bindings.py` 在 `ai_workflows` 表增加 `bindings` JSON 声明,`GET /api/v1/earth/workflow-bindings` 与前端 `workflow-bindings.js` 驱动信息卡、专题卡、Copilot 快捷动作及多目标对比触发。
|
||||
- `/advisor/playground` 升级为统一多模态对话输入台(图片/视频关键帧/网页链接 SSRF 隔离解析/JSON 及地球上下文自动识别挂载),支持 Markdown 渲染与 `/locate` / Nominatim SSL 重试保护。
|
||||
2. **三层轻量可扩展自进化与元进化(零改表 / 零迁移脚本)**:
|
||||
- 新增内建 `meta.workflow_evolver` 三节点元工作流(`diag_node -> patch_node -> verify_output`),并由 `backend/app/services/ai/workflow_evolver.py` 实现三层有界自举架构。
|
||||
- **Tier 0 不可变宪法内核(Python 硬约束)**:单层元递归锁(禁止自定义 `meta.*`)、`verify_output` 只读冻结、自动变更半径上限(单次最多 2 个且 `<= 40%` 节点)、`24h / 7d` 冷却与每日自动预算锁、以及 **5 次运行灰度观察自动回滚**(元引擎自身为 3 次下游结果窗口自动回滚)。
|
||||
- **Tier 1 业务自优化与模型漂移适配**:复用 `WorkflowRun.budget_used` 记录模型/耗时/版本号与 👍/👎 反馈,支持 0-Token 健康诊断、活跃模型切换检测、DGM 历史最佳父版本选择、Fixture A/B 对照、高频问题孵化自定义工作流及后台非阻塞自动进化(`off | draft | auto`)。
|
||||
- **Tier 2 元进化与可扩展注册表**:台账与策略存储于 `system_settings`(`ai_evolution_policy`、`ai_evolution_ledger` 上限 50 条),通过 `EvolutionSignalDetector` 与 `EvolutionEvaluator` 协议支持后续无侵入接入新探针与离线评测器。
|
||||
@@ -0,0 +1,62 @@
|
||||
# Earth 贴地影响范围与电影级三维视觉升级方案
|
||||
|
||||
> 状态:**已落地实现(随 `v0.83.0` 发布)**。已完成 Phase 1–4 全部核心引擎与渲染管线交付([influence-zones.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/influence-zones.js)、[scene_directives.py](/home/ray/dev/linkong/planet/backend/app/services/ai/scene_directives.py)、[surface-ribbon.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/surface-ribbon.js)、[earth-surface-material.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface-material.js)、[iridium-footprint-adapter.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/iridium-footprint-adapter.js) 及本地云图 `earth_clouds_2048.png`),仍保持 `three@0.128.0` 无全屏后处理约束。
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与现状诊断
|
||||
|
||||
核查 `frontend/public/earth/js/` 与 Agent `SceneSpec` 链路后,发现当前 3D 场景存在 6 项主要提升空间:
|
||||
|
||||
1. **贴地影响范围能力空白**:尚无面向新闻事件、多边会晤(如 APEC 中美俄及亚太梯度覆盖)或交互物件辐射半径的贴地矢量/球面范围层,无法支持自定义颜色、透明度、硬边界/渐变边缘切换及锋面扫光动画。
|
||||
2. **地球本体光影与晨昏散射**:[earth-surface-material.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface-material.js) 晨昏线为简单线性冷暖过渡,海面缺少太阳镜面高光(Sunglint),夜半球缺少城市灯火,云层使用 `DoubleSide` 易从边缘透出背面。
|
||||
3. **Windows WebGL2 下多处 `1px` 细线退化**:`LineBasicMaterial({ linewidth: 3 })` 在 Windows ANGLE 上锁定为 `1px`(国界悬停高亮、高空 BGP/算力逻辑弧线、选中海缆轮廓、船只航迹、卫星选中轨道均受此限制);而 [satellites.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellites.js) 已验证“屏幕空间自适应宽度 + 柔化边缘 Shader Ribbon”方案可行。
|
||||
4. **BGP 采集器雷达扇区**:[bgp.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/bgp.js) 通过高频销毁/重建几何体实现旋转,产生 GC 抖动且视觉偏硬。
|
||||
5. **Iridium 卫星覆盖足迹**:[iridium-footprint-adapter.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/iridium-footprint-adapter.js) 仍在每帧 CPU 循环重算 649 个顶点,未迁入 [satellite-footprint-geometry.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellite-footprint-geometry.js) 的 GPU 顶点投影管线。
|
||||
|
||||
---
|
||||
|
||||
## 2. 分期升级路线(Phase 1 → Phase 4)
|
||||
|
||||
### Phase 1(核心旗舰):贴地影响范围(Surface Influence Zones)Shader 引擎 + Agent/事件联动
|
||||
|
||||
- **目标文件**:
|
||||
- 新建 `frontend/public/earth/js/influence-zones.js`
|
||||
- 修改 [country-boundaries.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/country-boundaries.js)、[main.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/main.js)、[situational-copilot.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/situational-copilot.js)、[stage-narrative-player.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/stage-narrative-player.js)
|
||||
- 扩展后端 `SceneSpec.influence_zones`([workflow_runtime.py](/home/ray/dev/linkong/planet/backend/app/services/ai/workflow_runtime.py)、[stream_turn.py](/home/ray/dev/linkong/planet/backend/app/services/ai/stream_turn.py)、[earth_interactables.py](/home/ray/dev/linkong/planet/backend/app/services/earth_interactables.py))
|
||||
- **核心架构**:
|
||||
1. **零冲突渲染插槽**:复用同半径 `r = 100.48` 的 `128×128` 球壳(`createEarthSurfaceGeometry`),置于 `renderOrder = 0.965`(紧贴高清纹理 `0.96` 之上,严守在国界线 `0.97` 与全部交互图标之下),不破坏 `earth-surface.test.js` 断言。
|
||||
2. **双通道混合渲染**:
|
||||
- 国家/区域预设(如 `APEC` / `EU` / `ASEAN` / `G7` / `BRICS`)及任意多边形通过离屏高清 `CanvasTexture`(`2048×1024` / `4096×2048`)按层级 `tier` 从低到高叠画;修复 `-99` `ISO_A2/A3` 匹配并优先索引 `ADM0_A3`。
|
||||
- 圆形辐射区在片元 Shader 内按球面大圆角距离实时求解,保证极区与高纬无变形。
|
||||
3. **可调视觉参数与三种电影级入场动效**:支持任意色值、独立透明度、`edge_mode: "sharp" | "soft"` 边缘模式与羽化宽度,以及 `sweep`(方向性高亮能量锋面扫光铺开)、`radial`(中心大圆波纹扩散)、`fade`(柔缓浮现)三种入场模式。
|
||||
|
||||
### Phase 2:地球本体大气散射、海洋高光与立体云影升级
|
||||
|
||||
- **目标文件**:[earth-surface-material.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface-material.js)、[earth.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth.js)。
|
||||
- **核心内容**:
|
||||
1. 晨昏线升级为三阶物理瑞利散射(白昼 → 琥珀金暮光带 → 深蓝暗夜);
|
||||
2. 结合海陆掩码增加向阳海面柔和太阳镜面高光(Sunglint);
|
||||
3. 增加轻量本地夜半球城市灯火贴图(按 `1 - daylight` 混合,完全离线可用);
|
||||
4. 大气层补充太阳侧 Mie 前向散射光弧;
|
||||
5. 云层由 `DoubleSide` 改为 `FrontSide` Shader 并叠加微位移地表云影。
|
||||
|
||||
### Phase 3:通用发光丝带系统与雷达/弧线/海缆/航迹升级
|
||||
|
||||
- **目标文件**:新建 `frontend/public/earth/js/surface-ribbon.js`;升级 [bgp.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/bgp.js)、[compute-centers.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/compute-centers.js)、[cable-batches.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/cable-batches.js)、[vessels.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/vessels.js)、[country-boundaries.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/country-boundaries.js)。
|
||||
- **核心内容**:
|
||||
1. 抽出共享屏幕空间抗锯齿发光丝带底层(亮核 + 高斯羽化外晕),替代 Windows 下退化为 1px 的 `THREE.Line`;
|
||||
2. BGP 采集器雷达改为静态球面圆盘 + 60fps 片元扫描余辉与同心刻度(0 GC);
|
||||
3. 高空逻辑弧线支持生长动画与高速光弹脉冲;选中海缆叠层发光流光;船只航迹支持尾迹渐隐;国界悬停换用柔光轮廓。
|
||||
|
||||
### Phase 4:卫星覆盖 GPU 提纯与轨道丝带
|
||||
|
||||
- **目标文件**:[iridium-footprint-adapter.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/iridium-footprint-adapter.js)、[satellite-orbit-visual.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellite-orbit-visual.js)、[satellites.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellites.js)。
|
||||
- **核心内容**:将 Iridium 足迹迁入 GPU 顶点投影消除每帧 649 顶点 CPU 循环,并将选中卫星轨道升级为发光丝带脉冲。
|
||||
|
||||
---
|
||||
|
||||
## 3. 性能与质量约束
|
||||
|
||||
- 不增加全屏 RenderTarget 后处理管线,单层均匀控制在 `1~2 Draw Calls`,保障核显性能与桌面端录屏流畅度。
|
||||
- 所有球壳必须通过 [earth-surface.test.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface.test.js) 深度与渲染顺序回归测试。
|
||||
@@ -312,3 +312,17 @@ hover / locked 使用少量 overlay:
|
||||
| `frontend/public/earth/js/main.js` | 当前集中处理 hover、click、locked 和 info-card 入口 | 后续需要接入通用 icon picking 结果 |
|
||||
| `docs/technical/zh/earth-layer-style-reference.md` | 当前视觉参数参考 | 实现后同步默认 glow 和通用参数 |
|
||||
| `docs/technical/zh/earth-render-layer-order.md` | 当前层级参考 | 实现后同步 surface icon 层级范围 |
|
||||
|
||||
---
|
||||
|
||||
## 后续演进:跨图层聚合与屏幕空间防重叠(待排期)
|
||||
|
||||
当前聚合按图层控制器独立计算(`compute-centers`、`bgp-events`、`bgp-collectors`、`earth-interactables` 各自成簇),且仅使用固定球面世界距离(`CLUSTER_DISTANCE = 15`)与 `coLocatedGroups`(`0.00015°`)的展开态偏移。由此带来两个待解决的交互问题:
|
||||
|
||||
1. 当一个图层的折叠数字徽章(如 `compute-centers` 的 `2`)与另一图层的未聚合单点(如莫斯科同城 `bgp-collectors`)在低缩放下投影重合时,DOM 覆盖层 `.map-clusters` 会直接挡住底部 WebGL 图标并吞掉鼠标拾取事件。
|
||||
2. 固定世界距离加上单种子贪心聚类的质心偏移,在拉远视角下容易使相邻点未合并却在屏幕像素空间重合。
|
||||
|
||||
待选演进方向(排期前二选一):
|
||||
|
||||
- **方案 A(优先推荐)**:跨图层统一聚合 + 基于当前相机缩放的屏幕像素距离自适应归并(单徽章多色分段环天然复用现有 `conic-gradient` 视觉契约)。
|
||||
- **方案 B**:保持各图层语义独立,将折叠态聚合徽章纳入与异图层单点之间的屏幕空间碰撞避让,并补齐错位引导线以保证底层图标可独立拾取。
|
||||
@@ -132,15 +132,32 @@ New Model Studio endpoints for Beijing, Tokyo, Frankfurt and Virginia require th
|
||||
|
||||
Pagination and retries have a 30-second overall deadline. Network failures and 502/503/504 allow up to two attempts; authentication failures are not retried. Models are sorted by supplied creation/release dates, preserving upstream order on ties, without arbitrary list truncation. Public catalog membership does not establish account-specific generation permission.
|
||||
|
||||
Admin separates AI infrastructure from workflow orchestration across two areas:
|
||||
Admin separates AI configuration from workflow orchestration across two areas:
|
||||
|
||||
- **Operations and Settings → AI Infrastructure (`/ai`)**:
|
||||
- **Operations and Settings → AI (`/ai`)**:
|
||||
- `Model Providers`: manages provider, wire adapter, default model, LLM API key, proxy URL/token, catalog refresh (keyless official providers fall back to public aggregator catalogs sorted selected-first + MRU + release date with a 6-item collapsible list), set-as-default, and connectivity testing.
|
||||
- `Tool Calling`: manages WebSearch (including keyless SearXNG) and OCR tool credentials.
|
||||
- **AI Advisor (`/advisor/*`)**:
|
||||
- `Playground` (`/advisor/playground`): pure-chat debugging bench defaulting to `default.general` with slash commands and client-owned local Earth context drawer (`planet.earth_context.v1` / same-origin IndexedDB / `localStorage`).
|
||||
- `Workflows & Nodes` (`/advisor/workflows`): `@xyflow/react` visual graph over all 9 built-in workflows supporting node prompts, allowlisted tools, guardrails, immutable revisions/rollback, and allowlisted AI Diff tuning proposals.
|
||||
- `Run History` (`/advisor/runs`): execution trace audit with one-click canvas replay.
|
||||
- `Playground` (`/advisor/playground`): unified multimodal debugging workbench (text, images, sampled video keyframes, SSRF-isolated web links, JSON, and automatic Earth context mounting) with slash commands, Markdown rendering, and inline 👍/👎 assistant feedback persisted in `WorkflowRun.budget_used`.
|
||||
- `Workflows & Nodes` (`/advisor/workflows`): `@xyflow/react` visual graph studio over all 10 built-in workflows (including `meta.workflow_evolver`) and custom DAGs executed via `dag_executor.py`, supporting Earth interactive `bindings`, immutable revisions/rollback, Fixture A/B evaluation, and 3-tier bounded self-evolution controls.
|
||||
- `Run History` (`/advisor/runs`): execution trace audit surfacing model, latency, revision, and feedback filters with one-click canvas replay and trace-guided tuning.
|
||||
|
||||
### Three-Tier Workflow Self-Evolution and Meta-Evolution
|
||||
|
||||
Implemented in [workflow_evolver.py](/home/ray/dev/linkong/planet/backend/app/services/ai/workflow_evolver.py) with **zero database schema changes or migrations** by reusing `ai_workflows`, `ai_workflow_revisions`, `ai_workflow_fixtures`, `workflow_runs.budget_used`, and `system_settings` (`ai_evolution_policy` and `ai_evolution_ledger`):
|
||||
|
||||
- **Tier 0 (Immutable Python Constitution Kernel)**: enforces acyclic DAG structure and trigger/output preservation, blocks emptying `system_prompt`, restricts tools to allowlisted IDs, caps auto-mode blast radius (`<= 2` nodes and `<= 40%` of nodes), freezes the `verify_output` node on `meta.workflow_evolver`, blocks custom `meta.*` creation (single-level recursion lock), enforces `24h / 7d` cooldowns and daily auto-evolution quotas, and runs a **5-run canary window** with automatic rollback on consecutive failures or elevated bad-rating rates (with a 3-outcome meta-canary rollback guard on `meta.workflow_evolver`).
|
||||
- **Tier 1 (Business Optimization & Model Drift Adaptation)**: `GET /api/v1/ai/evolution/health/{workflow_id}` computes 0-token health metrics, active model capability drift, unused tools, and DGM best-parent revision recommendations; `POST /api/v1/ai/evolution/propose/{workflow_id}` reads live `diag_node` / `patch_node` prompts from `meta.workflow_evolver` alongside historical ledger lessons; `POST /api/v1/ai/evolution/eval/{workflow_id}` runs Fixture A/B checks and `POST /api/v1/ai/evolution/incubate` proposes new workflows from frequent `default.general` queries. Non-blocking post-run hooks run via `schedule_post_run_evolution`.
|
||||
- **Tier 2 (Meta-Evolution & Extensibility Hooks)**: `POST /api/v1/ai/evolution/meta-evolve` evolves `meta.workflow_evolver` prompts under an independent `meta_mode` (`off | draft | auto`) using objective ledger outcomes; `EvolutionSignalDetector` (`SIGNAL_DETECTORS`) and `EvolutionEvaluator` (`EVALUATORS`) provide clean `Protocol` extension points.
|
||||
- **Evolution safety constraints (hardened after the v0.82.0 review)**:
|
||||
- **"No change" is a valid outcome**: a valid empty `node_patches` list ends the round with `applied_status: no_change` (no revision, no ledger entry); the deterministic fallback only patches on real signals (failures/downvotes/model capability mismatch/admin instruction/ledger outcomes) and never pads prompts.
|
||||
- **Gradable A/B fixtures**: fixtures accept `expect` (`numbers`, `must_include`, `must_not_include`, `require_uncertainty_without_evidence`, `min_evidence`, stored in `context_json.expect`) on `POST /api/v1/ai/workflows/{id}/fixtures`; grading covers execution errors, guardrail verification, and assertions, and any fixture that passes on live but fails on the candidate yields `regressed`. **Auto-publish requires the A/B gate**: missing fixtures, fixtures without assertions, or any regression block publication.
|
||||
- **Live revision baseline**: background/auto-publish evolution always starts from the live revision, never reads or clears unpublished human drafts (auto-draft mode skips when a human draft exists), records the full candidate-vs-live diff in `changes_vs_live`, and applies the auto blast-radius limit to that full diff.
|
||||
- **Canary cannot overwrite newer revisions**: before settling, the canary checks the live revision is still its target; if a manual publish/rollback superseded it, the entry becomes `superseded` without rollback (same for the meta canary).
|
||||
- **Meta fields must take effect**: meta-evolution may only change `diag_node.system_prompt / prompt` and `patch_node.system_prompt / prompt / thinking_enabled`, all of which feed the business request (`build_business_evolution_request`); meta-evolution stays off by default.
|
||||
- **Earth workflow data, evidence, and card output**: `dag_executor.py` selects each data source's own target ID by entity type (cable/vessel/BGP multi-select is order-independent); `interactive / ingest` edges route strictly by trigger source (a news click no longer runs the RSS localization branch); strict-JSON nodes such as `compute.posture.brief` run non-streaming, are verified via `StrategicPostureBrief` + evidence IDs, rendered as narrative, and the output node compiles the compute `view_spec` workbench (delivered via a closing `meta` event and `done.view_spec`); a failed `require_evidence` guardrail appends a "cause pending verification" block with follow-ups and marks `done.status` as `unverified` with `verification`.
|
||||
- **Draft binding isolation**: Earth entry bindings edited in a draft live in `draft_graph.bindings` (returned as `draft_bindings`), apply only on publish, and are restored by discarding the draft; each published revision snapshots bindings in `graph_json.bindings` so rollback restores them. "Save bindings only" (`PATCH /workflows/{id}`) remains an explicit immediate action.
|
||||
- **Feedback & Policy APIs**: `POST /api/v1/ai/runs/{run_id}/feedback`, `GET /api/v1/ai/runs?feedback=negative|positive`, `GET/PUT /api/v1/ai/evolution/policy`, `GET /api/v1/ai/evolution/ledger`, and `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss`.
|
||||
|
||||
Save, set-as-default, and connectivity testing remain three separate responsibilities. Runtime prompts resolve from published `AIWorkflow` nodes and versioned `default_prompts.json` resources while preserving `task_key` compatibility.
|
||||
|
||||
|
||||
@@ -376,7 +376,7 @@ If future cable, satellite, or news cruise is added, do not copy a new set of `m
|
||||
|
||||
`globe-navigation.js` retains the safe zoom-distance mapping. Mouse and single-touch drags uniformly use legacy screen deltas, 0.18 smoothing and release inertia, including movement outside the globe silhouette; ray/sphere intersection no longer gates dragging. Normal zoom retains legacy sensitivity. Once the globe exceeds the viewport, a smooth surface-distance/viewport cap limits excessive rotation at extreme zoom. Horizontal motion uses geographic yaw, vertical input changes tilt, and quaternion math prevents multi-revolution reversal. Pinch transitions and pointer capture remain intact.
|
||||
|
||||
Surface markers retain category icons and fixed geographic cluster membership. Numbered solid circles expand through a 320ms tween above 250% zoom; zoom never regroups members, and 500% has no aggregate badges. Vessels retain independent heading arrows without clustering. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md).
|
||||
Surface markers retain category icons and fixed geographic cluster membership. `28px` dark translucent-core circular badges with colored outer rings expand through a 320ms tween above 250% zoom; zoom never regroups members, and 500% has no aggregate badges. Vessels retain independent heading arrows without clustering. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md).
|
||||
|
||||
Wheel input has two paths. Traditional mouse wheels keep the 10% step and short animation, using `wheelZoomTarget` as the logical base for continuous wheel input. Trackpads and high-precision wheels use the pixel delta for continuous zoom and call `setZoomLevel()` directly instead of passing through the 10% stepped animation. The trackpad path also filters a short-window, old-direction residual delta after a real direction change so inertia tails do not pull a just-reversed zoom back in the previous direction.
|
||||
|
||||
@@ -508,7 +508,7 @@ Focus state and per-type limits decide expanded cards versus capsules. Shared st
|
||||
|
||||
### Cluster badges and Spiderfy
|
||||
|
||||
Ordinary surface markers retain GPU batches. Each aggregate uses the same projected children in `cluster-presentation.js` through collapse, expansion and the final resting state. A 26px solid numbered circle represents the group, with an amber ring for mixed categories. Membership changes only with data or filters, never through intermediate groups while zooming.
|
||||
Ordinary surface markers retain GPU batches. Each aggregate uses the same projected children in `cluster-presentation.js` through collapse, expansion and the final resting state. Badges share a `28px` dark-glass core with white tabular counts: single-type groups wear a `2.5px` solid `--cluster-color` ring, while mixed groups render a proportional `conic-gradient` ring (`--cluster-ring` with `4deg` dark dividers and a minimum minority arc floor) plus localized subtype breakdowns via `formatClusterTitle`. Membership changes only with data or filters, never through intermediate groups while zooming.
|
||||
|
||||
`cluster-motion.js` drives a 320ms cubic tween after visible icons are prepared and decoded, with encoded textures cached. Children interpolate from the group center to their real projections; `marker-stack.js` owns final display offsets. Animation and resting endpoints retain the same DOM nodes, with continuous reversal.
|
||||
|
||||
@@ -609,3 +609,14 @@ When compute image configuration has no model/group rules, resolution uses a bou
|
||||
### Satellite Compression, Twinkle & Compute Site Differentiation
|
||||
|
||||
`compute-site-types.js` distinguishes `supercomputer`, `gpu_cluster`, `data_center`, `cloud_center`, and `edge_node` markers/legends by color, while `satellites.js` provides altitude compression (`altitudeCompression`), short comet trails, and GPU-attribute twinkle intensity controls (`twinklePhase` / `twinkleShape`) alongside a simplified footprint toggle focused on Starlink.
|
||||
|
||||
### Dynamic Workflow Bindings, Borderless Desktop Recording, and Bilingual Alignment
|
||||
|
||||
- `workflow-bindings.js` fetches `/api/v1/earth/workflow-bindings` and dynamically projects published custom/built-in workflow actions onto matching Earth surfaces (info cards, news/topic cards, Copilot quick actions, and multi-target comparison tray).
|
||||
- Electron `screen-recorder.ts` captures `win.webContents.mainFrame` cleanly without framing chrome while preserving native Alt menu access, and Earth `i18n.js` / `index.html` keep `zh-CN` and `en-US` copy separated cleanly while syncing locale preferences with the console.
|
||||
|
||||
### Surface Influence Zones, Cinematic Shading, and Prefer-One-Bend Callouts (v0.83.0)
|
||||
|
||||
- **Surface Influence Zones & Stage Directives** (`influence-zones.js` + `scene_directives.py`): renders geopolitical country/region presets and great-circle radius zones emitted by AI/stage directives via single-pass offscreen `scratchCanvas` soft-blur compositing and explicit `tier` / `z_index` stacking (`renderOrderBase = 0.965`, strictly between HD imagery `0.96` and borders `0.97`).
|
||||
- **Rayleigh Scattering, Ribbons & GPU Iridium Projection**: `earth-surface-material.js` and `earth.js` pair with `earth_clouds_2048.png` for Rayleigh terminator shading, soft surface cloud shadows, and grazing water highlights; `surface-ribbon.js` unifies screen-space anti-aliased glowing ribbons for borders, BGP radar/stage arcs, cable pulses, vessel tracks, and selected satellite orbits; `iridium-footprint-adapter.js` moves Iridium footprint vertices onto GPU projection.
|
||||
- **Prefer-One-Bend Callout Routing & Write Auth**: `callout-connector.js` (`applyPreferredOneBendAnchor`) shifts aligned perimeter anchors toward the card body/header when sufficient major-axis distance and edge span exist so connectors prefer one clean bend (never exceeding one bend, gracefully falling back to a 2-point line on compact capsules or short spans); `admin-write-auth.js` gates Earth-side compute location collection and saving behind admin token refresh and `/login` prompts.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Earth interactable clustering
|
||||
|
||||
`interactable.js` owns fixed geographic membership, `cluster-motion.js` owns timed tweening, and `cluster-presentation.js` owns circular badges, projected children, picking and Spiderfy. Independent markers remain GPU Points. Each clustered child uses the same DOM icon throughout its animation and at the final position.
|
||||
`interactable.js` owns fixed geographic membership, `cluster-motion.js` owns timed tweening, and `cluster-presentation.js` owns `28px` dark-glass circular badges (`2.5px` solid or proportional `conic-gradient` multi-type rings), projected children, picking and Spiderfy. Independent markers remain GPU Points. Each clustered child uses the same DOM icon throughout its animation and at the final position.
|
||||
|
||||
## Membership and zoom
|
||||
|
||||
|
||||
@@ -20,8 +20,10 @@ Note: the layer control panel order and the registration / startup load order ar
|
||||
| 0 | Earth base sphere | `earth.js` | `CONFIG.earthRadius` | Surface picking fallback target | Dark base; still visible when all optional map layers are off. |
|
||||
| 0.2 | Country dark tint | `country-boundaries.js` | `tintAltitudeOffset` | Raycast disabled | Used when HD texture is off. |
|
||||
| 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset = 0.32`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off; radius is separated from the base sphere to avoid far-zoom z-fighting. |
|
||||
| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere. |
|
||||
| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering shares the surface pass; no fullscreen post-processing. |
|
||||
| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere; uses Rayleigh terminator shading and subtle grazing water reflection. |
|
||||
| 0.962 | Cloud shadow shell | `earth.js` | Shared HD surface radius with slight angular offset | `depthTest: true`, `depthWrite: false`, raycast disabled | Follows the cloud toggle and casts soft surface cloud shadows from `earth_clouds_2048.png`, strictly above `0.96` and below `0.965`. |
|
||||
| 0.965 | Surface influence zones | `influence-zones.js`, `scene_directives.py` | Reuses the `128×128` spherical shell at `r = 100.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`); `renderOrderBase = 0.965`, stepping by `0.0003` per tier | `depthTest: true`, `depthWrite: false`, raycast disabled | Supports single-pass offscreen soft blur compositing for country presets and great-circle fragment shading for circular zones; stays above `0.96` HD imagery and strictly below `0.97` borders and all surface icons. |
|
||||
| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 (`FrontSide` shader + `earth_clouds_2048.png`) | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering and Mie forward glow combine across the surface/atmosphere shells without fullscreen post-processing. |
|
||||
| 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cables and landing-point anchors share the HD surface offset `0.48` and the same triangle-surface coordinates | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. |
|
||||
| 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. |
|
||||
| 2.05 | Grid lines | `earth.js` | `CONFIG.earthRadius + 0.14` | Raycast disabled | Low-opacity lines over HD texture. |
|
||||
@@ -108,4 +110,4 @@ Co-located markers share a compact projection stack across categories; screen co
|
||||
|
||||
Regional news and compute retain the `#earth-region-callouts` root (z-index 20) and share flank/corridor assignment with object details through `callout-stage-arbitrator.js`, which assigns symmetric left and right flanks to bilateral `CN` and `US` spotlight peers via `bilateralPeerKey`. Expanded cards inside the regional root use 50, drag foreground 55, hover expansion 60–65, ordinary capsules 30, and dimmed/shrunk rear capsules 8, whereas spotlight and hover-expanded cards stay 100% opaque on the rear hemisphere while switching their connector to a dashed `.is-rear` rim guide and exposing a header rotate-to-front button.
|
||||
|
||||
Compute hub drill-down overlays and stage logical AS route arcs follow strict shell separation and batching rules: China's eight National Compute Hubs render through a single GPU-instanced `createInteractableLayer` at `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` (`renderOrder = 4.58`); western green-hub `AdditiveBlending` pulse rings use `renderOrder = 4.42` (`depthWrite: false`), and East-West synergy arcs batch into one elevated `LineSegments` (`renderOrder = 4.55`) to prevent far-zoom z-fighting; stage logical AS route arcs render as high-altitude before/after trajectories (`renderOrder = 4.72` / `4.76`) and dispose geometry and materials immediately on hide or tour exit.
|
||||
Compute hub drill-down overlays and stage logical AS route arcs follow strict shell separation and batching rules: China's eight National Compute Hubs render through a single GPU-instanced `createInteractableLayer` at `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` (`renderOrder = 4.58`); western green-hub `AdditiveBlending` pulse rings use `renderOrder = 4.42` (`depthWrite: false`); East-West synergy arcs, stage logical AS routes, country hover highlights, selected cable pulses, vessel tracks, and selected satellite orbits share the screen-space anti-aliased `surface-ribbon.js` pipeline (avoiding the Windows ANGLE 1px `THREE.Line` cap); and Iridium footprints run through GPU vertex projection in `iridium-footprint-adapter.js`, disposing geometry and materials immediately on hide or tour exit.
|
||||
@@ -35,14 +35,13 @@ Admin now owns the official admin routes:
|
||||
- `/advisor/playground`
|
||||
- `/advisor/workflows`
|
||||
- `/advisor/runs`
|
||||
- `/ops/monitoring`
|
||||
- `/ai`
|
||||
- `/earth-content`
|
||||
- `/collection-management`
|
||||
- `/settings`
|
||||
- `/logs`
|
||||
|
||||
(Legacy `/bgp`, `/alerts/*`, `/ai/prompts`, and `/ai/playground` remain only as `<Navigate replace />` redirects.)
|
||||
(Legacy `/ops/monitoring`, `/bgp`, `/alerts/*`, `/ai/prompts`, and `/ai/playground` remain only as `<Navigate replace />` redirects to `/advisor/*`.)
|
||||
|
||||
These routes render [AdminRoutes.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/AdminRoutes.tsx). Page metadata and menu entries come from [manifest.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/routes/manifest.tsx). Admin is the only console entry point; there is no parallel console or rollback route.
|
||||
|
||||
@@ -301,7 +300,7 @@ Responsibilities:
|
||||
|
||||
`App.tsx` uses it to decide whether to redirect to the login page. `/docs` remains a public route, but the backend decides the visible catalog and content from the token; anonymous visitors only receive public docs.
|
||||
|
||||
### 2. AI Infrastructure and AI Advisor
|
||||
### 2. AI and AI Advisor
|
||||
|
||||
Files:
|
||||
|
||||
@@ -312,11 +311,11 @@ Files:
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- `/ai` is scoped to **AI Infrastructure** (`模型供应商` Model Providers and `工具调用` Tool Calling only), redirecting `?section=prompts` and `?section=playground` to `/advisor/*`
|
||||
- `模型供应商` includes keyless official-provider aggregator fallback sorting (`selected-first -> MRU -> release date`) with a collapsible 6-item list, unified tactile `<Select>` and dark-mode numeric steppers, and active sidebar group persistence across reloads
|
||||
- `/advisor/playground` delivers a pure-chat debugging workspace with slash commands and a Client-Owned Local Context Drawer (`localStorage`, same-origin Earth IndexedDB, `planet.earth_context.v1` JSON paste, and explicit Save Fixture)
|
||||
- `/advisor/workflows` renders a 3-column `@xyflow/react` visual editor over all 9 built-in workflows, allowlisted tools, guardrails, immutable revisions/rollback, and AI Diff proposals
|
||||
- `/advisor/runs` and `/ops/monitoring` house execution trace audits and consolidated non-AI monitoring alerts
|
||||
- `/ai` focuses on **AI** (`模型供应商` Model Providers and `工具调用` Tool Calling), redirecting `?section=prompts` and `?section=playground` to `/advisor/*`
|
||||
- `模型供应商` includes keyless official-provider aggregator fallback sorting (`selected-first -> MRU -> release date`), a collapsible 6-item list with permanent vendor/keyword filters, chevron expand with auto-scroll, unified tactile `<Select>` and dark-mode numeric steppers, and active sidebar group persistence across reloads
|
||||
- `/advisor/playground` delivers a unified multimodal debugging workspace (images, sampled video frames, SSRF-isolated links, JSON, Markdown output, Client-Owned Local Context Drawer, and inline 👍/👎 run feedback)
|
||||
- `/advisor/workflows` renders a 3-column `@xyflow/react` visual editor over all 10 built-in workflows (including `meta.workflow_evolver`) and custom DAGs with Earth interactive bindings, revisions/rollback, lazy-loaded header `Evolution` policy/meta-evolution popover, and Inspector 0-token health/drift diagnostics + Fixture A/B comparison
|
||||
- `/advisor/runs` houses execution trace audits (model, latency, revision, and feedback filter) and canvas replay; Admin & Advisor pages share auto-hiding `<Scrollbar>` overlays and clean zh/en separation. Legacy `/ops/monitoring`, `/bgp`, and `/alerts/*` redirect cleanly to `/advisor/playground`, while live BGP layers render on `/earth`
|
||||
|
||||
Legacy `/playground`, `/bgp`, and `/alerts/*` routes are preserved only as `<Navigate replace />` redirects.
|
||||
|
||||
|
||||
+10
-12
@@ -76,8 +76,7 @@ The console at `http://localhost:3000/admin` is built with React plus Tactile UI
|
||||
| Playground | `/advisor/playground` | Pure-chat AI Advisor workbench with local Earth context drawer |
|
||||
| Workflows & Nodes | `/advisor/workflows` | `@xyflow/react` visual workflow editor, revision rollback, and AI Diff tuning |
|
||||
| Run History | `/advisor/runs` | AI workflow execution trace audit and canvas replay |
|
||||
| Monitoring & Alerts | `/ops/monitoring` | Consolidated system alerts, BGP incidents/anomalies/events, and collector health |
|
||||
| AI Infrastructure | `/ai` | Model providers and WebSearch/OCR tool credentials |
|
||||
| AI | `/ai` | Model providers and WebSearch/OCR tool credentials |
|
||||
| Earth Content | `/earth-content` | TV livestreams, boundary precision, base-map and layer-resource entry points |
|
||||
| Collection Management | `/collection-management` | Collectors, scheduling, collection history entry points |
|
||||
| Logs | `/logs` | Usually visible only to super admin |
|
||||
@@ -144,21 +143,21 @@ Steps:
|
||||
- `total stored`, `last 24h`, `last 1h`, and `unique MMSI` show historical collection volume
|
||||
- `disconnected` with a recent error means the upstream or network dropped; click `Reconnect`
|
||||
|
||||
## Configure AI Infrastructure and Use AI Advisor
|
||||
## Configure AI and Use AI Advisor
|
||||
|
||||
`/ai?section=integrations` (**AI Infrastructure**) manages model providers and tool credentials, while `/advisor/playground`, `/advisor/workflows`, and `/advisor/runs` (**AI Advisor**) provide pure-chat debugging, visual node orchestration, and run auditing:
|
||||
`/ai?section=integrations` (**AI**) manages model providers and tool credentials, while `/advisor/playground`, `/advisor/workflows`, and `/advisor/runs` (**AI Advisor**) provide pure-chat debugging, visual node orchestration, and run auditing:
|
||||
|
||||
- **AI Infrastructure (`/ai`)**:
|
||||
- `Model Providers`: default LLM provider, model, base URL, API key, local `aiprovider` proxy, and connection test; official keyless providers (incl. GLM, Meta, Gemini, Grok, DeepSeek, OpenAI, MiniMax) fall back to public aggregator catalogs sorted selected-first + MRU + release date with a collapsible 6-item list
|
||||
- **AI (`/ai`)**:
|
||||
- `Model Providers`: default LLM provider, model, base URL, API key, local `aiprovider` proxy, and connection test; official keyless providers (incl. GLM, Meta, Gemini, Grok, DeepSeek, OpenAI, MiniMax) fall back to public aggregator catalogs sorted selected-first + MRU + release date, showing 6 collapsed items by default with persistent vendor/keyword search and chevron-only expansion
|
||||
- `Tool Calls`: dropdown for WebSearch (including keyless SearXNG) and OCR
|
||||
- **AI Advisor (`/advisor/*`)**:
|
||||
- `Playground` (`/advisor/playground`): pure-chat debugging workbench defaulting to `default.general`; supports `/bgp-brief`, `/alerts-brief`, `/situational-brief`, and `/locate` slash commands plus a **Client-Owned Local Context Drawer** (reads browser `localStorage`, same-origin Earth IndexedDB sessions, or pasted `planet.earth_context.v1` JSON exported from Earth Copilot without forcing backend persistence unless explicitly saved as a workflow fixture)
|
||||
- `Workflows & Nodes` (`/advisor/workflows`): `@xyflow/react` canvas for all 9 built-in workflows (`default.general`, `earth.copilot.chat`, `earth.news.enrich`, `earth.news.analysis`, `location.resolve_unknown`, `ops.bgp_brief`, `ops.alerts_brief`, `ops.situational_alerts_brief`, `collection.mapping_and_guide`) supporting prompts, allowlisted tools, guardrails, draft/publish/rollback revisions, run trace replay, and **AI Diff Auto-Tuning Proposals**
|
||||
- `Run History` (`/advisor/runs`): filterable audit log linking directly to canvas replay and workflow optimization
|
||||
- `Playground` (`/advisor/playground`): unified multimodal debugging workbench (images, sampled video frames, web links, JSON, and Markdown rendering) defaulting to `default.general`; supports `/bgp-brief`, `/alerts-brief`, `/situational-brief`, and `/locate` slash commands plus a Client-Owned Local Context Drawer (`localStorage`, same-origin Earth IndexedDB, or pasted `planet.earth_context.v1` JSON), and inline 👍/👎 response feedback for continuous workflow improvement.
|
||||
- `Workflows & Nodes` (`/advisor/workflows`): `@xyflow/react` visual studio for all 10 built-in workflows (including `meta.workflow_evolver`) and custom DAGs with Earth interactive bindings and revision rollback; the header **Evolution** policy popover configures global auto-optimization / meta-evolution (`off`, auto-draft, or auto-publish with 5-run canary rollback) and recent ledger entries, while the Inspector **Tuning** tab shows 0-token health metrics, active model drift alerts, per-workflow lock toggle, one-click Optimize / Adapt Model / Incubate New actions, and Fixture A/B comparison.
|
||||
- `Run History` (`/advisor/runs`): filterable audit log by workflow, status, and feedback quality, displaying model, latency, revision badges, and one-click links to canvas replay or tuning.
|
||||
|
||||
Legacy routes (`/ai/prompts`, `/ai/playground`, `/playground`, `/bgp`, `/alerts/*`, plus legacy prompts/playground query sections) automatically redirect to their new counterparts under `/advisor/*` and `/ops/monitoring`.
|
||||
Legacy routes (`/ai/prompts`, `/ai/playground`, `/playground`, `/ops/monitoring`, `/bgp`, `/alerts/*`, plus legacy prompts/playground query sections) automatically redirect to their counterparts under `/advisor/*`.
|
||||
|
||||
> The Electron Desktop Client also includes native Screen Recording (`CmdOrCtrl+Shift+F9` under the **Screen Recording** menu) with audio toggle (`recordAudio`), hide-cursor/custom cursor overlay (`recordHideCursor`), auto-save to `Videos/Planet Earth/`, and Windows portable/installer layout under `C:\Users\qklov\AppData\Local\Planet\{current,releases}`.
|
||||
> The Electron Desktop Client also includes native borderless main-frame Screen Recording (`CmdOrCtrl+Shift+F9` under the **Screen Recording** menu, preserving native Alt menu access) with audio toggle (`recordAudio`), hide-cursor/custom cursor overlay (`recordHideCursor`), auto-save to `Videos/Planet Earth/`, and Windows portable/installer layout under `C:\Users\qklov\AppData\Local\Planet\{current,releases}`.
|
||||
|
||||
### Model Providers
|
||||
|
||||
@@ -255,7 +254,6 @@ To let a regular user read developer or operations docs, add `docs_developer` or
|
||||
|
||||
- `/datasources`: source directory. The `Built-in Sources` tab can be filtered by product domain, layer/module, enabled state, last run status, whether collected records exist, and search text. With no rows selected, the primary button shows `Trigger All`; after selecting rows, it becomes `Trigger Selected N` and submits only those sources. The top-right queue button shows a queue icon when empty and a pure circular total-progress indicator while tasks exist; it opens a floating panel grouped by running, completed, failed, and skipped. Failed rows can retry, and completed rows can jump to detail. `Realtime Sources` is for AISStream / WebSocket long connections and shows connection health, stored totals, time-window counters, and Start / Stop / Reconnect actions. Endpoint/credential/header editing happens at `/collection-management -> Collectors`.
|
||||
- `/data`: collected data table — used to verify "did data arrive", "is the freshness right", "does a source emit valid records"
|
||||
- `/ops/monitoring`: consolidated operational monitoring and alerts view (system alerts, BGP incidents, anomalies, collectors with location collection, and observation events; legacy `/bgp` and `/alerts/*` routes redirect here)
|
||||
|
||||
## AI Advisor (Playground, Workflows, and Run History)
|
||||
|
||||
|
||||
@@ -493,6 +493,9 @@ The production host checks the latest stable Git tags and OCI `release-manifest:
|
||||
|
||||
A failed rollout restores the previous application images and hotfix manifest while preserving database writes. An interrupted rollout resumes recovery on the next check. A failed version waits for an explicit retry or a newer release. The most recent pre-change database backups and version records are under `/var/lib/planet-release-deploy/last-success/` and `last-failed/`. Retry after resolving the underlying error.
|
||||
|
||||
> [!WARNING]
|
||||
> **Host-managed files are NOT auto-updated by `planet-release-deploy.timer` (publishing ≠ deployed)**: The timer replaces application container digests and publishes Earth hotfixes from OCI `release-manifest:<tag>`, but does **not** overwrite host-resident `/usr/local/lib/planet-release/production_deploy.py`, `deploy/systemd/*`, `/opt/planet/current/compose*.yaml` env/mounts, or host Nginx configs. Whenever a release modifies those files and deployment (`部署` / `发版部署`) is requested, sync the changed host files before rolling out or running `--retry` (so stale host verification logic such as new 401 auth gates cannot trigger a false-positive rollback), then verify live container digests plus `https://api.rclaw.top/health/ready` and `https://rclaw.top/api/v1/client/update-manifest`.
|
||||
|
||||
```bash
|
||||
systemctl list-timers planet-release-deploy.timer
|
||||
journalctl -u planet-release-deploy.service -n 40
|
||||
|
||||
@@ -38,7 +38,7 @@ After landing on the `/admin` dashboard, here's a recommended walk-through:
|
||||
2. `/ai?section=integrations`: fill an LLM provider (e.g. `minimax` / `openai`), model, base URL, API key, and click the plug at the end of the base URL to check the model catalog (official keyless providers fall back to public aggregator catalogs sorted selected-first + MRU + release date with a collapsible 6-item list); verify generation in `/advisor/playground` and edit node workflows in `/advisor/workflows`. Optional WebSearch / OCR tools live under `/ai?section=tools`
|
||||
3. `/earth-content?section=brand`: maintain the Earth HUD logo and title image in Branding. The Upload button inside each URL field opens a file picker, and image files can also be dropped directly onto the matching field. Save the brand configuration after upload
|
||||
4. `/datasources` or `/data`: check whether collectors have produced data. Use `/datasources -> Built-in Sources` for finite collectors: with no rows selected, click `Trigger All`; after selecting rows, the primary button becomes `Trigger Selected N`. The top-right queue button shows progress. Use `/datasources -> Realtime Sources` for AISStream / WebSocket health and counters
|
||||
5. `/ops/monitoring`: inspect system alerts, BGP incidents/anomalies/events, and collector health
|
||||
5. `/advisor/playground`: chat with AI Advisor or run `/bgp-brief` / `/alerts-brief` for BGP posture and collection-health briefings (live BGP layers render on `/earth`)
|
||||
6. `/users` (super_admin only): open accounts for teammates or adjust their groups (or issue scoped `X-API-Key` tokens in `/settings` and grant `api_access` for external/UE5 API consumers)
|
||||
|
||||
## 4. Open Earth
|
||||
|
||||
@@ -132,15 +132,32 @@ AI 配置页使用的接口:
|
||||
|
||||
完整分页和重试受 30 秒总超时保护;网络故障及 502/503/504 最多尝试两次,鉴权失败不重试。按接口提供的创建/发布日期倒序排列;日期相同时保留上游顺序,不截断为固定数量。公共目录只表示供应商公开的模型集合,不代表账号已获得每个模型的生成权限。
|
||||
|
||||
Admin 的 AI 页面已按基础设施与参谋编排拆分为两组信息架构:
|
||||
Admin 的 AI 页面已按模型配置与参谋编排拆分为两部分:
|
||||
|
||||
- **运维与配置 → AI 基础设施 (`/ai`)**:
|
||||
- **运维与配置 → AI (`/ai`)**:
|
||||
- `模型供应商`:管理 provider、协议适配、默认模型、LLM API Key、代理地址、代理 token、模型列表刷新(无 Key 官方源回退公共聚合目录,按「已选优先 + 最近使用 + 发布时间」排序并折叠展示 6 项)、设为默认和轻量连通性测试。
|
||||
- `工具调用`:管理 WebSearch(支持免 Key 的 SearXNG 等)和 OCR 等工具配置。
|
||||
- **AI 参谋 (`/advisor/*`)**:
|
||||
- `Playground` (`/advisor/playground`):纯净对话调试台,默认 `default.general`,支持斜杠简报指令及客户端自持的本地地球上下文抽屉(`planet.earth_context.v1` / 同源 IndexedDB / `localStorage`)。
|
||||
- `工作流与节点` (`/advisor/workflows`):管理全站 9 条内建工作流的 `@xyflow/react` 节点图(提示词、工具白名单、护栏、`Draft / Publish / Rollback` 版本历史与受白名单约束的 AI Diff 调优提案)。
|
||||
- `运行记录` (`/advisor/runs`):审计每次对话、地球 Copilot 与位置 Agent 的执行轨迹。
|
||||
- `Playground` (`/advisor/playground`):统一多模态对话调试台(文本、图片、视频关键帧、SSRF 安全隔离外链、JSON 及自动识别地球上下文),支持斜杠简报/定位指令、Markdown 渲染以及助手回复行内 👍/👎 反馈采集(写入 `WorkflowRun.budget_used`)。
|
||||
- `工作流与节点` (`/advisor/workflows`):基于 `@xyflow/react` 编排全站 10 条内建工作流(含 `meta.workflow_evolver` 自进化元引擎)及自定义工作流,支持多节点 DAG 流式执行(`dag_executor.py`)、地球交互绑定(`bindings`)、`Draft / Publish / Rollback` 版本历史,以及三层有界自进化/元进化控制与 Fixture A/B 样本对照。
|
||||
- `运行记录` (`/advisor/runs`):记录模型、耗时、版本号与赞踩评价,支持按质量筛选并一键跳转画布回放或带轨迹调优。
|
||||
|
||||
### 三层工作流自进化与元进化
|
||||
|
||||
后端 [workflow_evolver.py](/home/ray/dev/linkong/planet/backend/app/services/ai/workflow_evolver.py) 在 **零新增数据库表/零迁移脚本** 的前提下,复用 `ai_workflows`、`ai_workflow_revisions`、`ai_workflow_fixtures`、`workflow_runs.budget_used` 与 `system_settings`(`ai_evolution_policy`、`ai_evolution_ledger`)实现有界自举:
|
||||
|
||||
- **Tier 0(Python 不可变宪法内核)**:强制校验 DAG 无环与入口/输出保留、禁止清空 `system_prompt`、禁止使用非白名单工具、限制自动变更半径(单次 `<= 2` 个且 `<= 40%` 节点)、永久冻结元引擎 `verify_output` 节点、禁止自定义 `meta.*` 命名空间(单层元递归锁)、按 `24h / 7d` 冷却与每日自动预算加锁,并在自动发布后启动 **5 次运行灰度观察窗**(连续 2 次失败或差评/失败率超阈即自动回滚,元引擎自身受下游 3 次结果窗口自动回退保护)。
|
||||
- **Tier 1(业务自优化与模型漂移适配)**:`GET /api/v1/ai/evolution/health/{workflow_id}` 执行 0-Token 健康度与活跃模型能力漂移诊断并计算 DGM 历史最佳父版本;`POST /api/v1/ai/evolution/propose/{workflow_id}` 结合 `meta.workflow_evolver` 线上发布的 `diag_node` / `patch_node` 提示词及历史进化台账正负经验产出补丁;`POST /api/v1/ai/evolution/eval/{workflow_id}` 与 `POST /api/v1/ai/evolution/incubate` 分别支持样本 A/B 对照与从 `default.general` 高频提问孵化新工作流。运行完成后通过 `schedule_post_run_evolution` 异步非阻塞检查灰度与冷却条件。
|
||||
- **Tier 2(元进化 & 可扩展注册表)**:`POST /api/v1/ai/evolution/meta-evolve` 按独立开关(`off | draft | auto`)迭代 `meta.workflow_evolver` 提示词策略;同时通过 `EvolutionSignalDetector`(`SIGNAL_DETECTORS`)与 `EvolutionEvaluator`(`EVALUATORS`)协议方便后续扩展新探针或评测器。
|
||||
- **进化安全约束(v0.82.0 复核后补强)**:
|
||||
- **允许「无需修改」**:模型返回合法的空 `node_patches` 时本轮以 `applied_status: no_change` 正常结束,不生成新版本与台账;确定性兜底仅在检测到真实信号(失败/差评/模型能力不匹配/管理员指令/台账结果)时才出补丁,不再追加泛化提示词。
|
||||
- **可判对错的 A/B 样本**:样本可在 `POST /api/v1/ai/workflows/{id}/fixtures` 的 `expect` 中声明 `numbers`、`must_include`、`must_not_include`、`require_uncertainty_without_evidence`、`min_evidence`(存于 `context_json.expect`);评测同时判定执行错误、护栏校验与断言,任一样本在候选版本上由通过变失败即判 `regressed`。**自动发布前强制执行 A/B 门禁**:没有样本、样本无断言或存在退化都会拦截发布。
|
||||
- **以线上版本为基线**:后台/自动发布进化始终基于当前生效版本生成候选,不读取也不清空未发布的人工草稿(自动草稿模式遇到人工草稿直接跳过),台账 `changes_vs_live` 记录候选相对线上版本的完整差异,自动发布变更半径也按完整差异计算。
|
||||
- **灰度防覆盖**:灰度结算前核对当前生效版本仍是本轮灰度目标,若已被人工发布或回滚取代则标记 `superseded` 且不回滚(元引擎灰度同理)。
|
||||
- **元进化字段必须生效**:元进化仅允许修改 `diag_node.system_prompt / prompt` 与 `patch_node.system_prompt / prompt / thinking_enabled`,这些字段都会进入业务进化请求(`build_business_evolution_request`);元进化默认保持关闭。
|
||||
- **地球工作流取数、证据与卡片输出**:`dag_executor.py` 按实体类型为每个数据源选取各自对象 ID(多选海缆/船舶/BGP 时与点击顺序无关);`interactive / ingest` 边按实际触发来源路由(前台新闻分析不再执行后台汉化分支);`compute.posture.brief` 等严格 JSON 节点以非流式执行,经 `StrategicPostureBrief` 与证据 ID 核验后渲染为正文,并在输出节点编译算力 `view_spec` 工作台(通过收尾 `meta` 事件与 `done.view_spec` 下发);`require_evidence` 护栏未通过时向用户追加「原因待核实」与待查项,`done.status` 记为 `unverified` 并附 `verification`。
|
||||
- **草稿绑定隔离**:草稿中的地球入口绑定保存在 `draft_graph.bindings`(详情返回 `draft_bindings`),仅在发布时生效、丢弃草稿即恢复;每个发布版本的 `graph_json.bindings` 同时快照绑定,回滚时一并恢复。「仅保存绑定」(`PATCH /workflows/{id}`)仍为即时生效的显式操作。
|
||||
- **反馈与运行记录接口**:`POST /api/v1/ai/runs/{run_id}/feedback`(提交 `-1 | 0 | 1` 评价与原因备注,差评实时复核灰度健康)与 `GET /api/v1/ai/runs?feedback=negative|positive`;战略策略与台账维护由 `GET/PUT /api/v1/ai/evolution/policy`、`GET /api/v1/ai/evolution/ledger` 与 `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss` 提供。
|
||||
|
||||
保存、设为默认和连通性测试是三个独立职责:保存只持久化表单,设为默认只切换默认 provider/tool,连通性测试只验证当前草稿是否可用,不应隐式保存或切换默认项。
|
||||
|
||||
|
||||
@@ -433,7 +433,7 @@ asset 图标大小由 `Interactable` 的 `icon.fitSize` 控制。SVG / 图片文
|
||||
|
||||
跨 Interactable 的同坐标关系也在公共层记录,但真实位置必须始终以 `icon_base_position` 为准。缩放、避让、聚合和后续 spiderfy 展开都只能改变屏幕表现,不能写回 `marker.position` 或 `THREE.Points` 里的业务锚点;巡航定位、详情卡、搜索定位和 picking 返回对象都必须落回真实经纬度。多个图标归入同一个经纬度 key 时,公共层只写 `icon_avoidance_*` 元数据,供业务层弱化 halo 或显示聚合提示;真正的低缩放聚合应通过独立 cluster glyph / screen layout 层实现,而不是把对象沿地表切平面挪开。
|
||||
|
||||
地表标记保留分类图标,聚合使用固定地理成员及带数量的实心圆。缩放只驱动 320ms 展开/收拢补间,不重新分档聚类;超过 250% 展开,500% 无聚合圆标。船只关闭聚合,保留独立航向箭头。实现与验收见 [聚合说明](/home/ray/dev/linkong/planet/docs/technical/zh/earth-interactable-clustering.md)。
|
||||
地表标记保留分类图标,聚合使用固定地理成员及 `28px` 深色半透明内核搭配分色外环的圆形徽标。缩放只驱动 320ms 展开/收拢补间,不重新分档聚类;超过 250% 展开,500% 无聚合圆标。船只关闭聚合,保留独立航向箭头。实现与验收见 [聚合说明](/home/ray/dev/linkong/planet/docs/technical/zh/earth-interactable-clustering.md)。
|
||||
|
||||
接口细节、生命周期和接入示例见:
|
||||
|
||||
@@ -641,7 +641,7 @@ Earth 由 `earth-runtime-plugin.mjs` 将本地模块合并为带内容哈希的
|
||||
|
||||
### 聚合圆标与 Spiderfy
|
||||
|
||||
普通地表标记继续由 `interactable.js` 批量绘制;聚合组使用 `cluster-presentation.js` 的同一组投影节点贯穿合并、展开和展开后停留。圆标为 26px 实心渐变圆,显示真实成员数,混合类别带琥珀外圈。分组只随数据或筛选更新,缩放过程中不反复拆成中间子簇。
|
||||
普通地表标记继续由 `interactable.js` 批量绘制;聚合组使用 `cluster-presentation.js` 的同一组投影节点贯穿合并、展开和展开后停留。圆标统一采用 `28px` 深色半透明玻璃内核与白字计数,单类别使用 `2.5px` 纯色圆环,混合类别由 `buildClusterRingGradient` 生成按占比分段(带 `4°` 深色分隔与最小可见扇区下限)的 `conic-gradient` 多色圆环,并通过 `formatClusterTitle` 输出本地化大类/子类别明细。分组只随数据或筛选更新,缩放过程中不反复拆成中间子簇。
|
||||
|
||||
`cluster-motion.js` 用固定 320ms 三次缓动控制进度。可见图标准备和解码完成后才开始计时,纹理编码按缓存复用;子点从组中心补间到真实标记投影,最终显示偏移由 `marker-stack.js` 统一计算。动画与终点保持同一个 DOM 节点,反向切换从当前进度续接。
|
||||
|
||||
@@ -748,3 +748,14 @@ BGP 观测站以 collector 编号建立标记索引。共享索引不登记空 I
|
||||
|
||||
- `compute-site-types.js` 为 `supercomputer`、`gpu_cluster`、`data_center`、`cloud_center`、`edge_node` 提供差异化配色与图例辨识;
|
||||
- `satellites.js` 支持卫星高度压缩滑块(`altitudeCompression`)、短彗尾轨迹效果与基于 GPU 顶点属性(`twinklePhase` / `twinkleShape`)的闪烁强度调节,并移除了非 Starlink 星座的冗余地表覆盖开关以保持图面洁净。
|
||||
|
||||
### 动态工作流绑定、桌面无边框录屏与双语对齐
|
||||
|
||||
- `workflow-bindings.js` 拉取 `/api/v1/earth/workflow-bindings` 发布的白名单工作流绑定,依据当前选中实体类型与交互界面位面(信息卡、新闻卡、算力专题卡、Copilot 快捷动作与多选对比托盘)动态渲染专项分析动作。
|
||||
- Electron 客户端 `screen-recorder.ts` 以 `win.webContents.mainFrame` 捕获无边框纯净画面并保持 Windows 原生 Alt 菜单兼容;`i18n.js` 与 `index.html` 对齐 `zh-CN` / `en-US` 纯净语种映射并同步管理台语言偏好。
|
||||
|
||||
### 贴地影响范围、三维视觉升级与优先一折连线(v0.83.0)
|
||||
|
||||
- **贴地影响范围与阶段导演指令**(`influence-zones.js` + `scene_directives.py`):支持 AI / 场景指令下发 `influence_zones`(国家/区域预设多边形及大圆辐射区),通过单次离屏 `scratchCanvas` 模糊合成与层级排序(`tier` / `z_index`)渲染可配置颜色、透明度、`edge_mode`(`sharp` / `soft`)及入场扫光;保持 `renderOrderBase = 0.965`,位于高清地表之上、国界与交互图标之下。
|
||||
- **行星本体光影与丝带管线**:`earth-surface-material.js` 与 `earth.js` 结合本地 `earth_clouds_2048.png` 实现三阶瑞利散射晨昏过渡、海面掠射高光与地表云影投影;`surface-ribbon.js` 为国界 hover、BGP 雷达/高空路由、选中海缆流光、船舶尾迹及选中卫星轨道提供统一屏幕空间抗锯齿发光丝带;`iridium-footprint-adapter.js` 将 Iridium 足迹迁入 GPU 顶点投影。
|
||||
- **卡片连线优先一折与管理写鉴权**:`callout-connector.js`(`applyPreferredOneBendAnchor`)在主轴跨度与卡片可用边长充足时优先偏出单一折点(严格保持 `<= 1` 折,短距或紧凑胶囊平滑退化为 2 点直线);`admin-write-auth.js` 统一管控 Earth 侧算力中心位置采集与保存的管理员会话鉴权及 `/login` 引导。
|
||||
@@ -1,6 +1,6 @@
|
||||
# 智能星球可交互图标聚合
|
||||
|
||||
`interactable.js` 负责固定地理成员,`cluster-motion.js` 负责时间补间,`cluster-presentation.js` 负责圆形聚合、展开图标、拾取与 Spiderfy。普通独立标记继续使用 GPU Points;聚合成员从动画开始到终点由同一 DOM 图标显示,不再切回另一套位置。
|
||||
`interactable.js` 负责固定地理成员,`cluster-motion.js` 负责时间补间,`cluster-presentation.js` 负责 `28px` 深色玻璃内核搭配 `2.5px` 纯色或按子类别占比分段的 `conic-gradient` 圆环聚合徽标、展开图标、拾取与 Spiderfy。普通独立标记继续使用 GPU Points;聚合成员从动画开始到终点由同一 DOM 图标显示,不再切回另一套位置。
|
||||
|
||||
## 成员与缩放
|
||||
|
||||
|
||||
@@ -21,8 +21,10 @@
|
||||
| 0 | 智能星球基座球 | `earth.js` | `CONFIG.earthRadius` | 地表拾取兜底目标 | 深色基座,所有可选地图层关闭时仍可见。 |
|
||||
| 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset = 0.32`,与海陆填色共用网格及半径 | depthTest=true、depthWrite=false,禁用 raycast | 加载占位及高清材质关闭时使用;填色就绪后按 renderOrder 覆盖。 |
|
||||
| 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 |
|
||||
| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距。 |
|
||||
| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3 | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照并入高清地表,不新增全屏后处理。 |
|
||||
| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距;支持三阶瑞利散射晨昏过渡与海面掠射光。 |
|
||||
| 0.962 | 云影投影球壳 | `earth.js` | 与高清材质共用球半径、微角偏移 | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 随大气云图开关联动,基于 `earth_clouds_2048.png` 投射柔和地表云影,严格位于 `0.96` 之上、`0.965` 之下。 |
|
||||
| 0.965 | 贴地影响范围层 | `influence-zones.js`, `scene_directives.py` | 复用 `r = 100.48`(`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`)`128×128` 球壳;`renderOrderBase = 0.965`,按 `tier` / `z_index` 递增 `0.0003` | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 支持区域预设单次离屏模糊合成与圆形大圆距离片元着色,严格压在 `0.96` 高清地表之上且低于国界线 `0.97` 与全部交互图标。 |
|
||||
| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3(`FrontSide` Shader + `earth_clouds_2048.png`) | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照与 Mie 前向散射并入高清地表与大气壳,不新增全屏后处理。 |
|
||||
| 1 | 海缆 / 登陆点 | `cables.js`, `cable-batches.js` | 海缆全量线段合并为一个 `LineSegments`;登陆点全量使用实例化 billboard;`renderOrder = 1`、海缆与登陆点统一使用高清地表 `0.48` 偏移和同源三角表面坐标 | 原始 `Line` / `Sprite` 仅作为逐项拾取和选择状态对象,材质不再单独绘制;登陆点仍按球体遮挡判断背面可见性,批量材质 `depthTest: false` | 样式通过线缆样式纹理和登陆点实例属性同步;保留颜色、脉冲、尺寸、显隐与点击语义。 |
|
||||
| 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 |
|
||||
| 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 |
|
||||
@@ -110,4 +112,4 @@ Earth 的地表不是单一 mesh,而是多层近似同心球:基座球、海
|
||||
|
||||
区域新闻与算力保留 `#earth-region-callouts` 根节点(z-index 20),并与物件详情共享 `callout-stage-arbitrator.js` 的左右侧及纵向走廊;中美双主舞台对比卡通过 `bilateralPeerKey` 对称分配左右走廊。区域根内展开卡片为 50、拖拽前景为 55,悬停展开层为 60–65;普通胶囊为 30,背面胶囊为 8 并渐淡缩小,而主舞台及悬停展开卡在背面时保持正文 100% 不透明,仅将连线切换为 `.is-rear` 虚线边缘引导并激活标题栏“转至正面视角”按钮。
|
||||
|
||||
算力专题下钻图层与逻辑路由演出弧线严格遵守同心壳深度与合批规则:中国“东数西算”八大国家算力枢纽复用 `createInteractableLayer` 单次实例化合批,贴地偏移为 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`、`renderOrder = 4.58`;西部绿电枢纽双环 `AdditiveBlending` 脉冲环 `renderOrder = 4.42`(`depthWrite: false`),东西部协同弧线合批为单次 `LineSegments`(`renderOrder = 4.55`,顶点抬升高于球面壳避免远景 z-fighting);BGP 舞台回放逻辑 AS 路由弧线以高空虚线/实线绘制(`renderOrder = 4.72` / `4.76`),退出或隐藏图层时立即 `dispose()` 几何与材质。
|
||||
算力专题下钻图层与逻辑路由演出弧线严格遵守同心壳深度与合批规则:中国“东数西算”八大国家算力枢纽复用 `createInteractableLayer` 单次实例化合批,贴地偏移为 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`、`renderOrder = 4.58`;西部绿电枢纽双环 `AdditiveBlending` 脉冲环 `renderOrder = 4.42`(`depthWrite: false`),东西部协同弧线与高空 BGP 逻辑路由、国界 hover、选中海缆流光、船舶尾迹及选中卫星轨道共用 `surface-ribbon.js` 屏幕空间抗锯齿发光丝带底层(摆脱 Windows ANGLE 下 `THREE.Line` 1px 限制),Iridium 足迹通过 `iridium-footprint-adapter.js` 迁入 GPU 顶点投影;退出或隐藏图层时立即 `dispose()` 几何与材质。
|
||||
@@ -35,14 +35,13 @@
|
||||
- `/advisor/playground`
|
||||
- `/advisor/workflows`
|
||||
- `/advisor/runs`
|
||||
- `/ops/monitoring`
|
||||
- `/ai`
|
||||
- `/earth-content`
|
||||
- `/collection-management`
|
||||
- `/settings`
|
||||
- `/logs`
|
||||
|
||||
(旧 `/bgp`、`/alerts/*`、`/ai/prompts`、`/ai/playground` 作为 `<Navigate replace />` 兼容重定向保留。)
|
||||
(旧 `/ops/monitoring`、`/bgp`、`/alerts/*`、`/ai/prompts`、`/ai/playground` 作为 `<Navigate replace />` 兼容重定向至 `/advisor/*` 保留。)
|
||||
|
||||
这些路径渲染 [AdminRoutes.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/AdminRoutes.tsx),页面清单和菜单元信息来自 [manifest.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/routes/manifest.tsx)。控制台是唯一后台入口,不再维护并行控制台或回退路由。
|
||||
|
||||
@@ -301,7 +300,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
`App.tsx` 用它判断是否进入登录页。`/docs` 仍是公开路由,但目录和正文由后端按 token 决定;未登录时只返回公开文档。
|
||||
|
||||
### 2. AI 基础设施与 AI 参谋
|
||||
### 2. AI 与 AI 参谋
|
||||
|
||||
文件:
|
||||
|
||||
@@ -312,12 +311,12 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
职责:
|
||||
|
||||
- `/ai` 收口为 **AI 基础设施**(仅保留 `模型供应商` 与 `工具调用` 两个分区),不再承担 `提示词` 与 `Playground`;旧参数 `prompts`、`playground` 自动跳转至 `/advisor/workflows` 与 `/advisor/playground`
|
||||
- `模型供应商` 分区支持免 Key 官方供应商的公共聚合目录回退、「已选优先 + 最近使用 + 发布时间」排序与默认 6 项折叠预览、自定义 `<Select>` 与深色数字步进控件,以及左侧栏按当前激活分组自动保持展开
|
||||
- `/ai` 收口为 **AI**(保留 `模型供应商` 与 `工具调用` 两个分区),不再承担 `提示词` 与 `Playground`;旧参数 `prompts`、`playground` 自动跳转至 `/advisor/workflows` 与 `/advisor/playground`
|
||||
- `模型供应商` 分区支持免 Key 官方供应商的公共聚合目录回退、「已选优先 + 最近使用 + 发布时间」排序与默认 6 项折叠预览、纯箭头展开与展开后自动下滚聚焦、常驻厂商/关键词筛选、自定义 `<Select>` 与深色数字步进控件,以及左侧栏按当前激活分组自动保持展开
|
||||
- `工具调用` 分区先选择工具(WebSearch 含免 Key 的 SearXNG / OCR),再管理对应 API 与开关状态;未启用时除开关外的配置项和测试入口置灰
|
||||
- `/advisor/playground` 为纯净对话调试台,配备客户端本地上下文抽屉(同源 IndexedDB + `localStorage` + `planet.earth_context.v1` JSON 导入/挂载,可选保存为样本)与斜杠简报指令
|
||||
- `/advisor/workflows` 采用三栏单屏 `@xyflow/react` 画布,编辑 9 条内建工作流节点提示词、白名单工具、护栏、版本回滚与 AI Patch Diff 提案预览
|
||||
- `/advisor/runs` 与 `/ops/monitoring` 分别承接运行审计轨迹与合并后的系统/BGP 原始观测告警
|
||||
- `/advisor/playground` 为统一多模态对话调试台(支持图片/视频采样/网页链接/JSON、Markdown 渲染、客户端本地上下文抽屉与 👍/👎 运行质量反馈)
|
||||
- `/advisor/workflows` 采用三栏单屏 `@xyflow/react` 画布,编辑 10 条内建工作流(含 `meta.workflow_evolver` 元引擎)与自定义工作流节点提示词、白名单工具、地球交互绑定、版本回滚,并提供懒加载的顶栏「自进化策略」弹窗及检查器「调优」0-Token 健康/漂移面板与 Fixture A/B 样本对照
|
||||
- `/advisor/runs` 承接运行审计轨迹(展示版本号、模型、耗时与赞踩反馈筛选)与画布回放;控制台与 AI 参谋全部界面文案已完成中英文隔离与自动隐藏 `<Scrollbar>` 统一。旧 `/ops/monitoring`、`/bgp` 与 `/alerts/*` 已合并重定向至 `/advisor/playground`,BGP 实时空间图层仍在 `/earth` 展示。
|
||||
|
||||
旧路径 `/playground`、`/bgp`、`/alerts/*` 仅保留 `<Navigate replace />` 兼容重定向。
|
||||
|
||||
|
||||
+10
-12
@@ -76,8 +76,7 @@
|
||||
| Playground | `/advisor/playground` | AI 参谋纯净对话调试台与本地上下文抽屉 |
|
||||
| 工作流与节点 | `/advisor/workflows` | `@xyflow/react` 9 条工作流节点编排、修订历史与 AI Diff 调优 |
|
||||
| 运行记录 | `/advisor/runs` | AI 工作流运行轨迹审计与画布回放 |
|
||||
| 告警与观测 | `/ops/monitoring` | 集中查看系统告警、BGP 事故/异常/观测事件与采集器健康度 |
|
||||
| AI 基础设施 | `/ai` | 模型供应商与 WebSearch/OCR 工具凭据配置 |
|
||||
| AI | `/ai` | 模型供应商与 WebSearch/OCR 工具凭据配置 |
|
||||
| 智能星球内容 | `/earth-content` | 电视直播、国界精度、底图和图层资源入口 |
|
||||
| 采集管理 | `/collection-management` | 采集器、采集调度、采集历史入口 |
|
||||
| 系统日志 | `/logs` | 通常仅 super admin 可见 |
|
||||
@@ -147,21 +146,21 @@
|
||||
- `累计入库`、`近 24h`、`近 1h` 和 `唯一 MMSI` 用于判断历史采集量
|
||||
- 如果显示 `disconnected` 且有最近错误,可以点击 `重连`
|
||||
|
||||
## 配置 AI 基础设施与使用 AI 参谋
|
||||
## 配置 AI 与使用 AI 参谋
|
||||
|
||||
`/ai?section=integrations`(**AI 基础设施**)用于维护模型供应商与外部工具凭据,`/advisor/playground`、`/advisor/workflows` 与 `/advisor/runs`(**AI 参谋**)负责纯对话调试、节点编排与审计:
|
||||
`/ai?section=integrations`(**AI**)用于维护模型供应商与外部工具凭据,`/advisor/playground`、`/advisor/workflows` 与 `/advisor/runs`(**AI 参谋**)负责纯对话调试、节点编排与审计:
|
||||
|
||||
- **AI 基础设施 (`/ai`)**:
|
||||
- `模型供应商`:默认 LLM provider、模型、Base URL、API Key、本地 `aiprovider` 代理和连接测试;未填 Key 的主流官方供应商(含 GLM、Meta、Gemini、Grok、DeepSeek、OpenAI、MiniMax 等)可免 Key 刷新公共聚合目录并按已选优先/最近使用排序、默认折叠展示 6 项
|
||||
- **AI (`/ai`)**:
|
||||
- `模型供应商`:默认 LLM provider、模型、Base URL、API Key、本地 `aiprovider` 代理和连接测试;未填 Key 的主流官方供应商(含 GLM、Meta、Gemini、Grok、DeepSeek、OpenAI、MiniMax 等)可免 Key 刷新公共聚合目录并按「已选优先 + 最近使用」排序,默认折叠展示 6 项,下拉厂商/关键词常驻可见并支持一键展开查看更多。
|
||||
- `工具调用`:通过下拉菜单选择具体工具,当前支持 WebSearch(含免 Key 的 SearXNG)和 OCR
|
||||
- **AI 参谋 (`/advisor/*`)**:
|
||||
- `Playground` (`/advisor/playground`):纯净对话调试台,默认绑定 `default.general` 通用参谋工作流;支持 `/bgp-brief`、`/alerts-brief`、`/situational-brief`、`/locate` 等斜杠简报/定位指令,并自带 **客户端本地上下文抽屉**(直读同源 Earth IndexedDB 会话与浏览器 `localStorage`,也可粘贴桌面端导出的 `planet.earth_context.v1` JSON;只有显式点击「保存为工作流样本」才会写入工作流测试样本表)
|
||||
- `工作流与节点` (`/advisor/workflows`):基于 `@xyflow/react` 可视化编排 9 条内建工作流(`default.general`、`earth.copilot.chat`、`earth.news.enrich`、`earth.news.analysis`、`location.resolve_unknown`、`ops.bgp_brief`、`ops.alerts_brief`、`ops.situational_alerts_brief`、`collection.mapping_and_guide`),编辑各节点提示词、白名单工具、模型覆盖与护栏,支持草稿、发布回滚、运行轨迹画布回放以及「AI Diff 自动调优提案」
|
||||
- `运行记录` (`/advisor/runs`):审计每次参谋对话、地球 Copilot 与位置 Agent 的执行链路并一键跳至画布回放
|
||||
- `Playground` (`/advisor/playground`):统一多模态对话调试台(支持图片、视频采样帧、外链与 JSON,以及 Markdown 渲染),默认绑定 `default.general` 通用参谋工作流;支持 `/bgp-brief`、`/alerts-brief`、`/situational-brief`、`/locate` 等斜杠简报/定位指令,并提供客户端本地上下文抽屉(直读同源 Earth IndexedDB 会话与浏览器 `localStorage`,或自动识别粘贴的 `planet.earth_context.v1` JSON;只有显式点击「保存为工作流样本」才会写入测试样本表)。每条助手回复右下角支持 👍/👎 反馈并补充原因备注,用于持续改进工作流质量。
|
||||
- `工作流与节点` (`/advisor/workflows`):基于 `@xyflow/react` 可视化编排 10 条内建工作流(含 `meta.workflow_evolver` 自进化元引擎)及自定义工作流,编辑提示词、白名单工具、地球交互绑定与护栏,支持草稿/发布/回滚。顶栏「自进化策略」可配置全局自动优化与元进化模式(关闭 / 自动草稿 / 自动发布 + 5 次运行灰度回滚)及近期 50 条进化台账;检查器「调优」页签提供 0-Token 健康度诊断、活跃模型切换漂移提示、工作流防自动改锁定开关、一键优化/适配模型/孵化新工作流以及样本 A/B 对照。
|
||||
- `运行记录` (`/advisor/runs`):支持按工作流、运行状态与赞踩反馈筛选,审计模型、耗时、版本号、轨迹并一键跳转画布回放或带记录调优。
|
||||
|
||||
旧路径 `/ai/prompts`、`/ai/playground`、`/playground` 以及旧的 prompts / playground 查询参数会自动重定向到新的 `AI 参谋` 页面。
|
||||
|
||||
> 桌面客户端内置录屏能力(`12a478a9`):在桌面端菜单栏「录屏 / Screen Recording」中可使用 `CmdOrCtrl+Shift+F9` 启停录屏,支持勾选「录制声音」与「隐藏光标 / 自定义光标浮层」,录制完成后自动保存至系统 `Videos/Planet Earth/` 并提供一键打开目录。Windows 本地安装约定位于 `C:\Users\qklov\AppData\Local\Planet\current` 与 `releases\`。
|
||||
> 桌面客户端内置录屏能力:在桌面端菜单栏「录屏 / Screen Recording」中可使用 `CmdOrCtrl+Shift+F9` 启停无边框主画面录屏(支持原生 Alt 菜单),支持勾选「录制声音」与「隐藏光标 / 自定义光标浮层」,录制完成后自动保存至系统 `Videos/Planet Earth/` 并提供一键打开目录。Windows 本地安装约定位于 `C:\Users\qklov\AppData\Local\Planet\current` 与 `releases\`。
|
||||
|
||||
### 模型供应商
|
||||
|
||||
@@ -190,7 +189,7 @@ Base URL 输入框尾端的插头图标会触发轻量连接测试:检查代
|
||||
|
||||
进入 `/advisor/workflows` 选择具体工作流与节点,可在右侧检查器修改 `System Prompt`、`Prompt`、授权工具白名单与护栏 JSON;保存为草稿可先在 Playground 验证,点击「发布生效」即写入不可变版本历史并支持一键回滚。
|
||||
|
||||
旧的 `/bgp`、`/alerts/system`、`/alerts/bgp` 与 `/alerts/situational` 已合并收敛为 `/ops/monitoring`(**运维与配置 → 告警与观测**),访问旧链接会自动跳转。
|
||||
旧的 `/ops/monitoring`、`/bgp`、`/alerts/system`、`/alerts/bgp` 与 `/alerts/situational` 已收口进 **AI 参谋**(`/advisor/playground` `/bgp-brief` 与 `/alerts-brief`),原实时 BGP 图层直接在 `/earth` 查看;访问旧链接会自动跳转。
|
||||
|
||||
## 系统设置
|
||||
|
||||
@@ -256,7 +255,6 @@ Base URL 输入框尾端的插头图标会触发轻量连接测试:检查代
|
||||
|
||||
- `/datasources`:数据源目录。`内置源` 支持按产品域、层级、启用状态、最近执行状态、是否已有采集数据和关键词筛选;未勾选时主按钮显示“触发全部”,勾选多行后会变成“触发已选 N”,并只提交所选数据源。右上角队列按钮空态显示队列图标,有任务时显示纯圆环总进度;点击后打开队列浮层,按运行中、完成、失败和跳过分组,失败项可重试,完成项可跳到详情或按任务编号打开系统日志。`实时源` 面向 AISStream / WebSocket 长连接,展示连接健康、累计入库、时间窗统计和启动 / 停止 / 重连操作。接口、凭证、请求头的编辑统一在 `/collection-management` 的"采集器"。
|
||||
- `/data`:采集后数据表,适合排查"数据是否已经进入系统"、"更新时间是否符合预期"、"某个数据源是否产出有效记录"
|
||||
- `/ops/monitoring`:统一的运维告警与 BGP 观测台,包含系统告警、BGP 事故、BGP 异常、BGP 采集器(含位置采集)与 BGP 观测事件(原 `/bgp`、`/alerts/*` 自动跳转至此)
|
||||
|
||||
## AI 参谋(Playground、工作流与运行审计)
|
||||
|
||||
|
||||
@@ -493,6 +493,9 @@ python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)"
|
||||
|
||||
上线失败时,服务恢复上一版的镜像摘要和热更新清单,保留数据库里的业务写入。事务记录在重启后仍可恢复。失败的版本会暂停自动重试,较新的正式版仍可上线。`/var/lib/planet-release-deploy/last-success/` 和 `last-failed/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。
|
||||
|
||||
> [!WARNING]
|
||||
> **宿主机文件不会随发版镜像自动更新(发版 ≠ 已部署)**:`planet-release-deploy.timer` 只按 OCI manifest 替换应用容器镜像与发布 Earth 热更包,**不会**自动覆盖宿主机上的 `/usr/local/lib/planet-release/production_deploy.py`、`deploy/systemd/*`、`/opt/planet/current/compose*.yaml`(如新增环境变量或挂载)以及宿主机 Nginx 配置。每次改动这些文件并要求“部署 / 发版部署 / 上线”时,务必先按下方安装命令同步宿主机对应文件,再执行 `--retry` 或重启服务,否则旧版 `production_deploy.py` 可能按过时验收规则(例如新增鉴权后返回 `401`)误判失败并自动回退;完成后还应校验目标容器镜像摘要与公网 `/health/ready`、`/api/v1/client/update-manifest` 版本号。
|
||||
|
||||
```bash
|
||||
systemctl list-timers planet-release-deploy.timer
|
||||
journalctl -u planet-release-deploy.service -n 40
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
2. `/ai?section=integrations`:填一个 LLM provider(例如 `minimax` / `openai`)、模型名、Base URL、API Key,点 Base URL 末端的插头检查模型目录;未填写 Key 的官方主流供应商(含 GLM、Meta、Gemini、Grok、DeepSeek、OpenAI、MiniMax 等)会自动回退公共聚合目录,目录按「已选优先 + 最近使用 + 发布时间」排序并支持 6 项折叠预览;实际生成前往 `/advisor/playground` 验证,提示词与工具流可在 `/advisor/workflows` 编排。WebSearch / OCR 工具可在 `/ai?section=tools` 配置
|
||||
3. `/earth-content?section=brand`:在“品牌标识”里维护智能星球的 Logo 和标题图;对应地址字段内的“上传”按钮支持选择文件,也支持把图片直接拖到字段上,保存后会应用到智能星球 HUD
|
||||
4. `/datasources` 或 `/data`:看采集器是否已经产出数据。有限采集器看 `/datasources -> 内置源`,不勾选时点“触发全部”,勾选后主按钮会变成“触发已选 N”;右上角队列按钮可查看进度。AISStream / WebSocket 长连接看 `/datasources -> 实时源` 的健康状态和计数
|
||||
5. `/ops/monitoring`:集中查看系统告警、BGP 事故/异常/观测事件与采集器健康状态
|
||||
5. `/advisor/playground`:与 AI 参谋对话调试或输入 `/bgp-brief`、`/alerts-brief` 查看 BGP 态势与采集健康简报(原始 BGP 图层直接在 `/earth` 查看)
|
||||
6. `/users`(仅 `super_admin`):根据需要给同事开账号或调权限组(如外部 UE5/API 集成可在 `/settings` 生成长期 `X-API-Key` 或分配 `api_access` 权限组)
|
||||
|
||||
## 4. 打开智能星球
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.81.0`
|
||||
- `dev` 当前开发分支历史推导到:`0.83.0`
|
||||
|
||||
## Timeline
|
||||
|
||||
| Version | Type | Branch | Commit | Summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `0.83.0` | feature | `dev` | `v0.83.0` | Earth Phase 1–4 贴地影响范围与三维视觉升级、聚合分色环与优先一折连线、AI 参谋自进化加固与数据源连通性修复、桌面客户端启动与资源包更新及代码文档清理 |
|
||||
| `0.82.0` | feature | `dev` | `v0.82.0` | AI 参谋 3 层工作流自进化与元进化(Tier-0 安全内核/金丝雀回滚/Fixture A/B 评测/多模态 Playground 与地球绑定)、Electron 无边框录屏与 i18n、AI 模型目录升级及 README Mermaid 架构图 |
|
||||
| `0.81.0` | feature | `dev` | `v0.81.0` | 重构 AI 参谋(纯聊天 Playground/本地上下文抽屉/React Flow 9 工作流编排/AI Diff 调优/运行审计)与告警观测台,升级 L0–L4 Tool-Calling 位置 Agent、防爬鉴权与 X-API-Key、桌面录屏及多模型聚合目录 |
|
||||
| `0.80.3` | improvement | `dev` | `v0.80.3` | 发布含全平台最新客户端安装包与 Earth 热更包的 0.80.3;固化仅含客户端更新才创建 Gitea Release 与 OCI release-manifest 发现规则 |
|
||||
| `0.80.2` | improvement | `dev` | `v0.80.2` | 统一 Admin 控件设计参数与 Harness 校验,支持本地客户端全平台打包及按改动范围分层发版部署 |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-frontend",
|
||||
"version": "0.81.0",
|
||||
"version": "0.83.0",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 761 KiB |
@@ -1308,15 +1308,28 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
|
||||
position: absolute;
|
||||
z-index: 162;
|
||||
left: 50%;
|
||||
bottom: calc(86px * var(--hud-scale));
|
||||
bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1));
|
||||
transform: translateX(-50%);
|
||||
width: min(calc(760px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset)));
|
||||
width: min(calc(640px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset)));
|
||||
padding: 0;
|
||||
border-radius: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
border-color: rgba(145, 195, 255, 0.38);
|
||||
transition: bottom 0.24s ease;
|
||||
}
|
||||
|
||||
body:has(.earth-bottom-dock > :not([hidden])) .stage-narrative-bar {
|
||||
bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1) + 48px);
|
||||
}
|
||||
|
||||
body:has(.earth-toolbar-cluster.is-expanded) .stage-narrative-bar {
|
||||
bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1));
|
||||
}
|
||||
|
||||
body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidden])) .stage-narrative-bar {
|
||||
bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1) + 48px);
|
||||
}
|
||||
|
||||
.stage-narrative-bar__top {
|
||||
@@ -4163,6 +4176,12 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
|
||||
background: rgba(120, 180, 255, 0.2);
|
||||
}
|
||||
|
||||
.wb-action-pill.is-active {
|
||||
border-color: rgba(164, 214, 255, 0.56);
|
||||
background: rgba(92, 180, 255, 0.24);
|
||||
color: #e0f2fe;
|
||||
}
|
||||
|
||||
.wb-action-pill .material-symbols-rounded {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -4031,15 +4031,14 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
max-height: calc(30px * var(--hud-scale));
|
||||
aspect-ratio: 1 / 1;
|
||||
padding: 0;
|
||||
border: 1px solid rgba(122, 180, 255, 0.24);
|
||||
border: 1px solid rgba(212, 227, 244, 0.16);
|
||||
border-radius: 50%;
|
||||
background:
|
||||
radial-gradient(circle at 35% 22%, rgba(255, 255, 255, 0.2), transparent 58%),
|
||||
linear-gradient(180deg, rgba(121, 159, 207, 0.18), rgba(72, 101, 139, 0.24));
|
||||
background: rgba(255, 255, 255, 0.045);
|
||||
color: var(--hud-title);
|
||||
cursor: pointer;
|
||||
vertical-align: middle;
|
||||
transition:
|
||||
background 0.16s ease,
|
||||
border-color 0.18s ease,
|
||||
color 0.18s ease,
|
||||
transform 0.18s ease,
|
||||
@@ -4065,7 +4064,8 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
|
||||
.earth-settings-reload-action:hover {
|
||||
transform: translateY(-1px);
|
||||
border-color: rgba(125, 197, 255, 0.46);
|
||||
background: rgba(255, 255, 255, 0.09);
|
||||
border-color: rgba(148, 197, 255, 0.36);
|
||||
}
|
||||
|
||||
.earth-settings-reload-action:disabled {
|
||||
@@ -4577,20 +4577,26 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
|
||||
.earth-shortcut-key {
|
||||
min-width: calc(68px * var(--hud-scale));
|
||||
border: 1px solid rgba(122, 180, 255, 0.24);
|
||||
border-radius: calc(6px * var(--hud-scale));
|
||||
background:
|
||||
radial-gradient(circle at 35% 22%, rgba(255, 255, 255, 0.16), transparent 58%),
|
||||
linear-gradient(180deg, rgba(121, 159, 207, 0.16), rgba(72, 101, 139, 0.2));
|
||||
border: 1px solid rgba(212, 227, 244, 0.16);
|
||||
border-radius: 0;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: var(--hud-title);
|
||||
padding: calc(6px * var(--hud-scale)) calc(10px * var(--hud-scale));
|
||||
font: inherit;
|
||||
font-size: calc(0.68rem * var(--hud-scale));
|
||||
font-weight: 800;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
cursor: pointer;
|
||||
transition: background 0.16s ease, border-color 0.16s ease, color 0.16s ease;
|
||||
}
|
||||
|
||||
.earth-shortcut-key:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-color: rgba(148, 197, 255, 0.34);
|
||||
}
|
||||
|
||||
.earth-shortcut-key.is-capturing {
|
||||
background: rgba(52, 211, 153, 0.12);
|
||||
border-color: rgba(110, 226, 188, 0.52);
|
||||
color: #d8fff3;
|
||||
}
|
||||
@@ -5095,13 +5101,18 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
.legend-filter {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-radius: calc(4px * var(--hud-scale));
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.16s ease, background 0.16s ease;
|
||||
}
|
||||
.legend-filter:hover { background: rgba(255, 255, 255, 0.06); }
|
||||
.legend-filter[aria-pressed="false"] { opacity: 0.35; }
|
||||
.legend-filter[aria-pressed="false"]:hover,
|
||||
.legend-filter[aria-pressed="false"]:focus-visible { opacity: 0.95; }
|
||||
.legend-filter:focus-visible { outline: 1px solid #7dd3fc; outline-offset: -1px; }
|
||||
|
||||
.satellite-labels { position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 6; contain: layout style paint; }
|
||||
@@ -5119,13 +5130,14 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
.map-clusters { position:absolute; inset:0; pointer-events:none; z-index:5; }
|
||||
.map-clusters__legs { position:absolute; inset:0; width:100%; height:100%; overflow:visible; pointer-events:none; }
|
||||
.map-clusters__legs line { stroke:#94a3b8; stroke-width:1; }
|
||||
.map-cluster-badge { position:absolute; width:26px; height:26px; padding:0; display:grid; place-items:center;
|
||||
transform:translate(-50%,-50%); border-radius:50%; border:1.5px solid color-mix(in srgb,var(--cluster-color,#a855f7),#ffffff 68%);
|
||||
background:linear-gradient(135deg,var(--cluster-color,#a855f7),color-mix(in srgb,var(--cluster-color,#a855f7),#020617 40%));
|
||||
box-shadow:0 0 14px color-mix(in srgb,var(--cluster-color,#a855f7),transparent 30%),0 4px 10px #0008;
|
||||
color:white; font:800 11px system-ui,sans-serif; cursor:pointer; pointer-events:auto; }
|
||||
.map-cluster-badge { position:absolute; width:28px; height:28px; padding:0; display:grid; place-items:center;
|
||||
transform:translate(-50%,-50%); border-radius:50%; border:2.5px solid transparent;
|
||||
background:linear-gradient(155deg,rgba(15,25,42,0.92),rgba(7,13,24,0.95)) padding-box,linear-gradient(var(--cluster-color,#a855f7),var(--cluster-color,#a855f7)) border-box;
|
||||
box-shadow:inset 0 1px 0 rgba(255,255,255,0.16),0 0 12px color-mix(in srgb,var(--cluster-color,#38bdf8),transparent 64%),0 4px 10px #0008;
|
||||
color:white; font:800 11px system-ui,sans-serif; font-variant-numeric:tabular-nums; cursor:pointer; pointer-events:auto; }
|
||||
.map-cluster-badge:hover { transform:translate(-50%,-50%) scale(1.18); }
|
||||
.map-cluster-badge.is-mixed::after { content:""; position:absolute; inset:-4px; border:1.5px solid #f59e0b; border-radius:50%; pointer-events:none; }
|
||||
.map-cluster-badge.is-mixed {
|
||||
background:linear-gradient(155deg,rgba(15,25,42,0.92),rgba(7,13,24,0.95)) padding-box,var(--cluster-ring,conic-gradient(#14b8a6,#a855f7)) border-box; }
|
||||
.map-cluster-child { position:absolute; left:0; top:0; width:36px; height:36px; border:0; padding:0; background:transparent; cursor:pointer; pointer-events:auto; }
|
||||
.map-cluster-child img { width:100%; height:100%; pointer-events:none; }
|
||||
.map-cluster-badge[hidden],.map-cluster-child[hidden] { display:none; }
|
||||
@@ -5147,3 +5159,149 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
@media (prefers-reduced-motion:reduce) { .has-bgp > .map-cluster-bgp-pulse { animation:none; display:none; } }
|
||||
|
||||
.map-cluster-child.is-selected img { filter:drop-shadow(0 0 5px var(--member-color,#38bdf8)) brightness(1.15); }
|
||||
|
||||
.earth-bottom-dock {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1));
|
||||
transform: translateX(-50%);
|
||||
z-index: 160;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
width: max-content;
|
||||
max-width: min(94vw, 1080px);
|
||||
pointer-events: none;
|
||||
transition: bottom 0.24s ease;
|
||||
}
|
||||
body:has(.earth-toolbar-cluster.is-expanded) .earth-bottom-dock {
|
||||
bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1));
|
||||
}
|
||||
.layout-mode-mobile .earth-bottom-dock {
|
||||
bottom: calc(88px + var(--safe-bottom, 0px));
|
||||
flex-direction: column-reverse;
|
||||
max-width: calc(100vw - 16px);
|
||||
}
|
||||
|
||||
.earth-influence-pill {
|
||||
position: relative;
|
||||
flex: 0 1 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
height: 38px;
|
||||
box-sizing: border-box;
|
||||
max-width: min(86vw, 680px);
|
||||
padding: 6px 10px 6px 12px;
|
||||
border-radius: 999px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.earth-bottom-dock:has(#earth-target-tray:not([hidden])) .earth-influence-pill {
|
||||
max-width: min(56vw, 520px);
|
||||
}
|
||||
.layout-mode-mobile .earth-bottom-dock:has(#earth-target-tray:not([hidden])) .earth-influence-pill {
|
||||
max-width: calc(100vw - 16px);
|
||||
}
|
||||
.earth-influence-pill[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.earth-influence-pill__viewport {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.earth-influence-pill__viewport.is-marquee {
|
||||
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%);
|
||||
mask-image: linear-gradient(90deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%);
|
||||
}
|
||||
.earth-influence-pill__track {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 24px;
|
||||
width: max-content;
|
||||
}
|
||||
.earth-influence-pill__viewport.is-marquee .earth-influence-pill__track {
|
||||
animation: earthInfluenceMarquee var(--marquee-duration, 18s) linear infinite;
|
||||
}
|
||||
.earth-influence-pill:hover .earth-influence-pill__track {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
.earth-influence-pill__group {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex: none;
|
||||
}
|
||||
@keyframes earthInfluenceMarquee {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
}
|
||||
to {
|
||||
transform: translateX(calc(-50% - 12px));
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.earth-influence-pill__viewport.is-marquee {
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
-webkit-mask-image: none;
|
||||
mask-image: none;
|
||||
}
|
||||
.earth-influence-pill__viewport.is-marquee .earth-influence-pill__track {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
.earth-influence-pill__item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1.2;
|
||||
color: rgba(241, 245, 249, 0.92);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.earth-influence-pill__dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
flex: none;
|
||||
background: var(--zone-color, #38bdf8);
|
||||
}
|
||||
.earth-influence-pill__slider-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding-left: 8px;
|
||||
border-left: 1px solid rgba(148, 163, 184, 0.22);
|
||||
}
|
||||
.earth-influence-pill__slider {
|
||||
width: 72px;
|
||||
accent-color: #38bdf8;
|
||||
cursor: pointer;
|
||||
}
|
||||
.earth-influence-pill__clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: rgba(148, 163, 184, 0.16);
|
||||
color: rgba(226, 232, 240, 0.9);
|
||||
cursor: pointer;
|
||||
}
|
||||
.earth-influence-pill__clear:hover {
|
||||
background: rgba(148, 163, 184, 0.28);
|
||||
}
|
||||
.earth-influence-pill__clear .earth-influence-pill-icon.material-symbols-rounded {
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
line-height: 16px;
|
||||
}
|
||||
@@ -829,6 +829,19 @@ body[data-callout-line-style="bold"] .callout-connector circle {
|
||||
font-size: calc(0.7rem * var(--hud-scale));
|
||||
}
|
||||
|
||||
.info-card-auth-link {
|
||||
display: inline-block;
|
||||
margin-left: calc(6px * var(--hud-scale));
|
||||
color: var(--hud-accent);
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.info-card-auth-link:hover,
|
||||
.info-card-auth-link:focus-visible {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.info-card-compute-collect-candidates {
|
||||
margin-top: calc(6px * var(--hud-scale));
|
||||
display: flex;
|
||||
@@ -986,3 +999,176 @@ body[data-callout-line-style="bold"] .callout-connector circle {
|
||||
.news-summary-reserve { display:block; visibility:hidden; }
|
||||
.news-summary-output { position:absolute; inset:0; display:block; }
|
||||
.info-card-news-meta-grid--compact { grid-template-columns:minmax(0,1.4fr) minmax(0,.75fr) minmax(0,1fr); }
|
||||
|
||||
/* Dynamic Earth workflow binding menu & multi-object compare tray */
|
||||
.earth-workflow-menu {
|
||||
position: fixed;
|
||||
z-index: 220;
|
||||
padding: 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
border-radius: 0;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.earth-workflow-menu__head {
|
||||
padding: 4px 8px 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--hud-text-soft);
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.earth-workflow-menu__item {
|
||||
width: 100%;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--hud-title);
|
||||
border-radius: 8px;
|
||||
padding: 7px 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.earth-workflow-menu__item:hover {
|
||||
background: rgba(92, 200, 255, 0.16);
|
||||
border-color: rgba(92, 200, 255, 0.28);
|
||||
}
|
||||
|
||||
.earth-workflow-menu__icon.material-symbols-rounded,
|
||||
.earth-target-tray__icon.material-symbols-rounded {
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
line-height: 1;
|
||||
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.earth-workflow-menu__label {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.earth-workflow-menu__tag {
|
||||
font-size: 10px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
background: rgba(92, 200, 255, 0.18);
|
||||
color: #8be0ff;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.earth-workflow-menu__sep {
|
||||
height: 1px;
|
||||
margin: 3px 6px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.earth-target-tray {
|
||||
position: relative;
|
||||
flex: 0 1 auto;
|
||||
max-width: min(90vw, 640px);
|
||||
min-height: 38px;
|
||||
box-sizing: border-box;
|
||||
padding: 5px 8px;
|
||||
border-radius: 999px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
letter-spacing: 0;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.earth-target-tray[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.earth-target-tray__list {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.earth-target-tray__chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 26px;
|
||||
padding: 0 6px 0 9px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(92, 200, 255, 0.24);
|
||||
background: rgba(92, 200, 255, 0.12);
|
||||
color: var(--hud-title);
|
||||
font-size: 12px;
|
||||
max-width: 180px;
|
||||
}
|
||||
|
||||
.earth-target-tray__chip-label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.earth-target-tray__chip-remove {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--hud-text-soft);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.earth-target-tray__chip-remove:hover {
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
color: var(--hud-title);
|
||||
}
|
||||
|
||||
.earth-target-tray__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.earth-target-tray__analyze {
|
||||
height: 26px;
|
||||
padding: 0 11px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(92, 200, 255, 0.35);
|
||||
background: rgba(92, 200, 255, 0.22);
|
||||
color: #e6f7ff;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
cursor: pointer;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.earth-target-tray .hud-panel__action {
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.earth-target-tray__analyze:hover {
|
||||
background: rgba(92, 200, 255, 0.32);
|
||||
}
|
||||
@@ -205,11 +205,19 @@
|
||||
transition: color 0.18s ease;
|
||||
}
|
||||
|
||||
/* Icon brightens when layer is active */
|
||||
/* Icon brightens when layer is active or hovered */
|
||||
.layer-row:has(.layer-row-toggle.active) .layer-row-icon {
|
||||
color: var(--hud-accent);
|
||||
}
|
||||
|
||||
.layer-row:hover:not(:has(.layer-row-toggle.is-disabled)) .layer-row-icon {
|
||||
color: var(--hud-title);
|
||||
}
|
||||
|
||||
.layer-row:hover:has(.layer-row-toggle.active) .layer-row-icon {
|
||||
color: var(--hud-accent);
|
||||
}
|
||||
|
||||
.layer-row-copy {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
|
||||
@@ -368,6 +368,11 @@
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.earth-zoom-toolbar .earth-zoom-btn:hover,
|
||||
.earth-zoom-toolbar .earth-zoom-btn:focus-visible {
|
||||
color: #38bdf8;
|
||||
}
|
||||
|
||||
.earth-zoom-toolbar .earth-zoom-value {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
"three": "https://esm.sh/three@0.128.0",
|
||||
"three": "https://esm.sh/three@0.160.1",
|
||||
"pmtiles": "https://esm.sh/pmtiles@4.4.1",
|
||||
"@mapbox/vector-tile": "https://esm.sh/@mapbox/vector-tile@2.0.4",
|
||||
"pbf": "https://esm.sh/pbf@4.0.1",
|
||||
@@ -125,7 +125,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">cable</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">海缆</span>
|
||||
<span class="layer-row-meta">Subsea Cables</span>
|
||||
<span class="layer-row-meta">全球海底光缆</span>
|
||||
</div>
|
||||
<button id="toggle-cables" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换海缆显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -135,7 +135,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">satellite_alt</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">卫星</span>
|
||||
<span class="layer-row-meta">Satellites</span>
|
||||
<span class="layer-row-meta">近地与同步轨道卫星</span>
|
||||
</div>
|
||||
<button id="toggle-satellites" class="layer-row-toggle" type="button" role="switch" aria-checked="false" title="切换卫星显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -145,7 +145,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">memory</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">算力中心</span>
|
||||
<span class="layer-row-meta">Compute Centers</span>
|
||||
<span class="layer-row-meta">超算与智算集群</span>
|
||||
</div>
|
||||
<button id="open-compute-topic" class="hud-panel__action" type="button" aria-label="算力对比浮层" title="算力对比浮层"><span class="material-symbols-rounded" aria-hidden="true">monitoring</span></button>
|
||||
<button id="toggle-compute-centers" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换算力中心显示">
|
||||
@@ -156,7 +156,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">directions_boat</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">船只</span>
|
||||
<span class="layer-row-meta">AIS Vessels</span>
|
||||
<span class="layer-row-meta">全球船舶实时动态</span>
|
||||
</div>
|
||||
<button id="toggle-vessels" class="layer-row-toggle" type="button" role="switch" aria-checked="false" title="切换船只显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -165,10 +165,10 @@
|
||||
<div class="layer-row" data-layer-name="bgp观测 routing signals">
|
||||
<span class="material-symbols-rounded layer-row-icon">hub</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">BGP观测</span>
|
||||
<span class="layer-row-meta">Routing Signals</span>
|
||||
<span class="layer-row-label">BGP 观测</span>
|
||||
<span class="layer-row-meta">全球路由异常信号</span>
|
||||
</div>
|
||||
<button id="toggle-bgp" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换BGP观测显示">
|
||||
<button id="toggle-bgp" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换 BGP 观测显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -176,7 +176,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">landscape</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">地形</span>
|
||||
<span class="layer-row-meta">Terrain</span>
|
||||
<span class="layer-row-meta">三维地表起伏</span>
|
||||
</div>
|
||||
<button id="toggle-terrain" class="layer-row-toggle" type="button" role="switch" aria-checked="false" title="切换地形显示" data-status-target="terrain-status">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -186,7 +186,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">globe</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">高清材质</span>
|
||||
<span class="layer-row-meta">High-Res Texture</span>
|
||||
<span class="layer-row-meta">高清地表纹理</span>
|
||||
</div>
|
||||
<button id="toggle-earth-high-res-texture" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换高清材质显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -196,7 +196,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">cloud</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">大气云图</span>
|
||||
<span class="layer-row-meta">Cloud Layer</span>
|
||||
<span class="layer-row-meta">全球云层覆盖</span>
|
||||
</div>
|
||||
<button id="toggle-atmosphere-clouds" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换大气云图显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -206,7 +206,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">public</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">国界</span>
|
||||
<span class="layer-row-meta">Country Borders</span>
|
||||
<span class="layer-row-meta">国家与地区边界</span>
|
||||
</div>
|
||||
<button id="toggle-country-boundaries" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换国界显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -216,7 +216,7 @@
|
||||
<span class="material-symbols-rounded layer-row-icon">grid_4x4</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">经纬线</span>
|
||||
<span class="layer-row-meta">Graticule</span>
|
||||
<span class="layer-row-meta">经纬度网格</span>
|
||||
</div>
|
||||
<button id="toggle-grid-lines" class="layer-row-toggle" type="button" role="switch" aria-checked="false" title="切换经纬线显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
@@ -418,7 +418,7 @@
|
||||
</div>
|
||||
<div class="stats-footer">
|
||||
<span class="stats-footer-dot"></span>
|
||||
<span id="vessel-live-summary" class="stats-footer-text" data-earth-stat="vessel-live-summary">AISStream 未连接</span>
|
||||
<span id="vessel-live-summary" class="stats-footer-text" data-earth-stat="vessel-live-summary">船舶实时通道未连接</span>
|
||||
</div>
|
||||
|
||||
<!-- hidden elements kept for JS compatibility -->
|
||||
@@ -433,7 +433,7 @@
|
||||
<span class="hud-panel-title hud-panel__title tv-panel-header-title">Live 新闻</span>
|
||||
</div>
|
||||
<div id="tv-header-controls-live" class="tv-panel-header-controls tv-panel-header-controls--live">
|
||||
<button id="tv-source-select" class="tv-panel-select hud-select-trigger" type="button" aria-label="选择新闻直播源" aria-haspopup="dialog" aria-expanded="false"></button>
|
||||
<button id="tv-source-select" class="tv-panel-select hud-select-trigger" type="button" aria-label="选择 Live 新闻源" aria-haspopup="dialog" aria-expanded="false"></button>
|
||||
<div class="tv-panel-toolbar-actions">
|
||||
<button id="tv-refresh" class="hud-panel__action hud-panel__action--refresh" type="button" title="刷新直播源" aria-label="刷新直播源">
|
||||
<span class="material-symbols-rounded">refresh</span>
|
||||
@@ -464,7 +464,7 @@
|
||||
</div>
|
||||
<div id="tv-source-meta" class="tv-panel-subtitle">当前未配置可播放新闻直播源</div>
|
||||
<div id="tv-source-catalog" class="tv-panel-catalog">频道目录待同步</div>
|
||||
<div id="tv-source-notes" class="tv-panel-notes">支持后台配置默认源与采集器补充源。</div>
|
||||
<div id="tv-source-notes" class="tv-panel-notes">可在后台配置默认频道与采集源。</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -491,7 +491,7 @@
|
||||
</div>
|
||||
|
||||
<button id="desktop-news-ticker" class="earth-news-ticker" type="button" aria-label="打开态势新闻">
|
||||
<span id="news-ticker-region" class="earth-news-ticker__region">GLOBAL</span>
|
||||
<span id="news-ticker-region" class="earth-news-ticker__region">全球</span>
|
||||
<span class="earth-news-ticker__viewport">
|
||||
<span id="news-ticker-track" class="earth-news-ticker__track">正在准备全球态势新闻...</span>
|
||||
</span>
|
||||
@@ -501,7 +501,7 @@
|
||||
<div class="hud-panel__header earth-news-hud__header hud-panel-drag-handle">
|
||||
<div class="hud-panel__title-group">
|
||||
<span class="hud-panel-title hud-panel__title">态势聚合新闻</span>
|
||||
<span id="news-region-chip" class="news-region-chip hud-panel__chip">global</span>
|
||||
<span id="news-region-chip" class="news-region-chip hud-panel__chip">全球</span>
|
||||
</div>
|
||||
<div class="hud-panel__actions">
|
||||
<button class="hud-panel__action" type="button" data-news-region-cards aria-pressed="false" title="显示区域新闻卡片" aria-label="显示区域新闻卡片"><span class="material-symbols-rounded" aria-hidden="true">view_carousel</span></button>
|
||||
@@ -671,11 +671,11 @@
|
||||
</div>
|
||||
<div class="earth-mobile-search-chips" role="group" aria-label="快捷分类筛选">
|
||||
<button type="button" class="earth-mobile-search-chip is-active" data-search-filter="all">全部</button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="satellite" data-search-keyword="卫星">🛰️ 卫星</button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="cable" data-search-keyword="海缆">🌊 海缆</button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="landing_point" data-search-keyword="登陆点">📍 登陆点</button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="compute_center" data-search-keyword="算力">🖥️ 算力</button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="bgp" data-search-keyword="BGP">⚡ BGP</button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="satellite" data-search-keyword="卫星"><span aria-hidden="true">🛰️ </span><span>卫星</span></button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="cable" data-search-keyword="海缆"><span aria-hidden="true">🌊 </span><span>海缆</span></button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="landing_point" data-search-keyword="登陆点"><span aria-hidden="true">📍 </span><span>登陆点</span></button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="compute_center" data-search-keyword="算力"><span aria-hidden="true">🖥️ </span><span>算力</span></button>
|
||||
<button type="button" class="earth-mobile-search-chip" data-search-filter="bgp" data-search-keyword="BGP"><span aria-hidden="true">⚡ </span><span>BGP</span></button>
|
||||
</div>
|
||||
<div id="mobile-earth-search-meta" class="earth-mobile-search-meta">输入关键词或轻点上方分类快速探索地球对象</div>
|
||||
<div id="mobile-earth-search-results" class="earth-mobile-search-results" role="listbox" aria-label="移动端搜索结果"></div>
|
||||
@@ -686,12 +686,12 @@
|
||||
<div class="earth-mobile-page earth-mobile-page--situation">
|
||||
<div class="earth-mobile-page-intro">
|
||||
<span class="earth-mobile-page-kicker">态势总览</span>
|
||||
<span class="earth-mobile-page-summary">面向移动端整合的全球态势概览</span>
|
||||
<span class="earth-mobile-page-summary">全球关键设施与实时态势概览</span>
|
||||
</div>
|
||||
<div class="earth-mobile-workbench-actions" role="group" aria-label="移动端态势工作台入口">
|
||||
<button id="mobile-open-situational-copilot" class="earth-mobile-workbench-btn is-primary" type="button">
|
||||
<span class="material-symbols-rounded" aria-hidden="true">forum</span>
|
||||
<span>打开 AI 态势参谋</span>
|
||||
<span>打开 AI 参谋</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="earth-mobile-stats-grid">
|
||||
@@ -739,7 +739,7 @@
|
||||
<div class="earth-mobile-situation-card">
|
||||
<div class="earth-mobile-situation-card-title">实时态势监控</div>
|
||||
<div id="mobile-bgp-status-summary" class="earth-mobile-situation-status" data-earth-stat="bgp-status-summary">暂无观测数据</div>
|
||||
<div id="mobile-vessel-live-summary" class="earth-mobile-situation-status" data-earth-stat="vessel-live-summary">AISStream 未连接</div>
|
||||
<div id="mobile-vessel-live-summary" class="earth-mobile-situation-status" data-earth-stat="vessel-live-summary">船舶实时通道未连接</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -829,7 +829,7 @@
|
||||
<div id="mobile-tv-source-title" class="earth-mobile-tv-title">暂无可用频道</div>
|
||||
<div id="mobile-tv-source-meta" class="earth-mobile-tv-subtitle">当前未配置可播放新闻直播源</div>
|
||||
<div id="mobile-tv-source-catalog" class="earth-mobile-tv-catalog">频道目录待同步</div>
|
||||
<div id="mobile-tv-source-notes" class="earth-mobile-tv-notes">支持后台配置默认源与采集器补充源。</div>
|
||||
<div id="mobile-tv-source-notes" class="earth-mobile-tv-notes">可在后台配置默认频道与采集源。</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -841,14 +841,14 @@
|
||||
<span class="earth-mobile-page-kicker">动作捕捉</span>
|
||||
<span class="earth-mobile-page-summary">查看浏览器摄像头画面、骨架连线和当前匹配动作</span>
|
||||
</div>
|
||||
<div class="earth-mobile-motion-empty">动捕调试画面已并入设置里的动捕模式。</div>
|
||||
<div class="earth-mobile-motion-empty">请在设置中开启「动捕调试模式」查看摄像头与骨骼识别。</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="earth-mobile-drawer-slot" data-drawer-slot="settings">
|
||||
<div class="earth-mobile-page earth-mobile-page--settings">
|
||||
<div class="earth-mobile-page-intro">
|
||||
<span class="earth-mobile-page-kicker">设置</span>
|
||||
<span class="earth-mobile-page-summary">仅保留移动端仍有意义的智能星球配置</span>
|
||||
<span class="earth-mobile-page-summary">调整智能星球展示与交互偏好</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-tabs" role="tablist" aria-label="移动端设置分类">
|
||||
<button type="button" class="earth-mobile-settings-tab is-active" data-settings-tab="runtime" aria-selected="true">运行</button>
|
||||
@@ -863,7 +863,7 @@
|
||||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">旋转模式</span>
|
||||
<span class="earth-mobile-settings-subtitle">旋转、巡航和动捕是互斥运行模式</span>
|
||||
<span class="earth-mobile-settings-subtitle">切换地球自动旋转、模块巡航或动捕控制</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择旋转模式">
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-rotation-mode="rotate" aria-pressed="true">旋转模式</button>
|
||||
@@ -910,7 +910,7 @@
|
||||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">巡航队列</span>
|
||||
<span class="earth-mobile-settings-subtitle">控制巡航项按原始顺序、大区轮转或随机播放。</span>
|
||||
<span class="earth-mobile-settings-subtitle">控制巡航按默认顺序、按大区或随机播放。</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择巡航队列模式">
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-cruise-queue-mode="default" aria-pressed="true">默认</button>
|
||||
@@ -1067,7 +1067,7 @@
|
||||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked" data-satellite-altitude-compression-row>
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">轨道高度压缩</span>
|
||||
<span class="earth-mobile-settings-subtitle">100% 为默认压缩,0% 为 1:1 真实比例</span>
|
||||
<span class="earth-mobile-settings-subtitle">调节高轨卫星与地表的高度展示比例</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-slider-row">
|
||||
<input class="earth-mobile-settings-slider" type="range" min="0" max="1" step="0.01" value="1" data-satellite-altitude-compression aria-label="轨道高度压缩">
|
||||
@@ -1111,7 +1111,7 @@
|
||||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">新闻类型</span>
|
||||
<span class="earth-mobile-settings-subtitle">只筛选当前浏览器的新闻面板与新闻巡航,不改变后台新闻源。</span>
|
||||
<span class="earth-mobile-settings-subtitle">筛选新闻面板与巡航中显示的新闻类别。</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-chip-group" role="group" aria-label="选择新闻类型">
|
||||
<button type="button" class="earth-mobile-settings-chip is-active" data-news-category-toggle="politics" aria-pressed="true">政治</button>
|
||||
@@ -1215,11 +1215,11 @@
|
||||
>
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">动捕输入源</span>
|
||||
<span class="earth-mobile-settings-subtitle">本机摄像头内置识别无需装服务;Motion Agent 仅用于外接或 RTSP</span>
|
||||
<span class="earth-mobile-settings-subtitle">本机摄像头可直接使用;动捕服务用于外接相机或 RTSP 流</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择动捕输入源">
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-motion-provider="browser_camera" aria-pressed="true">本机摄像头</button>
|
||||
<button type="button" class="earth-mobile-settings-pill" data-motion-provider="motion_agent" aria-pressed="false">Motion Agent</button>
|
||||
<button type="button" class="earth-mobile-settings-pill" data-motion-provider="motion_agent" aria-pressed="false">动捕服务</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -1228,12 +1228,12 @@
|
||||
>
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">摄像头模式</span>
|
||||
<span class="earth-mobile-settings-subtitle" data-motion-camera-mode-summary>自动检测可用物理摄像头;单摄走 2D,双摄 3D 深度规划中</span>
|
||||
<span class="earth-mobile-settings-subtitle" data-motion-camera-mode-summary>自动识别可用物理摄像头</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择摄像头模式">
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-motion-camera-mode="auto" aria-pressed="true">自动检测</button>
|
||||
<button type="button" class="earth-mobile-settings-pill" data-motion-camera-mode="single" aria-pressed="false">单摄 2D</button>
|
||||
<button type="button" class="earth-mobile-settings-pill" data-motion-camera-mode="dual_3d" aria-pressed="false" disabled title="双摄真 3D 深度识别已在规划中">双摄 3D (规划中)</button>
|
||||
<button type="button" class="earth-mobile-settings-pill" data-motion-camera-mode="dual_3d" aria-pressed="false" disabled title="双摄 3D 模式即将支持">双摄 3D</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -1242,7 +1242,7 @@
|
||||
>
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">摄像头设备</span>
|
||||
<span class="earth-mobile-settings-subtitle">仅列物理摄像头(自动过滤常见虚拟/红外设备)</span>
|
||||
<span class="earth-mobile-settings-subtitle">选择用于动作识别的物理摄像头</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-chip-group" role="group" aria-label="移动端选择摄像头设备" data-motion-camera-device-list>
|
||||
<button type="button" class="earth-mobile-settings-chip is-active" data-motion-camera-device="" aria-pressed="true">自动选择</button>
|
||||
@@ -1289,7 +1289,7 @@
|
||||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">星球语言</span>
|
||||
<span class="earth-mobile-settings-subtitle">同步 Docs 和控制台语言偏好</span>
|
||||
<span class="earth-mobile-settings-subtitle">同步文档和控制台语言偏好</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-segmented earth-mobile-settings-segmented--locale" role="group" aria-label="星球语言" style="--item-count: 2;">
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-earth-locale="zh-CN" aria-pressed="true">中文</button>
|
||||
@@ -1305,7 +1305,7 @@
|
||||
<div class="earth-mobile-settings-title">关于</div>
|
||||
<div class="earth-about-card earth-about-card--mobile">
|
||||
<div class="earth-about-logo-frame">
|
||||
<img class="earth-about-logo" src="./assets/brand/lim-logo.png" alt="浙江大学临空智能媒体研究院 Logo">
|
||||
<img class="earth-about-logo" src="./assets/brand/lim-logo.png" alt="浙江大学临空智能媒体研究院标识">
|
||||
</div>
|
||||
<div class="earth-about-heading">
|
||||
<div class="earth-about-title-row">
|
||||
@@ -1368,8 +1368,8 @@
|
||||
</span>
|
||||
<span id="mobile-details-status-badge" class="earth-mobile-details-status-badge" hidden></span>
|
||||
</div>
|
||||
<h2 id="mobile-details-title" class="earth-mobile-details-title">STARLINK-34561</h2>
|
||||
<div id="mobile-details-subtitle" class="earth-mobile-details-subtitle">NORAD 65,081 · 近地点 481 km</div>
|
||||
<h2 id="mobile-details-title" class="earth-mobile-details-title"></h2>
|
||||
<div id="mobile-details-subtitle" class="earth-mobile-details-subtitle"></div>
|
||||
</header>
|
||||
|
||||
<!-- Quick Metrics Grid (Primary Highlights) -->
|
||||
@@ -1471,7 +1471,7 @@
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">旋转模式</span>
|
||||
<span class="earth-settings-item-subtitle">旋转、巡航和动捕是互斥运行模式;巡航按模块轮播,动捕消费手势控制</span>
|
||||
<span class="earth-settings-item-subtitle">切换地球自动旋转、模块巡航或动捕控制</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="选择旋转模式" style="--item-count: 3;">
|
||||
<button
|
||||
@@ -1581,7 +1581,7 @@
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">巡航队列</span>
|
||||
<span class="earth-settings-item-subtitle">控制巡航项按原始顺序、大区轮转或随机洗牌播放。</span>
|
||||
<span class="earth-settings-item-subtitle">控制巡航按默认顺序、按大区或随机播放。</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="选择巡航队列模式" style="--item-count: 3;">
|
||||
<button type="button" class="earth-settings-segmented-btn is-active" data-cruise-queue-mode="default" aria-pressed="true">默认</button>
|
||||
@@ -1730,7 +1730,7 @@
|
||||
<label class="earth-settings-item" for="toggle-satellite-real-altitude">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">真实卫星高度</span>
|
||||
<span class="earth-settings-item-subtitle">按真实轨道高度压缩分层显示,关闭后使用旧版同层球面</span>
|
||||
<span class="earth-settings-item-subtitle">按真实轨道高度分层显示,关闭后统一展示在同一球面</span>
|
||||
</div>
|
||||
<span class="earth-settings-switch">
|
||||
<input id="toggle-satellite-real-altitude" type="checkbox" data-satellite-real-altitude-toggle checked>
|
||||
@@ -1740,7 +1740,7 @@
|
||||
<div class="earth-settings-item earth-settings-item--stacked" data-satellite-altitude-compression-row>
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">轨道高度压缩</span>
|
||||
<span class="earth-settings-item-subtitle">100% 为默认对数压缩,调至 0% 按 1:1 真实比例展开高轨</span>
|
||||
<span class="earth-settings-item-subtitle">调节高轨卫星与地表的高度展示比例</span>
|
||||
</div>
|
||||
<div class="earth-settings-slider-row">
|
||||
<input class="earth-settings-slider" type="range" min="0" max="1" step="0.01" value="1" data-satellite-altitude-compression aria-label="轨道高度压缩">
|
||||
@@ -1819,7 +1819,7 @@
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">新闻类型</span>
|
||||
<span class="earth-settings-item-subtitle">只筛选当前浏览器的新闻面板与新闻巡航,不改变后台新闻源。</span>
|
||||
<span class="earth-settings-item-subtitle">筛选新闻面板与巡航中显示的新闻类别。</span>
|
||||
</div>
|
||||
<div class="earth-settings-chip-group" role="group" aria-label="选择新闻类型">
|
||||
<button type="button" class="earth-settings-chip is-active" data-news-category-toggle="politics" aria-pressed="true">政治</button>
|
||||
@@ -1884,7 +1884,7 @@
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">算力卡同时展开数</span>
|
||||
<span class="earth-settings-item-subtitle">控制画面中可同时保持完整展示的算力卡片数量,其余卡片精简为胶囊</span>
|
||||
<span class="earth-settings-item-subtitle">控制同时完整展开的算力卡数量</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="算力卡同时展开数" style="--item-count: 4;">
|
||||
<button type="button" class="earth-settings-segmented-btn is-active" data-max-cards="compute" data-limit="1" aria-pressed="true">1 张</button>
|
||||
@@ -1896,7 +1896,7 @@
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">新闻卡同时展开数</span>
|
||||
<span class="earth-settings-item-subtitle">控制画面中可同时保持完整展示的新闻卡片数量,其余卡片精简为胶囊</span>
|
||||
<span class="earth-settings-item-subtitle">控制同时完整展开的新闻卡数量</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="新闻卡同时展开数" style="--item-count: 4;">
|
||||
<button type="button" class="earth-settings-segmented-btn is-active" data-max-cards="news" data-limit="1" aria-pressed="true">1 张</button>
|
||||
@@ -1917,7 +1917,7 @@
|
||||
>
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">动捕调试模式</span>
|
||||
<span class="earth-settings-item-subtitle">打开骨架连线面板;未匹配为红线,匹配动作后变绿</span>
|
||||
<span class="earth-settings-item-subtitle">显示摄像头识别的骨架连线与匹配动作</span>
|
||||
</div>
|
||||
<span class="earth-settings-switch">
|
||||
<input id="toggle-motion-debug" type="checkbox" data-motion-debug-toggle>
|
||||
@@ -1930,11 +1930,11 @@
|
||||
>
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">动捕输入源</span>
|
||||
<span class="earth-settings-item-subtitle">本机摄像头内置本地骨骼识别(Web 与客户端通用);Motion Agent 仅用于外接或 RTSP 服务</span>
|
||||
<span class="earth-settings-item-subtitle">本机摄像头可直接使用;动捕服务用于外接相机或 RTSP 流</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="选择动捕输入源" style="--item-count: 2;">
|
||||
<button type="button" class="earth-settings-segmented-btn is-active" data-motion-provider="browser_camera" aria-pressed="true">本机摄像头</button>
|
||||
<button type="button" class="earth-settings-segmented-btn" data-motion-provider="motion_agent" aria-pressed="false">Motion Agent</button>
|
||||
<button type="button" class="earth-settings-segmented-btn" data-motion-provider="motion_agent" aria-pressed="false">动捕服务</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -1943,12 +1943,12 @@
|
||||
>
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">摄像头模式</span>
|
||||
<span class="earth-settings-item-subtitle" data-motion-camera-mode-summary>自动检测可用物理摄像头;单摄走 2D,双摄 3D 深度规划中</span>
|
||||
<span class="earth-settings-item-subtitle" data-motion-camera-mode-summary>自动识别可用物理摄像头</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="选择摄像头模式" style="--item-count: 3;">
|
||||
<button type="button" class="earth-settings-segmented-btn is-active" data-motion-camera-mode="auto" aria-pressed="true">自动检测</button>
|
||||
<button type="button" class="earth-settings-segmented-btn" data-motion-camera-mode="single" aria-pressed="false">单摄 2D</button>
|
||||
<button type="button" class="earth-settings-segmented-btn" data-motion-camera-mode="dual_3d" aria-pressed="false" disabled title="双摄真 3D 深度识别已在规划中">双摄 3D (规划中)</button>
|
||||
<button type="button" class="earth-settings-segmented-btn" data-motion-camera-mode="dual_3d" aria-pressed="false" disabled title="双摄 3D 模式即将支持">双摄 3D</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -1957,7 +1957,7 @@
|
||||
>
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">摄像头设备</span>
|
||||
<span class="earth-settings-item-subtitle">仅列物理摄像头(自动过滤常见虚拟/红外设备)</span>
|
||||
<span class="earth-settings-item-subtitle">选择用于动作识别的物理摄像头</span>
|
||||
</div>
|
||||
<div class="earth-settings-chip-group" role="group" aria-label="选择摄像头设备" data-motion-camera-device-list>
|
||||
<button type="button" class="earth-settings-chip is-active" data-motion-camera-device="" aria-pressed="true">自动选择</button>
|
||||
@@ -1969,7 +1969,7 @@
|
||||
>
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">识别动作</span>
|
||||
<span class="earth-settings-item-subtitle">未勾选的动作不会触发星球端控制;Motion Agent 会同步过滤这些动作</span>
|
||||
<span class="earth-settings-item-subtitle">关闭后不会触发对应的交互控制</span>
|
||||
</div>
|
||||
<div class="earth-settings-chip-grid" role="group" aria-label="选择动捕识别动作">
|
||||
<button type="button" class="earth-settings-chip is-active" data-motion-gesture-toggle="rotate_left" aria-pressed="true">左旋</button>
|
||||
@@ -1994,7 +1994,7 @@
|
||||
<div class="earth-shortcut-panel-heading">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">键盘控制</span>
|
||||
<span class="earth-settings-item-subtitle">点击按键后按下新的快捷键;Esc 取消录入,冲突快捷键不会保存</span>
|
||||
<span class="earth-settings-item-subtitle">点击按键后按下新快捷键;按 Esc 取消</span>
|
||||
</div>
|
||||
<button class="earth-settings-reload-action earth-settings-reload-action--text" type="button" data-shortcut-reset-all>恢复默认</button>
|
||||
</div>
|
||||
@@ -2008,7 +2008,7 @@
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">星球语言</span>
|
||||
<span class="earth-settings-item-subtitle">同步 Docs 和控制台语言偏好</span>
|
||||
<span class="earth-settings-item-subtitle">同步文档和控制台语言偏好</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented earth-settings-segmented--locale" role="group" aria-label="星球语言" style="--item-count: 2;">
|
||||
<button type="button" class="earth-settings-segmented-btn is-active" data-earth-locale="zh-CN" aria-pressed="true">中文</button>
|
||||
@@ -2052,12 +2052,12 @@
|
||||
<div class="earth-settings-list">
|
||||
<div class="earth-settings-item earth-settings-item--stacked earth-about-card">
|
||||
<div class="earth-about-logo-frame">
|
||||
<img class="earth-about-logo" src="./assets/brand/lim-logo.png" alt="浙江大学临空智能媒体研究院 Logo">
|
||||
<img class="earth-about-logo" src="./assets/brand/lim-logo.png" alt="浙江大学临空智能媒体研究院标识">
|
||||
</div>
|
||||
<div class="earth-about-heading">
|
||||
<span class="earth-about-kicker">About</span>
|
||||
<span class="earth-about-kicker">关于</span>
|
||||
<strong>智能星球计划</strong>
|
||||
<span>v0.65.2</span>
|
||||
<span>v0.76.18</span>
|
||||
</div>
|
||||
<p class="earth-about-copy">
|
||||
面向临空场景下的智能媒体研究、全球态势感知与多源开放数据巡航,提供可视化观测、事件聚合与交互式探索能力。
|
||||
|
||||
@@ -2,9 +2,9 @@ const EARTH_ABOUT_API = "/api/v1/earth/about";
|
||||
|
||||
const DEFAULT_ABOUT = {
|
||||
logo_src: "./assets/brand/lim-logo.png",
|
||||
kicker: "About",
|
||||
kicker: "关于",
|
||||
title: "智能星球计划",
|
||||
version: "v0.65.2",
|
||||
version: "v0.76.18",
|
||||
description:
|
||||
"面向临空场景下的智能媒体研究、全球态势感知与多源开放数据巡航,提供可视化观测、事件聚合与交互式探索能力。",
|
||||
meta: [
|
||||
@@ -62,7 +62,7 @@ function renderAboutCard(about, isMobile = false) {
|
||||
|
||||
return `
|
||||
<div class="earth-about-logo-frame">
|
||||
<img class="earth-about-logo" src="${escapeAttribute(about.logo_src)}" alt="${escapeAttribute(about.title)} Logo">
|
||||
<img class="earth-about-logo" src="${escapeAttribute(about.logo_src)}" alt="浙江大学临空智能媒体研究院标识">
|
||||
</div>
|
||||
<div class="earth-about-heading">
|
||||
<span class="earth-about-kicker">${escapeHtml(about.kicker)}</span>
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
export const ADMIN_AUTH_STORAGE_KEY = "auth-storage";
|
||||
export const ADMIN_AUTH_REFRESH_ENDPOINT = "/api/v1/auth/refresh";
|
||||
export const ADMIN_AUTH_REQUIRED_CODE = "ADMIN_AUTH_REQUIRED";
|
||||
export const ADMIN_AUTH_REQUIRED_MESSAGE = "需要管理员登录后才能采集或保存算力中心位置";
|
||||
|
||||
const pendingRefreshByStorage = new WeakMap();
|
||||
|
||||
export function getAdminLoginUrl() {
|
||||
return "/login";
|
||||
}
|
||||
|
||||
export function createAdminAuthRequiredError(status, message = ADMIN_AUTH_REQUIRED_MESSAGE) {
|
||||
const error = new Error(message || ADMIN_AUTH_REQUIRED_MESSAGE);
|
||||
error.code = ADMIN_AUTH_REQUIRED_CODE;
|
||||
error.status = status;
|
||||
error.loginUrl = getAdminLoginUrl();
|
||||
return error;
|
||||
}
|
||||
|
||||
export function isAdminAuthRequiredError(error) {
|
||||
return Boolean(
|
||||
error &&
|
||||
(error.code === ADMIN_AUTH_REQUIRED_CODE || error.status === 401 || error.status === 403),
|
||||
);
|
||||
}
|
||||
|
||||
function resolveStorage(storage) {
|
||||
if (storage !== undefined) return storage;
|
||||
try {
|
||||
return globalThis.localStorage ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function readStoredAdminAuthState(storage) {
|
||||
const targetStorage = resolveStorage(storage);
|
||||
const empty = { rawEnvelope: null, token: "", refreshToken: "", user: undefined };
|
||||
if (!targetStorage || typeof targetStorage.getItem !== "function") {
|
||||
return empty;
|
||||
}
|
||||
try {
|
||||
const raw = targetStorage.getItem(ADMIN_AUTH_STORAGE_KEY);
|
||||
if (!raw) return empty;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== "object") return empty;
|
||||
const state = parsed.state && typeof parsed.state === "object" ? parsed.state : {};
|
||||
const token = typeof state.token === "string" ? state.token.trim() : "";
|
||||
const refreshToken = typeof state.refreshToken === "string" ? state.refreshToken.trim() : "";
|
||||
return {
|
||||
rawEnvelope: parsed,
|
||||
token,
|
||||
refreshToken,
|
||||
user: state.user,
|
||||
};
|
||||
} catch {
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
|
||||
export function persistStoredAdminAuthState({ token, refreshToken, user }, storage) {
|
||||
const targetStorage = resolveStorage(storage);
|
||||
if (!targetStorage || typeof targetStorage.setItem !== "function") {
|
||||
return;
|
||||
}
|
||||
const { rawEnvelope } = readStoredAdminAuthState(targetStorage);
|
||||
const baseEnvelope = rawEnvelope && typeof rawEnvelope === "object" ? rawEnvelope : { version: 0 };
|
||||
const baseState =
|
||||
baseEnvelope.state && typeof baseEnvelope.state === "object" ? baseEnvelope.state : {};
|
||||
const nextState = {
|
||||
...baseState,
|
||||
token: token ?? null,
|
||||
refreshToken: refreshToken ?? null,
|
||||
...(user !== undefined ? { user } : {}),
|
||||
};
|
||||
try {
|
||||
targetStorage.setItem(
|
||||
ADMIN_AUTH_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
...baseEnvelope,
|
||||
state: nextState,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Ignore storage quota / security errors.
|
||||
}
|
||||
}
|
||||
|
||||
export function clearStoredAdminAuthTokens(storage) {
|
||||
const targetStorage = resolveStorage(storage);
|
||||
if (!targetStorage || typeof targetStorage.setItem !== "function") {
|
||||
return;
|
||||
}
|
||||
const { rawEnvelope } = readStoredAdminAuthState(targetStorage);
|
||||
if (!rawEnvelope) return;
|
||||
persistStoredAdminAuthState({ token: null, refreshToken: null }, targetStorage);
|
||||
}
|
||||
|
||||
export async function refreshStoredAdminAuthToken({
|
||||
fetchImpl = globalThis.fetch,
|
||||
storage,
|
||||
} = {}) {
|
||||
const targetStorage = resolveStorage(storage);
|
||||
const { refreshToken } = readStoredAdminAuthState(targetStorage);
|
||||
if (!refreshToken || typeof fetchImpl !== "function") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const storageKey = targetStorage && typeof targetStorage === "object" ? targetStorage : null;
|
||||
if (storageKey && pendingRefreshByStorage.has(storageKey)) {
|
||||
const existing = pendingRefreshByStorage.get(storageKey);
|
||||
if (existing.fetchImpl === fetchImpl) {
|
||||
return existing.promise;
|
||||
}
|
||||
}
|
||||
|
||||
const refreshPromise = (async () => {
|
||||
try {
|
||||
const response = await fetchImpl(ADMIN_AUTH_REFRESH_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${refreshToken}`,
|
||||
},
|
||||
});
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
clearStoredAdminAuthTokens(targetStorage);
|
||||
return null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
const payload = await response.json().catch(() => null);
|
||||
const nextToken =
|
||||
typeof payload?.access_token === "string" ? payload.access_token.trim() : "";
|
||||
if (!nextToken) {
|
||||
return null;
|
||||
}
|
||||
const nextRefreshToken =
|
||||
typeof payload?.refresh_token === "string" && payload.refresh_token.trim()
|
||||
? payload.refresh_token.trim()
|
||||
: refreshToken;
|
||||
persistStoredAdminAuthState(
|
||||
{
|
||||
token: nextToken,
|
||||
refreshToken: nextRefreshToken,
|
||||
...(payload?.user !== undefined ? { user: payload.user } : {}),
|
||||
},
|
||||
targetStorage,
|
||||
);
|
||||
return nextToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
if (storageKey) {
|
||||
const entry = { fetchImpl, promise: refreshPromise };
|
||||
pendingRefreshByStorage.set(storageKey, entry);
|
||||
refreshPromise.finally(() => {
|
||||
if (pendingRefreshByStorage.get(storageKey) === entry) {
|
||||
pendingRefreshByStorage.delete(storageKey);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
export function buildAdminWriteHeaders(tokenOverride, storage) {
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
const token =
|
||||
typeof tokenOverride === "string"
|
||||
? tokenOverride.trim()
|
||||
: readStoredAdminAuthState(storage).token;
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export async function fetchAdminWriteJson(
|
||||
endpoint,
|
||||
payload = {},
|
||||
{
|
||||
fetchImpl = globalThis.fetch,
|
||||
storage,
|
||||
authMessage = ADMIN_AUTH_REQUIRED_MESSAGE,
|
||||
} = {},
|
||||
) {
|
||||
if (!endpoint) throw new Error("endpoint is required");
|
||||
const targetStorage = resolveStorage(storage);
|
||||
let { token, refreshToken } = readStoredAdminAuthState(targetStorage);
|
||||
|
||||
if (!token && refreshToken) {
|
||||
token = (await refreshStoredAdminAuthToken({ fetchImpl, storage: targetStorage })) || "";
|
||||
}
|
||||
|
||||
let response = await fetchImpl(endpoint, {
|
||||
method: "POST",
|
||||
headers: buildAdminWriteHeaders(token, targetStorage),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
const nextToken = await refreshStoredAdminAuthToken({ fetchImpl, storage: targetStorage });
|
||||
if (nextToken && nextToken !== token) {
|
||||
response = await fetchImpl(endpoint, {
|
||||
method: "POST",
|
||||
headers: buildAdminWriteHeaders(nextToken, targetStorage),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw createAdminAuthRequiredError(response.status, authMessage);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import {
|
||||
ADMIN_AUTH_REFRESH_ENDPOINT,
|
||||
ADMIN_AUTH_REQUIRED_CODE,
|
||||
ADMIN_AUTH_STORAGE_KEY,
|
||||
fetchAdminWriteJson,
|
||||
isAdminAuthRequiredError,
|
||||
readStoredAdminAuthState,
|
||||
} from "./admin-write-auth.js";
|
||||
|
||||
function createMemoryStorage(initialState = null) {
|
||||
const store = new Map();
|
||||
if (initialState !== null) {
|
||||
store.set(ADMIN_AUTH_STORAGE_KEY, JSON.stringify(initialState));
|
||||
}
|
||||
return {
|
||||
getItem(key) {
|
||||
return store.has(key) ? store.get(key) : null;
|
||||
},
|
||||
setItem(key, value) {
|
||||
store.set(key, String(value));
|
||||
},
|
||||
removeItem(key) {
|
||||
store.delete(key);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function jsonResponse(status, body) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
test("refreshes expired access token on 401, persists tokens, and retries write request", async () => {
|
||||
const storage = createMemoryStorage({
|
||||
version: 0,
|
||||
state: {
|
||||
token: "expired-access",
|
||||
refreshToken: "valid-refresh-1",
|
||||
user: { id: 1, role: "admin" },
|
||||
},
|
||||
});
|
||||
const calls = [];
|
||||
const fetchImpl = async (url, init = {}) => {
|
||||
calls.push({ url, method: init.method, auth: init.headers?.Authorization });
|
||||
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
||||
return jsonResponse(200, {
|
||||
access_token: "fresh-access-2",
|
||||
refresh_token: "fresh-refresh-2",
|
||||
user: { id: 1, role: "admin", username: "ops" },
|
||||
});
|
||||
}
|
||||
if (init.headers?.Authorization === "Bearer expired-access") {
|
||||
return jsonResponse(401, { detail: "Token expired" });
|
||||
}
|
||||
if (init.headers?.Authorization === "Bearer fresh-access-2") {
|
||||
return jsonResponse(200, { success: true, candidates: [{ latitude: 1.2, longitude: 3.4 }] });
|
||||
}
|
||||
return jsonResponse(401, { detail: "Unexpected auth header" });
|
||||
};
|
||||
|
||||
const response = await fetchAdminWriteJson(
|
||||
"/api/v1/visualization/compute-centers/cc-1/collect-location",
|
||||
{ name: "AI-03" },
|
||||
{ fetchImpl, storage },
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({
|
||||
success: true,
|
||||
candidates: [{ latitude: 1.2, longitude: 3.4 }],
|
||||
});
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
url: "/api/v1/visualization/compute-centers/cc-1/collect-location",
|
||||
method: "POST",
|
||||
auth: "Bearer expired-access",
|
||||
},
|
||||
{
|
||||
url: ADMIN_AUTH_REFRESH_ENDPOINT,
|
||||
method: "POST",
|
||||
auth: "Bearer valid-refresh-1",
|
||||
},
|
||||
{
|
||||
url: "/api/v1/visualization/compute-centers/cc-1/collect-location",
|
||||
method: "POST",
|
||||
auth: "Bearer fresh-access-2",
|
||||
},
|
||||
]);
|
||||
|
||||
const persisted = readStoredAdminAuthState(storage);
|
||||
expect(persisted.token).toBe("fresh-access-2");
|
||||
expect(persisted.refreshToken).toBe("fresh-refresh-2");
|
||||
expect(persisted.user).toEqual({ id: 1, role: "admin", username: "ops" });
|
||||
});
|
||||
|
||||
test("proactively refreshes when access token is missing but refresh token exists", async () => {
|
||||
const storage = createMemoryStorage({
|
||||
version: 0,
|
||||
state: {
|
||||
token: null,
|
||||
refreshToken: "valid-refresh-only",
|
||||
},
|
||||
});
|
||||
const calls = [];
|
||||
const fetchImpl = async (url, init = {}) => {
|
||||
calls.push({ url, auth: init.headers?.Authorization });
|
||||
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
||||
return jsonResponse(200, {
|
||||
access_token: "proactive-access",
|
||||
refresh_token: "valid-refresh-only",
|
||||
});
|
||||
}
|
||||
return jsonResponse(200, { saved: true });
|
||||
};
|
||||
|
||||
const response = await fetchAdminWriteJson(
|
||||
"/api/v1/visualization/compute-centers/cc-2/location",
|
||||
{ latitude: 10, longitude: 20 },
|
||||
{ fetchImpl, storage },
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(calls).toEqual([
|
||||
{ url: ADMIN_AUTH_REFRESH_ENDPOINT, auth: "Bearer valid-refresh-only" },
|
||||
{ url: "/api/v1/visualization/compute-centers/cc-2/location", auth: "Bearer proactive-access" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("deduplicates concurrent /auth/refresh calls when multiple writes hit 401 simultaneously", async () => {
|
||||
const storage = createMemoryStorage({
|
||||
version: 0,
|
||||
state: {
|
||||
token: "stale-token",
|
||||
refreshToken: "shared-refresh",
|
||||
},
|
||||
});
|
||||
let refreshCount = 0;
|
||||
const fetchImpl = async (url, init = {}) => {
|
||||
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
||||
refreshCount += 1;
|
||||
await Promise.resolve();
|
||||
return jsonResponse(200, {
|
||||
access_token: "deduped-token",
|
||||
refresh_token: "shared-refresh",
|
||||
});
|
||||
}
|
||||
if (init.headers?.Authorization === "Bearer stale-token") {
|
||||
return jsonResponse(401, { detail: "Expired" });
|
||||
}
|
||||
return jsonResponse(200, { ok: true, url });
|
||||
};
|
||||
|
||||
const [resA, resB] = await Promise.all([
|
||||
fetchAdminWriteJson("/api/v1/visualization/compute-centers/a/collect-location", {}, { fetchImpl, storage }),
|
||||
fetchAdminWriteJson("/api/v1/visualization/compute-centers/b/collect-location", {}, { fetchImpl, storage }),
|
||||
]);
|
||||
|
||||
expect(resA.status).toBe(200);
|
||||
expect(resB.status).toBe(200);
|
||||
expect(refreshCount).toBe(1);
|
||||
});
|
||||
|
||||
test("throws typed ADMIN_AUTH_REQUIRED error and clears stale tokens when refresh rejects with 401", async () => {
|
||||
const storage = createMemoryStorage({
|
||||
version: 0,
|
||||
state: {
|
||||
token: "dead-access",
|
||||
refreshToken: "dead-refresh",
|
||||
},
|
||||
});
|
||||
const fetchImpl = async (url) => {
|
||||
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
||||
return jsonResponse(401, { detail: "Invalid refresh token" });
|
||||
}
|
||||
return jsonResponse(401, { detail: "Invalid access token" });
|
||||
};
|
||||
|
||||
let caught = null;
|
||||
try {
|
||||
await fetchAdminWriteJson(
|
||||
"/api/v1/visualization/compute-centers/cc-3/collect-location",
|
||||
{},
|
||||
{ fetchImpl, storage },
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(isAdminAuthRequiredError(caught)).toBe(true);
|
||||
expect(caught?.code).toBe(ADMIN_AUTH_REQUIRED_CODE);
|
||||
expect(caught?.status).toBe(401);
|
||||
expect(caught?.loginUrl).toBe("/login");
|
||||
|
||||
const persisted = readStoredAdminAuthState(storage);
|
||||
expect(persisted.token).toBe("");
|
||||
expect(persisted.refreshToken).toBe("");
|
||||
});
|
||||
|
||||
test("throws typed ADMIN_AUTH_REQUIRED immediately on 403 without refreshing or clearing storage", async () => {
|
||||
const storage = createMemoryStorage({
|
||||
version: 0,
|
||||
state: {
|
||||
token: "non-admin-access",
|
||||
refreshToken: "non-admin-refresh",
|
||||
},
|
||||
});
|
||||
let refreshCalls = 0;
|
||||
const fetchImpl = async (url) => {
|
||||
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
||||
refreshCalls += 1;
|
||||
}
|
||||
return jsonResponse(403, { detail: "Administrator privileges required" });
|
||||
};
|
||||
|
||||
let caught = null;
|
||||
try {
|
||||
await fetchAdminWriteJson(
|
||||
"/api/v1/visualization/compute-centers/cc-4/collect-location",
|
||||
{},
|
||||
{ fetchImpl, storage },
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(refreshCalls).toBe(0);
|
||||
expect(isAdminAuthRequiredError(caught)).toBe(true);
|
||||
expect(caught?.code).toBe(ADMIN_AUTH_REQUIRED_CODE);
|
||||
expect(caught?.status).toBe(403);
|
||||
const persisted = readStoredAdminAuthState(storage);
|
||||
expect(persisted.token).toBe("non-admin-access");
|
||||
expect(persisted.refreshToken).toBe("non-admin-refresh");
|
||||
});
|
||||
|
||||
test("preserves existing refresh token when /auth/refresh fails with transient 500", async () => {
|
||||
const storage = createMemoryStorage({
|
||||
version: 0,
|
||||
state: {
|
||||
token: "maybe-expired",
|
||||
refreshToken: "keep-this-refresh",
|
||||
},
|
||||
});
|
||||
const fetchImpl = async (url) => {
|
||||
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
||||
return jsonResponse(500, { detail: "Temporary upstream failure" });
|
||||
}
|
||||
return jsonResponse(401, { detail: "Expired" });
|
||||
};
|
||||
|
||||
let caught = null;
|
||||
try {
|
||||
await fetchAdminWriteJson(
|
||||
"/api/v1/visualization/compute-centers/cc-5/collect-location",
|
||||
{},
|
||||
{ fetchImpl, storage },
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(isAdminAuthRequiredError(caught)).toBe(true);
|
||||
expect(caught?.status).toBe(401);
|
||||
const persisted = readStoredAdminAuthState(storage);
|
||||
expect(persisted.refreshToken).toBe("keep-this-refresh");
|
||||
});
|
||||
+99
-131
@@ -940,114 +940,141 @@ function projectLatLon(lat, lon, bearingDeg, distanceDeg) {
|
||||
};
|
||||
}
|
||||
|
||||
function createCoverageBoundaryLine(points, color, opacity = 0.3) {
|
||||
const geometry = new THREE.BufferGeometry().setFromPoints(points);
|
||||
const material = new THREE.LineBasicMaterial({
|
||||
color,
|
||||
transparent: true,
|
||||
opacity,
|
||||
depthWrite: false,
|
||||
blending: THREE.AdditiveBlending,
|
||||
});
|
||||
return new THREE.Line(geometry, material);
|
||||
}
|
||||
const BGP_RADAR_VERTEX_SHADER = `
|
||||
attribute vec2 aPolar;
|
||||
varying vec2 vPolar;
|
||||
|
||||
void main() {
|
||||
vPolar = aPolar;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
const BGP_RADAR_FRAGMENT_SHADER = `
|
||||
uniform vec3 uColor;
|
||||
uniform float uOpacity;
|
||||
uniform float uTime;
|
||||
uniform float uScanSpeed;
|
||||
uniform float uSectorHalfSpan;
|
||||
varying vec2 vPolar;
|
||||
|
||||
void main() {
|
||||
float r = clamp(vPolar.x, 0.0, 1.0);
|
||||
float angle = vPolar.y;
|
||||
float pxR = clamp(fwidth(r), 0.0006, 0.0045);
|
||||
|
||||
float sweepAngle = mod(uTime * uScanSpeed, 6.2831853);
|
||||
float delta = mod(sweepAngle - angle + 6.2831853, 6.2831853);
|
||||
|
||||
float span = clamp(uSectorHalfSpan * 2.0, 0.35, 2.2);
|
||||
float beamTrail = (1.0 - smoothstep(0.0, span, delta)) * smoothstep(0.03, 0.96, r) * (1.0 - r * 0.25);
|
||||
float leadingArm = exp(-(delta * delta) / 0.0018) * step(0.03, r);
|
||||
|
||||
// Precision ~1.25px hairline concentric rings via WebGL2 fwidth()
|
||||
float ring1 = 1.0 - smoothstep(0.0, pxR * 1.35, abs(r - 0.333));
|
||||
float ring2 = 1.0 - smoothstep(0.0, pxR * 1.35, abs(r - 0.666));
|
||||
float outerRim = 1.0 - smoothstep(0.0, pxR * 1.55, abs(r - 0.993));
|
||||
float ticks = smoothstep(0.955, 0.992, r) * (1.0 - step(0.996, r)) * pow(abs(cos(angle * 6.0)), 42.0);
|
||||
|
||||
float hairline = max(max(ring1, ring2) * 0.42, max(outerRim * 0.82, ticks * 0.55));
|
||||
float ambientTint = 0.025 * (1.0 - smoothstep(0.0, 1.0, r));
|
||||
float alpha = clamp((ambientTint + beamTrail * 0.22 + leadingArm * 0.45 + hairline * 0.65) * uOpacity * 3.4, 0.0, 0.85);
|
||||
if (alpha < 0.003) discard;
|
||||
|
||||
vec3 beamColor = mix(uColor, vec3(0.94, 0.97, 1.0), clamp(leadingArm * 0.28 + outerRim * 0.14, 0.0, 0.35));
|
||||
gl_FragColor = vec4(beamColor, alpha);
|
||||
#include <colorspace_fragment>
|
||||
}
|
||||
`;
|
||||
|
||||
function createCoverageSectorMesh(
|
||||
anchorLatitude,
|
||||
anchorLongitude,
|
||||
startBearingDeg,
|
||||
endBearingDeg,
|
||||
_startBearingDeg,
|
||||
_endBearingDeg,
|
||||
reachDeg,
|
||||
altitude,
|
||||
color,
|
||||
opacity = 0.12,
|
||||
radialSegments = 8,
|
||||
angularSegments = 28,
|
||||
opacity = 0.24,
|
||||
radialSegments = 14,
|
||||
angularSegments = 96,
|
||||
scanSpeed = 0.72,
|
||||
sectorHalfSpan = Math.PI * 0.22,
|
||||
) {
|
||||
const positions = [];
|
||||
const polarCoords = [];
|
||||
|
||||
for (let radialIndex = 0; radialIndex < radialSegments; radialIndex += 1) {
|
||||
const innerDistance = (reachDeg * radialIndex) / radialSegments;
|
||||
const outerDistance = (reachDeg * (radialIndex + 1)) / radialSegments;
|
||||
const rInnerNorm = radialIndex / radialSegments;
|
||||
const rOuterNorm = (radialIndex + 1) / radialSegments;
|
||||
const innerDistance = reachDeg * rInnerNorm;
|
||||
const outerDistance = reachDeg * rOuterNorm;
|
||||
|
||||
for (let angularIndex = 0; angularIndex < angularSegments; angularIndex += 1) {
|
||||
const startProgress = angularIndex / angularSegments;
|
||||
const endProgress = (angularIndex + 1) / angularSegments;
|
||||
const startBearing = startBearingDeg + (endBearingDeg - startBearingDeg) * startProgress;
|
||||
const endBearing = startBearingDeg + (endBearingDeg - startBearingDeg) * endProgress;
|
||||
const startAngle = (angularIndex / angularSegments) * Math.PI * 2;
|
||||
const endAngle = ((angularIndex + 1) / angularSegments) * Math.PI * 2;
|
||||
const startBearing = (startAngle * 180) / Math.PI;
|
||||
const endBearing = (endAngle * 180) / Math.PI;
|
||||
|
||||
const innerStart = projectLatLon(anchorLatitude, anchorLongitude, startBearing, innerDistance);
|
||||
const innerEnd = projectLatLon(anchorLatitude, anchorLongitude, endBearing, innerDistance);
|
||||
const outerStart = projectLatLon(anchorLatitude, anchorLongitude, startBearing, outerDistance);
|
||||
const outerEnd = projectLatLon(anchorLatitude, anchorLongitude, endBearing, outerDistance);
|
||||
|
||||
const innerStartVector = latLonToVector3(innerStart.latitude, innerStart.longitude, altitude);
|
||||
const innerEndVector = latLonToVector3(innerEnd.latitude, innerEnd.longitude, altitude);
|
||||
const outerStartVector = latLonToVector3(outerStart.latitude, outerStart.longitude, altitude);
|
||||
const outerEndVector = latLonToVector3(outerEnd.latitude, outerEnd.longitude, altitude);
|
||||
const vIS = latLonToVector3(innerStart.latitude, innerStart.longitude, altitude);
|
||||
const vIE = latLonToVector3(innerEnd.latitude, innerEnd.longitude, altitude);
|
||||
const vOS = latLonToVector3(outerStart.latitude, outerStart.longitude, altitude);
|
||||
const vOE = latLonToVector3(outerEnd.latitude, outerEnd.longitude, altitude);
|
||||
|
||||
positions.push(
|
||||
innerStartVector.x, innerStartVector.y, innerStartVector.z,
|
||||
outerStartVector.x, outerStartVector.y, outerStartVector.z,
|
||||
outerEndVector.x, outerEndVector.y, outerEndVector.z,
|
||||
vIS.x, vIS.y, vIS.z,
|
||||
vOS.x, vOS.y, vOS.z,
|
||||
vOE.x, vOE.y, vOE.z,
|
||||
vIS.x, vIS.y, vIS.z,
|
||||
vOE.x, vOE.y, vOE.z,
|
||||
vIE.x, vIE.y, vIE.z,
|
||||
);
|
||||
positions.push(
|
||||
innerStartVector.x, innerStartVector.y, innerStartVector.z,
|
||||
outerEndVector.x, outerEndVector.y, outerEndVector.z,
|
||||
innerEndVector.x, innerEndVector.y, innerEndVector.z,
|
||||
polarCoords.push(
|
||||
rInnerNorm, startAngle,
|
||||
rOuterNorm, startAngle,
|
||||
rOuterNorm, endAngle,
|
||||
rInnerNorm, startAngle,
|
||||
rOuterNorm, endAngle,
|
||||
rInnerNorm, endAngle,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
|
||||
geometry.setAttribute("aPolar", new THREE.Float32BufferAttribute(polarCoords, 2));
|
||||
geometry.computeVertexNormals();
|
||||
|
||||
const material = new THREE.MeshBasicMaterial({
|
||||
color,
|
||||
const material = new THREE.ShaderMaterial({
|
||||
uniforms: {
|
||||
uColor: { value: color instanceof THREE.Color ? color.clone() : new THREE.Color(color) },
|
||||
uOpacity: { value: opacity },
|
||||
uTime: { value: (typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001 },
|
||||
uScanSpeed: { value: scanSpeed },
|
||||
uSectorHalfSpan: { value: sectorHalfSpan },
|
||||
},
|
||||
extensions: { derivatives: true },
|
||||
vertexShader: BGP_RADAR_VERTEX_SHADER,
|
||||
fragmentShader: BGP_RADAR_FRAGMENT_SHADER,
|
||||
transparent: true,
|
||||
opacity,
|
||||
side: THREE.DoubleSide,
|
||||
depthWrite: false,
|
||||
depthTest: true,
|
||||
polygonOffset: true,
|
||||
polygonOffsetFactor: 1,
|
||||
polygonOffsetUnits: 1,
|
||||
blending: THREE.AdditiveBlending,
|
||||
blending: THREE.NormalBlending,
|
||||
toneMapped: false,
|
||||
});
|
||||
|
||||
return new THREE.Mesh(geometry, material);
|
||||
}
|
||||
|
||||
function createRadialBoundaryPoints(
|
||||
anchorLatitude,
|
||||
anchorLongitude,
|
||||
bearingDeg,
|
||||
reachDeg,
|
||||
altitude,
|
||||
segments = 18,
|
||||
) {
|
||||
const points = [];
|
||||
|
||||
for (let step = 0; step <= segments; step += 1) {
|
||||
const progress = step / segments;
|
||||
const projected = projectLatLon(
|
||||
anchorLatitude,
|
||||
anchorLongitude,
|
||||
bearingDeg,
|
||||
reachDeg * progress,
|
||||
);
|
||||
points.push(
|
||||
latLonToVector3(
|
||||
projected.latitude,
|
||||
projected.longitude,
|
||||
altitude,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
function attachCollectorEffectSprites(marker) {
|
||||
const activity = marker.userData.activity;
|
||||
const heatHalo = createOverlaySprite({
|
||||
@@ -1792,34 +1819,6 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
|
||||
const coverageColor = collectorBaseColor;
|
||||
const boundaryAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.44;
|
||||
const fillAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.4;
|
||||
const leftBoundaryPoints = createRadialBoundaryPoints(
|
||||
anchorLatitude,
|
||||
anchorLongitude,
|
||||
startBearing,
|
||||
corridorReach,
|
||||
boundaryAltitude,
|
||||
);
|
||||
const rightBoundaryPoints = createRadialBoundaryPoints(
|
||||
anchorLatitude,
|
||||
anchorLongitude,
|
||||
endBearing,
|
||||
corridorReach,
|
||||
boundaryAltitude,
|
||||
);
|
||||
const outerArcPoints = [];
|
||||
const outerArcSteps = 28;
|
||||
for (let step = 0; step <= outerArcSteps; step += 1) {
|
||||
const progress = step / outerArcSteps;
|
||||
const bearingDeg = startBearing + (endBearing - startBearing) * progress;
|
||||
const projected = projectLatLon(anchorLatitude, anchorLongitude, bearingDeg, corridorReach);
|
||||
outerArcPoints.push(
|
||||
latLonToVector3(
|
||||
projected.latitude,
|
||||
projected.longitude,
|
||||
boundaryAltitude,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const sectorFill = createCoverageSectorMesh(
|
||||
anchorLatitude,
|
||||
@@ -1829,40 +1828,16 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
|
||||
corridorReach,
|
||||
fillAltitude,
|
||||
coverageColor,
|
||||
0.12,
|
||||
0.24,
|
||||
);
|
||||
sectorFill.renderOrder = 2;
|
||||
bgpCollectorRadarGroup.add(sectorFill);
|
||||
|
||||
const outerArc = createCoverageBoundaryLine(
|
||||
outerArcPoints,
|
||||
coverageColor,
|
||||
0.9,
|
||||
);
|
||||
outerArc.renderOrder = 3;
|
||||
bgpCollectorRadarGroup.add(outerArc);
|
||||
|
||||
const leftBoundary = createCoverageBoundaryLine(
|
||||
leftBoundaryPoints,
|
||||
coverageColor,
|
||||
0.76,
|
||||
);
|
||||
leftBoundary.renderOrder = 3;
|
||||
bgpCollectorRadarGroup.add(leftBoundary);
|
||||
|
||||
const rightBoundary = createCoverageBoundaryLine(
|
||||
rightBoundaryPoints,
|
||||
coverageColor,
|
||||
0.76,
|
||||
);
|
||||
rightBoundary.renderOrder = 3;
|
||||
bgpCollectorRadarGroup.add(rightBoundary);
|
||||
|
||||
activeCollectorOverlayContext = {
|
||||
marker,
|
||||
earth,
|
||||
baseRotation,
|
||||
lastRebuildAt: performance.now(),
|
||||
radarMaterial: sectorFill.material,
|
||||
};
|
||||
bgpOverlayGroup.visible = showBGP;
|
||||
}
|
||||
@@ -1883,17 +1858,10 @@ function updateCollectorOverlayScan(lockedObjectType, lockedObject) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = performance.now();
|
||||
if (now - activeCollectorOverlayContext.lastRebuildAt < COLLECTOR_SCAN_REBUILD_MS) {
|
||||
return;
|
||||
const uniforms = activeCollectorOverlayContext.radarMaterial?.uniforms;
|
||||
if (uniforms?.uTime) {
|
||||
uniforms.uTime.value = (typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001;
|
||||
}
|
||||
|
||||
const rotationOffsetRad = now * COLLECTOR_SCAN_SPEED_RAD;
|
||||
showBGPCollectorCoverageOverlay(
|
||||
activeCollectorOverlayContext.marker,
|
||||
activeCollectorOverlayContext.earth,
|
||||
{ rotationOffsetRad },
|
||||
);
|
||||
}
|
||||
|
||||
export function getBGPLegendItems() {
|
||||
|
||||
@@ -91,10 +91,11 @@ export function createCableLineBatch(lines) {
|
||||
vec3 color = vStyle.rgb;
|
||||
if (vStyle.a < 0.0) {
|
||||
float pulse = smoothstep(0.6, 1.0, fract(vProgress * ${CABLE_CONFIG.visual.pulseRepeats.toFixed(1)} - uTime * ${CABLE_CONFIG.visual.pulseSpeed.toFixed(1)}));
|
||||
color = mix(vec3(0.3, 0.8, 1.0), vec3(0.7, 1.0, 1.0), pulse);
|
||||
color = mix(vec3(0.073, 0.604, 1.0), vec3(0.448, 1.0, 1.0), pulse);
|
||||
alpha = max(alpha, 0.8 + pulse * 0.2);
|
||||
}
|
||||
gl_FragColor = vec4(color, alpha);
|
||||
#include <colorspace_fragment>
|
||||
}
|
||||
`,
|
||||
});
|
||||
@@ -184,17 +185,18 @@ export function createLandingPointBatch(markers, texture) {
|
||||
float radius = distance(coreUv, vec2(0.5));
|
||||
float border = smoothstep(0.242, 0.254, radius) * (1.0 - smoothstep(0.283, 0.296, radius));
|
||||
float brightness = max(vStyle.r, max(vStyle.g, vStyle.b));
|
||||
color.rgb = mix(color.rgb, vec3(1.0, 0.86, 0.3) * brightness, border);
|
||||
color.rgb = mix(color.rgb, vec3(1.0, 0.71, 0.073) * brightness, border);
|
||||
// The normal yellow core stays unchanged; only related points glow.
|
||||
float halo = exp(-radius * radius * ${CABLE_CONFIG.landingPointVisual.related.haloFalloff.toFixed(1)})
|
||||
* smoothstep(0.29, 0.32, radius)
|
||||
* (1.0 - smoothstep(0.7, 0.82, radius)) * vEmphasis;
|
||||
float haloAlpha = halo * vStyle.a;
|
||||
float alpha = color.a + haloAlpha * (1.0 - color.a);
|
||||
color.rgb = (color.rgb * color.a + vec3(1.0, 0.63, 0.08) * haloAlpha * (1.0 - color.a)) / max(alpha, 0.001);
|
||||
color.rgb = (color.rgb * color.a + vec3(1.0, 0.355, 0.007) * haloAlpha * (1.0 - color.a)) / max(alpha, 0.001);
|
||||
color.a = alpha;
|
||||
if (color.a < 0.01) discard;
|
||||
gl_FragColor = color;
|
||||
#include <colorspace_fragment>
|
||||
}
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ test("only related landing points get a glow and clearing selection removes it",
|
||||
return marker;
|
||||
});
|
||||
const batch = createLandingPointBatch(markers, texture);
|
||||
expect(batch.object.material.fragmentShader).toContain("#include <colorspace_fragment>");
|
||||
batch.object.onBeforeRender();
|
||||
const emphasis = batch.object.geometry.attributes.emphasis;
|
||||
expect(emphasis.getX(0)).toBe(0);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { isLegendItemEnabled } from "./legend-filters.js";
|
||||
|
||||
import * as THREE from "three";
|
||||
import { createCableLineBatch, createLandingPointBatch } from "./cable-batches.js";
|
||||
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
|
||||
import { cableSurfacePoint, calculateGreatCirclePoints } from "./cable-surface.js";
|
||||
import { configureColorTexture } from "./texture-colors.js";
|
||||
|
||||
@@ -28,6 +29,15 @@ let cableStates = new Map();
|
||||
let cablesVisible = true;
|
||||
let cableLineBatch = null;
|
||||
let landingPointBatch = null;
|
||||
let lockedCableRibbonMesh = null;
|
||||
|
||||
function clearLockedCableRibbon() {
|
||||
if (!lockedCableRibbonMesh) return;
|
||||
lockedCableRibbonMesh.parent?.remove?.(lockedCableRibbonMesh);
|
||||
lockedCableRibbonMesh.geometry?.dispose?.();
|
||||
lockedCableRibbonMesh.material?.dispose?.();
|
||||
lockedCableRibbonMesh = null;
|
||||
}
|
||||
const _lpEarthWorldPos = new THREE.Vector3();
|
||||
const _lpWorldPos = new THREE.Vector3();
|
||||
const _lpCameraRel = new THREE.Vector3();
|
||||
@@ -43,10 +53,11 @@ let landingPointTexture = null;
|
||||
function getLandingPointDimColor() {
|
||||
const dimColor = CABLE_CONFIG.landingPointVisual.dimmed.colorRGB;
|
||||
const brightness = CABLE_CONFIG.landingPointVisual.dimBrightness;
|
||||
const color = new THREE.Color(
|
||||
const color = new THREE.Color().setRGB(
|
||||
(dimColor.r * brightness) / 255,
|
||||
(dimColor.g * brightness) / 255,
|
||||
(dimColor.b * brightness) / 255,
|
||||
...(THREE.SRGBColorSpace ? [THREE.SRGBColorSpace] : []),
|
||||
);
|
||||
return `#${color.getHexString()}`;
|
||||
}
|
||||
@@ -401,10 +412,10 @@ export async function loadLandingPoints(scene, earthObj, options = {}) {
|
||||
marker.userData = {
|
||||
type: "landingPoint",
|
||||
source_id: properties.source_id,
|
||||
name: properties.name || "未知登陆站",
|
||||
name: properties.name || "未知登陆点",
|
||||
cableNames: properties.cable_names || [],
|
||||
country: properties.country || "未知国家",
|
||||
status: properties.status || "Unknown",
|
||||
status: properties.status || "未知",
|
||||
latitude: lat,
|
||||
longitude: lon,
|
||||
landing_visual_state: "normal",
|
||||
@@ -435,13 +446,56 @@ export async function loadLandingPoints(scene, earthObj, options = {}) {
|
||||
}
|
||||
|
||||
export function handleCableClick(cable) {
|
||||
clearLockedCableRibbon();
|
||||
lockedCable = cable;
|
||||
|
||||
if (cable) {
|
||||
const cableId = cable.userData?.id;
|
||||
const segments = (cableId ? getCablesById(cableId) : [cable]).filter(Boolean);
|
||||
const polylines = [];
|
||||
for (const line of segments) {
|
||||
const posAttr = line?.geometry?.attributes?.position;
|
||||
if (!posAttr || posAttr.count < 2) continue;
|
||||
const pts = [];
|
||||
for (let i = 0; i < posAttr.count; i += 1) {
|
||||
pts.push(new THREE.Vector3(posAttr.getX(i), posAttr.getY(i), posAttr.getZ(i)));
|
||||
}
|
||||
if (pts.length >= 2) polylines.push(pts);
|
||||
}
|
||||
const parent = cable.parent || cableLineBatch?.object?.parent;
|
||||
if (parent && polylines.length > 0) {
|
||||
const color = cable.userData?.originalColor ?? 0x38bdf8;
|
||||
const ribbonGeo = createSurfaceRibbonGeometry(polylines);
|
||||
const ribbonMat = createSurfaceRibbonMaterial({
|
||||
color,
|
||||
halfWidthPx: 4.8,
|
||||
opacity: 0.92,
|
||||
pulseSpeed: 0.65,
|
||||
pulseFreq: 2.6,
|
||||
pulseIntensity: 0.68,
|
||||
additive: true,
|
||||
});
|
||||
lockedCableRibbonMesh = new THREE.Mesh(ribbonGeo, ribbonMat);
|
||||
lockedCableRibbonMesh.name = "locked-cable-glow-ribbon";
|
||||
lockedCableRibbonMesh.renderOrder = (CABLE_CONFIG.lineRenderOrder || 1.1) + 0.08;
|
||||
lockedCableRibbonMesh.raycast = () => {};
|
||||
lockedCableRibbonMesh.visible = cablesVisible;
|
||||
const startedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
|
||||
lockedCableRibbonMesh.onBeforeRender = () => {
|
||||
const now = typeof performance !== "undefined" ? performance.now() : Date.now();
|
||||
ribbonMat.uniforms.uTime.value = (now - startedAt) * 0.001;
|
||||
};
|
||||
parent.add(lockedCableRibbonMesh);
|
||||
}
|
||||
}
|
||||
|
||||
setLegendItems("cables", getCableLegendItems());
|
||||
|
||||
setLegendMode("cables");
|
||||
}
|
||||
|
||||
export function clearCableSelection() {
|
||||
clearLockedCableRibbon();
|
||||
lockedCable = null;
|
||||
setLegendItems("cables", getCableLegendItems());
|
||||
}
|
||||
@@ -605,6 +659,7 @@ export function toggleCables(show) {
|
||||
cablesVisible = show;
|
||||
if (cableLineBatch) cableLineBatch.object.visible = show;
|
||||
if (landingPointBatch) landingPointBatch.object.visible = show;
|
||||
if (lockedCableRibbonMesh) lockedCableRibbonMesh.visible = Boolean(show);
|
||||
cableLines.forEach((cable) => {
|
||||
cable.visible = cablesVisible && isLegendItemEnabled("cables", cable.userData?.name || "未知线缆");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { createConnectorPath, createSlidingConnectorPoints } from "./callout-connector.js";
|
||||
|
||||
const detailCard = { x: 80, y: 120, width: 320, height: 380 };
|
||||
|
||||
test("aligned horizontal detail card prefers one balanced upward bend toward header", () => {
|
||||
const source = { x: 640, y: 310 };
|
||||
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
|
||||
expect(path).not.toBeNull();
|
||||
expect(path.points).toHaveLength(3);
|
||||
|
||||
const [p0, p1, p2] = path.points;
|
||||
expect(p0).toEqual(source);
|
||||
expect(p2.x).toBe(408);
|
||||
expect(p2.y).toBeLessThan(source.y);
|
||||
expect(p2.y).toBeGreaterThanOrEqual(detailCard.y + 12);
|
||||
expect(p2.y).toBeLessThanOrEqual(detailCard.y + detailCard.height - 12);
|
||||
expect(p1.y).toBe(p2.y);
|
||||
|
||||
const seg1 = Math.hypot(p1.x - p0.x, p1.y - p0.y);
|
||||
const seg2 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
|
||||
const total = seg1 + seg2;
|
||||
expect(seg1 / total).toBeGreaterThanOrEqual(0.44);
|
||||
expect(seg1 / total).toBeLessThanOrEqual(0.56);
|
||||
|
||||
expect(p1.x).toBeLessThanOrEqual(p0.x);
|
||||
expect(p1.x).toBeGreaterThanOrEqual(p2.x);
|
||||
});
|
||||
|
||||
test("aligned horizontal point near card top bends downward smoothly into card body", () => {
|
||||
const source = { x: 640, y: 140 };
|
||||
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
|
||||
expect(path).not.toBeNull();
|
||||
expect(path.points).toHaveLength(3);
|
||||
|
||||
const [, p1, p2] = path.points;
|
||||
expect(p2.x).toBe(408);
|
||||
expect(p2.y).toBeGreaterThan(source.y);
|
||||
expect(p2.y).toBeLessThanOrEqual(detailCard.y + detailCard.height - 12);
|
||||
expect(p1.y).toBe(p2.y);
|
||||
});
|
||||
|
||||
test("small natural offset outside safe span preserves direction and deepens to crisp bend", () => {
|
||||
const source = { x: 640, y: 124 };
|
||||
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
|
||||
expect(path).not.toBeNull();
|
||||
expect(path.points).toHaveLength(3);
|
||||
|
||||
const [, , p2] = path.points;
|
||||
expect(p2.x).toBe(408);
|
||||
expect(p2.y).toBeGreaterThan(source.y + 18);
|
||||
expect(p2.y).toBeLessThanOrEqual(detailCard.y + detailCard.height - 12);
|
||||
});
|
||||
|
||||
test("short compact capsule and close-range sources fall back cleanly to straight line", () => {
|
||||
const capsule = { x: 80, y: 200, width: 220, height: 42 };
|
||||
const capsulePath = createSlidingConnectorPoints({ x: 480, y: 221 }, capsule, { targetGapPx: 8 });
|
||||
expect(capsulePath).not.toBeNull();
|
||||
expect(capsulePath.points).toHaveLength(2);
|
||||
|
||||
const closePath = createSlidingConnectorPoints({ x: 444, y: 310 }, detailCard, { targetGapPx: 8 });
|
||||
expect(closePath).not.toBeNull();
|
||||
expect(closePath.points).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("aligned vertical entrance produces one horizontal bend within safe corner padding", () => {
|
||||
const source = { x: 240, y: 640 };
|
||||
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
|
||||
expect(path).not.toBeNull();
|
||||
expect(path.points).toHaveLength(3);
|
||||
|
||||
const [, p1, p2] = path.points;
|
||||
expect(p2.y).toBe(508);
|
||||
expect(p2.x).toBeLessThan(source.x);
|
||||
expect(p2.x).toBeGreaterThanOrEqual(detailCard.x + 12);
|
||||
expect(p2.x).toBeLessThanOrEqual(detailCard.x + detailCard.width - 12);
|
||||
expect(p1.x).toBe(p2.x);
|
||||
});
|
||||
|
||||
test("preferBend false preserves straight line for aligned cards", () => {
|
||||
const path = createConnectorPath({ x: 640, y: 310 }, detailCard, {
|
||||
targetGapPx: 8,
|
||||
preferBend: false,
|
||||
});
|
||||
expect(path).not.toBeNull();
|
||||
expect(path.points).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("connector sweep never exceeds one bend across surrounding positions", () => {
|
||||
for (let x = 20; x <= 760; x += 60) {
|
||||
for (let y = 40; y <= 620; y += 45) {
|
||||
const path = createSlidingConnectorPoints({ x, y }, detailCard, { targetGapPx: 8 });
|
||||
expect(path).not.toBeNull();
|
||||
expect(path.points.length === 2 || path.points.length === 3).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -10,6 +10,13 @@ const DEFAULT_CLASS_NAME = "callout-connector";
|
||||
const DEFAULT_DRAW_ANIMATION_NAME = "calloutConnectorDraw";
|
||||
const DEFAULT_SOURCE_ANCHOR_GAP_PX = 6;
|
||||
const MIN_SOURCE_ANCHOR_GAP_PX = 4;
|
||||
const MIN_BEND_MAJOR_PX = 48;
|
||||
const MIN_BEND_MINOR_PX = 18;
|
||||
const PREFERRED_BEND_MIN_PX = 24;
|
||||
const PREFERRED_BEND_MAX_PX = 72;
|
||||
const PREFERRED_BEND_RATIO = 0.24;
|
||||
const MAX_BEND_SLOPE_RATIO = 0.42;
|
||||
const BEND_CORNER_PADDING_PX = 12;
|
||||
|
||||
// A connector only needs a surface around its own path, not a full-screen
|
||||
// SVG per card. Include the node animation and selection shadow extents.
|
||||
@@ -527,6 +534,58 @@ function createAdaptiveConnectorPoints(source, target, options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function applyPreferredOneBendAnchor(start, end, targetRect) {
|
||||
if (!start || !end || !targetRect) return end;
|
||||
const isHorizontalEntrance = end.side === "left" || end.side === "right";
|
||||
const dMajor = isHorizontalEntrance ? Math.abs(end.x - start.x) : Math.abs(end.y - start.y);
|
||||
if (dMajor < MIN_BEND_MAJOR_PX) return end;
|
||||
|
||||
const startAxis = isHorizontalEntrance ? start.y : start.x;
|
||||
const endAxis = isHorizontalEntrance ? end.y : end.x;
|
||||
const dMinor = Math.abs(endAxis - startAxis);
|
||||
const desiredMinor = Math.min(
|
||||
clamp(dMajor * PREFERRED_BEND_RATIO, PREFERRED_BEND_MIN_PX, PREFERRED_BEND_MAX_PX),
|
||||
dMajor * MAX_BEND_SLOPE_RATIO,
|
||||
);
|
||||
if (dMinor >= desiredMinor) return end;
|
||||
|
||||
const rectMin = isHorizontalEntrance ? targetRect.top : targetRect.left;
|
||||
const rectMax = isHorizontalEntrance ? targetRect.bottom : targetRect.right;
|
||||
const edgeLength = Math.max(0, rectMax - rectMin);
|
||||
const cornerPadding = Math.min(BEND_CORNER_PADDING_PX, edgeLength * 0.5);
|
||||
const edgeMin = rectMin + cornerPadding;
|
||||
const edgeMax = rectMax - cornerPadding;
|
||||
if (edgeMax - edgeMin < MIN_BEND_MINOR_PX) return end;
|
||||
|
||||
let nextAxis = endAxis;
|
||||
if (dMinor >= 4) {
|
||||
const sign = endAxis >= startAxis ? 1 : -1;
|
||||
const candidate = clamp(startAxis + sign * desiredMinor, edgeMin, edgeMax);
|
||||
const gain = Math.abs(candidate - startAxis);
|
||||
if (gain < MIN_BEND_MINOR_PX || gain <= dMinor) return end;
|
||||
nextAxis = candidate;
|
||||
} else {
|
||||
const candMin = clamp(startAxis - desiredMinor, edgeMin, edgeMax);
|
||||
const candMax = clamp(startAxis + desiredMinor, edgeMin, edgeMax);
|
||||
const gainMin = startAxis - candMin;
|
||||
const gainMax = candMax - startAxis;
|
||||
if (gainMin >= desiredMinor - 0.5) {
|
||||
nextAxis = candMin;
|
||||
} else if (gainMax >= desiredMinor - 0.5) {
|
||||
nextAxis = candMax;
|
||||
} else if (Math.max(gainMin, gainMax) >= MIN_BEND_MINOR_PX) {
|
||||
nextAxis = gainMin >= gainMax ? candMin : candMax;
|
||||
} else {
|
||||
return end;
|
||||
}
|
||||
}
|
||||
|
||||
const ratio = (nextAxis - rectMin) / Math.max(1, edgeLength);
|
||||
return isHorizontalEntrance
|
||||
? { ...end, y: nextAxis, ratio }
|
||||
: { ...end, x: nextAxis, ratio };
|
||||
}
|
||||
|
||||
export function createSlidingConnectorPoints(source, target, options = {}) {
|
||||
const resolvedSource = resolveConnectorAnchor(source);
|
||||
if (!resolvedSource) return null;
|
||||
@@ -579,6 +638,10 @@ export function createSlidingConnectorPoints(source, target, options = {}) {
|
||||
}
|
||||
if (!end) return null;
|
||||
|
||||
if (options.preferBend !== false && candidateSides.length > 0) {
|
||||
end = applyPreferredOneBendAnchor(start, end, targetRect);
|
||||
}
|
||||
|
||||
const normal = { left: [-1, 0], right: [1, 0], top: [0, -1], bottom: [0, 1] }[end.side];
|
||||
const deltaX = Math.abs(end.x - start.x);
|
||||
const deltaY = Math.abs(end.y - start.y);
|
||||
|
||||
@@ -1,9 +1,169 @@
|
||||
import * as THREE from "three";
|
||||
import { CONFIG, BGP_CONFIG } from "./constants.js";
|
||||
import { COMPUTE_SITE_TYPES } from "./compute-site-types.js";
|
||||
import { getEarthLocale, translateText } from "./i18n.js";
|
||||
import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js";
|
||||
import { createClusterTween } from "./cluster-motion.js";
|
||||
import { markerPresentationId, markerStackGroups, markerStackLayout } from "./marker-stack.js";
|
||||
|
||||
const CLUSTER_RING_GAP_DEG = 4;
|
||||
const CLUSTER_RING_DIVIDER_COLOR = "rgba(6, 13, 24, 0.92)";
|
||||
|
||||
export const CLUSTER_KIND_PRIORITY = Object.freeze({
|
||||
supercomputer: 0,
|
||||
gpu_cluster: 1,
|
||||
data_center: 2,
|
||||
cloud_center: 3,
|
||||
edge_node: 4,
|
||||
critical: 10,
|
||||
high: 11,
|
||||
medium: 12,
|
||||
low: 13,
|
||||
hot: 20,
|
||||
idle: 24,
|
||||
military: 30,
|
||||
passenger: 31,
|
||||
cargo: 32,
|
||||
tanker: 33,
|
||||
fishing: 34,
|
||||
other: 35,
|
||||
});
|
||||
|
||||
const BGP_SEVERITY_LABELS = Object.freeze({
|
||||
critical: "严重事件",
|
||||
high: "高危事件",
|
||||
medium: "中危事件",
|
||||
low: "低危事件",
|
||||
});
|
||||
|
||||
const BGP_COLLECTOR_TIER_LABELS = Object.freeze({
|
||||
hot: "高活跃观测站",
|
||||
high: "高活跃观测站",
|
||||
medium: "中活跃观测站",
|
||||
low: "低活跃观测站",
|
||||
idle: "静态观测站",
|
||||
});
|
||||
|
||||
const VESSEL_KIND_LABELS = Object.freeze({
|
||||
cargo: "货轮",
|
||||
tanker: "油轮",
|
||||
passenger: "客船",
|
||||
fishing: "渔船",
|
||||
military: "军舰",
|
||||
other: "其他船只",
|
||||
});
|
||||
|
||||
export function getClusterKindLabel(type, kind) {
|
||||
if (kind && Object.hasOwn(COMPUTE_SITE_TYPES, kind)) {
|
||||
return translateText(COMPUTE_SITE_TYPES[kind].label);
|
||||
}
|
||||
if (type === "bgp" && kind && Object.hasOwn(BGP_SEVERITY_LABELS, kind)) {
|
||||
return translateText(BGP_SEVERITY_LABELS[kind]);
|
||||
}
|
||||
if (type === "bgp_collector" && kind && Object.hasOwn(BGP_COLLECTOR_TIER_LABELS, kind)) {
|
||||
return translateText(BGP_COLLECTOR_TIER_LABELS[kind]);
|
||||
}
|
||||
if (type === "vessel" && kind && Object.hasOwn(VESSEL_KIND_LABELS, kind)) {
|
||||
return translateText(VESSEL_KIND_LABELS[kind]);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function resolveKindPriority(type, kind) {
|
||||
if (type === "bgp_collector" && kind === "high") return 21;
|
||||
if (type === "bgp_collector" && kind === "medium") return 22;
|
||||
if (type === "bgp_collector" && kind === "low") return 23;
|
||||
if (kind && Object.hasOwn(CLUSTER_KIND_PRIORITY, kind)) {
|
||||
return CLUSTER_KIND_PRIORITY[kind];
|
||||
}
|
||||
return 999;
|
||||
}
|
||||
|
||||
export function summarizeClusterComposition(members, getOwner) {
|
||||
const byTypeKind = new Map();
|
||||
for (const marker of members) {
|
||||
const type = String(marker?.userData?.type || "");
|
||||
const kind = String(marker?.userData?.icon_kind || "");
|
||||
const key = `${type}:${kind}`;
|
||||
const existing = byTypeKind.get(key);
|
||||
if (existing) {
|
||||
existing.count += 1;
|
||||
continue;
|
||||
}
|
||||
const owner = getOwner?.(marker);
|
||||
const color = owner?.getMarkerColor?.(marker) || "#38bdf8";
|
||||
byTypeKind.set(key, { key, type, kind, color, count: 1 });
|
||||
}
|
||||
const groups = [...byTypeKind.values()].sort((a, b) => (
|
||||
b.count - a.count
|
||||
|| resolveKindPriority(a.type, a.kind) - resolveKindPriority(b.type, b.kind)
|
||||
|| a.key.localeCompare(b.key)
|
||||
));
|
||||
return {
|
||||
groups,
|
||||
total: members.length,
|
||||
isMixed: groups.length > 1,
|
||||
dominantColor: groups[0]?.color || "#38bdf8",
|
||||
};
|
||||
}
|
||||
|
||||
export function buildClusterRingGradient(groups, total) {
|
||||
if (!Array.isArray(groups) || groups.length <= 1 || total <= 0) {
|
||||
return "none";
|
||||
}
|
||||
const available = 360 - groups.length * CLUSTER_RING_GAP_DEG;
|
||||
const minDeg = Math.min(20, available / (groups.length * 2));
|
||||
const rawDegrees = groups.map((group) => (group.count / total) * available);
|
||||
let deficit = 0;
|
||||
let totalSurplus = 0;
|
||||
for (const deg of rawDegrees) {
|
||||
if (deg < minDeg) deficit += minDeg - deg;
|
||||
else totalSurplus += deg - minDeg;
|
||||
}
|
||||
const degrees = rawDegrees.map((deg) => {
|
||||
if (deg < minDeg) return minDeg;
|
||||
if (deficit > 0 && totalSurplus > 0) {
|
||||
return deg - deficit * ((deg - minDeg) / totalSurplus);
|
||||
}
|
||||
return deg;
|
||||
});
|
||||
|
||||
const stops = [];
|
||||
let cursor = 0;
|
||||
groups.forEach((group, index) => {
|
||||
const start = cursor;
|
||||
const end = start + degrees[index];
|
||||
const gapEnd = index === groups.length - 1 ? 360 : end + CLUSTER_RING_GAP_DEG;
|
||||
stops.push(`${group.color} ${start.toFixed(1)}deg ${end.toFixed(1)}deg`);
|
||||
stops.push(`${CLUSTER_RING_DIVIDER_COLOR} ${end.toFixed(1)}deg ${gapEnd.toFixed(1)}deg`);
|
||||
cursor = gapEnd;
|
||||
});
|
||||
return `conic-gradient(from 0deg, ${stops.join(", ")})`;
|
||||
}
|
||||
|
||||
export function formatClusterTitle(members, composition) {
|
||||
const sampleNames = members
|
||||
.slice(0, 3)
|
||||
.map((marker) => marker.userData?.name || marker.userData?.collector || marker.userData?.title || marker.userData?.type)
|
||||
.filter(Boolean)
|
||||
.join(" / ");
|
||||
if (composition.isMixed) {
|
||||
const breakdown = composition.groups
|
||||
.map((group) => {
|
||||
const label = getClusterKindLabel(group.type, group.kind);
|
||||
return label ? `${label} ${group.count}` : `${group.kind || group.type} ${group.count}`;
|
||||
})
|
||||
.join(" / ");
|
||||
return `${members.length} · ${breakdown}${sampleNames ? ` · ${sampleNames}` : ""}`;
|
||||
}
|
||||
const sole = composition.groups[0];
|
||||
const soleLabel = sole ? getClusterKindLabel(sole.type, sole.kind) : "";
|
||||
if (soleLabel) {
|
||||
return `${members.length} ${soleLabel}${sampleNames ? ` · ${sampleNames}` : ""}`;
|
||||
}
|
||||
return `${members.length} · ${sampleNames}`;
|
||||
}
|
||||
|
||||
export function createClusterPresentation({ getOwner, onHiddenChange }) {
|
||||
const entries = new Map();
|
||||
let root = null, svg = null, expandedId = null, previousZoom = null;
|
||||
@@ -204,17 +364,22 @@ export function createClusterPresentation({ getOwner, onHiddenChange }) {
|
||||
}
|
||||
const owner = getOwner(members[0]);
|
||||
const center = project(entry.record.position, owner, camera);
|
||||
const types = new Set(members.map(marker => `${marker.userData.type}:${marker.userData.icon_kind}`));
|
||||
const color = owner.getMarkerColor(members[0]);
|
||||
entry.button.style.setProperty("--cluster-color", color);
|
||||
entry.button.classList.toggle("is-mixed", types.size > 1);
|
||||
entry.button.classList.toggle("has-bgp", members.some(marker => ["bgp","bgp_collector"].includes(marker.userData.type)));
|
||||
const countText = String(members.length);
|
||||
if (entry.count.textContent !== countText) entry.count.textContent = countText;
|
||||
const title = `${members.length} · ${members.slice(0,3).map(marker => marker.userData.name || marker.userData.collector || marker.userData.type).join(" / ")}`;
|
||||
if (entry.button.title !== title) {
|
||||
entry.button.title = title;
|
||||
entry.button.setAttribute("aria-label", title);
|
||||
const composition = summarizeClusterComposition(members, getOwner);
|
||||
const hasBgp = members.some(marker => ["bgp", "bgp_collector"].includes(marker.userData.type));
|
||||
const visualKey = `${getEarthLocale()}|${composition.groups.map(group => `${group.key}:${group.count}:${group.color}`).join(",")}|${members.slice(0, 3).map(idOf).join(",")}|${hasBgp}`;
|
||||
if (entry.visualKey !== visualKey) {
|
||||
entry.visualKey = visualKey;
|
||||
entry.button.style.setProperty("--cluster-color", composition.dominantColor);
|
||||
entry.button.style.setProperty("--cluster-ring", buildClusterRingGradient(composition.groups, composition.total));
|
||||
entry.button.classList.toggle("is-mixed", composition.isMixed);
|
||||
entry.button.classList.toggle("has-bgp", hasBgp);
|
||||
const countText = String(members.length);
|
||||
if (entry.count.textContent !== countText) entry.count.textContent = countText;
|
||||
const title = formatClusterTitle(members, composition);
|
||||
if (entry.button.title !== title) {
|
||||
entry.button.title = title;
|
||||
entry.button.setAttribute("aria-label", title);
|
||||
}
|
||||
}
|
||||
const ariaExpanded = String(progress > 0.5);
|
||||
if (entry.ariaExpanded !== ariaExpanded) {
|
||||
|
||||
@@ -2,10 +2,14 @@ import {expect,test,spyOn} from "bun:test";
|
||||
import * as THREE from "three";
|
||||
import {createInteractableLayer,updateInteractableClusters,clearInteractableClusters} from "./interactable.js";
|
||||
import {distanceForGlobeZoom} from "./globe-navigation.js";
|
||||
import {createClusterPresentation} from "./cluster-presentation.js";
|
||||
import {
|
||||
buildClusterRingGradient,
|
||||
createClusterPresentation,
|
||||
summarizeClusterComposition,
|
||||
} from "./cluster-presentation.js";
|
||||
|
||||
class Node {
|
||||
constructor(tag){this.tag=tag;this.children=[];this.style={setProperty(){}};this.classes=new Set();this.classList={add:(name)=>this.classes.add(name),toggle:(name,on)=>on?this.classes.add(name):this.classes.delete(name)};this.attrs={};this.events={};this.hidden=false;}
|
||||
constructor(tag){this.tag=tag;this.children=[];this.vars={};this.style={setProperty:(k,v)=>{this.vars[k]=v;}};this.classes=new Set();this.classList={add:(name)=>this.classes.add(name),toggle:(name,on)=>on?this.classes.add(name):this.classes.delete(name)};this.attrs={};this.events={};this.hidden=false;}
|
||||
toDataURL(){return "data:image/png;base64,";}
|
||||
getContext(){return new Proxy({}, {get:()=>()=>{}});}
|
||||
append(node){node.parent=this;this.children.push(node);}
|
||||
@@ -192,3 +196,58 @@ test("500% co-located groups finish spiderfy, keep source positions and clean up
|
||||
});
|
||||
}finally{liveLayer?.clearData();clearInteractableClusters();presentation.destroy();clock.mockRestore();Object.assign(globalThis,original);}
|
||||
});
|
||||
|
||||
test("cluster badge renders dark glass core with proportional conic-gradient ring for mixed clusters and dominant tie-breaks",()=>{
|
||||
const original={document:globalThis.document,window:globalThis.window,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight};
|
||||
const root=new Node("root");
|
||||
globalThis.document={createElement:tag=>new Node(tag),createElementNS:(_,tag)=>new Node(tag),getElementById:()=>root,addEventListener(){},removeEventListener(){}};
|
||||
globalThis.window={addEventListener(){},removeEventListener(){},dispatchEvent(){}};
|
||||
globalThis.innerWidth=1200;globalThis.innerHeight=800;
|
||||
const earth=new THREE.Object3D(),group=new THREE.Group();earth.add(group);earth.updateMatrixWorld(true);
|
||||
const camera=new THREE.PerspectiveCamera(75,1.5,.1,5000);camera.position.z=350;camera.updateMatrixWorld();
|
||||
const colors={supercomputer:"#a855f7",gpu_cluster:"#14b8a6",data_center:"#818cf8"};
|
||||
const owner={group,isMarkerVisible:()=>true,getMarkerColor:(m)=>colors[m.userData.icon_kind]||"#38bdf8",getMarkerImage:()=>"data:image/png;base64,"};
|
||||
const makeMarker=(id,kind)=>{const m=new THREE.Object3D();m.position.set(0,0,100.5);m.userData={id,name:`site-${id}`,type:"compute_center",icon_layer_id:"compute",icon_kind:kind};return m;};
|
||||
const presentation=createClusterPresentation({getOwner:()=>owner,onHiddenChange(){}});
|
||||
try {
|
||||
// 1. Single-type cluster keeps solid color fill and no ring gradient.
|
||||
const singleMarkers=[makeMarker("s1","gpu_cluster"),makeMarker("s2","gpu_cluster")];
|
||||
presentation.update([{clusterId:"single",position:new THREE.Vector3(0,0,100.5),markers:singleMarkers,expanded:false}],camera,1,singleMarkers,null);
|
||||
const singleBadge=root.children[0].children.find(n=>n.className==="map-cluster-badge"&&n.children.some(c=>c.textContent==="2"));
|
||||
expect(singleBadge.classes.has("is-mixed")).toBe(false);
|
||||
expect(singleBadge.vars["--cluster-color"]).toBe("#14b8a6");
|
||||
expect(singleBadge.vars["--cluster-ring"]).toBe("none");
|
||||
expect(singleBadge.title).toContain("GPU 集群");
|
||||
|
||||
// 2. Mixed cluster puts majority type (#a855f7, 10) first in ring & dominantColor even if minority markers come first.
|
||||
const mixedMarkers=[
|
||||
...Array.from({length:4},(_,i)=>makeMarker(`a-gpu-${i}`,"gpu_cluster")),
|
||||
...Array.from({length:10},(_,i)=>makeMarker(`z-super-${i}`,"supercomputer")),
|
||||
];
|
||||
presentation.update([{clusterId:"mixed",position:new THREE.Vector3(0,0,100.5),markers:mixedMarkers,expanded:false}],camera,1,mixedMarkers,null);
|
||||
const mixedBadge=root.children[0].children.find(n=>n.className==="map-cluster-badge"&&n.children.some(c=>c.textContent==="14"));
|
||||
expect(mixedBadge.classes.has("is-mixed")).toBe(true);
|
||||
expect(mixedBadge.vars["--cluster-color"]).toBe("#a855f7");
|
||||
expect(mixedBadge.vars["--cluster-ring"]).toStartWith("conic-gradient(from 0deg, #a855f7 0.0deg");
|
||||
expect(mixedBadge.vars["--cluster-ring"]).toContain("#14b8a6");
|
||||
expect(mixedBadge.vars["--cluster-ring"]).toContain("360.0deg");
|
||||
expect(mixedBadge.title).toContain("超算中心 10 / GPU 集群 4");
|
||||
|
||||
// 3. Minority 1-of-50 stays visible with >= 15deg arc and ends cleanly at 360.0deg.
|
||||
const skewedMarkers=[
|
||||
makeMarker("minority","gpu_cluster"),
|
||||
...Array.from({length:49},(_,i)=>makeMarker(`maj-${i}`,"data_center")),
|
||||
];
|
||||
const skewedComp=summarizeClusterComposition(skewedMarkers,()=>owner);
|
||||
const skewedRing=buildClusterRingGradient(skewedComp.groups,skewedComp.total);
|
||||
const gpuSliceMatch=skewedRing.match(/#14b8a6\s+([\d.]+)deg\s+([\d.]+)deg/);
|
||||
expect(gpuSliceMatch).not.toBeNull();
|
||||
expect(Number(gpuSliceMatch[2])-Number(gpuSliceMatch[1])).toBeGreaterThanOrEqual(15);
|
||||
expect(skewedRing).toEndWith("360.0deg)");
|
||||
|
||||
// 4. Equal-count tie breaks deterministically by business priority (supercomputer over gpu_cluster).
|
||||
const tiedComp=summarizeClusterComposition([makeMarker("a","gpu_cluster"),makeMarker("b","supercomputer")],()=>owner);
|
||||
expect(tiedComp.groups.map(g=>g.kind)).toEqual(["supercomputer","gpu_cluster"]);
|
||||
expect(tiedComp.dominantColor).toBe("#a855f7");
|
||||
}finally{presentation.destroy();Object.assign(globalThis,original);}
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
SURFACE_AVOIDANCE_PROFILES,
|
||||
} from "./interactable.js";
|
||||
import { latLonToVector3 } from "./utils.js";
|
||||
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
|
||||
import { fetchAdminWriteJson } from "./admin-write-auth.js";
|
||||
|
||||
const COMPUTE_CENTER_RENDER_ORDER = 4.5;
|
||||
const COMPUTE_CENTER_POINT_SIZE = 36;
|
||||
@@ -38,28 +40,6 @@ let computeTopicQuery = null;
|
||||
let loadGeneration = 0;
|
||||
let loadController = null;
|
||||
|
||||
function readStoredAdminAuthToken() {
|
||||
try {
|
||||
const raw = globalThis.localStorage?.getItem("auth-storage");
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw);
|
||||
return typeof parsed?.state?.token === "string" && parsed.state.token.trim()
|
||||
? parsed.state.token.trim()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildAdminWriteHeaders() {
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
const token = readStoredAdminAuthToken();
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export function setComputeTopicQuery(query) {
|
||||
computeTopicQuery = query;
|
||||
loadGeneration += 1;
|
||||
@@ -481,21 +461,13 @@ export function getUnresolvedComputeCenters() {
|
||||
// keys) is domain-specific; the request/response envelope is unified
|
||||
// (success / candidates / attempted_queries / failure_reason / context).
|
||||
export async function collectLocationCandidates(endpoint, payload = {}) {
|
||||
if (!endpoint) throw new Error("endpoint is required");
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: buildAdminWriteHeaders(),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
const response = await fetchAdminWriteJson(endpoint, payload);
|
||||
if (!response.ok) {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new Error("需要管理员登录后才能采集或保存算力中心位置");
|
||||
}
|
||||
const text = await response.text().catch(() => "");
|
||||
let detail = "";
|
||||
try {
|
||||
const payload = JSON.parse(text);
|
||||
detail = payload?.detail?.reason || payload?.detail?.message || payload?.detail || "";
|
||||
const parsed = JSON.parse(text);
|
||||
detail = parsed?.detail?.reason || parsed?.detail?.message || parsed?.detail || "";
|
||||
} catch {
|
||||
detail = text;
|
||||
}
|
||||
@@ -515,7 +487,7 @@ export async function getComputeCenterLocationCapability({ force = false } = {})
|
||||
return {
|
||||
enabled: false,
|
||||
provider: null,
|
||||
reason: `WebSearch 状态检查失败:HTTP ${response.status} ${text}`.trim(),
|
||||
reason: `Web Search 状态检查失败:HTTP ${response.status} ${text}`.trim(),
|
||||
};
|
||||
}
|
||||
const payload = await response.json();
|
||||
@@ -528,7 +500,7 @@ export async function getComputeCenterLocationCapability({ force = false } = {})
|
||||
.catch((error) => ({
|
||||
enabled: false,
|
||||
provider: null,
|
||||
reason: `WebSearch 状态检查失败:${error?.message || error}`,
|
||||
reason: `Web Search 状态检查失败:${error?.message || error}`,
|
||||
}));
|
||||
}
|
||||
return computeCenterLocationCapabilityPromise;
|
||||
@@ -561,32 +533,25 @@ export async function saveComputeCenterLocation(sourceId, candidate = {}, contex
|
||||
throw new Error("candidate latitude/longitude are required");
|
||||
}
|
||||
const url = `${COLLECT_LOCATION_API_BASE}/${encodeURIComponent(sourceId)}/location`;
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: buildAdminWriteHeaders(),
|
||||
body: JSON.stringify({
|
||||
source: context?.source ?? null,
|
||||
name: context?.name ?? candidate?.matched_location_name ?? candidate?.display_name ?? null,
|
||||
operator: context?.operator ?? null,
|
||||
site: context?.site ?? null,
|
||||
city: candidate?.city ?? context?.city ?? null,
|
||||
country: candidate?.country ?? context?.country ?? null,
|
||||
latitude,
|
||||
longitude,
|
||||
precision: candidate?.precision ?? "city",
|
||||
confidence: candidate?.confidence ?? null,
|
||||
location_source: candidate?.source ?? "manual_selection",
|
||||
source_url: candidate?.source_url ?? null,
|
||||
source_note: candidate?.source_note ?? null,
|
||||
raw_payload: candidate || {},
|
||||
needs_confirmation: false,
|
||||
verification_status: "verified",
|
||||
}),
|
||||
const response = await fetchAdminWriteJson(url, {
|
||||
source: context?.source ?? null,
|
||||
name: context?.name ?? candidate?.matched_location_name ?? candidate?.display_name ?? null,
|
||||
operator: context?.operator ?? null,
|
||||
site: context?.site ?? null,
|
||||
city: candidate?.city ?? context?.city ?? null,
|
||||
country: candidate?.country ?? context?.country ?? null,
|
||||
latitude,
|
||||
longitude,
|
||||
precision: candidate?.precision ?? "city",
|
||||
confidence: candidate?.confidence ?? null,
|
||||
location_source: candidate?.source ?? "manual_selection",
|
||||
source_url: candidate?.source_url ?? null,
|
||||
source_note: candidate?.source_note ?? null,
|
||||
raw_payload: candidate || {},
|
||||
needs_confirmation: false,
|
||||
verification_status: "verified",
|
||||
});
|
||||
if (!response.ok) {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new Error("需要管理员登录后才能采集或保存算力中心位置");
|
||||
}
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new Error(
|
||||
`Save compute center location failed: HTTP ${response.status} ${text}`.trim(),
|
||||
@@ -733,6 +698,7 @@ let nationalHubSynergyGroup = null;
|
||||
let nationalHubSynergyMaterial = null;
|
||||
let nationalHubPulseEntries = [];
|
||||
let stageLogicalArcGroup = null;
|
||||
let stageLogicalArcEntries = [];
|
||||
const _hubWorldVec = new THREE.Vector3();
|
||||
const _earthCenterVec = new THREE.Vector3();
|
||||
const _hubNormalVec = new THREE.Vector3();
|
||||
@@ -916,7 +882,7 @@ export async function setNationalComputeHubsOverlay(
|
||||
lines.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.14;
|
||||
lines.userData = {
|
||||
relation_kind: "hub_synergy_preview",
|
||||
label: "国家枢纽协同关系示意(东数西算结对调度,非实时物理光纤流量)",
|
||||
label: "国家枢纽协同关系(非实时物理链路)",
|
||||
};
|
||||
nationalHubSynergyGroup.add(lines);
|
||||
}
|
||||
@@ -956,7 +922,37 @@ export async function setNationalComputeHubsOverlay(
|
||||
return { active: true, count: markerItems.length };
|
||||
}
|
||||
|
||||
function buildElevatedArcPolyline(
|
||||
fromLat,
|
||||
fromLon,
|
||||
toLat,
|
||||
toLon,
|
||||
{
|
||||
baseOffset = COMPUTE_CENTER_CONFIG.altitudeOffset + 0.08,
|
||||
peakLift = 4.2,
|
||||
segments = 44,
|
||||
} = {},
|
||||
) {
|
||||
const vStart = latLonToVector3(fromLat, fromLon, 1).normalize();
|
||||
const vEnd = latLonToVector3(toLat, toLon, 1).normalize();
|
||||
const pts = [];
|
||||
const tempVec = new THREE.Vector3();
|
||||
for (let i = 0; i <= segments; i += 1) {
|
||||
const t = i / segments;
|
||||
tempVec.copy(vStart).lerp(vEnd, t);
|
||||
if (tempVec.lengthSq() < 1e-6) {
|
||||
tempVec.set(0, 1, 0);
|
||||
} else {
|
||||
tempVec.normalize();
|
||||
}
|
||||
const radius = CONFIG.earthRadius + baseOffset + Math.sin(Math.PI * t) * peakLift;
|
||||
pts.push(tempVec.clone().multiplyScalar(radius));
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
export function clearStageLogicalArcsOverlay() {
|
||||
stageLogicalArcEntries = [];
|
||||
if (!stageLogicalArcGroup) return;
|
||||
disposeThreeGroupChildren(stageLogicalArcGroup);
|
||||
stageLogicalArcGroup.parent?.remove?.(stageLogicalArcGroup);
|
||||
@@ -971,10 +967,8 @@ export function setStageLogicalArcsOverlay(earth, arcs = []) {
|
||||
stageLogicalArcGroup.name = "stage-logical-as-routes";
|
||||
earth.add(stageLogicalArcGroup);
|
||||
|
||||
const beforePos = [];
|
||||
const beforeCol = [];
|
||||
const afterPos = [];
|
||||
const afterCol = [];
|
||||
const beforePolylines = [];
|
||||
const afterPolylines = [];
|
||||
|
||||
for (const arc of arcs) {
|
||||
const fLat = Number(arc?.from_lat);
|
||||
@@ -983,55 +977,71 @@ export function setStageLogicalArcsOverlay(earth, arcs = []) {
|
||||
const tLon = Number(arc?.to_lon);
|
||||
if (![fLat, fLon, tLat, tLon].every(Number.isFinite)) continue;
|
||||
const isBefore = arc.phase === "before";
|
||||
const seg = buildElevatedArcSegments(fLat, fLon, tLat, tLon, {
|
||||
const poly = buildElevatedArcPolyline(fLat, fLon, tLat, tLon, {
|
||||
baseOffset: COMPUTE_CENTER_CONFIG.altitudeOffset + 0.35,
|
||||
peakLift: isBefore ? 6.4 : 8.6,
|
||||
segments: 44,
|
||||
startColor: new THREE.Color(isBefore ? 0x64748b : 0xf59e0b),
|
||||
endColor: new THREE.Color(isBefore ? 0x94a3b8 : 0xfb7185),
|
||||
dashed: isBefore,
|
||||
});
|
||||
if (isBefore) {
|
||||
beforePos.push(...seg.positions);
|
||||
beforeCol.push(...seg.colors);
|
||||
} else {
|
||||
afterPos.push(...seg.positions);
|
||||
afterCol.push(...seg.colors);
|
||||
if (isBefore) beforePolylines.push(poly);
|
||||
else afterPolylines.push(poly);
|
||||
}
|
||||
|
||||
const startedAtMs = typeof performance !== "undefined" ? performance.now() : Date.now();
|
||||
|
||||
if (beforePolylines.length) {
|
||||
const geom = createSurfaceRibbonGeometry(beforePolylines);
|
||||
const mat = createSurfaceRibbonMaterial({
|
||||
color: 0x64748b,
|
||||
glowColor: 0x94a3b8,
|
||||
halfWidthPx: 2.6,
|
||||
opacity: 0.68,
|
||||
pulseSpeed: 0.25,
|
||||
pulseFreq: 1.5,
|
||||
pulseIntensity: 0.18,
|
||||
reveal: 1.0,
|
||||
additive: false,
|
||||
});
|
||||
const mesh = new THREE.Mesh(geom, mat);
|
||||
mesh.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.22;
|
||||
mesh.raycast = () => {};
|
||||
stageLogicalArcGroup.add(mesh);
|
||||
stageLogicalArcEntries.push({ material: mat, startedAtMs, revealDurationMs: 0 });
|
||||
}
|
||||
|
||||
if (afterPolylines.length) {
|
||||
const geom = createSurfaceRibbonGeometry(afterPolylines);
|
||||
const mat = createSurfaceRibbonMaterial({
|
||||
color: 0xf59e0b,
|
||||
glowColor: 0xfb7185,
|
||||
halfWidthPx: 4.8,
|
||||
opacity: 0.94,
|
||||
pulseSpeed: 0.72,
|
||||
pulseFreq: 2.4,
|
||||
pulseIntensity: 0.75,
|
||||
reveal: 0.0,
|
||||
additive: true,
|
||||
});
|
||||
const mesh = new THREE.Mesh(geom, mat);
|
||||
mesh.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.24;
|
||||
mesh.raycast = () => {};
|
||||
stageLogicalArcGroup.add(mesh);
|
||||
stageLogicalArcEntries.push({ material: mat, startedAtMs, revealDurationMs: 650 });
|
||||
}
|
||||
}
|
||||
|
||||
export function updateStageLogicalArcsAnimation() {
|
||||
if (!stageLogicalArcEntries.length) return;
|
||||
const nowMs = typeof performance !== "undefined" ? performance.now() : Date.now();
|
||||
const nowSec = nowMs * 0.001;
|
||||
for (const entry of stageLogicalArcEntries) {
|
||||
const uniforms = entry.material?.uniforms;
|
||||
if (!uniforms) continue;
|
||||
uniforms.uTime.value = nowSec;
|
||||
if (entry.revealDurationMs > 0) {
|
||||
const linear = Math.max(0, Math.min(1, (nowMs - entry.startedAtMs) / entry.revealDurationMs));
|
||||
uniforms.uReveal.value = 1 - Math.pow(1 - linear, 2.2);
|
||||
}
|
||||
}
|
||||
|
||||
if (beforePos.length) {
|
||||
const geom = new THREE.BufferGeometry();
|
||||
geom.setAttribute("position", new THREE.Float32BufferAttribute(beforePos, 3));
|
||||
geom.setAttribute("color", new THREE.Float32BufferAttribute(beforeCol, 3));
|
||||
const mat = new THREE.LineBasicMaterial({
|
||||
vertexColors: true,
|
||||
transparent: true,
|
||||
opacity: 0.62,
|
||||
depthTest: true,
|
||||
depthWrite: false,
|
||||
});
|
||||
const line = new THREE.LineSegments(geom, mat);
|
||||
line.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.22;
|
||||
stageLogicalArcGroup.add(line);
|
||||
}
|
||||
|
||||
if (afterPos.length) {
|
||||
const geom = new THREE.BufferGeometry();
|
||||
geom.setAttribute("position", new THREE.Float32BufferAttribute(afterPos, 3));
|
||||
geom.setAttribute("color", new THREE.Float32BufferAttribute(afterCol, 3));
|
||||
const mat = new THREE.LineBasicMaterial({
|
||||
vertexColors: true,
|
||||
transparent: true,
|
||||
opacity: 0.92,
|
||||
depthTest: true,
|
||||
depthWrite: false,
|
||||
blending: THREE.AdditiveBlending,
|
||||
});
|
||||
const line = new THREE.LineSegments(geom, mat);
|
||||
line.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.24;
|
||||
stageLogicalArcGroup.add(line);
|
||||
}
|
||||
}
|
||||
|
||||
export function focusComputeEntityById(earth, entityId) {
|
||||
@@ -1103,6 +1113,7 @@ export function getComputeCenterPointerIntersections(options) {
|
||||
export function updateComputeCenterVisualState(lockedObjectType, lockedObject, camera) {
|
||||
updateComputeCenterLocationPreview();
|
||||
updateNationalHubPulses(camera);
|
||||
updateStageLogicalArcsAnimation();
|
||||
if (nationalHubOverlayActive) {
|
||||
nationalComputeHubLayer.updateVisualState(lockedObjectType, lockedObject, camera);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export const COMPUTE_MODE_OPTIONS = [
|
||||
},
|
||||
{
|
||||
mode: "bilateral_rpi",
|
||||
shortZh: "双边RPI",
|
||||
shortZh: "双边 RPI",
|
||||
shortEn: "CN/US RPI",
|
||||
labelZh: "中美相对平价指数 (US=100%)",
|
||||
labelEn: "Relative Parity Index (US=100%)",
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { createHUDPanel } from "./hud-panels.js";
|
||||
import { sharedHudFocusStack } from "./hud-focus-stack.js";
|
||||
import { getEarthLocale, localizeCountryName } from "./i18n.js";
|
||||
import { normalizeEarthTarget, openWorkflowActionPicker } from "./workflow-bindings.js";
|
||||
|
||||
const API = "/api/v1/data-products/compute";
|
||||
const POSTURE_API = "/api/v1/situational-awareness/posture/compute";
|
||||
@@ -421,7 +422,7 @@ export function initComputeTopic({
|
||||
return `<section class="compute-card__section compute-card__posture-box">
|
||||
<div class="compute-card__posture-header">
|
||||
<span class="compute-card__posture-kicker">✦ ${escape(text("战略参谋研判", "Strategic Posture Brief"))}</span>
|
||||
${postureData.revision ? `<span class="compute-card__posture-rev">Rev.${escape(postureData.revision)}</span>` : ""}
|
||||
${postureData.revision ? `<span class="compute-card__posture-rev">${escape(text(`第 ${postureData.revision} 版`, `Rev.${postureData.revision}`))}</span>` : ""}
|
||||
</div>
|
||||
<p class="compute-card__posture-copy">${escape(assertion)}</p>
|
||||
<div class="compute-card__action-bar">
|
||||
@@ -538,7 +539,7 @@ export function initComputeTopic({
|
||||
const missing = ["bilateral_share", "bilateral_rpi"].includes(basis) && !["CN", "US"].includes(entry.code)
|
||||
? text("暂无可比数据:双边口径仅适用于中国与美国", "No comparable data: bilateral basis applies to China and the US")
|
||||
: obsWindow.isAfterLatestReference && obsWindow.latestReferenceLabel
|
||||
? text(`选定年份 (${year}) 晚于最新已核实参考期 (${obsWindow.latestReferenceLabel}),不静默回填冒充当年实测`, `Selected year (${year}) is later than latest verified period (${obsWindow.latestReferenceLabel}); withheld without backfill`)
|
||||
? text(`选定年份(${year})晚于最新已核实参考期(${obsWindow.latestReferenceLabel}),暂无当年实测数据`, `Selected year (${year}) is later than latest verified period (${obsWindow.latestReferenceLabel}); data not yet available`)
|
||||
: entryKind(entry) === "region"
|
||||
? text("暂无可比数据:该区域缺少完整的同年同口径统计", "No comparable data: region lacks complete same-year statistics")
|
||||
: text("暂无可比数据:缺少已核验同口径统计", "No comparable data: verified statistics unavailable");
|
||||
@@ -586,7 +587,7 @@ export function initComputeTopic({
|
||||
if (!trendChange) return "";
|
||||
const sign = trendChange.change > 0 ? "+" : "";
|
||||
const arrow = trendChange.change > 0 ? "▲" : trendChange.change < 0 ? "▼" : "•";
|
||||
const unit = trendChange.unit === "percentage_points" ? "pp" : "EFlops";
|
||||
const unit = trendChange.unit === "percentage_points" ? text("百分点", "pp") : "EFlops";
|
||||
const tone = trendChange.change > 0 ? "is-up" : trendChange.change < 0 ? "is-down" : "is-flat";
|
||||
return `<span class="compute-card__delta-pill ${tone}" title="${escape(`${trendChange.fromYear} → ${trendChange.toYear}`)}">${arrow} ${sign}${trendChange.change} ${unit} <small>(${trendChange.fromYear}→${trendChange.toYear})</small></span>`;
|
||||
}
|
||||
@@ -668,7 +669,7 @@ export function initComputeTopic({
|
||||
${members.length ? `<section class="compute-card__section"><h4>${text("区域成员", "Region members")} <span>${members.length}</span></h4><div class="compute-card__members">${members.map((member) => `<span class="earth-settings-chip earth-settings-chip--with-icon">${participantIdentity(member)}<span>${escape(nameOf(member))}</span></span>`).join("")}</div></section>` : ""}
|
||||
<section class="compute-card__section">
|
||||
<h4>${text("已核验重点集群样本", "Verified Facility Samples")} <span>${escape(sampleStatus)}</span></h4>
|
||||
<p class="compute-card__empty">${text("设施条数仅代表公开已收录样本,不代表国家总算力。", "Facility counts reflect publicly indexed samples only, not national total compute.")}</p>
|
||||
<p class="compute-card__empty">${text("设施条数仅反映已收录公开样本。", "Facility counts reflect publicly indexed samples only.")}</p>
|
||||
${sourceBreakdown ? `<p class="compute-card__sample"><span>${escape(sourceBreakdown)}</span></p>` : ""}
|
||||
${locations.length ? `<div class="compute-card__facilities">${locations.slice(0, 4).map((feature) => `<button type="button" class="earth-settings-chip" data-facility="${escape(feature.id)}">${escape(feature.properties?.name || feature.id)}</button>`).join("")}</div>` : facilities && !facilityError ? `<p class="compute-card__empty">${text("当前快照没有已核验定位设施记录。", "No verified geolocated facility records in this snapshot.")}</p>` : ""}
|
||||
</section>
|
||||
@@ -791,7 +792,7 @@ export function initComputeTopic({
|
||||
return `<button type="button" class="earth-mobile-settings-chip is-active" data-remove="${escape(code)}" aria-label="${text("移除", "Remove")} ${escape(entry ? nameOf(entry) : code)}"><span class="earth-settings-chip__label">${escape(entry ? nameOf(entry) : code)}</span><span class="earth-settings-chip__remove" aria-hidden="true">×</span></button>`;
|
||||
}).join("")}</div></div>
|
||||
<label class="earth-mobile-settings-card compute-mobile__field"><div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("参考期", "Period")}</span><span class="earth-mobile-settings-subtitle">${text("历史设施按年末快照读取", "Historical facilities use year-end snapshots")}</span></div><select data-year aria-label="${text("参考年份", "Reference year")}"><option value="">${text("最新观测", "Latest observation")}</option>${(history?.years || []).map((value) => `<option value="${value}" ${String(value) === year ? "selected" : ""}>${value}</option>`).join("")}</select></label>
|
||||
<label class="earth-mobile-settings-card compute-mobile__field"><div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("指标口径", "Measure")}</span><span class="earth-mobile-settings-subtitle">${text("区域缺失值不会从设施样本反推", "Missing regional values are never inferred from facility samples")}</span></div><select data-mode aria-label="${text("指标口径", "Metric basis")}">${modeSelectOptions().map(([value, label]) => `<option value="${value}" ${mode === value ? "selected" : ""}>${label}</option>`).join("")}</select></label>
|
||||
<label class="earth-mobile-settings-card compute-mobile__field"><div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("指标口径", "Measure")}</span><span class="earth-mobile-settings-subtitle">${text("按已核实区域口径统计", "Computed on verified regional basis")}</span></div><select data-mode aria-label="${text("指标口径", "Metric basis")}">${modeSelectOptions().map(([value, label]) => `<option value="${value}" ${mode === value ? "selected" : ""}>${label}</option>`).join("")}</select></label>
|
||||
</div>
|
||||
${selectionNotice ? `<p class="earth-mobile-page-summary" role="status">${escape(selectionNotice)}</p>` : ""}
|
||||
${mobileStatusHtml()}
|
||||
@@ -815,7 +816,7 @@ export function initComputeTopic({
|
||||
<section class="compute-mobile__detail-section"><h3>${text("趋势与分差", "Trend & Divergence")}</h3>${view.value == null ? coverageHtml(entry, view.row) : ""}${isBilateral ? dualBilateralChartsHtml(entry) : historyChartHtml(entry)}</section>
|
||||
${postureBriefHtml(entry, view.activeEvidenceId)}
|
||||
${view.members.length ? `<section class="compute-mobile__detail-section"><h3>${text("区域成员", "Region members")} <span>${view.members.length}</span></h3><div class="compute-card__members">${view.members.map((member) => `<span class="earth-mobile-settings-chip is-active earth-settings-chip--with-icon">${participantIdentity(member)}<span>${escape(nameOf(member))}</span></span>`).join("")}</div></section>` : ""}
|
||||
<section class="compute-mobile__detail-section"><h3>${text("已核验设施样本", "Verified Facility Samples")} <span>${escape(view.sampleStatus)}</span></h3><p class="earth-mobile-detail-empty">${text("设施条数仅代表公开已收录样本,不代表国家总算力。", "Facility counts reflect publicly indexed samples only, not national total compute.")}</p>${view.sourceBreakdown ? `<p class="earth-mobile-detail-type">${escape(view.sourceBreakdown)}</p>` : ""}${facilityStatus}</section>
|
||||
<section class="compute-mobile__detail-section"><h3>${text("已核验设施样本", "Verified Facility Samples")} <span>${escape(view.sampleStatus)}</span></h3><p class="earth-mobile-detail-empty">${text("设施条数仅反映已收录公开样本。", "Facility counts reflect publicly indexed samples only.")}</p>${view.sourceBreakdown ? `<p class="earth-mobile-detail-type">${escape(view.sourceBreakdown)}</p>` : ""}${facilityStatus}</section>
|
||||
${mediaHtml(view.locations)}
|
||||
${view.evidence ? `<section class="compute-mobile__detail-section"><h3>${text("来源与证据", "Source and evidence")}</h3><p class="earth-mobile-detail-title">${escape(view.evidence.title || "")}</p><p class="earth-mobile-detail-type">${escape(view.evidence.publisher || "")} · ${escape(view.evidence.report_year || view.evidence.published_at || "")}</p>${view.evidence.locator ? `<p class="earth-mobile-detail-type">${escape(view.evidence.locator)}</p>` : ""}${sourceUrl ? `<a class="earth-mobile-action-btn" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开来源", "Open source")} ↗</a>` : ""}</section>` : ""}`;
|
||||
}
|
||||
@@ -1231,14 +1232,26 @@ export function initComputeTopic({
|
||||
return;
|
||||
}
|
||||
if (button.dataset.action === "open-copilot") {
|
||||
openCopilot?.({
|
||||
const code = button.dataset.card || "CN";
|
||||
const entry = catalog().find((item) => item.code === code) || { code, name: code };
|
||||
const normalized = normalizeEarthTarget("compute_region", entry);
|
||||
const fallbackDetail = {
|
||||
domain: "compute",
|
||||
selectedCodes: [...countries],
|
||||
focusYear: year ? Number(year) : null,
|
||||
mode: history?.mode || mode,
|
||||
entityId: button.dataset.card || "CN",
|
||||
entityId: code,
|
||||
revision: postureData?.revision || null,
|
||||
evidence: history?.evidence || {},
|
||||
};
|
||||
openWorkflowActionPicker({
|
||||
anchorEl: button,
|
||||
surface: "topic_card",
|
||||
targets: [normalized],
|
||||
fallbackDetail,
|
||||
onSelect: (detail) => {
|
||||
openCopilot?.({ ...fallbackDetail, ...detail });
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -536,10 +536,12 @@ export const GRID_CONFIG = {
|
||||
|
||||
export const CLOUD_LAYER_CONFIG = {
|
||||
radiusOffset: 3,
|
||||
shadowAltitudeOffset: 0.52,
|
||||
widthSegments: 64,
|
||||
heightSegments: 64,
|
||||
opacity: 0.15,
|
||||
textureUrl: "./assets/earth_clouds_1024.png",
|
||||
opacity: 0.34,
|
||||
shadowOpacity: 0.08,
|
||||
textureUrl: "./assets/earth_clouds_2048.png",
|
||||
};
|
||||
|
||||
export const EARTH_MATERIAL_CONFIG = {
|
||||
@@ -572,15 +574,21 @@ export const EARTH_MATERIAL_CONFIG = {
|
||||
oceanTint: [0.008, 0.016, 0.024],
|
||||
oceanAmbient: [0.0015, 0.004, 0.012],
|
||||
},
|
||||
terminator: [-0.075, 0.16],
|
||||
terminator: [-0.14, 0.22],
|
||||
oceanReflection: [0.025, 0.12, 0.32],
|
||||
atmosphereColor: [0.08, 0.28, 0.65],
|
||||
innerRimStrength: 0.28,
|
||||
twilightWarmColor: [0.95, 0.38, 0.12],
|
||||
twilightWarmStrength: 0.0,
|
||||
sunglintStrength: 0.0,
|
||||
landReliefStrength: 0.12,
|
||||
},
|
||||
atmosphere: {
|
||||
radiusFactor: 1.025,
|
||||
color: [0.18, 0.48, 0.88],
|
||||
strength: 0.65,
|
||||
mieColor: [0.92, 0.56, 0.30],
|
||||
mieStrength: 0.18,
|
||||
},
|
||||
|
||||
dayNight: {
|
||||
|
||||
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user