Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,42 @@ 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 (
|
||||
compute_workflow_health,
|
||||
dismiss_ledger_entry,
|
||||
get_evolution_ledger,
|
||||
get_evolution_policy,
|
||||
incubate_workflow_from_runs,
|
||||
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 +74,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,6 +133,43 @@ 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 = ""
|
||||
@@ -78,12 +183,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 +226,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 +321,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 +352,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),
|
||||
)
|
||||
@@ -243,17 +459,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 +501,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 +663,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 +671,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 +679,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 +725,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 +768,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 +847,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 +861,145 @@ 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 = ""
|
||||
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"])
|
||||
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 +1011,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 +1020,30 @@ 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,
|
||||
},
|
||||
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()
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,7 @@ 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 {},
|
||||
"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):
|
||||
|
||||
@@ -0,0 +1,823 @@
|
||||
"""Lightweight topological DAG workflow executor for AI Advisor and Earth Copilot."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
import json
|
||||
import re
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest
|
||||
from app.services.ai.thinking_sanitizer import strip_thinking_text
|
||||
from app.services.ai.tool_registry import (
|
||||
TimeBasis,
|
||||
isolate_untrusted_external_text,
|
||||
query_bgp_incidents_tool,
|
||||
query_cable_posture_tool,
|
||||
query_compute_posture_tool,
|
||||
query_global_situational_tool,
|
||||
query_recent_earth_news_tool,
|
||||
query_satellite_posture_tool,
|
||||
query_vessel_posture_tool,
|
||||
safe_web_fetch,
|
||||
)
|
||||
from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES
|
||||
from app.services.compute_center_locations import build_compute_center_location_query
|
||||
from app.services.location.agent_resolver import run_l1_structured_facility_resolvers
|
||||
|
||||
logger = get_logger(__name__, service="ai_dag_executor")
|
||||
|
||||
_TEMPLATE_VAR_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}")
|
||||
_L1_KNOWLEDGE_TOOL_IDS = frozenset(
|
||||
{"builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"}
|
||||
)
|
||||
|
||||
|
||||
def summarize_targets(targets: list[dict[str, Any]] | None) -> str:
|
||||
"""Format selected Earth targets into a concise deterministic summary."""
|
||||
if not targets:
|
||||
return "全球多域当前态势"
|
||||
parts: list[str] = []
|
||||
for item in targets[:8]:
|
||||
etype = str(item.get("entity_type") or item.get("type") or "entity").strip()
|
||||
label = str(item.get("label") or item.get("name") or item.get("entity_id") or "").strip()
|
||||
lat = item.get("latitude")
|
||||
lon = item.get("longitude")
|
||||
coord = ""
|
||||
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
|
||||
coord = f"({lat:.2f}, {lon:.2f})"
|
||||
token = f"{etype}「{label or etype}」{coord}"
|
||||
parts.append(token)
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def render_workflow_template(
|
||||
template: str,
|
||||
*,
|
||||
question: str = "",
|
||||
targets: list[dict[str, Any]] | None = None,
|
||||
node_outputs: dict[str, str] | None = None,
|
||||
) -> str:
|
||||
"""Interpolate `{{...}}` placeholders safely without Python `.format` or eval."""
|
||||
raw = str(template or "")
|
||||
if not raw or "{{" not in raw:
|
||||
return raw
|
||||
first = targets[0] if targets else {}
|
||||
outputs = node_outputs or {}
|
||||
targets_summary = summarize_targets(targets)
|
||||
|
||||
def _lookup(key: str) -> str:
|
||||
if key == "question":
|
||||
return question
|
||||
if key == "targets_summary":
|
||||
return targets_summary
|
||||
if key.startswith("target."):
|
||||
sub = key[len("target.") :]
|
||||
if sub == "label":
|
||||
return str(first.get("label") or first.get("name") or "")
|
||||
if sub == "type":
|
||||
return str(first.get("entity_type") or first.get("type") or "")
|
||||
if sub == "id":
|
||||
return str(first.get("entity_id") or first.get("id") or "")
|
||||
if sub == "lat":
|
||||
val = first.get("latitude")
|
||||
return f"{val:.4f}" if isinstance(val, (int, float)) else ""
|
||||
if sub == "lon":
|
||||
val = first.get("longitude")
|
||||
return f"{val:.4f}" if isinstance(val, (int, float)) else ""
|
||||
if sub in {"kind", "layer"}:
|
||||
return str(first.get(sub) or "")
|
||||
return ""
|
||||
if key.startswith("node."):
|
||||
nid = key[len("node.") :]
|
||||
return str(outputs.get(nid) or "")[:4000]
|
||||
if key.endswith(".output"):
|
||||
nid = key[: -len(".output")]
|
||||
return str(outputs.get(nid) or "")[:4000]
|
||||
return ""
|
||||
|
||||
return _TEMPLATE_VAR_RE.sub(lambda m: _lookup(m.group(1)), raw)
|
||||
|
||||
|
||||
def _extract_target_ids_and_codes(
|
||||
targets: list[dict[str, Any]],
|
||||
earth_context: dict[str, Any],
|
||||
) -> tuple[str | None, list[str], str]:
|
||||
first = targets[0] if targets else {}
|
||||
primary_id = str(
|
||||
first.get("entity_id")
|
||||
or first.get("id")
|
||||
or earth_context.get("entity_id")
|
||||
or ""
|
||||
).strip() or None
|
||||
codes = earth_context.get("selected_codes")
|
||||
if not isinstance(codes, list) or not codes:
|
||||
codes = ["CN", "US"]
|
||||
else:
|
||||
codes = [str(c).strip().upper() for c in codes if str(c).strip()][:12] or ["CN", "US"]
|
||||
mode = str(earth_context.get("mode") or "global_share")
|
||||
return primary_id, codes, mode
|
||||
|
||||
|
||||
async def _execute_tool(
|
||||
db: Any,
|
||||
tool_id: str,
|
||||
*,
|
||||
question: str,
|
||||
targets: list[dict[str, Any]],
|
||||
earth_context: dict[str, Any],
|
||||
allow_external_tools: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""Execute one whitelisted read-only or controlled external tool cleanly."""
|
||||
primary_id, codes, mode = _extract_target_ids_and_codes(targets, earth_context)
|
||||
time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment]
|
||||
if time_basis not in {"live", "as_known_then", "retrospective"}:
|
||||
time_basis = "retrospective"
|
||||
cutoff_at = earth_context.get("cutoff_at")
|
||||
visible_layers = earth_context.get("visible_layers")
|
||||
visible_layers_dict = visible_layers if isinstance(visible_layers, dict) else None
|
||||
|
||||
if tool_id == "query_global_situational":
|
||||
return await query_global_situational_tool(
|
||||
db,
|
||||
selected_codes=codes,
|
||||
visible_layers=visible_layers_dict,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
if tool_id == "query_compute_posture":
|
||||
return await query_compute_posture_tool(
|
||||
db,
|
||||
countries=codes,
|
||||
mode=mode,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
if tool_id == "query_bgp_incidents":
|
||||
incidents = await query_bgp_incidents_tool(
|
||||
db,
|
||||
incident_key=primary_id if any(t.get("entity_type") == "bgp" for t in targets) else None,
|
||||
limit=8,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
return {"items": incidents, "count": len(incidents)}
|
||||
if tool_id == "query_cable_posture":
|
||||
return await query_cable_posture_tool(
|
||||
db,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
entity_id=primary_id if any(t.get("entity_type") in {"cable", "landing_point"} for t in targets) else None,
|
||||
)
|
||||
if tool_id == "query_satellite_posture":
|
||||
return await query_satellite_posture_tool(
|
||||
db,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
entity_id=primary_id if any(t.get("entity_type") == "satellite" for t in targets) else None,
|
||||
)
|
||||
if tool_id == "query_vessel_posture":
|
||||
return await query_vessel_posture_tool(
|
||||
db,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
entity_id=primary_id if any(t.get("entity_type") == "vessel" for t in targets) else None,
|
||||
)
|
||||
if tool_id == "query_recent_earth_news":
|
||||
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
|
||||
region = str(news_ctx.get("region_key") or "").strip() or None
|
||||
return await query_recent_earth_news_tool(db, region=region, limit=10)
|
||||
if tool_id in _L1_KNOWLEDGE_TOOL_IDS:
|
||||
target_name = str(
|
||||
(targets[0].get("label") if targets else "")
|
||||
or question
|
||||
or "Unknown Facility"
|
||||
).strip()
|
||||
query = build_compute_center_location_query(name=target_name)
|
||||
candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db)
|
||||
return {
|
||||
"candidates": [
|
||||
{
|
||||
"display_name": c.display_name,
|
||||
"country": c.country,
|
||||
"latitude": c.latitude,
|
||||
"longitude": c.longitude,
|
||||
"precision": c.precision,
|
||||
"confidence": c.confidence,
|
||||
"source": c.source,
|
||||
"source_note": c.source_note,
|
||||
}
|
||||
for c in candidates[:5]
|
||||
],
|
||||
"resolver_log": resolver_log,
|
||||
}
|
||||
if tool_id == "web_search":
|
||||
if not allow_external_tools:
|
||||
return {"skipped": "external_web_search_admin_only"}
|
||||
from app.api.v1.settings import get_web_search_client
|
||||
|
||||
client = await get_web_search_client(db)
|
||||
search_q = " ".join(
|
||||
part for part in [summarize_targets(targets) if targets else "", question] if part
|
||||
).strip()[:200]
|
||||
if not search_q:
|
||||
return {"items": []}
|
||||
hits = await client.search(search_q, max_results=5)
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"title": h.title,
|
||||
"url": h.url,
|
||||
"snippet": h.compact_text(400),
|
||||
"source_provider": h.source_provider,
|
||||
}
|
||||
for h in hits
|
||||
]
|
||||
}
|
||||
if tool_id in {"safe_web_fetch", "fetch_source_url"}:
|
||||
if not allow_external_tools:
|
||||
return {"skipped": "external_fetch_admin_only"}
|
||||
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
|
||||
target_props = targets[0].get("properties") if targets and isinstance(targets[0].get("properties"), dict) else {}
|
||||
url = str(news_ctx.get("url") or target_props.get("url") or "").strip()
|
||||
if not url:
|
||||
return {"skipped": "no_target_url"}
|
||||
fetched = await safe_web_fetch(url)
|
||||
return isolate_untrusted_external_text(fetched.final_url or fetched.url, fetched.title, fetched.text)
|
||||
return {"skipped": f"unsupported_tool:{tool_id}"}
|
||||
|
||||
|
||||
def _has_meaningful_tool_data(tool_results: dict[str, Any]) -> bool:
|
||||
for val in tool_results.values():
|
||||
if not isinstance(val, dict):
|
||||
continue
|
||||
if val.get("skipped") or val.get("error"):
|
||||
continue
|
||||
for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels"):
|
||||
seq = val.get(key)
|
||||
if isinstance(seq, list) and len(seq) > 0:
|
||||
return True
|
||||
if val.get("excerpt") or val.get("summary"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _topological_sort_nodes(
|
||||
nodes: list[dict[str, Any]],
|
||||
edges: list[dict[str, Any]],
|
||||
) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, Any]]], dict[str, list[str]]]:
|
||||
enabled_nodes = [n for n in nodes if isinstance(n, dict) and n.get("enabled", True)][:MAX_WORKFLOW_NODES]
|
||||
node_map = {str(n["id"]): n for n in enabled_nodes if n.get("id")}
|
||||
adj: dict[str, list[str]] = {nid: [] for nid in node_map}
|
||||
incoming: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
indeg: dict[str, int] = {nid: 0 for nid in node_map}
|
||||
|
||||
for edge in edges:
|
||||
if not isinstance(edge, dict):
|
||||
continue
|
||||
src = str(edge.get("source") or "")
|
||||
tgt = str(edge.get("target") or "")
|
||||
if src in node_map and tgt in node_map and src != tgt:
|
||||
adj[src].append(tgt)
|
||||
incoming[tgt].append(edge)
|
||||
indeg[tgt] += 1
|
||||
|
||||
queue = deque(nid for nid, d in indeg.items() if d == 0)
|
||||
ordered: list[dict[str, Any]] = []
|
||||
while queue:
|
||||
nid = queue.popleft()
|
||||
ordered.append(node_map[nid])
|
||||
for nxt in adj[nid]:
|
||||
indeg[nxt] -= 1
|
||||
if indeg[nxt] == 0:
|
||||
queue.append(nxt)
|
||||
|
||||
# Fallback: preserve enabled order if partial edge misalignment occurs.
|
||||
seen = {str(n["id"]) for n in ordered}
|
||||
for n in enabled_nodes:
|
||||
if str(n["id"]) not in seen:
|
||||
ordered.append(n)
|
||||
return ordered, incoming, adj
|
||||
|
||||
|
||||
def _has_downstream_llm(
|
||||
start_id: str,
|
||||
adj: dict[str, list[str]],
|
||||
node_types: dict[str, str],
|
||||
) -> bool:
|
||||
visited: set[str] = set()
|
||||
stack = list(adj.get(start_id) or [])
|
||||
while stack:
|
||||
cur = stack.pop()
|
||||
if cur in visited:
|
||||
continue
|
||||
visited.add(cur)
|
||||
if node_types.get(cur) in {"llm_agent", "tool_agent"}:
|
||||
return True
|
||||
stack.extend(adj.get(cur) or [])
|
||||
return False
|
||||
|
||||
|
||||
def _eval_edge_condition(
|
||||
edge: dict[str, Any],
|
||||
pred_state: dict[str, Any],
|
||||
targets: list[dict[str, Any]],
|
||||
) -> bool:
|
||||
cond = str(edge.get("condition") or "always").strip()
|
||||
if cond in {"always", "", "interactive", "ingest", "not_terminal", "high_confidence_hit", "fallback_to_agent"}:
|
||||
return True
|
||||
if cond == "on_empty_or_low_confidence":
|
||||
return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6
|
||||
if cond == "on_entity_type":
|
||||
raw_val = str(edge.get("condition_value") or "").strip()
|
||||
if not raw_val:
|
||||
return False
|
||||
wanted = {item.strip().lower() for item in raw_val.split(",") if item.strip()}
|
||||
target_types = {str(t.get("entity_type") or t.get("type") or "").strip().lower() for t in targets}
|
||||
return bool(wanted & target_types)
|
||||
return True
|
||||
|
||||
|
||||
def _build_deterministic_fallback_markdown(
|
||||
*,
|
||||
workflow_name: str,
|
||||
question: str,
|
||||
targets: list[dict[str, Any]],
|
||||
tool_results: dict[str, Any],
|
||||
ai_configured: bool,
|
||||
) -> str:
|
||||
lines = [f"### {workflow_name}", ""]
|
||||
if targets:
|
||||
lines.append(f"- **聚焦目标**:{summarize_targets(targets)}")
|
||||
if question:
|
||||
lines.append(f"- **分析问题**:{question}")
|
||||
if tool_results:
|
||||
lines.append("- **已加载遥测工具**:" + "、".join(f"`{k}`" for k in tool_results.keys()))
|
||||
lines.append("")
|
||||
if not ai_configured:
|
||||
lines.append("> 当前系统尚未配置可用 AI Provider,以上为确定性规则与遥测快照摘要;配置模型后可启用深度推理节点。")
|
||||
elif tool_results:
|
||||
preview = json.dumps(tool_results, ensure_ascii=False, default=str)[:1200]
|
||||
lines.append(f"```json\n{preview}\n```")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
async def run_workflow_dag_stream(
|
||||
*,
|
||||
db: Any,
|
||||
workflow: dict[str, Any],
|
||||
question: str,
|
||||
use_draft: bool = False,
|
||||
targets: list[dict[str, Any]] | None = None,
|
||||
earth_context: dict[str, Any] | None = None,
|
||||
attachments: list[dict[str, Any]] | None = None,
|
||||
images: list[dict[str, Any]] | None = None,
|
||||
history: list[dict[str, Any]] | None = None,
|
||||
ai_client: Any = None,
|
||||
request: Any = None,
|
||||
run_id: str = "",
|
||||
model_override: str | None = None,
|
||||
allow_external_tools: bool = False,
|
||||
extra_meta: dict[str, Any] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
"""Execute a workflow DAG topologically and emit structured SSE-ready events."""
|
||||
wf_id = str(workflow.get("workflow_id") or "default.general")
|
||||
wf_name = str(workflow.get("name") or wf_id)
|
||||
active_rev = int(workflow.get("active_revision") or 1)
|
||||
bindings = workflow.get("bindings") if isinstance(workflow.get("bindings"), dict) else {}
|
||||
graph = (
|
||||
workflow.get("draft_graph")
|
||||
if use_draft and isinstance(workflow.get("draft_graph"), dict)
|
||||
else workflow.get("published_graph")
|
||||
) or {}
|
||||
raw_nodes = list(graph.get("nodes") or [])
|
||||
raw_edges = list(graph.get("edges") or [])
|
||||
ordered_nodes, incoming_map, adj = _topological_sort_nodes(raw_nodes, raw_edges)
|
||||
node_types = {str(n["id"]): str(n.get("node_type") or "llm_agent") for n in ordered_nodes}
|
||||
|
||||
clean_targets = [t for t in (targets or []) if isinstance(t, dict)][:8]
|
||||
clean_earth_ctx = dict(earth_context or {})
|
||||
planned_ids = [str(n["id"]) for n in ordered_nodes]
|
||||
|
||||
yield {
|
||||
"event": "meta",
|
||||
"data": {
|
||||
"run_id": run_id,
|
||||
"workflow_id": wf_id,
|
||||
"workflow_name": wf_name,
|
||||
"active_revision": active_rev,
|
||||
"use_draft": use_draft,
|
||||
"targets_count": len(clean_targets),
|
||||
"planned_nodes": planned_ids,
|
||||
"nodes": planned_ids,
|
||||
**(extra_meta or {}),
|
||||
},
|
||||
}
|
||||
|
||||
ai_ready = False
|
||||
provider_name = ""
|
||||
default_model = ""
|
||||
if ai_client is not None and hasattr(ai_client, "is_ready"):
|
||||
try:
|
||||
ai_ready, provider_name, default_model = await ai_client.is_ready()
|
||||
except Exception:
|
||||
ai_ready = False
|
||||
|
||||
node_states: dict[str, dict[str, Any]] = {}
|
||||
node_outputs: dict[str, str] = {}
|
||||
tool_results: dict[str, Any] = {}
|
||||
evidence: dict[str, Any] = {}
|
||||
executed_trace: list[str] = []
|
||||
effective_question = question.strip()
|
||||
final_answer_md = ""
|
||||
final_reasoning_md = ""
|
||||
generation_mode = "deterministic_baseline"
|
||||
zero_token = True
|
||||
resolved_provider: str | None = None
|
||||
resolved_model: str | None = None
|
||||
scene_spec: dict[str, Any] | None = None
|
||||
last_llm_output: str = ""
|
||||
|
||||
for node in ordered_nodes:
|
||||
nid = str(node["id"])
|
||||
ntype = str(node.get("node_type") or "llm_agent")
|
||||
ntitle = str(node.get("title") or nid)
|
||||
|
||||
inc_edges = incoming_map.get(nid) or []
|
||||
if inc_edges:
|
||||
passed = False
|
||||
for edge in inc_edges:
|
||||
pred_id = str(edge.get("source") or "")
|
||||
pred_state = node_states.get(pred_id)
|
||||
if not pred_state or pred_state.get("skipped"):
|
||||
continue
|
||||
if _eval_edge_condition(edge, pred_state, clean_targets):
|
||||
passed = True
|
||||
break
|
||||
if not passed:
|
||||
node_states[nid] = {"skipped": True, "confidence": 1.0, "is_empty": False}
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "skipped"},
|
||||
}
|
||||
continue
|
||||
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "running"},
|
||||
}
|
||||
|
||||
if ntype in {"trigger", "input"}:
|
||||
tmpl = str(bindings.get("prompt_template") or node.get("prompt") or "").strip()
|
||||
if not effective_question and tmpl:
|
||||
effective_question = render_workflow_template(
|
||||
tmpl,
|
||||
question=effective_question,
|
||||
targets=clean_targets,
|
||||
node_outputs=node_outputs,
|
||||
).strip()
|
||||
summary = summarize_targets(clean_targets)
|
||||
node_outputs[nid] = summary
|
||||
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
|
||||
executed_trace.append(nid)
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||||
}
|
||||
continue
|
||||
|
||||
if ntype == "deterministic":
|
||||
local_results: dict[str, Any] = {}
|
||||
l1_ran = False
|
||||
for tid in node.get("tools") or []:
|
||||
if tid in _L1_KNOWLEDGE_TOOL_IDS:
|
||||
if l1_ran:
|
||||
continue
|
||||
l1_ran = True
|
||||
result_key = "l1_facility_lookup"
|
||||
else:
|
||||
result_key = tid
|
||||
try:
|
||||
res = await _execute_tool(
|
||||
db,
|
||||
tid,
|
||||
question=effective_question or question,
|
||||
targets=clean_targets,
|
||||
earth_context=clean_earth_ctx,
|
||||
allow_external_tools=allow_external_tools,
|
||||
)
|
||||
local_results[result_key] = res
|
||||
tool_results[result_key] = res
|
||||
if isinstance(res, dict) and isinstance(res.get("evidence"), dict):
|
||||
evidence.update(res["evidence"])
|
||||
executed_trace.append(f"{nid}:{tid}")
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Deterministic DAG tool failed",
|
||||
event="ai_dag.tool.failed",
|
||||
context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)},
|
||||
)
|
||||
local_results[result_key] = {"error": str(exc)}
|
||||
has_data = _has_meaningful_tool_data(local_results)
|
||||
node_outputs[nid] = json.dumps(local_results, ensure_ascii=False, default=str)[:4000]
|
||||
node_states[nid] = {
|
||||
"skipped": False,
|
||||
"confidence": 0.9 if has_data else 0.4,
|
||||
"is_empty": not has_data,
|
||||
}
|
||||
if nid not in executed_trace:
|
||||
executed_trace.append(nid)
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {
|
||||
"node_id": nid,
|
||||
"title": ntitle,
|
||||
"node_type": ntype,
|
||||
"status": "completed",
|
||||
"tools_count": len(local_results),
|
||||
},
|
||||
}
|
||||
continue
|
||||
|
||||
if ntype in {"llm_agent", "tool_agent"}:
|
||||
has_next_llm = _has_downstream_llm(nid, adj, node_types)
|
||||
sys_prompt = render_workflow_template(
|
||||
str(node.get("system_prompt") or "").strip()
|
||||
or "你是智能星球(Planet)AI 参谋。结合当前地球上下文、选中交互物件与工具证据,给出严谨客观的中文分析。",
|
||||
question=effective_question or question,
|
||||
targets=clean_targets,
|
||||
node_outputs=node_outputs,
|
||||
)
|
||||
node_prompt = render_workflow_template(
|
||||
str(node.get("prompt") or "").strip(),
|
||||
question=effective_question or question,
|
||||
targets=clean_targets,
|
||||
node_outputs=node_outputs,
|
||||
)
|
||||
objective = (
|
||||
f"{node_prompt}\n\n用户请求:{effective_question or question}"
|
||||
if node_prompt
|
||||
else (effective_question or question)
|
||||
).strip()
|
||||
|
||||
# Execute any extra read-only tools configured directly on the LLM node before inference.
|
||||
node_tool_results: dict[str, Any] = {}
|
||||
for tid in node.get("tools") or []:
|
||||
if tid in tool_results or tid in _L1_KNOWLEDGE_TOOL_IDS:
|
||||
continue
|
||||
try:
|
||||
res = await _execute_tool(
|
||||
db,
|
||||
tid,
|
||||
question=effective_question or question,
|
||||
targets=clean_targets,
|
||||
earth_context=clean_earth_ctx,
|
||||
allow_external_tools=allow_external_tools,
|
||||
)
|
||||
node_tool_results[tid] = res
|
||||
tool_results[tid] = res
|
||||
if isinstance(res, dict) and isinstance(res.get("evidence"), dict):
|
||||
evidence.update(res["evidence"])
|
||||
except Exception as exc:
|
||||
node_tool_results[tid] = {"error": str(exc)}
|
||||
|
||||
ctx_payload: dict[str, Any] = {
|
||||
"targets": clean_targets,
|
||||
"targets_summary": summarize_targets(clean_targets),
|
||||
"tool_results": tool_results,
|
||||
"upstream_outputs": {k: v[:2000] for k, v in node_outputs.items()},
|
||||
"evidence": evidence,
|
||||
}
|
||||
if clean_earth_ctx:
|
||||
ctx_payload["earth_context"] = clean_earth_ctx
|
||||
if attachments:
|
||||
ctx_payload["attachments"] = attachments[:8]
|
||||
|
||||
parsed_images: list[ImageAttachment] = []
|
||||
if not has_next_llm and images:
|
||||
for raw_img in images[:8]:
|
||||
try:
|
||||
parsed_images.append(ImageAttachment.model_validate(raw_img))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
chat_msgs = [
|
||||
ChatMessage(role=str(m["role"]), content=str(m["content"])) # type: ignore[arg-type]
|
||||
for m in (history or [])[-12:]
|
||||
if isinstance(m, dict) and m.get("role") in {"user", "assistant"} and m.get("content")
|
||||
]
|
||||
|
||||
preferred_model = (
|
||||
str(model_override or "").strip()
|
||||
or str(node.get("model_override") or "").strip()
|
||||
or None
|
||||
)
|
||||
req = SituationalAnalysisRequest(
|
||||
title=f"Planet AI Advisor · {wf_name}",
|
||||
objective=objective[:24000],
|
||||
system_prompt=sys_prompt[:8000],
|
||||
context=ctx_payload,
|
||||
preferred_model=preferred_model,
|
||||
thinking={"mode": "auto"} if bool(node.get("thinking_enabled", True)) else {"mode": "off"},
|
||||
native_web_search=bool(node.get("native_web_search", False)) and allow_external_tools,
|
||||
messages=[] if has_next_llm else chat_msgs,
|
||||
images=parsed_images,
|
||||
)
|
||||
|
||||
if not ai_ready or ai_client is None:
|
||||
fallback_md = _build_deterministic_fallback_markdown(
|
||||
workflow_name=wf_name,
|
||||
question=effective_question or question,
|
||||
targets=clean_targets,
|
||||
tool_results=tool_results,
|
||||
ai_configured=False,
|
||||
)
|
||||
node_outputs[nid] = fallback_md
|
||||
node_states[nid] = {"skipped": False, "confidence": 0.65, "is_empty": False}
|
||||
executed_trace.append(nid)
|
||||
if not has_next_llm:
|
||||
final_answer_md = fallback_md
|
||||
yield {"event": "text", "data": {"delta": fallback_md}}
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||||
}
|
||||
continue
|
||||
|
||||
timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300))
|
||||
if has_next_llm:
|
||||
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec)
|
||||
clean_text, inline_thoughts = strip_thinking_text(str(getattr(resp, "content", "") or ""))
|
||||
node_outputs[nid] = clean_text or str(getattr(resp, "content", "") or "")
|
||||
if node_outputs[nid]:
|
||||
last_llm_output = node_outputs[nid]
|
||||
resolved_provider = getattr(resp, "provider", None) or provider_name
|
||||
resolved_model = getattr(resp, "model", None) or preferred_model or default_model
|
||||
if inline_thoughts:
|
||||
final_reasoning_md = f"{final_reasoning_md}\n\n" + "\n\n".join(inline_thoughts)
|
||||
final_reasoning_md = final_reasoning_md.strip()
|
||||
generation_mode = "llm_verified"
|
||||
zero_token = False
|
||||
node_states[nid] = {
|
||||
"skipped": False,
|
||||
"confidence": 0.85 if node_outputs[nid] else 0.4,
|
||||
"is_empty": not bool(node_outputs[nid].strip()),
|
||||
}
|
||||
executed_trace.append(nid)
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||||
}
|
||||
else:
|
||||
text_parts: list[str] = []
|
||||
reasoning_parts: list[str] = []
|
||||
resolved_provider = provider_name or None
|
||||
resolved_model = preferred_model or default_model or None
|
||||
async for ev in ai_client.stream_analyze(req, request_id=run_id):
|
||||
if request is not None and await request.is_disconnected():
|
||||
return
|
||||
ev_type = str(ev.get("event") or "")
|
||||
if ev_type == "start":
|
||||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||||
resolved_provider = ev["provider"]
|
||||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||||
resolved_model = ev["model"]
|
||||
elif ev_type == "reasoning" and ev.get("delta"):
|
||||
delta = str(ev["delta"])
|
||||
reasoning_parts.append(delta)
|
||||
yield {"event": "reasoning", "data": {"delta": delta}}
|
||||
elif ev_type == "text" and ev.get("delta"):
|
||||
delta = str(ev["delta"])
|
||||
text_parts.append(delta)
|
||||
yield {"event": "text", "data": {"delta": delta}}
|
||||
elif ev_type == "done":
|
||||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||||
resolved_provider = ev["provider"]
|
||||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||||
resolved_model = ev["model"]
|
||||
elif ev_type == "error":
|
||||
err_msg = str(ev.get("message") or ev.get("detail") or "AI stream error")
|
||||
raise RuntimeError(err_msg)
|
||||
|
||||
raw_text = "".join(text_parts)
|
||||
clean_text, inline_thoughts = strip_thinking_text(raw_text)
|
||||
final_answer_md = (clean_text or raw_text).strip()
|
||||
if inline_thoughts:
|
||||
reasoning_parts.extend(inline_thoughts)
|
||||
if reasoning_parts:
|
||||
joined = "".join(reasoning_parts).strip()
|
||||
final_reasoning_md = f"{final_reasoning_md}\n\n{joined}".strip() if final_reasoning_md else joined
|
||||
generation_mode = "llm_verified"
|
||||
zero_token = False
|
||||
node_outputs[nid] = final_answer_md
|
||||
node_states[nid] = {
|
||||
"skipped": False,
|
||||
"confidence": 0.9 if final_answer_md else 0.35,
|
||||
"is_empty": not bool(final_answer_md),
|
||||
}
|
||||
executed_trace.append(nid)
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||||
}
|
||||
continue
|
||||
|
||||
if ntype == "guardrail":
|
||||
gr = node.get("guardrails") if isinstance(node.get("guardrails"), dict) else {}
|
||||
passed = True
|
||||
warnings: list[str] = []
|
||||
if gr.get("require_evidence") and not evidence:
|
||||
passed = False
|
||||
warnings.append("缺少结构化证据条目(require_evidence)")
|
||||
min_chars = int(gr.get("min_output_chars") or 0)
|
||||
if min_chars > 0 and len(final_answer_md) < min_chars:
|
||||
passed = False
|
||||
warnings.append(f"输出长度低于最低阈值({min_chars} 字符)")
|
||||
forbidden = gr.get("forbidden_phrases")
|
||||
if isinstance(forbidden, list) and final_answer_md:
|
||||
hits = [str(p) for p in forbidden if str(p) and str(p) in final_answer_md]
|
||||
if hits:
|
||||
passed = False
|
||||
warnings.append("命中禁用表述: " + ", ".join(hits[:5]))
|
||||
disclaimer = str(gr.get("append_disclaimer") or "").strip()
|
||||
if disclaimer and final_answer_md and disclaimer not in final_answer_md:
|
||||
extra_block = f"\n\n> {disclaimer}"
|
||||
final_answer_md += extra_block
|
||||
yield {"event": "text", "data": {"delta": extra_block}}
|
||||
node_states[nid] = {
|
||||
"skipped": False,
|
||||
"confidence": 0.95 if passed else 0.45,
|
||||
"is_empty": False,
|
||||
"warnings": warnings,
|
||||
}
|
||||
executed_trace.append(nid)
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {
|
||||
"node_id": nid,
|
||||
"title": ntitle,
|
||||
"node_type": ntype,
|
||||
"status": "completed",
|
||||
"guardrail_passed": passed,
|
||||
},
|
||||
}
|
||||
continue
|
||||
|
||||
if ntype == "output":
|
||||
params = node.get("params") if isinstance(node.get("params"), dict) else {}
|
||||
fly_enabled = bool(params.get("fly_to_target", True))
|
||||
if fly_enabled and clean_targets:
|
||||
first = clean_targets[0]
|
||||
lat = first.get("latitude")
|
||||
lon = first.get("longitude")
|
||||
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
|
||||
scene_spec = {
|
||||
"fly_to": {
|
||||
"lat": float(lat),
|
||||
"lon": float(lon),
|
||||
"zoom": float(params.get("fly_zoom") or 1.45),
|
||||
},
|
||||
"highlight_entities": [
|
||||
str(t.get("entity_id") or t.get("id"))
|
||||
for t in clean_targets
|
||||
if t.get("entity_id") or t.get("id")
|
||||
],
|
||||
}
|
||||
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
|
||||
executed_trace.append(nid)
|
||||
yield {
|
||||
"event": "node",
|
||||
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
|
||||
}
|
||||
|
||||
if not final_answer_md:
|
||||
final_answer_md = last_llm_output or _build_deterministic_fallback_markdown(
|
||||
workflow_name=wf_name,
|
||||
question=effective_question or question,
|
||||
targets=clean_targets,
|
||||
tool_results=tool_results,
|
||||
ai_configured=ai_ready,
|
||||
)
|
||||
yield {"event": "text", "data": {"delta": final_answer_md}}
|
||||
|
||||
yield {
|
||||
"event": "done",
|
||||
"data": {
|
||||
"run_id": run_id,
|
||||
"workflow_id": wf_id,
|
||||
"workflow_name": wf_name,
|
||||
"status": "completed",
|
||||
"generation_mode": generation_mode,
|
||||
"zero_token": zero_token,
|
||||
"provider": resolved_provider,
|
||||
"model": resolved_model,
|
||||
"nodes": executed_trace,
|
||||
"evidence": evidence,
|
||||
"scene_spec": scene_spec,
|
||||
"answer_markdown": final_answer_md,
|
||||
"reasoning_markdown": final_reasoning_md,
|
||||
"text_length": len(final_answer_md),
|
||||
},
|
||||
}
|
||||
@@ -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,12 +25,15 @@ 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_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 classify_turn_intent, execute_session_turn
|
||||
from app.services.ai_client import AIProviderClient
|
||||
|
||||
@@ -271,6 +276,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 +342,160 @@ 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)
|
||||
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,
|
||||
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 {}),
|
||||
},
|
||||
):
|
||||
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 == "done":
|
||||
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"])
|
||||
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):
|
||||
updated_recent = [*recent_history, {"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)
|
||||
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:
|
||||
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,
|
||||
},
|
||||
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] = {}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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,672 @@
|
||||
"""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()
|
||||
|
||||
|
||||
@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. Propose `model_adapt` (deterministic fallback fills minimal patch)
|
||||
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["constitution_ok"] is True
|
||||
assert len(prop["changes"]) >= 1
|
||||
|
||||
# 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 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},
|
||||
)
|
||||
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()
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.81.0",
|
||||
"version": "0.82.0",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
|
||||
@@ -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, type Display } 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 });
|
||||
|
||||
@@ -752,6 +752,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 +761,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 +782,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>
|
||||
|
||||
@@ -8,6 +8,26 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [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
|
||||
|
||||
@@ -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 贴地影响范围与电影级三维视觉升级方案
|
||||
|
||||
> 状态:**规划待排期**(全量 Three.js / 着色器 / Agent 场景协议只读评估已完成,当前无需升级 `three@0.128.0` 亦不引入全屏后处理 `UnrealBloomPass`,全部效果可在核显与 Electron 60fps 录屏约束下通过轻量化自定义 Shader 实现)。
|
||||
|
||||
---
|
||||
|
||||
## 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) 深度与渲染顺序回归测试。
|
||||
@@ -132,15 +132,24 @@ 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.
|
||||
- **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.
|
||||
|
||||
|
||||
@@ -609,3 +609,8 @@ 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.
|
||||
@@ -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,24 @@ 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`)协议方便后续扩展新探针或评测器。
|
||||
- **反馈与运行记录接口**:`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,连通性测试只验证当前草稿是否可用,不应隐式保存或切换默认项。
|
||||
|
||||
|
||||
@@ -748,3 +748,8 @@ 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` 纯净语种映射并同步管理台语言偏好。
|
||||
@@ -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,13 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.81.0`
|
||||
- `dev` 当前开发分支历史推导到:`0.82.0`
|
||||
|
||||
## Timeline
|
||||
|
||||
| Version | Type | Branch | Commit | Summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `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.82.0",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
|
||||
@@ -986,3 +986,172 @@ 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: 12px;
|
||||
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: fixed;
|
||||
left: 50%;
|
||||
bottom: calc(var(--hud-offset, 16px) + 4px);
|
||||
transform: translateX(-50%);
|
||||
z-index: 160;
|
||||
max-width: min(720px, calc(100vw - 24px));
|
||||
padding: 6px 8px;
|
||||
border-radius: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.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: 28px;
|
||||
padding: 0 10px;
|
||||
border-radius: 8px;
|
||||
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__analyze:hover {
|
||||
background: rgba(92, 200, 255, 0.32);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -401,10 +401,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",
|
||||
|
||||
@@ -515,7 +515,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 +528,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;
|
||||
@@ -916,7 +916,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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Vendored
+34
-32
@@ -440,14 +440,14 @@ function normalizeKeyboardShortcuts(rawShortcuts = {}) {
|
||||
|
||||
function getShortcutDisplayLabel(binding) {
|
||||
const normalized = normalizeShortcutBinding(binding);
|
||||
if (!normalized) return "未设置";
|
||||
if (!normalized) return translateText("未设置");
|
||||
return normalized
|
||||
.replaceAll("ArrowUp", "↑")
|
||||
.replaceAll("ArrowDown", "↓")
|
||||
.replaceAll("ArrowLeft", "←")
|
||||
.replaceAll("ArrowRight", "→")
|
||||
.replaceAll("Space", "空格")
|
||||
.replaceAll("Enter", "回车")
|
||||
.replaceAll("Space", translateText("空格"))
|
||||
.replaceAll("Enter", translateText("回车"))
|
||||
.replaceAll("Escape", "Esc")
|
||||
.replaceAll("Plus", "+")
|
||||
.replaceAll("Ctrl", "Ctrl")
|
||||
@@ -457,7 +457,7 @@ function getShortcutDisplayLabel(binding) {
|
||||
function getShortcutAliasesLabel(definition) {
|
||||
const aliases = Array.isArray(definition?.aliases) ? definition.aliases : [];
|
||||
if (aliases.length === 0) return "";
|
||||
return `备用:${aliases.map(getShortcutDisplayLabel).join(" / ")}`;
|
||||
return translateText(`备用:${aliases.map(getShortcutDisplayLabel).join(" / ")}`);
|
||||
}
|
||||
|
||||
function getShortcutForAction(actionId) {
|
||||
@@ -1501,7 +1501,7 @@ function formatZoomPercent(zoom) {
|
||||
}
|
||||
|
||||
function getZoomResetTooltipText(zoom) {
|
||||
return `重置缩放到${formatZoomPercent(zoom)}`;
|
||||
return translateText(`重置缩放到${formatZoomPercent(zoom)}`);
|
||||
}
|
||||
|
||||
function getZoomResetStatusMessage(zoom) {
|
||||
@@ -1949,11 +1949,11 @@ function syncMotionCameraModeControls(nextMode = motionCameraMode) {
|
||||
|
||||
function syncMotionCameraTopologySummary() {
|
||||
const count = motionDetectedCameras.length;
|
||||
let summaryText = "自动检测可用物理摄像头;单摄走 2D,双摄 3D 深度规划中";
|
||||
let summaryText = "自动识别可用物理摄像头";
|
||||
if (motionDualCameraDetected) {
|
||||
summaryText = `检测到 ${count} 个物理摄像头:当前运行单摄 2D(双摄 3D 深度规划中)`;
|
||||
summaryText = `已检测到 ${count} 个物理摄像头(单摄 2D)`;
|
||||
} else if (count === 1) {
|
||||
summaryText = "已检测到 1 个物理摄像头(单摄 2D 本地骨骼识别)";
|
||||
summaryText = "已检测到 1 个物理摄像头(单摄 2D)";
|
||||
}
|
||||
document.querySelectorAll("[data-motion-camera-mode-summary]").forEach((el) => {
|
||||
if (el instanceof HTMLElement) {
|
||||
@@ -2526,7 +2526,7 @@ export function setSatelliteRealAltitudeEnabled(
|
||||
showStatusMessage(
|
||||
enabled
|
||||
? earthMessage("status.booleanSetting", { label: "卫星真实高度", enabled })
|
||||
: earthMessage("status.valueChanged", { label: "卫星", value: "旧版同层高度" }),
|
||||
: earthMessage("status.valueChanged", { label: "卫星", value: "同层球面" }),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
@@ -3485,7 +3485,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-grid-lines",
|
||||
icon: "grid_4x4",
|
||||
label: "经纬线",
|
||||
meta: "Graticule",
|
||||
meta: "经纬度网格",
|
||||
keywords: "经纬线 graticule 经纬 latitude longitude",
|
||||
defaultActive: false,
|
||||
displayOrder: 100,
|
||||
@@ -3502,7 +3502,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-country-boundaries",
|
||||
icon: "public",
|
||||
label: "国界线",
|
||||
meta: "Country Borders",
|
||||
meta: "国家与地区边界",
|
||||
keywords: "国界 国家 borders countries boundary",
|
||||
defaultActive: true,
|
||||
displayOrder: 90,
|
||||
@@ -3520,7 +3520,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-earth-high-res-texture",
|
||||
icon: "globe",
|
||||
label: "高清材质",
|
||||
meta: "High-Res Texture",
|
||||
meta: "高清地表影像",
|
||||
keywords: "高清 材质 纹理 texture hd 地表 earth",
|
||||
defaultActive: true,
|
||||
displayOrder: 70,
|
||||
@@ -3537,7 +3537,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-atmosphere-clouds",
|
||||
icon: "cloud",
|
||||
label: "大气云图",
|
||||
meta: "Cloud Layer",
|
||||
meta: "云层与大气",
|
||||
keywords: "大气 云图 云层 clouds atmosphere",
|
||||
defaultActive: true,
|
||||
displayOrder: 80,
|
||||
@@ -3554,7 +3554,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-cables",
|
||||
icon: "cable",
|
||||
label: "海缆",
|
||||
meta: "Subsea Cables",
|
||||
meta: "海底光缆网络",
|
||||
keywords: "海缆 subsea cables",
|
||||
defaultActive: true,
|
||||
displayOrder: 10,
|
||||
@@ -3574,7 +3574,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-compute-centers",
|
||||
icon: "memory",
|
||||
label: "算力中心",
|
||||
meta: "Compute Centers",
|
||||
meta: "全球算力基础设施",
|
||||
keywords: "算力中心 compute centers gpu 超算",
|
||||
defaultActive: true,
|
||||
displayOrder: 40,
|
||||
@@ -3591,7 +3591,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-bgp",
|
||||
icon: "hub",
|
||||
label: "BGP观测",
|
||||
meta: "Routing Signals",
|
||||
meta: "网络异常与监测",
|
||||
keywords: "bgp观测 routing signals",
|
||||
defaultActive: true,
|
||||
displayOrder: 50,
|
||||
@@ -3608,7 +3608,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-vessels",
|
||||
icon: "directions_boat",
|
||||
label: "船只",
|
||||
meta: "AIS Vessels",
|
||||
meta: "实时 AIS 船舶",
|
||||
keywords: "船只 船舶 ais vessels ships maritime",
|
||||
defaultActive: false,
|
||||
displayOrder: 45,
|
||||
@@ -3625,7 +3625,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-satellites",
|
||||
icon: "satellite_alt",
|
||||
label: "卫星",
|
||||
meta: "Satellites",
|
||||
meta: "地球轨道卫星",
|
||||
keywords: "卫星 satellites",
|
||||
defaultActive: false,
|
||||
displayOrder: 30,
|
||||
@@ -3642,7 +3642,7 @@ function getBuiltinLayerDefinitions() {
|
||||
buttonId: "toggle-terrain",
|
||||
icon: "landscape",
|
||||
label: "地形",
|
||||
meta: "Terrain",
|
||||
meta: "地形与高程",
|
||||
keywords: "地形 terrain",
|
||||
defaultActive: false,
|
||||
displayOrder: 60,
|
||||
@@ -4194,7 +4194,7 @@ async function fetchBoundaryPrecisionJson(path, options = {}) {
|
||||
throw new Error(detail);
|
||||
}
|
||||
if (!contentType.includes("application/json")) {
|
||||
throw new Error("后端没有返回 JSON 状态");
|
||||
throw new Error(translateText("服务响应格式异常"));
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
@@ -4208,20 +4208,22 @@ function renderBoundaryPrecisionStatus(payload = {}) {
|
||||
const failed = job.status === "failed" && boundaryBuildAttemptedThisSession;
|
||||
const progress = Math.max(0, Math.min(100, Number(job.progress || 0)));
|
||||
const failureMessage = job.code === "source_not_configured" || job.code === "missing_sources"
|
||||
? `高清国界更新源未配置完整:${job.message || job.code}`
|
||||
: `高清国界下载失败:${job.message || job.code || "请检查更新源"}`;
|
||||
? translateText(`高清国界更新源未配置:${job.message || job.code}`)
|
||||
: translateText(`高清国界下载失败:${job.message || job.code || "请检查更新源"}`);
|
||||
|
||||
els.statuses.forEach((status) => {
|
||||
status.textContent = "国界精度";
|
||||
status.textContent = translateText("国界精度");
|
||||
});
|
||||
els.details.forEach((detail) => {
|
||||
detail.textContent = running
|
||||
? (job.message || "正在准备高清国界")
|
||||
: failed
|
||||
? failureMessage
|
||||
: highReady
|
||||
? (enabled ? "当前使用高精国界;可重新获取并构建。" : "高精国界已就绪,切到高精会立即应用。")
|
||||
: "当前使用低精国界;切到高精会下载并构建。";
|
||||
detail.textContent = translateText(
|
||||
running
|
||||
? (job.message || "正在准备高清国界")
|
||||
: failed
|
||||
? failureMessage
|
||||
: highReady
|
||||
? (enabled ? "已开启高精国界" : "高精国界已就绪")
|
||||
: "当前使用低精国界",
|
||||
);
|
||||
});
|
||||
els.progressWraps.forEach((progressWrap) => {
|
||||
progressWrap.hidden = !running;
|
||||
@@ -4231,13 +4233,13 @@ function renderBoundaryPrecisionStatus(payload = {}) {
|
||||
});
|
||||
els.progressValues.forEach((progressValue) => {
|
||||
progressValue.textContent = job.status === "failed"
|
||||
? `失败:${job.message || job.code || "构建失败"}`
|
||||
? translateText(`失败:${job.message || job.code || "构建失败"}`)
|
||||
: `${running || job.status === "succeeded" ? progress || 100 : progress}%`;
|
||||
});
|
||||
els.buildButtons.forEach((buildButton) => {
|
||||
if (!(buildButton instanceof HTMLButtonElement)) return;
|
||||
buildButton.disabled = running;
|
||||
buildButton.textContent = "高精";
|
||||
buildButton.textContent = translateText("高精");
|
||||
buildButton.classList.toggle("is-active", enabled || running);
|
||||
buildButton.setAttribute("aria-pressed", enabled || running ? "true" : "false");
|
||||
});
|
||||
|
||||
@@ -129,6 +129,8 @@ export async function consumeCopilotStream(
|
||||
|
||||
if (eventName === "meta") {
|
||||
callbacks.onMeta?.(parsed);
|
||||
} else if (eventName === "node") {
|
||||
callbacks.onNode?.(parsed);
|
||||
} else if (eventName === "reasoning") {
|
||||
if (typeof parsed.delta === "string" && parsed.delta) {
|
||||
callbacks.onReasoningDelta?.(parsed.delta, parsed);
|
||||
@@ -141,7 +143,7 @@ export async function consumeCopilotStream(
|
||||
donePayload = parsed;
|
||||
callbacks.onDone?.(parsed);
|
||||
} else if (eventName === "error") {
|
||||
const err = new Error(parsed.detail || "AI stream error");
|
||||
const err = new Error(parsed.detail || parsed.message || "AI stream error");
|
||||
err.partial = Boolean(parsed.partial);
|
||||
throw err;
|
||||
}
|
||||
|
||||
@@ -110,6 +110,8 @@ export function finishFrameStats(start, renderer) {
|
||||
output.dataset.sampleSeconds = average.seconds.toFixed(1);
|
||||
output.textContent = `${Math.round(fps)} FPS`;
|
||||
positionFpsOutput();
|
||||
output.title = `${getEarthLocale() === "en-US" ? "Frame interval" : "帧间隔"} ${mean.toFixed(2)} ms · P95 ${p95.toFixed(2)} ms · CPU ${cpu.toFixed(2)} ms · Draw calls ${renderer.info.render.calls} · ${average.seconds.toFixed(1)}s AVG ${average.fps.toFixed(1)} FPS`;
|
||||
output.title = getEarthLocale() === "en-US"
|
||||
? `Frame interval ${mean.toFixed(2)} ms · P95 ${p95.toFixed(2)} ms · CPU ${cpu.toFixed(2)} ms · Draw calls ${renderer.info.render.calls} · ${average.seconds.toFixed(1)}s avg ${average.fps.toFixed(1)} FPS`
|
||||
: `帧间隔 ${mean.toFixed(2)} ms · P95 ${p95.toFixed(2)} ms · CPU ${cpu.toFixed(2)} ms · 绘制调用 ${renderer.info.render.calls} · ${average.seconds.toFixed(1)}s 均值 ${average.fps.toFixed(1)} FPS`;
|
||||
samples.length = 0; reportedAt = start;
|
||||
}
|
||||
@@ -128,6 +128,62 @@ const EARTH_MESSAGE_TEMPLATES = {
|
||||
zh: "算力中心坐标已保存",
|
||||
en: "Compute center coordinates saved",
|
||||
},
|
||||
"status.gpuFallbackCpu": {
|
||||
zh: "显存不足且帧率偏低,已切换至 CPU 软渲染",
|
||||
en: "Low VRAM & FPS: switched to CPU software rendering",
|
||||
},
|
||||
"status.gpuFallbackIntegrated": {
|
||||
zh: "显存不足且帧率偏低,已切换至集成显卡渲染",
|
||||
en: "Low VRAM & FPS: switched to integrated GPU rendering",
|
||||
},
|
||||
"status.gpuRestoredDiscrete": {
|
||||
zh: "显存充足,已切回独立显卡渲染",
|
||||
en: "VRAM available: restored discrete GPU rendering",
|
||||
},
|
||||
"status.recordingWriteFailed": {
|
||||
zh: ({ error }) => `录屏保存失败:${error}`,
|
||||
en: ({ error }) => `Recording save failed: ${error}`,
|
||||
},
|
||||
"status.recordingSaved": {
|
||||
zh: ({ path }) => `已保存录屏:${path}`,
|
||||
en: ({ path }) => `Saved recording: ${path}`,
|
||||
},
|
||||
"status.recordingNoFrames": {
|
||||
zh: "录屏已停止(无有效画面)",
|
||||
en: "Recording stopped (no captured frames)",
|
||||
},
|
||||
"status.recordingStartFailed": {
|
||||
zh: ({ error }) => `启动录屏失败:${error}`,
|
||||
en: ({ error }) => `Failed to start recording: ${error}`,
|
||||
},
|
||||
"status.recordingMutedFallback": {
|
||||
zh: "当前设备不支持系统音频录制,已静音录制",
|
||||
en: "System audio unavailable; recording muted",
|
||||
},
|
||||
"status.hotfixActive": {
|
||||
zh: ({ version }) => `已应用在线更新 v${version}`,
|
||||
en: ({ version }) => `Update v${version} active`,
|
||||
},
|
||||
"status.hotfixDownloading": {
|
||||
zh: ({ version }) => `正在下载更新 v${version}...`,
|
||||
en: ({ version }) => `Downloading update v${version}...`,
|
||||
},
|
||||
"status.oobeReturnAfterCollect": {
|
||||
zh: "完成首次采集后即可查看实时数据。",
|
||||
en: "Complete the first collection to view live data.",
|
||||
},
|
||||
"status.layerNotReady": {
|
||||
zh: ({ layer }) => `${localizedParam(layer, "zh-CN")}加载中`,
|
||||
en: ({ layer }) => `${localizedParam(layer, "en-US")} loading`,
|
||||
},
|
||||
"status.boundaryStatusError": {
|
||||
zh: ({ detail }) => `高精国界不可用:${detail}`,
|
||||
en: ({ detail }) => `High-precision boundaries unavailable: ${detail}`,
|
||||
},
|
||||
"status.cameraModeDetected": {
|
||||
zh: ({ count, mode }) => `检测到 ${count} 个物理摄像头:${mode === "dual" ? "双摄 3D" : "单摄 2D"}`,
|
||||
en: ({ count, mode }) => `${count} physical cameras detected: ${mode === "dual" ? "Dual 3D" : "Single 2D"}`,
|
||||
},
|
||||
"status.coordinatesSavedLater": {
|
||||
zh: "坐标已保存,地图稍后同步",
|
||||
en: "Coordinates saved; map will sync shortly",
|
||||
@@ -188,6 +244,10 @@ const EARTH_MESSAGE_TEMPLATES = {
|
||||
zh: "无可复制内容",
|
||||
en: "Nothing to copy",
|
||||
},
|
||||
"status.addedToCompare": {
|
||||
zh: "已加入多物件联合对比栏",
|
||||
en: "Added to multi-object compare tray",
|
||||
},
|
||||
"status.copyValue": {
|
||||
zh: ({ label, value }) => `已复制${label}:${value}`,
|
||||
en: ({ label, value }) => `Copied ${label}: ${value}`,
|
||||
@@ -235,16 +295,16 @@ const EARTH_MESSAGE_TEMPLATES = {
|
||||
: "Motion debug mode disabled",
|
||||
},
|
||||
"status.motionProvider": {
|
||||
zh: ({ provider }) => (provider === "motion_agent" ? "Motion Agent 已接管动捕输入" : "动捕已切换到本机摄像头(内置识别)"),
|
||||
en: ({ provider }) => (provider === "motion_agent" ? "Motion Agent now controls motion input" : "Motion switched to built-in local camera"),
|
||||
zh: ({ provider }) => (provider === "motion_agent" ? "动捕服务已接管动捕输入" : "动捕已切换到本机摄像头"),
|
||||
en: ({ provider }) => (provider === "motion_agent" ? "Motion service now controls motion input" : "Motion switched to local camera"),
|
||||
},
|
||||
"status.motionCameraMode": {
|
||||
zh: ({ mode }) => (mode === "single" ? "摄像头模式已切换为单摄 2D" : "摄像头模式已切换为自动检测"),
|
||||
en: ({ mode }) => (mode === "single" ? "Camera mode switched to Single 2D" : "Camera mode switched to Auto Detect"),
|
||||
},
|
||||
"status.motionDual3dPlanned": {
|
||||
zh: "双摄真 3D 深度模式规划中,当前自动使用单摄 2D",
|
||||
en: "Dual-camera 3D depth mode is planned; using Single 2D for now",
|
||||
zh: "双摄 3D 模式即将支持,当前自动使用单摄 2D",
|
||||
en: "Dual-camera 3D mode coming soon; using Single 2D",
|
||||
},
|
||||
"status.motionCameraDevice": {
|
||||
zh: ({ label }) => `动捕摄像头已切换为 ${localizedParam(label, "zh-CN")}`,
|
||||
@@ -259,8 +319,8 @@ const EARTH_MESSAGE_TEMPLATES = {
|
||||
en: "Motion gestures updated",
|
||||
},
|
||||
"status.settingsReset": {
|
||||
zh: "Earth 设置已重置",
|
||||
en: "Earth settings reset",
|
||||
zh: "设置已重置",
|
||||
en: "Settings reset",
|
||||
},
|
||||
"status.terrainUnavailable": {
|
||||
zh: "真实地形暂时不可用",
|
||||
@@ -456,6 +516,101 @@ const EXACT_TRANSLATIONS = {
|
||||
"切换大气云图显示": "Toggle atmosphere and clouds",
|
||||
"切换国界显示": "Toggle borders",
|
||||
"切换经纬线显示": "Toggle graticule",
|
||||
"同层球面": "Same-layer shell",
|
||||
"服务响应格式异常": "Invalid server response",
|
||||
"已开启高精国界": "High-precision boundaries enabled",
|
||||
"高精国界已就绪": "High-precision boundaries ready",
|
||||
"当前使用低精国界": "Using low-precision boundaries",
|
||||
"已检测到 1 个物理摄像头(单摄 2D)": "1 physical camera detected (single-cam 2D)",
|
||||
"船舶图片": "Vessel photo",
|
||||
"BGP 路由事件": "BGP routing incident",
|
||||
"运营中": "Operational",
|
||||
"总长度": "Total length",
|
||||
"运营状态": "Operational status",
|
||||
"投产年份": "Ready for service",
|
||||
"所属国家": "Country",
|
||||
"算力规模": "Compute scale",
|
||||
"功率消耗": "Power draw",
|
||||
"船舶": "Vessel",
|
||||
"航速": "Speed",
|
||||
"航行状态": "Navigational status",
|
||||
"路由前缀": "Route prefix",
|
||||
"未知星座": "Unknown constellation",
|
||||
"快讯摘要": "Brief summary",
|
||||
"待核验": "Pending verification",
|
||||
"暂无更多详细参数": "No additional specifications",
|
||||
"阅读原文": "Read source",
|
||||
"查看来源": "View source",
|
||||
"常规来源无可用结果": "No usable results from standard sources",
|
||||
"智能检索未找到可用候选": "No usable candidates found via smart lookup",
|
||||
"近地点": "Perigee",
|
||||
"远地点": "Apogee",
|
||||
"轨道倾角": "Inclination",
|
||||
"运行周期": "Orbital period",
|
||||
"涉事 ASN": "Involved ASNs",
|
||||
"当前事件": "Current incidents",
|
||||
"近24h事件": "Incidents (24h)",
|
||||
"船舶实时通道后台已连接": "Vessel live feed connected in background",
|
||||
"船舶实时通道正在重连": "Vessel live feed reconnecting",
|
||||
"船舶实时通道正在连接": "Vessel live feed connecting",
|
||||
"船舶实时通道未连接": "Vessel live feed disconnected",
|
||||
"关闭新闻直播": "Close Live News",
|
||||
"打开新闻直播": "Open Live News",
|
||||
"展开图层列表": "Expand layer list",
|
||||
"恢复布局": "Reset layout",
|
||||
"选择选项": "Select option",
|
||||
"选项列表": "Option list",
|
||||
"无匹配选项": "No matching options",
|
||||
"暂无可用选项": "No options available",
|
||||
"加载失败,点击重试": "Failed to load, click to retry",
|
||||
"正在加载…": "Loading…",
|
||||
"选择时间知识边界": "Select time knowledge basis",
|
||||
"时间口径模式": "Time basis mode",
|
||||
"暂无可用模式": "No modes available",
|
||||
"同步文档和控制台语言偏好": "Sync docs and console language preference",
|
||||
"外链": "External link",
|
||||
"可在后台配置默认频道与采集源。": "Configure default channels and collector sources in Admin.",
|
||||
"暂无观测数据": "No telemetry data",
|
||||
"按新闻来源筛选。": "Filter by news source.",
|
||||
"请分析这条全球新闻动态与潜在影响。": "Analyze this global news development and its potential impact.",
|
||||
"动捕服务已连接": "Motion Service Connected",
|
||||
"动捕服务": "Motion Service",
|
||||
"动捕服务连接异常": "Motion Service Error",
|
||||
"动捕服务未连接": "Motion Service Disconnected",
|
||||
"当前浏览器不支持摄像头采集": "Browser does not support camera capture",
|
||||
"摄像头功能需要在安全连接或本机环境下使用": "Camera capture requires HTTPS or localhost",
|
||||
"检测到双摄像头:当前使用单摄 2D 模式": "Dual cameras detected: using single-camera 2D mode",
|
||||
"匹配已暂停": "Matching paused",
|
||||
"未匹配动作": "No gesture matched",
|
||||
"等待骨架数据": "Waiting for skeleton data",
|
||||
"动捕未连接": "Motion disconnected",
|
||||
"未设置": "Not set",
|
||||
"空格": "Space",
|
||||
"回车": "Enter",
|
||||
"船舶类型": "Vessel type",
|
||||
"总吨位": "Gross tonnage",
|
||||
"国家代码": "Country code",
|
||||
"船舶呼号": "Call sign",
|
||||
"载重吨位": "Deadweight tonnage",
|
||||
"吃水深度": "Draft",
|
||||
"目的港": "Destination",
|
||||
"预计到达时间": "ETA",
|
||||
"建造年份": "Built year",
|
||||
"船籍": "Flag",
|
||||
"船舶状态": "Vessel status",
|
||||
"经纬度网格": "Graticule",
|
||||
"国家与地区边界": "Country Borders",
|
||||
"高清地表影像": "High-Res Texture",
|
||||
"云层与大气": "Cloud Layer",
|
||||
"海底光缆网络": "Subsea Cables",
|
||||
"全球算力基础设施": "Compute Centers",
|
||||
"网络异常与监测": "Routing Signals",
|
||||
"实时 AIS 船舶": "AIS Vessels",
|
||||
"地球轨道卫星": "Satellites",
|
||||
"地形与高程": "Terrain",
|
||||
"刚刚": "Just now",
|
||||
"节": "kt",
|
||||
"未找到匹配对象,可尝试名称、地点、NORAD、ASN、前缀等关键词。": "No matching objects found. Try a name, location, NORAD ID, ASN, or prefix.",
|
||||
"显示卫星": "Show Satellites",
|
||||
"隐藏卫星": "Hide Satellites",
|
||||
"显示船只": "Show Vessels",
|
||||
@@ -506,7 +661,8 @@ const EXACT_TRANSLATIONS = {
|
||||
"关闭图例": "Close legend",
|
||||
"关闭地球信息": "Close Earth info",
|
||||
"Live 新闻": "Live News",
|
||||
"选择新闻直播源": "Select live news source",
|
||||
"选择新闻直播源": "Select Live News source",
|
||||
"选择 Live 新闻源": "Select Live News source",
|
||||
"频道列表": "Channel list",
|
||||
"搜索频道、地区…": "Search channels, regions…",
|
||||
"无匹配频道": "No matching channels",
|
||||
@@ -531,7 +687,7 @@ const EXACT_TRANSLATIONS = {
|
||||
"HLS 播放列表格式无法解析": "Unable to parse HLS playlist",
|
||||
"HLS 分片格式无法解析": "Unable to parse HLS segment",
|
||||
"HLS 播放流不可用": "HLS stream unavailable",
|
||||
"直播放流不可用,已回退到官网直播页": "Live stream unavailable; falling back to the official live page",
|
||||
"直播流不可用,已切换至官方直播页": "Live stream unavailable; opening official page",
|
||||
"直播流网络波动,正在重试...": "Live stream network issue. Retrying...",
|
||||
"直播流正在恢复...": "Live stream recovering...",
|
||||
"已加载视频流,点击播放继续": "Video stream loaded. Click play to continue.",
|
||||
@@ -545,7 +701,7 @@ const EXACT_TRANSLATIONS = {
|
||||
"Live 新闻窗口已关闭": "Live News panel closed",
|
||||
"内置": "Built-in",
|
||||
"内置源": "Built-in",
|
||||
"采集": "Collected",
|
||||
"采集": "Collect",
|
||||
"采集源": "Collector source",
|
||||
"频道": "Channel",
|
||||
"尚未同步": "Not synced yet",
|
||||
@@ -618,15 +774,12 @@ const EXACT_TRANSLATIONS = {
|
||||
"真实地形": "Real terrain",
|
||||
"真实地形已显示": "Real terrain shown",
|
||||
"电缆": "Cables",
|
||||
"新闻类型": "News Types",
|
||||
"自动旋转": "Auto Rotate",
|
||||
"旋转": "Rotation",
|
||||
"巡航": "Cruise",
|
||||
"布局": "Layout",
|
||||
"视角": "View",
|
||||
"当前目标": "Current target",
|
||||
"国界": "Borders",
|
||||
"其他": "Other",
|
||||
"巡航队列": "Cruise Queue",
|
||||
"巡航大区顺序": "Cruise Region Order",
|
||||
"控制巡航项按原始顺序、大区轮转或随机播放。": "Control whether cruise items play in original order, by region, or randomly.",
|
||||
@@ -722,10 +875,6 @@ const EXACT_TRANSLATIONS = {
|
||||
"BGP 观测站": "BGP Collectors",
|
||||
"运行中": "Running",
|
||||
"当前无活跃事件": "No active events",
|
||||
"AISStream 未连接": "AISStream Disconnected",
|
||||
"船舶实时通道已连接 · 等待首批更新": "Vessel live updates connected · waiting for first updates",
|
||||
"AISStream 正在重连": "AISStream reconnecting",
|
||||
"AISStream 正在连接": "AISStream connecting",
|
||||
"暂无可播放直播源": "No playable live source",
|
||||
"打开 Live 新闻": "Open Live News",
|
||||
"关闭 Live 新闻": "Close Live News",
|
||||
@@ -751,23 +900,28 @@ const EXACT_TRANSLATIONS = {
|
||||
"高清材质加载中...": "HD texture loading...",
|
||||
"大气云图加载中...": "Atmosphere and clouds loading...",
|
||||
"船只加载中...": "Vessels loading...",
|
||||
"欢迎使用智能星球计划": "Welcome to Intelligent Planet",
|
||||
"登录控制台并完成首次采集后,Earth 将显示实时数据层。": "After signing in to the console and completing the first collection, Earth will display live data layers.",
|
||||
"系统初始化": "System Initialization",
|
||||
"欢迎使用智能星球": "Welcome to Intelligent Planet",
|
||||
"请登录控制台并完成首次采集,完成后将自动加载实时数据。": "Sign in to the console and complete initial collection to load live data.",
|
||||
"当前暂无可展示数据,可在控制台触发首次采集。": "No displayable data yet. Run initial collection in the console.",
|
||||
"演示模式已开启,正在展示初始化引导。": "Demo mode is active; showing initial setup guide.",
|
||||
"后端服务在线": "Backend service online",
|
||||
"登录控制台": "Sign in to Console",
|
||||
"配置或确认数据源": "Configure or confirm datasources",
|
||||
"触发首次采集": "Run the first collection",
|
||||
"回到 Earth 查看结果": "Return to Earth to view results",
|
||||
"回到智能星球查看结果": "Return to Intelligent Planet to view results",
|
||||
"去采集数据": "Collect data",
|
||||
"进入采集管理": "Open Collection Management",
|
||||
"查看文档": "View Docs",
|
||||
"概要": "Summary",
|
||||
"当前记录": "Current Records",
|
||||
"直播源": "Live Sources",
|
||||
"活跃数据源": "Active Datasources",
|
||||
"登录并采集数据": "Sign in and collect data",
|
||||
"先浏览 Earth": "Browse Earth first",
|
||||
"先浏览地球": "Explore Earth first",
|
||||
"控制图层控制面板显示": "Control layer panel visibility",
|
||||
"控制右侧图层控制面板显示": "Control the right-side layer panel",
|
||||
"图例": "Legend",
|
||||
"其他电缆": "Other Cables",
|
||||
"赤道轨道": "Equatorial",
|
||||
"低倾角轨道": "Low Incl.",
|
||||
"中倾角轨道": "Mid Incl.",
|
||||
@@ -932,7 +1086,6 @@ const EXACT_TRANSLATIONS = {
|
||||
"南极洲": "Antarctica",
|
||||
"全球": "Global",
|
||||
"美洲": "Americas",
|
||||
"欧洲": "Europe",
|
||||
"中东与非洲": "Middle East & Africa",
|
||||
"亚太": "Asia Pacific",
|
||||
"全球焦点": "Global Focus",
|
||||
@@ -1130,7 +1283,6 @@ const EXACT_TRANSLATIONS = {
|
||||
"最近事件类型": "Latest Event Type",
|
||||
"最近活跃时间": "Latest Activity",
|
||||
"日常覆盖范围": "Baseline Scope",
|
||||
"类型": "Type",
|
||||
"排名": "Rank",
|
||||
"实测算力": "Measured Compute",
|
||||
"估算算力": "Estimated Compute",
|
||||
@@ -1156,7 +1308,6 @@ const EXACT_TRANSLATIONS = {
|
||||
"经度": "Longitude",
|
||||
"说明": "Description",
|
||||
"字段来源": "Field Source",
|
||||
"新闻信号": "News Signal",
|
||||
"船舶资料": "Vessel Profile",
|
||||
"资料": "Profile",
|
||||
"媒体": "Media",
|
||||
@@ -1172,9 +1323,8 @@ const EXACT_TRANSLATIONS = {
|
||||
"采集坐标候选": "Collect coordinate candidates",
|
||||
"一键定位并采用最高置信候选": "Locate all and apply highest-confidence candidates",
|
||||
"一键定位": "Locate All",
|
||||
"采集": "Collected",
|
||||
"正在检查 WebSearch 状态,稍候即可定位。": "Checking WebSearch status; location will be available shortly.",
|
||||
"WebSearch 未开启,无法进行事实核查定位。": "WebSearch is disabled, so fact-checked location is unavailable.",
|
||||
"正在检查 Web Search 状态,稍候即可定位。": "Checking Web Search status; location will be available shortly.",
|
||||
"Web Search 未开启,无法进行事实核查定位。": "Web Search is disabled, so fact-checked location is unavailable.",
|
||||
"精确": "Precise",
|
||||
"站点": "Site",
|
||||
"候选": "Candidate",
|
||||
@@ -1208,7 +1358,7 @@ const EXACT_TRANSLATIONS = {
|
||||
"源数据自带坐标": "Source Coordinates",
|
||||
"ROR 组织注册 API": "ROR Registry API",
|
||||
"Nominatim 在线搜索": "Nominatim Online Search",
|
||||
"LLM factcheck 兜底": "LLM Factcheck Fallback",
|
||||
"智能检索兜底": "Smart Lookup Fallback",
|
||||
"待人工核验": "Needs Review",
|
||||
"估算位置": "Estimated Location",
|
||||
"已确认": "Confirmed",
|
||||
@@ -1319,25 +1469,39 @@ const PATTERN_TRANSLATIONS = [
|
||||
[/^(.+)暂时不可用$/, (match, locale) => `${translateText(match[1], locale)} temporarily unavailable`],
|
||||
[/^正在加载(.+)数据\.\.\.$/, (match, locale) => `Loading ${translateText(match[1], locale).toLowerCase()} data...`],
|
||||
[/^正在加载(.+)\.\.\.$/, (match, locale) => `Loading ${translateText(match[1], locale).toLowerCase()}...`],
|
||||
[/^(.+)加载失败: (.+)$/, (match, locale) => `${translateText(match[1], locale)} load failed: ${match[2]}`],
|
||||
[/^(.+)加载失败: (.+)$/, (match, locale) => `${translateText(match[1], locale)} load failed: ${translateText(match[2], locale)}`],
|
||||
[/^(.+)已切换为:(.+)$/, (match, locale) => `${translateText(match[1], locale)} switched to: ${translateText(match[2], locale)}`],
|
||||
[/^(.+)已设置为 (.+)$/, "$1 set to $2"],
|
||||
[/^(.+)已设置为 (.+)$/, (match, locale) => `${translateText(match[1], locale)} set to ${translateText(match[2], locale)}`],
|
||||
[/^(.+)已设为 (.+)$/, (match, locale) => `${translateText(match[1], locale)} set to ${translateText(match[2], locale)}`],
|
||||
[/^重置(.+)$/, "Reset $1"],
|
||||
[/^重置缩放到(.+)$/, (match, locale) => `Reset zoom to ${translateText(match[1], locale)}`],
|
||||
[/^重置(.+)$/, (match, locale) => `Reset ${translateText(match[1], locale)}`],
|
||||
[/^备用:(.+)$/, (match, locale) => `Alt: ${translateText(match[1], locale)}`],
|
||||
[/^(\d+) 条海缆$/, "$1 subsea cables"],
|
||||
[/^(\d+) 条$/, "$1"],
|
||||
[/^(\d+) 起$/, "$1"],
|
||||
[/^投产于 (.+)$/, "RFS $1"],
|
||||
[/^Web Search 状态检查失败:(.*)$/, "Web Search check failed: $1"],
|
||||
[/^已检测到 (\d+) 个物理摄像头(单摄 2D)$/, "$1 physical cameras detected (single-cam 2D)"],
|
||||
[/^高清国界更新源未配置:(.*)$/, "High-precision boundary update source not configured: $1"],
|
||||
[/^常规来源无可用结果;智能检索未生成可用候选:(.*)$/, "No usable results from standard sources; smart lookup found no candidates: $1"],
|
||||
[/^常规来源无可用结果;智能检索未找到可用候选。(.+)$/, "No usable results from standard sources; smart lookup found no candidates. $1"],
|
||||
[/^船舶实时通道后台已连接 · 最近 (.+)$/, (match, locale) => `Vessel live feed connected in background · Last ${translateText(match[1], locale)}`],
|
||||
[/^找到 (\d+) 个结果$/, "Found $1 results"],
|
||||
[/^(.+) 项参数$/, "$1 fields"],
|
||||
[/^已定位并采用 (\d+) 个最高置信候选(.*)$/, "Located and applied $1 highest-confidence candidates$2"],
|
||||
[/^已切换到(.+)$/, (match, locale) => `Switched to ${translateText(match[1], locale)}`],
|
||||
[/^最近同步 (.+)$/, "Last synced $1"],
|
||||
[/^缩放 (\d+)%$/, "Zoom $1%"],
|
||||
[/^船舶实时通道已连接 · (\d+) 次更新$/, "Vessel live updates connected · $1 updates"],
|
||||
[/^船舶实时通道已连接 · (\d+) 次更新 · (.+)$/, "Vessel live updates connected · $1 updates · $2"],
|
||||
[/^AISStream 后台已连接$/, "AISStream backend connected"],
|
||||
[/^AISStream 后台已连接 · 最近 (.+)$/, "AISStream backend connected · last seen $1"],
|
||||
[/^船舶实时通道已连接 · (\d+) 次更新 · (.+)$/, (match, locale) => `Vessel live updates connected · ${match[1]} updates · ${translateText(match[2], locale)}`],
|
||||
[/^船舶实时通道已连接 · 等待首批更新$/, "Vessel live updates connected · waiting for first updates"],
|
||||
[/^(\d+) 秒前$/, "$1s ago"],
|
||||
[/^(\d+) 分钟前$/, "$1m ago"],
|
||||
[/^新闻源请求失败: (\d+)$/, "News request failed: $1"],
|
||||
[/^来源 (.+)$/, "Source $1"],
|
||||
[/^更新 (.+)$/, "Updated $1"],
|
||||
[/^置信 (.+)$/, "Confidence $1"],
|
||||
[/^已复制(.+):(.+)$/, "Copied $1: $2"],
|
||||
[/^已复制(.+):(.+)$/, (match, locale) => `Copied ${translateText(match[1], locale)}: ${match[2]}`],
|
||||
[/^动捕: (.+)当前视野没有可选目标$/, (match, locale) => `Motion: ${translateText(match[1], locale)} has no selectable targets in view`],
|
||||
[/^动捕: 已切换到(.+)图层$/, (match, locale) => `Motion: switched to ${translateText(match[1], locale)} layer`],
|
||||
[/^动捕: 已切换到(.+)$/, (match, locale) => `Motion: switched to ${translateText(match[1], locale)}`],
|
||||
@@ -1360,7 +1524,9 @@ const PATTERN_TRANSLATIONS = [
|
||||
[/^常规来源没有可用坐标候选$/, "No coordinate candidates from regular sources"],
|
||||
[/^常规来源无结果;LLM 兜底未生成可用候选:(.+)$/, "Regular sources returned no result; LLM fallback produced no usable candidate: $1"],
|
||||
[/^常规来源无结果;LLM 兜底已尝试但没有返回可用候选。(.+)$/, "Regular sources returned no result; LLM fallback was attempted but returned no usable candidate. $1"],
|
||||
[/^(\d+)个观测站 \((.+) 等\)$/, "$1 collectors ($2 etc.)"],
|
||||
[/^(\d+)个观测站 \((.+)\)$/, "$1 collectors ($2)"],
|
||||
[/^(\d+)个前缀簇$/, "$1 prefix clusters"],
|
||||
[/^(.+) 等(\d+)地$/, "$1 + $2 regions"],
|
||||
[/^(.+) 等(\d+)处$/, "$1 + $2 sites"],
|
||||
[/^近24h (\d+)条事件 \/ (\d+)个前缀$/, "24h $1 events / $2 prefixes"],
|
||||
|
||||
@@ -3,6 +3,7 @@ import { COMPUTE_SITE_TYPES, isComputeSiteType } from "./compute-site-types.js";
|
||||
import { cardImageIdentity, mountCardImage, createCardImagePresenter } from "./card-images.js";
|
||||
import { sharedHudFocusStack } from "./hud-focus-stack.js";
|
||||
import { createTypewriter, waitForTypewriter } from "./typewriter.js";
|
||||
import { addTargetToCompare, normalizeEarthTarget, openWorkflowActionPicker } from "./workflow-bindings.js";
|
||||
// info-card.js - Unified info card module
|
||||
import { showStatusMessage } from './ui.js';
|
||||
import {
|
||||
@@ -119,7 +120,7 @@ async function ensureComputeCenterLocationCapability() {
|
||||
.catch((error) => {
|
||||
computeCenterLocationCapability = {
|
||||
enabled: false,
|
||||
reason: `WebSearch 状态检查失败:${error?.message || error}`,
|
||||
reason: infoText(`Web Search 状态检查失败:${error?.message || error}`),
|
||||
};
|
||||
updateComputeCenterLocationCapabilityDom();
|
||||
return computeCenterLocationCapability;
|
||||
@@ -242,6 +243,12 @@ function infoText(value, fallback = '') {
|
||||
return translated;
|
||||
}
|
||||
|
||||
function translateInfoCardValue(value) {
|
||||
if (value === undefined || value === null || value === '') return '';
|
||||
const text = String(value);
|
||||
return translateText(text);
|
||||
}
|
||||
|
||||
function escapeInfoCardHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, (char) => ({
|
||||
'&': '&',
|
||||
@@ -356,117 +363,118 @@ function getMobileDetailIdentity(type, config, data) {
|
||||
|
||||
if (type === 'satellite') {
|
||||
title = data?.name || `NORAD ${data?.norad_id}`;
|
||||
categoryLabel = '在轨卫星';
|
||||
subtitle = `NORAD ${data?.norad_id || '—'} · ${data?.constellation || '未知星座'}`;
|
||||
if (data?.constellation) statusBadge = data.constellation;
|
||||
categoryLabel = infoText('在轨卫星');
|
||||
subtitle = `NORAD ${data?.norad_id || '—'} · ${translateInfoCardValue(data?.constellation) || infoText('未知星座')}`;
|
||||
if (data?.constellation) statusBadge = translateInfoCardValue(data.constellation);
|
||||
if (data?.perigee != null && data.perigee !== '-') {
|
||||
metrics.push({ label: '近地点', value: `${data.perigee} km` });
|
||||
metrics.push({ label: infoText('近地点'), value: `${data.perigee} km` });
|
||||
}
|
||||
if (data?.apogee != null && data.apogee !== '-') {
|
||||
metrics.push({ label: '远地点', value: `${data.apogee} km` });
|
||||
metrics.push({ label: infoText('远地点'), value: `${data.apogee} km` });
|
||||
}
|
||||
if (data?.inclination != null && data.inclination !== '-') {
|
||||
metrics.push({ label: '轨道倾角', value: `${data.inclination}°` });
|
||||
metrics.push({ label: infoText('轨道倾角'), value: `${data.inclination}°` });
|
||||
}
|
||||
if (data?.period != null && data.period !== '-') {
|
||||
metrics.push({ label: '运行周期', value: `${data.period} 分钟` });
|
||||
metrics.push({ label: infoText('运行周期'), value: `${data.period} ${infoText('分钟')}` });
|
||||
}
|
||||
} else if (type === 'cable') {
|
||||
title = data?.name || '海底光缆';
|
||||
categoryLabel = '海底光缆';
|
||||
statusBadge = data?.status || '运营中';
|
||||
title = data?.name || infoText('海底光缆');
|
||||
categoryLabel = infoText('海底光缆');
|
||||
const cableStatus = translateInfoCardValue(data?.status) || infoText('运营中');
|
||||
statusBadge = cableStatus;
|
||||
statusBadgeType = (data?.status?.includes('退役') || data?.status?.includes('中断')) ? 'danger' : 'normal';
|
||||
subtitle = `${data?.status || '运营中'}${data?.rfs ? ' · 投产于 ' + data.rfs : ''}`;
|
||||
subtitle = `${cableStatus}${data?.rfs ? ` · ${infoText(`投产于 ${data.rfs}`)}` : ''}`;
|
||||
if (data?.length) {
|
||||
metrics.push({ label: '总长度', value: `${data.length} km` });
|
||||
metrics.push({ label: infoText('总长度'), value: `${data.length} km` });
|
||||
}
|
||||
if (data?.status) {
|
||||
metrics.push({ label: '运营状态', value: data.status });
|
||||
metrics.push({ label: infoText('运营状态'), value: cableStatus });
|
||||
}
|
||||
if (data?.rfs) {
|
||||
metrics.push({ label: '投产年份', value: String(data.rfs) });
|
||||
metrics.push({ label: infoText('投产年份'), value: String(data.rfs) });
|
||||
}
|
||||
} else if (type === 'landing_point') {
|
||||
title = data?.name || '海缆登陆点';
|
||||
categoryLabel = '海缆登陆点';
|
||||
subtitle = data?.country || '';
|
||||
if (data?.status) statusBadge = data.status;
|
||||
title = data?.name || infoText('海缆登陆点');
|
||||
categoryLabel = infoText('海缆登陆点');
|
||||
subtitle = translateInfoCardValue(data?.country) || '';
|
||||
if (data?.status) statusBadge = translateInfoCardValue(data.status);
|
||||
if (data?.cable_count != null) {
|
||||
metrics.push({ label: '关联海缆', value: `${data.cable_count} 条` });
|
||||
metrics.push({ label: infoText('关联海缆'), value: infoText(`${data.cable_count} 条`) });
|
||||
}
|
||||
if (data?.country) {
|
||||
metrics.push({ label: '所属国家', value: data.country });
|
||||
metrics.push({ label: infoText('所属国家'), value: translateInfoCardValue(data.country) });
|
||||
}
|
||||
} else if (isComputeSiteType(type) || type === 'supercomputer' || type === 'gpu_cluster') {
|
||||
title = data?.name || '算力中心';
|
||||
categoryLabel = data?.site_type_label || infoText(config?.title || '').replace('详情', '') || '算力中心';
|
||||
subtitle = [data?.city, data?.country].filter(Boolean).join(', ') || data?.country || '';
|
||||
title = data?.name || infoText('算力中心');
|
||||
categoryLabel = translateInfoCardValue(data?.site_type_label) || infoText(config?.title || '').replace(/\s*(Details|详情)$/i, '').trim() || infoText('算力中心');
|
||||
subtitle = [translateInfoCardValue(data?.city), translateInfoCardValue(data?.country)].filter(Boolean).join(', ') || translateInfoCardValue(data?.country) || '';
|
||||
if (data?.rank && data.rank !== '-') statusBadge = `TOP500 #${data.rank}`;
|
||||
if (data?.capacity && data.capacity !== '-') {
|
||||
metrics.push({ label: '算力规模', value: String(data.capacity) });
|
||||
metrics.push({ label: infoText('算力规模'), value: String(data.capacity) });
|
||||
}
|
||||
if (data?.gpu_count && data.gpu_count !== '-') {
|
||||
metrics.push({ label: 'GPU 数量', value: String(data.gpu_count) });
|
||||
metrics.push({ label: infoText('GPU 数量'), value: String(data.gpu_count) });
|
||||
}
|
||||
if (data?.power && data.power !== '-') {
|
||||
metrics.push({ label: '功率消耗', value: `${data.power} kW` });
|
||||
metrics.push({ label: infoText('功率消耗'), value: `${data.power} kW` });
|
||||
}
|
||||
} else if (type === 'vessel') {
|
||||
title = data?.name || `MMSI ${data?.mmsi}`;
|
||||
categoryLabel = data?.vessel_type || '船舶';
|
||||
subtitle = `MMSI ${data?.mmsi || '—'}${data?.flag ? ' · ' + data.flag : ''}`;
|
||||
categoryLabel = translateInfoCardValue(data?.vessel_type) || infoText('船舶');
|
||||
subtitle = `MMSI ${data?.mmsi || '—'}${data?.flag ? ' · ' + translateInfoCardValue(data.flag) : ''}`;
|
||||
if (data?.status && data.status !== '-') {
|
||||
statusBadge = data.status;
|
||||
statusBadge = translateInfoCardValue(data.status);
|
||||
statusBadgeType = data.status === '航行中' ? 'normal' : 'warning';
|
||||
}
|
||||
if (data?.speed != null && data.speed !== '-') {
|
||||
metrics.push({ label: '航速', value: `${data.speed} 节` });
|
||||
metrics.push({ label: infoText('航速'), value: `${data.speed} ${infoText('节')}` });
|
||||
}
|
||||
if (data?.course != null && data.course !== '-') {
|
||||
metrics.push({ label: '航向', value: `${data.course}°` });
|
||||
metrics.push({ label: infoText('航向'), value: `${data.course}°` });
|
||||
}
|
||||
if (data?.status && data.status !== '-') {
|
||||
metrics.push({ label: '航行状态', value: String(data.status) });
|
||||
metrics.push({ label: infoText('航行状态'), value: translateInfoCardValue(String(data.status)) });
|
||||
}
|
||||
} else if (type === 'bgp') {
|
||||
title = data?.anomaly_type || 'BGP 路由事件';
|
||||
categoryLabel = 'BGP 路由事件';
|
||||
subtitle = [data?.impacted_scope, data?.created_at].filter(Boolean).join(' · ');
|
||||
title = translateInfoCardValue(data?.anomaly_type) || infoText('BGP 路由事件');
|
||||
categoryLabel = infoText('BGP 路由事件');
|
||||
subtitle = [translateInfoCardValue(data?.impacted_scope), data?.created_at].filter(Boolean).join(' · ');
|
||||
if (data?.severity) {
|
||||
statusBadge = data.severity;
|
||||
statusBadge = translateInfoCardValue(data.severity);
|
||||
statusBadgeType = (data.severity.includes('高') || data.severity.includes('危')) ? 'danger' : 'warning';
|
||||
}
|
||||
if (data?.origin_asn) {
|
||||
metrics.push({ label: '涉及 ASN', value: `AS${data.origin_asn}` });
|
||||
metrics.push({ label: infoText('涉及 ASN'), value: `AS${data.origin_asn}` });
|
||||
}
|
||||
if (data?.severity) {
|
||||
metrics.push({ label: '严重度', value: data.severity });
|
||||
metrics.push({ label: infoText('严重度'), value: translateInfoCardValue(data.severity) });
|
||||
}
|
||||
if (data?.prefix) {
|
||||
metrics.push({ label: '路由前缀', value: data.prefix });
|
||||
metrics.push({ label: infoText('路由前缀'), value: data.prefix });
|
||||
}
|
||||
} else if (type === 'bgp_collector') {
|
||||
title = data?.collector || 'BGP 观测站';
|
||||
categoryLabel = 'BGP 观测站';
|
||||
subtitle = data?.location || '';
|
||||
if (data?.status) statusBadge = data.status;
|
||||
title = data?.collector || infoText('BGP 观测站');
|
||||
categoryLabel = infoText('BGP 观测站');
|
||||
subtitle = translateInfoCardValue(data?.location) || '';
|
||||
if (data?.status) statusBadge = translateInfoCardValue(data.status);
|
||||
if (data?.anomaly_count != null) {
|
||||
metrics.push({ label: '当前事件', value: `${data.anomaly_count} 起` });
|
||||
metrics.push({ label: infoText('当前事件'), value: infoText(`${data.anomaly_count} 起`) });
|
||||
}
|
||||
if (data?.recent_24h_observation_count != null) {
|
||||
metrics.push({ label: '近24h事件', value: `${data.recent_24h_observation_count} 起` });
|
||||
metrics.push({ label: infoText('近24h事件'), value: infoText(`${data.recent_24h_observation_count} 起`) });
|
||||
}
|
||||
} else if (type === 'news') {
|
||||
title = getNewsCardTitle(data);
|
||||
categoryLabel = '新闻信号';
|
||||
categoryLabel = infoText('新闻信号');
|
||||
subtitle = [data?.source, data?.publishedAtDisplay].filter(Boolean).join(' · ');
|
||||
if (data?.categoryLabel) statusBadge = data.categoryLabel;
|
||||
if (data?.categoryLabel) statusBadge = translateInfoCardValue(data.categoryLabel);
|
||||
url = data?.url || null;
|
||||
} else {
|
||||
title = data?.name || data?.label || infoText(config?.title || '对象详情');
|
||||
categoryLabel = infoText(config?.title || '对象详情').replace('详情', '').trim();
|
||||
subtitle = data?.country || data?.status || '';
|
||||
if (data?.status) statusBadge = data.status;
|
||||
categoryLabel = infoText(config?.title || '对象详情').replace(/\s*(Details|详情)$/i, '').trim();
|
||||
subtitle = translateInfoCardValue(data?.country || data?.status) || '';
|
||||
if (data?.status) statusBadge = translateInfoCardValue(data.status);
|
||||
}
|
||||
|
||||
return { title, categoryLabel, subtitle, statusBadge, statusBadgeType, url, metrics };
|
||||
@@ -577,10 +585,10 @@ function renderNativeMobileDetail(type, config, data) {
|
||||
`;
|
||||
const summaryOutput = propsEl.querySelector('[data-news-summary]');
|
||||
startTypewriterAnimation(summaryOutput, summary, { stepMs: 20, startDelayMs: 60 });
|
||||
if (propCountEl) propCountEl.textContent = '快讯摘要';
|
||||
if (propCountEl) propCountEl.textContent = infoText('快讯摘要');
|
||||
} else if (config?.className === 'compute_unresolved') {
|
||||
renderComputeCenterUnresolvedContent(propsEl, data);
|
||||
if (propCountEl) propCountEl.textContent = '待核验';
|
||||
if (propCountEl) propCountEl.textContent = infoText('待核验');
|
||||
} else {
|
||||
let rowsHtml = '';
|
||||
let fieldCount = 0;
|
||||
@@ -602,8 +610,8 @@ function renderNativeMobileDetail(type, config, data) {
|
||||
if (config?.className === 'vessel' && data?.enrichment) {
|
||||
rowsHtml += renderVesselEnrichmentSection(data.enrichment);
|
||||
}
|
||||
propsEl.innerHTML = rowsHtml || '<div class="earth-mobile-detail-empty">暂无更多详细参数</div>';
|
||||
if (propCountEl) propCountEl.textContent = `${fieldCount} 项参数`;
|
||||
propsEl.innerHTML = rowsHtml || `<div class="earth-mobile-detail-empty">${escapeInfoCardHtml(infoText('暂无更多详细参数'))}</div>`;
|
||||
if (propCountEl) propCountEl.textContent = infoText(`${fieldCount} 项参数`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -616,7 +624,7 @@ function renderNativeMobileDetail(type, config, data) {
|
||||
linkBtn.href = identity.url;
|
||||
linkBtn.hidden = false;
|
||||
const linkText = linkBtn.querySelector('span:last-child');
|
||||
if (linkText) linkText.textContent = type === 'news' ? '阅读原文' : '查看来源';
|
||||
if (linkText) linkText.textContent = infoText(type === 'news' ? '阅读原文' : '查看来源');
|
||||
} else {
|
||||
linkBtn.hidden = true;
|
||||
}
|
||||
@@ -659,14 +667,51 @@ function ensureMobileDetailsListener() {
|
||||
export function buildWorkbenchTarget(config, data) {
|
||||
if (!config || !data) return null;
|
||||
const targetName = data?.name || data?.city || data?.collector || '';
|
||||
const isEn = getEarthLocale() === 'en-US';
|
||||
switch (config.className) {
|
||||
case 'bgp':
|
||||
return data?.collector ? null : {
|
||||
domain: 'bgp',
|
||||
entityId: data.incident_key || data.event_key || data.id || null,
|
||||
label: '参谋取证调查',
|
||||
return data?.collector
|
||||
? {
|
||||
domain: 'bgp',
|
||||
entityType: 'bgp_collector',
|
||||
entityId: data.collector || null,
|
||||
label: '在 AI 参谋中分析',
|
||||
icon: 'forum',
|
||||
question: isEn
|
||||
? `Analyze the status and routing posture of BGP collector "${data.collector}"${data.location ? ` (${data.location})` : ''} using geographic topology and observation coverage.`
|
||||
: `请结合地理拓扑与观测覆盖,分析 BGP 观测站「${data.collector}」${data.location ? `(${data.location})` : ''} 的运行与路由态势。`,
|
||||
}
|
||||
: {
|
||||
domain: 'bgp',
|
||||
entityType: 'bgp',
|
||||
entityId: data.incident_key || data.event_key || data.id || null,
|
||||
label: '参谋取证调查',
|
||||
icon: 'forum',
|
||||
question: isEn
|
||||
? 'Investigate the impact scope, collector vantage points, and subsea cable physical boundaries for this BGP routing incident.'
|
||||
: '请取证分析此次 BGP 路由异动的影响范围、观测采集点与海缆物理边界。',
|
||||
};
|
||||
case 'compute_unresolved':
|
||||
return {
|
||||
domain: 'compute',
|
||||
entityType: 'compute_center_unresolved',
|
||||
entityId: data?.items?.[0]?.source_id || 'unresolved',
|
||||
label: '在 AI 参谋中定位核验',
|
||||
icon: 'forum',
|
||||
question: '请取证分析此次 BGP 路由异动的影响范围、观测采集点与海缆物理边界。',
|
||||
question: isEn
|
||||
? `Verify the physical campus location for unresolved compute center "${data?.items?.[0]?.name || 'Unlocated Cluster'}" (${data?.totalCount || 0} total) using available clues.`
|
||||
: `请结合已有线索核验待定位算力中心「${data?.items?.[0]?.name || '未定位集群'}」(共 ${data?.totalCount || 0} 条)的真实园区位置。`,
|
||||
};
|
||||
case 'earth_interactable':
|
||||
return {
|
||||
domain: 'global',
|
||||
entityType: 'earth_interactable',
|
||||
entityId: data.id || data.label || null,
|
||||
label: '在 AI 参谋中分析',
|
||||
icon: 'forum',
|
||||
question: isEn
|
||||
? `Analyze the surrounding infrastructure and situational characteristics around "${data.label || data.name || 'Data Point'}"${data.kind ? ` (${data.kind})` : ''} across multi-layer Earth telemetry.`
|
||||
: `请结合地球多图层遥测,分析交互点「${data.label || data.name || '数据点'}」${data.kind ? `(${data.kind})` : ''} 周边的基础设施与态势特征。`,
|
||||
};
|
||||
case 'cable':
|
||||
return {
|
||||
@@ -674,9 +719,13 @@ export function buildWorkbenchTarget(config, data) {
|
||||
entityId: data.name || data.cable_id || data.id || null,
|
||||
label: '在工作台分析海缆',
|
||||
icon: 'forum',
|
||||
question: targetName
|
||||
? `请结合内置海缆与登陆站数据,分析海底光缆「${targetName}」的链路态势与观测边界。`
|
||||
: '请结合内置海缆数据,分析当前海缆骨干结构与登陆点风险。',
|
||||
question: isEn
|
||||
? (targetName
|
||||
? `Analyze the link posture and observation boundaries of subsea cable "${targetName}" using cable and landing station data.`
|
||||
: 'Analyze current subsea cable backbone structure and landing point risks.')
|
||||
: (targetName
|
||||
? `请结合海缆与登陆站数据,分析海底光缆「${targetName}」的链路态势与观测边界。`
|
||||
: '请结合海缆数据,分析当前海缆骨干结构与登陆点风险。'),
|
||||
};
|
||||
case 'landing_point':
|
||||
return {
|
||||
@@ -684,9 +733,13 @@ export function buildWorkbenchTarget(config, data) {
|
||||
entityId: data.name || data.city || data.country || null,
|
||||
label: '在工作台分析登陆站',
|
||||
icon: 'forum',
|
||||
question: targetName
|
||||
? `请分析登陆点「${targetName}」接入的海底光缆拓扑集中度与区域边界。`
|
||||
: '请分析当前重点海底光缆登陆枢纽的汇聚态势。',
|
||||
question: isEn
|
||||
? (targetName
|
||||
? `Analyze the subsea cable topology concentration and regional boundaries at landing point "${targetName}".`
|
||||
: 'Analyze concentration trends across major subsea cable landing hubs.')
|
||||
: (targetName
|
||||
? `请分析登陆点「${targetName}」接入的海底光缆拓扑集中度与区域边界。`
|
||||
: '请分析当前重点海底光缆登陆枢纽的汇聚态势。'),
|
||||
};
|
||||
case 'satellite':
|
||||
return {
|
||||
@@ -694,9 +747,13 @@ export function buildWorkbenchTarget(config, data) {
|
||||
entityId: data.norad_id || data.norad_cat_id || data.name || null,
|
||||
label: '在工作台分析卫星',
|
||||
icon: 'forum',
|
||||
question: targetName
|
||||
? `请结合内置 TLE 轨道编目,分析卫星「${targetName}」所属星座与轨道态势。`
|
||||
: '请分析当前追踪卫星星座与 LEO/MEO/GEO 轨道分布态势。',
|
||||
question: isEn
|
||||
? (targetName
|
||||
? `Analyze the constellation and orbital posture of satellite "${targetName}" using TLE orbital catalog data.`
|
||||
: 'Analyze tracked satellite constellations and LEO/MEO/GEO orbital distribution.')
|
||||
: (targetName
|
||||
? `请结合 TLE 轨道编目,分析卫星「${targetName}」所属星座与轨道态势。`
|
||||
: '请分析当前追踪卫星星座与 LEO/MEO/GEO 轨道分布态势。'),
|
||||
};
|
||||
case 'vessel':
|
||||
return {
|
||||
@@ -704,9 +761,13 @@ export function buildWorkbenchTarget(config, data) {
|
||||
entityId: data.mmsi || data.name || null,
|
||||
label: '在工作台分析船舶',
|
||||
icon: 'forum',
|
||||
question: targetName
|
||||
? `请结合近 60 分钟 AIS 快照,分析船舶「${targetName}」的航行状态与海运态势。`
|
||||
: '请结合 AIS 快照,分析当前活跃海运船舶构型与在航态势。',
|
||||
question: isEn
|
||||
? (targetName
|
||||
? `Analyze the navigation status and maritime posture of vessel "${targetName}" from recent 60-minute AIS telemetry.`
|
||||
: 'Analyze active maritime vessel types and underway posture from AIS telemetry.')
|
||||
: (targetName
|
||||
? `请结合近 60 分钟 AIS 遥测数据,分析船舶「${targetName}」的航行状态与海运态势。`
|
||||
: '请结合 AIS 遥测数据,分析当前活跃海运船舶构型与在航态势。'),
|
||||
};
|
||||
case 'supercomputer':
|
||||
case 'gpu_cluster':
|
||||
@@ -718,9 +779,13 @@ export function buildWorkbenchTarget(config, data) {
|
||||
entityId: data.country_code || data.country || data.name || null,
|
||||
label: '在工作台分析算力',
|
||||
icon: 'forum',
|
||||
question: targetName
|
||||
? `请结合算力节点「${targetName}」,分析所在区域的全球算力格局与演进趋势。`
|
||||
: '请对比分析主要区域的全球算力份额与结构演进态势。',
|
||||
question: isEn
|
||||
? (targetName
|
||||
? `Analyze the global compute landscape and evolution trend around compute node "${targetName}".`
|
||||
: 'Compare and analyze global compute shares and structural evolution across major regions.')
|
||||
: (targetName
|
||||
? `请结合算力节点「${targetName}」,分析所在区域的全球算力格局与演进趋势。`
|
||||
: '请对比分析主要区域的全球算力份额与结构演进态势。'),
|
||||
};
|
||||
case 'news': {
|
||||
const newsTitle = data?.title || data?.name || '';
|
||||
@@ -729,9 +794,13 @@ export function buildWorkbenchTarget(config, data) {
|
||||
entityId: data?.id || null,
|
||||
label: '在 AI 参谋中分析',
|
||||
icon: 'forum',
|
||||
question: newsTitle
|
||||
? `请深度分析这条新闻:「${newsTitle}」`
|
||||
: '请结合当前地球多图层内置遥测数据,综合评估近期态势新闻关注区域的整体动态。',
|
||||
question: isEn
|
||||
? (newsTitle
|
||||
? `Provide an in-depth analysis of this news signal: "${newsTitle}"`
|
||||
: 'Synthesize recent regional situation dynamics alongside current multi-layer Earth telemetry.')
|
||||
: (newsTitle
|
||||
? `请深度分析这条新闻:「${newsTitle}」`
|
||||
: '请结合当前地球多图层遥测数据,综合评估近期态势新闻关注区域的整体动态。'),
|
||||
newsContext: {
|
||||
id: data?.id || null,
|
||||
title: newsTitle,
|
||||
@@ -1028,15 +1097,15 @@ function ensureCandidateActionBindings(rootOrChild, context) {
|
||||
}
|
||||
|
||||
function formatLocationCollectFailure(result) {
|
||||
const regularReason = result?.failure_reason || '常规来源没有可用坐标候选';
|
||||
const regularReason = result?.failure_reason || '常规来源无可用结果';
|
||||
const llmReason = result?.llm_failure_reason;
|
||||
if (llmReason) {
|
||||
return infoText(`常规来源无结果;LLM 兜底未生成可用候选:${llmReason}`);
|
||||
return infoText(`常规来源无可用结果;智能检索未生成可用候选:${llmReason}`);
|
||||
}
|
||||
const attempted = Array.isArray(result?.attempted_queries) ? result.attempted_queries : [];
|
||||
const attemptedLlm = attempted.some((query) => String(query || '').startsWith('llm_factcheck:'));
|
||||
if (attemptedLlm) {
|
||||
return infoText(`常规来源无结果;LLM 兜底已尝试但没有返回可用候选。${regularReason}`);
|
||||
return infoText(`常规来源无可用结果;智能检索未找到可用候选。${regularReason}`);
|
||||
}
|
||||
return infoText(regularReason);
|
||||
}
|
||||
@@ -1531,7 +1600,7 @@ function renderVesselEnrichmentSection(enrichment) {
|
||||
if (Array.isArray(media.payload.images) && media.payload.images.length > 0) {
|
||||
const tiles = media.payload.images
|
||||
.slice(0, MAX_VESSEL_MEDIA_TILES)
|
||||
.map((url) => `<img class="info-card-enrichment-thumb" src="${String(url)}" alt="vessel media" />`)
|
||||
.map((url) => `<img class="info-card-enrichment-thumb" src="${String(url)}" alt="${escapeInfoCardHtml(infoText('船舶图片'))}" />`)
|
||||
.join('');
|
||||
inner += `<div class="info-card-enrichment-media">${tiles}</div>`;
|
||||
}
|
||||
@@ -1546,6 +1615,34 @@ function renderVesselEnrichmentSection(enrichment) {
|
||||
`;
|
||||
}
|
||||
|
||||
const ENRICHMENT_FIELD_LABELS = {
|
||||
vessel_type: '船舶类型',
|
||||
gross_tonnage: '总吨位',
|
||||
country_code: '国家代码',
|
||||
callsign: '船舶呼号',
|
||||
call_sign: '船舶呼号',
|
||||
deadweight: '载重吨位',
|
||||
deadweight_tonnage: '载重吨位',
|
||||
draught: '吃水深度',
|
||||
draft: '吃水深度',
|
||||
destination: '目的港',
|
||||
eta: '预计到达时间',
|
||||
built: '建造年份',
|
||||
year_built: '建造年份',
|
||||
flag: '船籍',
|
||||
status: '船舶状态',
|
||||
length: '船长',
|
||||
imo: 'IMO',
|
||||
mmsi: 'MMSI',
|
||||
};
|
||||
|
||||
function localizeEnrichmentFieldKey(key) {
|
||||
const normalized = String(key || '').trim();
|
||||
const zhLabel = ENRICHMENT_FIELD_LABELS[normalized.toLowerCase()];
|
||||
if (zhLabel) return infoText(zhLabel);
|
||||
return infoText(normalized.replace(/_/g, ' '));
|
||||
}
|
||||
|
||||
function renderEnrichmentPayloadRows(payload) {
|
||||
let rows = '';
|
||||
for (const [key, value] of Object.entries(payload)) {
|
||||
@@ -1553,7 +1650,7 @@ function renderEnrichmentPayloadRows(payload) {
|
||||
if (typeof value === 'object') continue;
|
||||
rows += `
|
||||
<div class="info-card-property">
|
||||
<span class="info-card-label">${escapeInfoCardHtml(infoText(key))}</span>
|
||||
<span class="info-card-label">${escapeInfoCardHtml(localizeEnrichmentFieldKey(key))}</span>
|
||||
<span class="info-card-value">${escapeInfoCardHtml(infoText(String(value)))}</span>
|
||||
</div>
|
||||
`;
|
||||
@@ -1576,9 +1673,9 @@ function getMobilePopupTitle(type, data) {
|
||||
case 'cable': return data.name || infoText('海缆');
|
||||
case 'landing_point': return data.name || infoText('登陆点');
|
||||
case 'satellite': return data.name || infoText('卫星');
|
||||
case 'bgp': return data.anomaly_type || infoText('BGP事件');
|
||||
case 'bgp': return translateInfoCardValue(data.anomaly_type) || infoText('BGP事件');
|
||||
case 'news': return getNewsCardTitle(data);
|
||||
case 'bgp_collector': return data.collector || infoText('BGP观测站');
|
||||
case 'bgp_collector': return data.collector || infoText('BGP 观测站');
|
||||
case 'compute_center_unresolved': return infoText('待定位算力中心');
|
||||
case 'supercomputer': return data.name || infoText('超算');
|
||||
case 'gpu_cluster': return data.name || infoText('GPU集群');
|
||||
@@ -1598,7 +1695,7 @@ function getMobilePopupSubtitle(type, data) {
|
||||
case 'satellite': return data.norad_id ? `NORAD ${data.norad_id}` : infoText('卫星');
|
||||
case 'bgp': return infoText(data.severity || 'BGP路由异常');
|
||||
case 'news': return getNewsCardSummaryPreview(data, 30) || infoText('态势新闻');
|
||||
case 'bgp_collector': return data.location || infoText('BGP观测站');
|
||||
case 'bgp_collector': return translateInfoCardValue(data.location) || infoText('BGP 观测站');
|
||||
case 'compute_center_unresolved': return infoText(`${data?.totalCount || 0} 个待定位`);
|
||||
case 'supercomputer': return localizeCountryName(data.country) || infoText('超级计算机');
|
||||
case 'gpu_cluster': return localizeCountryName(data.country) || infoText('GPU集群');
|
||||
@@ -2181,17 +2278,32 @@ function mountCard() {
|
||||
workbenchBtn.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
if (!activeWorkbenchAction?.target) return;
|
||||
const { target, data: targetData } = activeWorkbenchAction;
|
||||
window.dispatchEvent(new CustomEvent('earth:open-workbench', {
|
||||
detail: {
|
||||
domain: target.domain || 'global',
|
||||
entityId: target.entityId || null,
|
||||
initialQuestion: target.question || '',
|
||||
autoAsk: true,
|
||||
newsContext: target.newsContext || null,
|
||||
data: targetData,
|
||||
const { type: actionType, target, data: targetData } = activeWorkbenchAction;
|
||||
const effectiveType = target.entityType || actionType || 'global';
|
||||
const normalized = normalizeEarthTarget(effectiveType, targetData);
|
||||
if (event.shiftKey) {
|
||||
addTargetToCompare(normalized);
|
||||
showStatusMessage(earthMessage("status.addedToCompare"), 'success');
|
||||
return;
|
||||
}
|
||||
const fallbackDetail = {
|
||||
domain: target.domain || 'global',
|
||||
entityId: target.entityId || null,
|
||||
initialQuestion: target.question || '',
|
||||
autoAsk: true,
|
||||
newsContext: target.newsContext || null,
|
||||
data: targetData,
|
||||
targets: [normalized],
|
||||
};
|
||||
openWorkflowActionPicker({
|
||||
anchorEl: workbenchBtn,
|
||||
surface: 'info_card',
|
||||
targets: [normalized],
|
||||
fallbackDetail,
|
||||
onSelect: (detail) => {
|
||||
window.dispatchEvent(new CustomEvent('earth:open-workbench', { detail }));
|
||||
},
|
||||
}));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2395,7 +2507,7 @@ export function showInfoCard(type, data, options = {}) {
|
||||
: infoText(config.title);
|
||||
|
||||
const workbenchTarget = buildWorkbenchTarget(config, data);
|
||||
activeWorkbenchAction = workbenchTarget ? { target: workbenchTarget, data } : null;
|
||||
activeWorkbenchAction = workbenchTarget ? { type, target: workbenchTarget, data } : null;
|
||||
if (workbenchBtn) {
|
||||
if (workbenchTarget) {
|
||||
const actionLabel = infoText(workbenchTarget.label);
|
||||
|
||||
@@ -93,7 +93,7 @@ function syncCurrentLabel(mode) {
|
||||
[document.getElementById("legend-current-label"), document.getElementById("mobile-situation-legend-mode")]
|
||||
.forEach((labelEl) => {
|
||||
if (labelEl) {
|
||||
const translatedLabel = getEarthLocale() === "en-US" ? nextLabel : translateText(nextLabel);
|
||||
const translatedLabel = translateText(nextLabel);
|
||||
labelEl.textContent = translatedLabel;
|
||||
labelEl.dataset.i18nOriginalTitle = translatedLabel;
|
||||
labelEl.title = translatedLabel;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { bgpEventIdentity } from "./bgp-identity.js";
|
||||
import { normalizeComputeSiteType } from "./compute-site-types.js";
|
||||
import { refreshEarthUpdateBatch } from "./earth-update-batch.js";
|
||||
import { loadWorkflowBindings } from "./workflow-bindings.js";
|
||||
import { createFrameProfile } from "./frame-profile.js";
|
||||
import { createFrameStageRunner } from "./frame-stages.js";
|
||||
import { initNewsRegionCards } from "./news-region-cards.js";
|
||||
@@ -3925,6 +3926,9 @@ function buildBGPIncidentNarrative(marker, impactedRegions) {
|
||||
const cableCount = getBGPRelatedCableNames(marker).length;
|
||||
const regionCount = impactedRegions.length;
|
||||
|
||||
if (getEarthLocale() === "en-US") {
|
||||
return `${eventLabel}, ${severityLabel}; ${observedBy}, affecting ${regionCount} region(s) with ${cableCount} cable clue(s)${routeLabel && routeLabel !== "-" ? `, path ${routeLabel}` : ""}.`;
|
||||
}
|
||||
return `${eventLabel},${severityLabel};${observedBy},影响${regionCount}个区域,关联${cableCount}条海缆线索${routeLabel && routeLabel !== "-" ? `,特征 ${routeLabel}` : ""}。`;
|
||||
}
|
||||
|
||||
@@ -4163,11 +4167,12 @@ function formatRelativeTime(value) {
|
||||
const date = value instanceof Date ? value : value ? new Date(value) : null;
|
||||
if (!date || Number.isNaN(date.getTime())) return null;
|
||||
const elapsedSeconds = Math.max(0, Math.round((Date.now() - date.getTime()) / 1000));
|
||||
if (elapsedSeconds < 5) return "刚刚";
|
||||
if (elapsedSeconds < 60) return `${elapsedSeconds} 秒前`;
|
||||
if (elapsedSeconds < 5) return translateText("刚刚");
|
||||
if (elapsedSeconds < 60) return translateText(`${elapsedSeconds} 秒前`);
|
||||
const elapsedMinutes = Math.round(elapsedSeconds / 60);
|
||||
if (elapsedMinutes < 60) return `${elapsedMinutes} 分钟前`;
|
||||
return date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
|
||||
if (elapsedMinutes < 60) return translateText(`${elapsedMinutes} 分钟前`);
|
||||
const locale = getEarthLocale() === "en-US" ? "en-US" : "zh-CN";
|
||||
return date.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
function formatVesselLiveSummary() {
|
||||
@@ -4175,18 +4180,18 @@ function formatVesselLiveSummary() {
|
||||
if (stream.connected) {
|
||||
const lastUpdate = formatRelativeTime(stream.lastUpdateAt);
|
||||
if (stream.updates > 0) {
|
||||
return `船舶实时通道已连接 · ${stream.updates} 次更新${lastUpdate ? ` · ${lastUpdate}` : ""}`;
|
||||
return translateText(`船舶实时通道已连接 · ${stream.updates} 次更新${lastUpdate ? ` · ${lastUpdate}` : ""}`);
|
||||
}
|
||||
return "船舶实时通道已连接 · 等待首批更新";
|
||||
return translateText("船舶实时通道已连接 · 等待首批更新");
|
||||
}
|
||||
const state = earthStatsSummary?.aisstreamConnectionState;
|
||||
if (state === "connected") {
|
||||
const lastSeen = formatRelativeTime(earthStatsSummary?.aisstreamLastSeenAt);
|
||||
return `AISStream 后台已连接${lastSeen ? ` · 最近 ${lastSeen}` : ""}`;
|
||||
return translateText(`船舶实时通道后台已连接${lastSeen ? ` · 最近 ${lastSeen}` : ""}`);
|
||||
}
|
||||
if (state === "reconnecting") return "AISStream 正在重连";
|
||||
if (state === "connecting") return "AISStream 正在连接";
|
||||
return "AISStream 未连接";
|
||||
if (state === "reconnecting") return translateText("船舶实时通道正在重连");
|
||||
if (state === "connecting") return translateText("船舶实时通道正在连接");
|
||||
return translateText("船舶实时通道未连接");
|
||||
}
|
||||
|
||||
function updateVesselToggleUi(enabled, vesselCount = getVesselCount()) {
|
||||
@@ -4610,6 +4615,7 @@ export function init() {
|
||||
}),
|
||||
}));
|
||||
newsRegionCards = initNewsRegionCards({ rootParent: regionCardRoot, spatial: regionCallouts.scope("news") });
|
||||
void loadWorkflowBindings();
|
||||
situationalCopilot = initSituationalCopilot({
|
||||
rootParent: container || document.body,
|
||||
onPreemptStage(reason) {
|
||||
@@ -4636,6 +4642,19 @@ export function init() {
|
||||
void stageNarrativePlayer?.play(key, { focusSource: "user" });
|
||||
},
|
||||
onApplySceneSpec(sceneSpec) {
|
||||
if (sceneSpec?.fly_to && camera) {
|
||||
const lat = Number(sceneSpec.fly_to.lat);
|
||||
const lon = Number(sceneSpec.fly_to.lon);
|
||||
if (Number.isFinite(lat) && Number.isFinite(lon)) {
|
||||
void focusEarthView(camera, {
|
||||
lat,
|
||||
lon,
|
||||
zoom: Number(sceneSpec.fly_to.zoom) || Math.max(getZoomLevel(), 1.35),
|
||||
duration: 850,
|
||||
suppressStatus: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (sceneSpec?.domain === "compute" && sceneSpec.enable_national_hubs) {
|
||||
computeTopic?.applyStageStep?.({
|
||||
computeMode: sceneSpec.compute_mode || "global_share",
|
||||
@@ -4720,6 +4739,9 @@ export function init() {
|
||||
entityId: options.entityId !== undefined ? options.entityId : (domain === "compute" ? "CN" : null),
|
||||
initialQuestion: options.initialQuestion || "",
|
||||
newsContext: options.newsContext || null,
|
||||
workflowId: options.workflowId !== undefined ? options.workflowId : null,
|
||||
workflowName: options.workflowName || "",
|
||||
targets: Array.isArray(options.targets) ? options.targets : [],
|
||||
autoAsk: options.autoAsk !== undefined ? Boolean(options.autoAsk) : true,
|
||||
includeDrill: Boolean(options.includeDrill),
|
||||
preserveActiveContext: Boolean(options.preserveActiveContext),
|
||||
@@ -4740,6 +4762,9 @@ export function init() {
|
||||
entityId: detail.entityId ?? null,
|
||||
initialQuestion: detail.initialQuestion || "",
|
||||
newsContext: detail.newsContext || null,
|
||||
workflowId: detail.workflowId ?? null,
|
||||
workflowName: detail.workflowName || "",
|
||||
targets: Array.isArray(detail.targets) ? detail.targets : [],
|
||||
autoAsk: detail.autoAsk !== undefined ? Boolean(detail.autoAsk) : true,
|
||||
includeDrill: Boolean(detail.includeDrill),
|
||||
});
|
||||
@@ -5746,11 +5771,12 @@ async function loadData() {
|
||||
} finally {
|
||||
if (loadToken === currentLoadToken && !destroyed) {
|
||||
completedStartupSteps += 1;
|
||||
const layerLabel = layer?.startupLabel || layer?.label || "";
|
||||
const progressMsg = layerLabel
|
||||
const rawLayerLabel = layer?.startupLabel || layer?.label || "";
|
||||
const translatedLabel = rawLayerLabel ? translateText(rawLayerLabel) : "";
|
||||
const progressMsg = translatedLabel
|
||||
? (getEarthLocale() === "en-US"
|
||||
? `Loaded layer: ${layerLabel}`
|
||||
: `已就绪:${layerLabel}`)
|
||||
? `Loaded layer: ${translatedLabel}`
|
||||
: `已就绪:${translatedLabel}`)
|
||||
: "";
|
||||
emitEarthStartupProgress(
|
||||
0.20 + (completedStartupSteps / totalStartupSteps) * 0.46,
|
||||
@@ -5817,10 +5843,11 @@ async function loadData() {
|
||||
await applyDeferredLayerVisibilitySettings({
|
||||
onLayerProgress: ({ label, completed, total }) => {
|
||||
if (loadToken !== currentLoadToken || destroyed) return;
|
||||
const layerMsg = label
|
||||
const translatedLabel = label ? translateText(label) : "";
|
||||
const layerMsg = translatedLabel
|
||||
? (getEarthLocale() === "en-US"
|
||||
? `Loading preferred layer: ${label}`
|
||||
: `正在加载偏好图层:${label}…`)
|
||||
? `Loading preferred layer: ${translatedLabel}`
|
||||
: `正在加载偏好图层:${translatedLabel}…`)
|
||||
: "";
|
||||
emitEarthStartupProgress(0.70 + (completed / Math.max(1, total)) * 0.18, layerMsg);
|
||||
},
|
||||
|
||||
@@ -103,16 +103,16 @@ export function createMotionAgentProvider(options = {}) {
|
||||
);
|
||||
}
|
||||
sendCommand("set_armed", { armed: true }, "earth-motion-armed-on-connect");
|
||||
onStatus("动捕 Agent 已连接", "info");
|
||||
onStatus("动捕服务已连接", "info");
|
||||
};
|
||||
socket.onmessage = (rawMessage) => onMessage(rawMessage?.data ?? rawMessage);
|
||||
socket.onerror = () => {
|
||||
emitState({ connected: false, error: "socket_error", message: "Motion Agent 连接异常" });
|
||||
emitState({ connected: false, error: "socket_error", message: "动捕服务连接异常" });
|
||||
};
|
||||
socket.onclose = () => {
|
||||
connected = false;
|
||||
socket = null;
|
||||
emitState({ connected: false, message: "Motion Agent 未连接" });
|
||||
emitState({ connected: false, message: "动捕服务未连接" });
|
||||
scheduleReconnect();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -551,7 +551,7 @@ async function importMediaPipeTasksVision(moduleUrls = MEDIAPIPE_TASKS_URLS) {
|
||||
failures.push(`${moduleUrl}: ${error?.message || String(error)}`);
|
||||
}
|
||||
}
|
||||
const error = new Error("无法加载 MediaPipe Tasks Vision 模块,请检查网络或切换 Motion Agent");
|
||||
const error = new Error("无法加载动作识别模块,请检查网络或切换至动捕服务");
|
||||
error.details = failures;
|
||||
throw error;
|
||||
}
|
||||
@@ -738,13 +738,13 @@ export function createBrowserCameraProvider(options = {}) {
|
||||
|
||||
async function startCamera() {
|
||||
if (!canUseBrowserCamera(mediaDevices)) {
|
||||
emitStatus("当前浏览器不支持 getUserMedia 摄像头接口", "error", {
|
||||
emitStatus("当前浏览器不支持摄像头采集", "error", {
|
||||
error: "get_user_media_unavailable",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if (!isSecureCameraContext()) {
|
||||
emitStatus("浏览器摄像头需要 HTTPS 或 localhost 环境", "error", {
|
||||
emitStatus("摄像头功能需要在 HTTPS 或本机环境下使用", "error", {
|
||||
error: "insecure_context",
|
||||
});
|
||||
return false;
|
||||
@@ -809,7 +809,7 @@ export function createBrowserCameraProvider(options = {}) {
|
||||
topology: currentTopology,
|
||||
});
|
||||
if (currentTopology?.dualCameraDetected) {
|
||||
emitStatus("检测到双摄像头:当前使用单摄 2D 模式(双摄 3D 深度规划中)", "info", {
|
||||
emitStatus("检测到双摄像头:当前使用单摄 2D 模式", "info", {
|
||||
topology: currentTopology,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { translateText } from "./i18n.js";
|
||||
import {
|
||||
MOTION_CONTROL_STATE_EVENT,
|
||||
MOTION_DEBUG_CLOSE_EVENT,
|
||||
@@ -47,7 +48,7 @@ let mobilePlayFlashTimer = null;
|
||||
let mobileLastTapAt = 0;
|
||||
|
||||
function getProviderLabel(value) {
|
||||
return value === "motion_agent" ? "Motion Agent" : "本机摄像头";
|
||||
return value === "motion_agent" ? "动捕服务" : "本机摄像头";
|
||||
}
|
||||
|
||||
function createCanvasElement() {
|
||||
@@ -114,7 +115,7 @@ function bindPanelControls() {
|
||||
|
||||
function setText(element, value) {
|
||||
if (element instanceof HTMLElement) {
|
||||
element.textContent = value;
|
||||
element.textContent = translateText(value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,7 +334,7 @@ function clearCanvas(message = "等待动捕数据") {
|
||||
ctx.font = `${Math.max(13, Math.round(canvas.width * 0.038))}px sans-serif`;
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(message, canvas.width / 2, canvas.height / 2);
|
||||
ctx.fillText(translateText(message), canvas.width / 2, canvas.height / 2);
|
||||
}
|
||||
|
||||
function hasDrawableVideoSource() {
|
||||
|
||||
@@ -93,9 +93,9 @@ const SOURCE_TYPE_LABELS = {
|
||||
"zh-CN": {
|
||||
rss: "RSS",
|
||||
atom: "Atom",
|
||||
aggregated: "Aggregated",
|
||||
aggregated: "聚合源",
|
||||
manual: "手动添加",
|
||||
reference: "Reference",
|
||||
reference: "参考链接",
|
||||
},
|
||||
"en-US": {
|
||||
rss: "RSS",
|
||||
@@ -123,28 +123,28 @@ const LOCATION_SOURCE_LABELS = {
|
||||
|
||||
const ENRICHMENT_STATUS_LABELS = {
|
||||
"zh-CN": {
|
||||
pending: "待增强",
|
||||
queued: "增强排队中",
|
||||
attempted: "增强中",
|
||||
success: "已汉化",
|
||||
content_only: "已汉化",
|
||||
location_only: "位置已增强",
|
||||
unavailable: "AI 未配置",
|
||||
provider_error: "增强失败",
|
||||
parse_error: "增强解析失败",
|
||||
no_result: "暂无增强结果",
|
||||
pending: "待处理",
|
||||
queued: "处理中",
|
||||
attempted: "处理中",
|
||||
success: "已翻译",
|
||||
content_only: "已翻译",
|
||||
location_only: "已定位",
|
||||
unavailable: "待配置 AI",
|
||||
provider_error: "翻译失败",
|
||||
parse_error: "解析失败",
|
||||
no_result: "暂无结果",
|
||||
},
|
||||
"en-US": {
|
||||
pending: "Pending",
|
||||
queued: "Queued",
|
||||
attempted: "Enhancing",
|
||||
success: "Localized",
|
||||
content_only: "Localized",
|
||||
location_only: "Location Enhanced",
|
||||
queued: "Processing",
|
||||
attempted: "Processing",
|
||||
success: "Translated",
|
||||
content_only: "Translated",
|
||||
location_only: "Located",
|
||||
unavailable: "AI Unconfigured",
|
||||
provider_error: "Enhancement Failed",
|
||||
provider_error: "Failed",
|
||||
parse_error: "Parse Failed",
|
||||
no_result: "No Enhancement",
|
||||
no_result: "No Result",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -207,22 +207,22 @@ const TITLE_PLACEHOLDERS = {
|
||||
|
||||
const SUMMARY_PLACEHOLDERS = {
|
||||
"zh-CN": {
|
||||
queued: "中文概要正在生成,请稍后刷新。",
|
||||
attempted: "中文概要正在生成,请稍后刷新。",
|
||||
provider_error: "中文概要生成失败,系统会重新提交增强任务。",
|
||||
parse_error: "中文概要解析失败,系统会重新提交增强任务。",
|
||||
unavailable: "AI 服务配置完成后将生成中文概要。",
|
||||
no_result: "中文概要暂未生成,系统会继续重试。",
|
||||
location_only: "已完成位置增强,中文概要将继续重试。",
|
||||
queued: "正在生成中文摘要,请稍候。",
|
||||
attempted: "正在生成中文摘要,请稍候。",
|
||||
provider_error: "中文摘要生成失败,稍后将重试。",
|
||||
parse_error: "中文摘要解析失败,稍后将重试。",
|
||||
unavailable: "配置 AI 后将自动生成中文摘要。",
|
||||
no_result: "暂无中文摘要。",
|
||||
location_only: "已完成定位,中文摘要生成中。",
|
||||
},
|
||||
"en-US": {
|
||||
queued: "English summary is being generated. Refresh shortly.",
|
||||
attempted: "English summary is being generated. Refresh shortly.",
|
||||
provider_error: "English summary generation failed and will be retried.",
|
||||
parse_error: "English summary parsing failed and will be retried.",
|
||||
unavailable: "English summary will be generated after AI is configured.",
|
||||
no_result: "English summary is pending and will be retried.",
|
||||
location_only: "Location is ready; English summary is still pending.",
|
||||
queued: "Generating English summary...",
|
||||
attempted: "Generating English summary...",
|
||||
provider_error: "English summary generation failed; retrying shortly.",
|
||||
parse_error: "English summary parse failed; retrying shortly.",
|
||||
unavailable: "Configure AI to generate English summaries.",
|
||||
no_result: "English summary unavailable.",
|
||||
location_only: "Located; generating English summary...",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -416,7 +416,7 @@ export function getNewsEnrichmentStatusLabel(statusOrItem) {
|
||||
const status = item ? item.enrichment_status : statusOrItem;
|
||||
const language = String(item?.content_language || "").toLowerCase();
|
||||
if (language.startsWith("zh") && status !== "success" && status !== "content_only") {
|
||||
if (status === "queued" || status === "attempted") return getEarthLocale() === "en-US" ? "English Translation Pending" : "英文补译中";
|
||||
if (status === "queued" || status === "attempted") return getEarthLocale() === "en-US" ? "Translating" : "翻译中";
|
||||
if (status === "provider_error" || status === "parse_error" || status === "no_result") return getEarthLocale() === "en-US" ? "Chinese Original" : "中文原文";
|
||||
return getEarthLocale() === "en-US" ? "Chinese Original" : "中文原文";
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { mapNewsItemToCruiseEvent } from "./news-cruise-adapter.js";
|
||||
import { getNewsRegionLabel } from "./news-locale.js";
|
||||
import { getCruiseNewsItems, getNewsPayload, ensureNewsPanelReady } from "./news.js";
|
||||
import { NEWS_CARD_REGIONS, createRegionalNewsRotation } from "./news-region-model.js";
|
||||
import { normalizeEarthTarget, openWorkflowActionPicker } from "./workflow-bindings.js";
|
||||
|
||||
const STORAGE_KEY = "planet.earth.news-region-cards.v1";
|
||||
const text = (zh,en) => getEarthLocale() === "en-US" ? en : zh;
|
||||
@@ -108,8 +109,12 @@ export function initNewsRegionCards({ rootParent, spatial }) {
|
||||
else if(action === "news-analyze") {
|
||||
if (!card.currentStory) return;
|
||||
const story = card.currentStory;
|
||||
window.dispatchEvent(new CustomEvent("earth:open-workbench", {
|
||||
detail: {
|
||||
const normalized = normalizeEarthTarget("news", story);
|
||||
openWorkflowActionPicker({
|
||||
anchorEl: card.analyze || element,
|
||||
surface: "news_card",
|
||||
targets: [normalized],
|
||||
fallbackDetail: {
|
||||
domain: "news",
|
||||
entityId: story.id || null,
|
||||
newsContext: story,
|
||||
@@ -118,7 +123,10 @@ export function initNewsRegionCards({ rootParent, spatial }) {
|
||||
: text("请分析这条全球新闻动态与潜在影响。", "Analyze this news development and its potential impact."),
|
||||
autoAsk: true,
|
||||
},
|
||||
}));
|
||||
onSelect: (detail) => {
|
||||
window.dispatchEvent(new CustomEvent("earth:open-workbench", { detail }));
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
else if(action === "card-collapse") {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { showStatusMessage } from "./ui.js";
|
||||
import { getNewsBreakingState, isBreakingActive, normalizeBreakingLevel } from "./news-breaking.js";
|
||||
import { createNewsRefreshController } from "./news-refresh-controller.js";
|
||||
import { normalizeEarthTarget, openWorkflowActionPicker } from "./workflow-bindings.js";
|
||||
import {
|
||||
applyEarthI18n,
|
||||
earthMessage,
|
||||
@@ -459,7 +460,7 @@ function normalizeNewsSourceType(value) {
|
||||
|
||||
function getNewsSourceDescriptor(item, sourcesByName, sourcesById) {
|
||||
const feedName = String(item?.feed_name || "").trim();
|
||||
const rawSourceName = String(item?.source || feedName || "NEWS").trim();
|
||||
const rawSourceName = String(item?.source || feedName || translateText("新闻")).trim();
|
||||
const sourceId = String(item?.source_id || "").trim();
|
||||
const sourceConfig = sourcesById.get(sourceId) || sourcesByName.get(feedName) || null;
|
||||
const sourceType = normalizeNewsSourceType(item?.source_type || sourceConfig?.source_type)
|
||||
@@ -696,7 +697,7 @@ function renderSourceFilterChips() {
|
||||
|
||||
function renderFilterPopover(kind) {
|
||||
const title = translateText(kind === "source" ? "新闻来源" : "新闻类型");
|
||||
const hint = translateText(kind === "source" ? "按大来源筛选,不影响后台抓取。" : "按新闻内容分类筛选。");
|
||||
const hint = translateText(kind === "source" ? "按新闻来源筛选。" : "按新闻内容分类筛选。");
|
||||
const content = kind === "source" ? renderSourceFilterChips() : renderCategoryFilterChips();
|
||||
|
||||
activeFilterPopover = kind;
|
||||
@@ -777,7 +778,7 @@ function renderTicker(nextPayload) {
|
||||
<span class="earth-news-ticker__item${breakingClass}" data-news-id="${escapeTickerText(item.id || "")}" data-breaking-level="${breakingLevel}">
|
||||
<span class="earth-news-ticker__source">${escapeTickerText(getNewsSourceNameLabel({
|
||||
id: item.source_id,
|
||||
name: item.source || item.feed_name || "NEWS",
|
||||
name: item.source || item.feed_name || translateText("新闻"),
|
||||
}))}</span>
|
||||
<span>${escapeTickerText(getNewsDisplaySummary(item))}</span>
|
||||
</span>
|
||||
@@ -1362,7 +1363,7 @@ async function refreshNews(lat, lon, {
|
||||
if (Array.isArray(nextPayload?.items) && nextPayload.items.length === 0) {
|
||||
const { status } = getElements();
|
||||
if (status) {
|
||||
status.textContent = translateText("当前区域暂无可用新闻,已完成一次聚合尝试");
|
||||
status.textContent = translateText("当前区域暂无可用新闻");
|
||||
}
|
||||
}
|
||||
applyEarthI18n();
|
||||
@@ -1583,27 +1584,37 @@ export function initNewsPanel() {
|
||||
if (matched) {
|
||||
const displayTitle = getNewsDisplayTitle(matched) || getNewsDisplaySummary(matched);
|
||||
const displaySummary = getNewsDisplaySummary(matched);
|
||||
window.dispatchEvent(new CustomEvent("earth:open-workbench", {
|
||||
detail: {
|
||||
const newsPayload = {
|
||||
id: matched.id || null,
|
||||
title: displayTitle,
|
||||
summary: displaySummary && displaySummary !== displayTitle ? displaySummary : (matched.summary || ""),
|
||||
source: matched.source || matched.feed_name || "",
|
||||
region: getNewsRegionDisplayLabel(matched.region, matched.display_region),
|
||||
region_key: matched.region || "",
|
||||
published_at: matched.published_at || "",
|
||||
category: matched.category || "",
|
||||
url: matched.url || "",
|
||||
latitude: matched.latitude ?? null,
|
||||
longitude: matched.longitude ?? null,
|
||||
};
|
||||
const normalized = normalizeEarthTarget("news", newsPayload);
|
||||
openWorkflowActionPicker({
|
||||
anchorEl: analyzeBtn,
|
||||
surface: "news_card",
|
||||
targets: [normalized],
|
||||
fallbackDetail: {
|
||||
domain: "news",
|
||||
entityId: matched.id || null,
|
||||
newsContext: {
|
||||
id: matched.id || null,
|
||||
title: displayTitle,
|
||||
summary: displaySummary && displaySummary !== displayTitle ? displaySummary : (matched.summary || ""),
|
||||
source: matched.source || matched.feed_name || "",
|
||||
region: getNewsRegionDisplayLabel(matched.region, matched.display_region),
|
||||
region_key: matched.region || "",
|
||||
published_at: matched.published_at || "",
|
||||
category: matched.category || "",
|
||||
url: matched.url || "",
|
||||
},
|
||||
newsContext: newsPayload,
|
||||
initialQuestion: displayTitle
|
||||
? (getEarthLocale() === "en-US" ? `Analyze this news story in depth: "${displayTitle}"` : `请深度分析这条新闻:「${displayTitle}」`)
|
||||
: translateText("请分析这条全球新闻动态与潜在影响。"),
|
||||
autoAsk: true,
|
||||
},
|
||||
}));
|
||||
onSelect: (detail) => {
|
||||
window.dispatchEvent(new CustomEvent("earth:open-workbench", { detail }));
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ function statusSteps(status) {
|
||||
{ label: "登录控制台", done: Boolean(status.authenticated), warn: !status.authenticated },
|
||||
{ label: "配置或确认数据源", done: Number(status.datasource_count || 0) > 0 || Number(status.custom_config_count || 0) > 0 },
|
||||
{ label: "触发首次采集", done: Boolean(status.has_collected_data), warn: !status.has_collected_data },
|
||||
{ label: "回到 Earth 查看结果", done: Boolean(status.ready) },
|
||||
{ label: "回到智能星球查看结果", done: Boolean(status.ready) },
|
||||
];
|
||||
if (status.demo_mode) {
|
||||
steps.unshift({ label: "演示模式已开启", done: true });
|
||||
@@ -69,10 +69,10 @@ function renderOobe(status) {
|
||||
const secondaryHref = status.collection_url || "/collection-management";
|
||||
const docsHref = status.docs_url || "/docs/manual";
|
||||
const subtitle = demoMode
|
||||
? "演示模式已开启,本次访问将直接展示初始化引导,不受现有采集数据影响。"
|
||||
? "演示模式已开启,正在展示初始化引导。"
|
||||
: authenticated
|
||||
? "当前还没有检测到可展示的数据,可以直接进入后台触发首次采集。"
|
||||
: "登录控制台并完成首次采集后,Earth 将显示实时数据层。";
|
||||
? "当前暂无可展示数据,可在控制台触发首次采集。"
|
||||
: "请登录控制台并完成首次采集,完成后将自动加载实时数据。";
|
||||
const steps = statusSteps(status)
|
||||
.map((step, index) => {
|
||||
const state = step.done ? "done" : step.warn ? "warn" : "pending";
|
||||
@@ -94,9 +94,9 @@ function renderOobe(status) {
|
||||
<div class="earth-oobe__scrim" data-oobe-close></div>
|
||||
<section class="earth-oobe__panel">
|
||||
<div class="earth-oobe__scan" aria-hidden="true"></div>
|
||||
<button type="button" class="earth-oobe__close" aria-label="先浏览 Earth" data-oobe-close>×</button>
|
||||
<div class="earth-oobe__eyebrow">SYSTEM INITIALIZATION</div>
|
||||
<h2 id="earth-oobe-title">欢迎使用智能星球计划</h2>
|
||||
<button type="button" class="earth-oobe__close" aria-label="先浏览地球" data-oobe-close>×</button>
|
||||
<div class="earth-oobe__eyebrow">系统初始化</div>
|
||||
<h2 id="earth-oobe-title">欢迎使用智能星球</h2>
|
||||
<p class="earth-oobe__subtitle">${subtitle}</p>
|
||||
<ul class="earth-oobe__steps">${steps}</ul>
|
||||
<div class="earth-oobe__stats">
|
||||
@@ -108,7 +108,7 @@ function renderOobe(status) {
|
||||
<a class="earth-oobe__primary" href="${escapeAttribute(primaryHref)}">${primaryText}</a>
|
||||
${authenticated ? `<a class="earth-oobe__secondary" href="${escapeAttribute(secondaryHref)}">进入采集管理</a>` : ""}
|
||||
${authenticated ? `<a class="earth-oobe__secondary" href="${escapeAttribute(docsHref)}">查看文档</a>` : ""}
|
||||
<button type="button" class="earth-oobe__ghost" data-oobe-close>先浏览 Earth</button>
|
||||
<button type="button" class="earth-oobe__ghost" data-oobe-close>先浏览地球</button>
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { translateText } from "./i18n.js";
|
||||
|
||||
let initialized = false;
|
||||
let resolveResultsFn = null;
|
||||
let onSelectResultFn = null;
|
||||
@@ -41,17 +43,17 @@ function getElements() {
|
||||
|
||||
function setMeta(text) {
|
||||
const { meta } = getElements();
|
||||
if (meta) meta.textContent = text;
|
||||
if (meta) meta.textContent = translateText(text);
|
||||
}
|
||||
|
||||
function updateEmptyState(query) {
|
||||
const { empty } = getElements();
|
||||
if (!empty) return;
|
||||
if (!query) {
|
||||
empty.textContent = "支持搜索海缆、登陆点、卫星、算力中心、BGP 事件与观测站。";
|
||||
empty.textContent = translateText("支持搜索海缆、登陆点、卫星、算力中心、BGP 事件与观测站。");
|
||||
return;
|
||||
}
|
||||
empty.textContent = "未找到匹配对象,可尝试名称、地点、NORAD、ASN、前缀等关键词。";
|
||||
empty.textContent = translateText("未找到匹配对象,可尝试名称、地点、NORAD、ASN、前缀等关键词。");
|
||||
}
|
||||
|
||||
function renderResults(query) {
|
||||
@@ -77,9 +79,9 @@ function renderResults(query) {
|
||||
</span>
|
||||
<span class="earth-search-result-copy">
|
||||
<span class="earth-search-result-title">${escapeHtml(result.title)}</span>
|
||||
<span class="earth-search-result-subtitle">${escapeHtml(result.subtitle || "")}</span>
|
||||
<span class="earth-search-result-subtitle">${escapeHtml(translateText(result.subtitle || ""))}</span>
|
||||
</span>
|
||||
<span class="earth-search-result-type">${escapeHtml(result.typeLabel || "")}</span>
|
||||
<span class="earth-search-result-type">${escapeHtml(translateText(result.typeLabel || ""))}</span>
|
||||
`;
|
||||
button.addEventListener("click", async () => {
|
||||
await selectResult(index);
|
||||
@@ -241,7 +243,7 @@ export function initSearchPanel({ resolveResults, onSelectResult } = {}) {
|
||||
input.value = "";
|
||||
} else {
|
||||
const keyword = chip.dataset.searchKeyword || chip.textContent.replace(/^[^\u4e00-\u9fa5a-zA-Z0-9]+/, "").trim();
|
||||
input.value = keyword;
|
||||
input.value = translateText(keyword);
|
||||
}
|
||||
runSearch().catch((err) => console.warn("Chip search failed:", err));
|
||||
});
|
||||
|
||||
@@ -4,6 +4,11 @@ import { getEarthLocale } from "./i18n.js";
|
||||
import { consumeCopilotStream, splitCopilotResponse } from "./copilot-stream.js";
|
||||
import { buildTurnHistoryPayload, createCopilotStore, deriveSessionTitle } from "./copilot-store.js";
|
||||
import { renderViewSpecWorkbench } from "./workbench-blocks.js";
|
||||
import {
|
||||
getCachedWorkflowBindings,
|
||||
matchWorkflowBindings,
|
||||
renderBindingPromptTemplate,
|
||||
} from "./workflow-bindings.js";
|
||||
|
||||
const SESSIONS_API = "/api/v1/situational-awareness/sessions";
|
||||
const RUNS_API = "/api/v1/situational-awareness/runs";
|
||||
@@ -141,6 +146,7 @@ const WORKBENCH_DOMAIN_CONFIG = {
|
||||
labelZh: "多图层综合",
|
||||
labelEn: "Multi-Layer Global",
|
||||
shortTag: "GLOBAL",
|
||||
shortTagZh: "全局",
|
||||
subjectType: "global_posture",
|
||||
promptsZh: [
|
||||
"结合当前开启图层,综合分析全球海缆、卫星、算力与航运的整体态势",
|
||||
@@ -160,6 +166,7 @@ const WORKBENCH_DOMAIN_CONFIG = {
|
||||
labelZh: "海底光缆",
|
||||
labelEn: "Subsea Cables",
|
||||
shortTag: "CABLE",
|
||||
shortTagZh: "海缆",
|
||||
subjectType: "cable_posture",
|
||||
promptsZh: [
|
||||
"梳理当前全球海底光缆骨干分布与重点登陆枢纽的集中风险",
|
||||
@@ -179,6 +186,7 @@ const WORKBENCH_DOMAIN_CONFIG = {
|
||||
labelZh: "在轨星座",
|
||||
labelEn: "Satellites",
|
||||
shortTag: "SAT",
|
||||
shortTagZh: "卫星",
|
||||
subjectType: "satellite_posture",
|
||||
promptsZh: [
|
||||
"分析当前在轨追踪卫星在 LEO / MEO / GEO 的轨道体制与星座格局",
|
||||
@@ -198,6 +206,7 @@ const WORKBENCH_DOMAIN_CONFIG = {
|
||||
labelZh: "全球算力",
|
||||
labelEn: "Compute",
|
||||
shortTag: "COMP",
|
||||
shortTagZh: "算力",
|
||||
subjectType: "compute_posture",
|
||||
promptsZh: [
|
||||
"对比分析中美及主要区域的全球算力格局与“剪刀差”成因",
|
||||
@@ -217,6 +226,7 @@ const WORKBENCH_DOMAIN_CONFIG = {
|
||||
labelZh: "海运 AIS",
|
||||
labelEn: "AIS Vessels",
|
||||
shortTag: "AIS",
|
||||
shortTagZh: "海运",
|
||||
subjectType: "vessel_posture",
|
||||
promptsZh: [
|
||||
"分析近 60 分钟全球 AIS 船舶的在航与锚泊比例及主要船型构成",
|
||||
@@ -236,6 +246,7 @@ const WORKBENCH_DOMAIN_CONFIG = {
|
||||
labelZh: "BGP 路由",
|
||||
labelEn: "BGP Routing",
|
||||
shortTag: "BGP",
|
||||
shortTagZh: "BGP",
|
||||
subjectType: "bgp_incident",
|
||||
promptsZh: [
|
||||
"最近 BGP 控制面路由观测涉及哪些 AS、前缀与采集点?",
|
||||
@@ -255,6 +266,7 @@ const WORKBENCH_DOMAIN_CONFIG = {
|
||||
labelZh: "新闻局势",
|
||||
labelEn: "Global News",
|
||||
shortTag: "NEWS",
|
||||
shortTagZh: "新闻",
|
||||
subjectType: "news_brief",
|
||||
promptsZh: [
|
||||
"综合分析近期全球热点新闻与国际局势的关键动向",
|
||||
@@ -529,6 +541,9 @@ export function initSituationalCopilot({
|
||||
resultId: null,
|
||||
revision: null,
|
||||
evidence: {},
|
||||
workflowId: null,
|
||||
workflowName: "",
|
||||
targets: [],
|
||||
};
|
||||
|
||||
let loading = false;
|
||||
@@ -1034,7 +1049,7 @@ export function initSituationalCopilot({
|
||||
<div class="hud-panel__title-group">
|
||||
<span class="material-symbols-rounded situational-copilot__header-icon" aria-hidden="true">compare</span>
|
||||
<h3 class="hud-panel__title">${escape(text("固定对照槽", "Pinned Comparison"))}</h3>
|
||||
<strong class="situational-copilot__rev-badge">Rev.${escape(activePin.revision || 1)}</strong>
|
||||
<strong class="situational-copilot__rev-badge">${escape(text(`第 ${activePin.revision || 1} 版`, `Rev.${activePin.revision || 1}`))}</strong>
|
||||
</div>
|
||||
<div class="hud-panel__actions">
|
||||
<button type="button" class="hud-panel__action" data-pin-remove="${escape(activePin.pinId)}" aria-label="${escape(text("移除此固定对照", "Unpin comparison"))}" title="${escape(text("移除此固定对照", "Unpin comparison"))}"><span class="material-symbols-rounded" aria-hidden="true">delete</span></button>
|
||||
@@ -1165,7 +1180,7 @@ export function initSituationalCopilot({
|
||||
<span class="material-symbols-rounded" aria-hidden="true">public</span>
|
||||
<span>${escape(text("地球推演", "Globe Tour"))}</span>
|
||||
</button>` : ""}
|
||||
<span class="wb-turn-meta wb-tabular">${modelBadgeHtml}${turn.revision && viewSpec ? `<span class="wb-turn-meta__sep" aria-hidden="true">·</span><span class="wb-turn-meta__rev">Rev.${escape(turn.revision)}</span>` : ""}</span>
|
||||
<span class="wb-turn-meta wb-tabular">${modelBadgeHtml}${turn.revision && viewSpec ? `<span class="wb-turn-meta__sep" aria-hidden="true">·</span><span class="wb-turn-meta__rev">${escape(text(`第 ${turn.revision} 版`, `Rev.${turn.revision}`))}</span>` : ""}</span>
|
||||
</div>`
|
||||
: "";
|
||||
|
||||
@@ -1246,8 +1261,8 @@ export function initSituationalCopilot({
|
||||
const newSessionLabel = text("新建对话", "New conversation");
|
||||
const historyLabel = text("历史会话与记忆", "History & Memory");
|
||||
const closeLabel = text("关闭态势工作台", "Close situational workbench");
|
||||
const exportContextLabel = text("导出本地上下文 JSON (供 AI 参谋使用)", "Export Local Context JSON for AI Advisor");
|
||||
const exportLabel = text("导出当前冻结修订版 Markdown 简报", "Export frozen revision Markdown brief");
|
||||
const exportContextLabel = text("导出本地上下文 JSON", "Export local context JSON");
|
||||
const exportLabel = text("导出当前版本 Markdown 简报", "Export Markdown brief");
|
||||
const watchLabel = text("订阅当前态势异动提醒", "Subscribe to topic watch alerts");
|
||||
const collapseLabel = collapsed
|
||||
? text("展开态势工作台", "Expand situational workbench")
|
||||
@@ -1275,7 +1290,7 @@ export function initSituationalCopilot({
|
||||
const scopeLabel = text(activeDomainMeta.labelZh, activeDomainMeta.labelEn);
|
||||
const latestTurn = latestCompletedTurn();
|
||||
const activeRevision = latestTurn?.revision ?? ctx.revision;
|
||||
const revBadge = activeRevision ? `Rev.${activeRevision}` : "";
|
||||
const revBadge = activeRevision ? text(`第 ${activeRevision} 版`, `Rev.${activeRevision}`) : "";
|
||||
const prompts = suggestedPrompts();
|
||||
panel.classList.toggle("hud-panel--collapsed", collapsed);
|
||||
|
||||
@@ -1306,6 +1321,27 @@ export function initSituationalCopilot({
|
||||
return `<button type="button" class="copilot-tag-chip ${active ? "is-active" : ""}" data-copilot-focus-tag="${escape(tagId)}" aria-pressed="${String(active)}"><span class="material-symbols-rounded" aria-hidden="true">${escape(meta.icon)}</span><span>${escape(text(meta.tagZh, meta.tagEn))}</span></button>`;
|
||||
}).join("");
|
||||
|
||||
const quickWorkflows = matchWorkflowBindings({
|
||||
surface: "copilot_quick",
|
||||
targets: Array.isArray(ctx.targets) && ctx.targets.length ? ctx.targets : [],
|
||||
catalog: getCachedWorkflowBindings(),
|
||||
}).slice(0, 6);
|
||||
const quickWorkflowsHtml = quickWorkflows.length
|
||||
? `<div class="copilot-focus-tags copilot-quick-workflows" role="group" aria-label="${escape(text("已绑定工作流快捷入口", "Bound workflows"))}">
|
||||
${quickWorkflows
|
||||
.map((wf) => {
|
||||
const b = wf.bindings || {};
|
||||
const wfLabel = getEarthLocale() === "en-US"
|
||||
? (b.action_label_en || wf.name_en || wf.name)
|
||||
: (b.action_label || wf.name);
|
||||
const wfIcon = b.icon || "bolt";
|
||||
const isActiveWf = ctx.workflowId === wf.workflow_id;
|
||||
return `<button type="button" class="copilot-tag-chip ${isActiveWf ? "is-active" : ""}" data-copilot-workflow-id="${escape(wf.workflow_id)}" aria-pressed="${String(isActiveWf)}"><span class="material-symbols-rounded" aria-hidden="true">${escape(wfIcon)}</span><span>${escape(wfLabel)}</span></button>`;
|
||||
})
|
||||
.join("")}
|
||||
</div>`
|
||||
: "";
|
||||
|
||||
const scopeDisplay = [text("AI 参谋聚焦", "AI Focus"), scopeLabel, scopeSuffix]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
@@ -1352,7 +1388,7 @@ export function initSituationalCopilot({
|
||||
</div>
|
||||
<div class="copilot-memory-summary__body copilot-md">${renderSafeMarkdown(conversationSummary)}</div>
|
||||
</div>`
|
||||
: `<div class="copilot-drawer__hint">${escape(text("当单次对话较长时,系统会自动把更早轮次压缩为摘要,既省 Token 又保留上下文脉络。", "Long conversations are automatically compacted into summaries while preserving recent turns."))}</div>`;
|
||||
: `<div class="copilot-drawer__hint">${escape(text("对话较长时会自动压缩早期内容为摘要,保留上下文脉络。", "Long conversations are automatically compacted into summaries while preserving context."))}</div>`;
|
||||
|
||||
const pinnedMemoryHtml = pinnedItems.length
|
||||
? `<div class="copilot-memory-pins">
|
||||
@@ -1419,6 +1455,7 @@ export function initSituationalCopilot({
|
||||
</div>
|
||||
</div>
|
||||
<div class="copilot-focus-tags" role="group" aria-label="${escape(text("预设分析聚焦标签", "Preset focus tags"))}">${focusTagsHtml}</div>
|
||||
${quickWorkflowsHtml}
|
||||
</div>`);
|
||||
|
||||
panel.innerHTML = `<header class="hud-panel__header hud-panel__header--inset hud-panel-drag-handle situational-copilot__header">
|
||||
@@ -1444,6 +1481,7 @@ export function initSituationalCopilot({
|
||||
<span class="situational-copilot__scope-detail">${escape(scopeDisplay)}</span>
|
||||
</span>
|
||||
<div class="situational-copilot__context-right">
|
||||
${ctx.workflowId ? `<button type="button" class="copilot-compacted-chip copilot-workflow-badge" data-copilot-clear-workflow="true" title="${escape(text(`工作流:${ctx.workflowName || ctx.workflowId}(点击切换回默认)`, `Workflow: ${ctx.workflowName || ctx.workflowId} (click to clear)`))}"><span class="material-symbols-rounded copilot-compacted-chip__icon" aria-hidden="true">alt_route</span><span>${escape(ctx.workflowName || ctx.workflowId)}</span><span class="material-symbols-rounded copilot-compacted-chip__icon" aria-hidden="true">close</span></button>` : ""}
|
||||
${conversationSummary ? `<button type="button" class="copilot-compacted-chip" data-copilot-action="open-memory" title="${escape(conversationSummary)}"><span class="material-symbols-rounded copilot-compacted-chip__icon" aria-hidden="true">compress</span><span>${escape(text("已压缩", "Compacted"))}</span></button>` : ""}
|
||||
${basisMenu.renderSlotHtml(ctx.timeBasis || "retrospective", escape(text("时间知识边界", "Time knowledge basis")))}
|
||||
${revBadge ? `<strong class="situational-copilot__rev-badge">${escape(revBadge)}</strong>` : ""}
|
||||
@@ -1798,6 +1836,8 @@ export function initSituationalCopilot({
|
||||
const legacyRequestPayload = {
|
||||
run_id: clientRunId,
|
||||
question: trimmed,
|
||||
...(ctx.workflowId ? { workflow_id: ctx.workflowId } : {}),
|
||||
...(Array.isArray(ctx.targets) && ctx.targets.length ? { targets: ctx.targets } : {}),
|
||||
domain: ctx.domain || null,
|
||||
selected_codes: ctx.selectedCodes || null,
|
||||
mode: ctx.mode || null,
|
||||
@@ -1905,10 +1945,22 @@ export function initSituationalCopilot({
|
||||
if (myEpoch !== requestEpoch) return;
|
||||
activeRunId = meta.run_id || clientRunId;
|
||||
turn.runId = meta.run_id || clientRunId;
|
||||
if (meta.workflow_name && !ctx.workflowName) {
|
||||
ctx.workflowName = String(meta.workflow_name);
|
||||
}
|
||||
applyTurnContextUpdate(turn, meta);
|
||||
syncSceneEffectsForTurn(turn, meta);
|
||||
render({ scrollToBottom: isNearBottom() });
|
||||
},
|
||||
onNode: (nodeEv) => {
|
||||
if (myEpoch !== requestEpoch) return;
|
||||
const nodeTitle = String(nodeEv?.title || nodeEv?.node_id || "").trim();
|
||||
if (!nodeTitle) return;
|
||||
const statusLabel = nodeEv?.status === "running"
|
||||
? text(`正在执行节点:${nodeTitle}`, `Running node: ${nodeTitle}`)
|
||||
: text(`已完成节点:${nodeTitle}`, `Completed node: ${nodeTitle}`);
|
||||
setStage(statusLabel, nodeEv?.node_type ? String(nodeEv.node_type) : "");
|
||||
},
|
||||
onReasoningDelta: (delta) => {
|
||||
if (myEpoch !== requestEpoch) return;
|
||||
turn.rawReasoning += delta;
|
||||
@@ -1927,6 +1979,14 @@ export function initSituationalCopilot({
|
||||
turn.zeroToken = done.zero_token !== false;
|
||||
if (done.provider !== undefined) turn.provider = done.provider;
|
||||
if (done.model !== undefined) turn.model = done.model;
|
||||
if (done.evidence && typeof done.evidence === "object") {
|
||||
turn.evidence = { ...(turn.evidence || {}), ...done.evidence };
|
||||
ctx.evidence = { ...(ctx.evidence || {}), ...turn.evidence };
|
||||
}
|
||||
if (done.scene_spec) {
|
||||
turn.sceneSpec = done.scene_spec;
|
||||
syncSceneEffectsForTurn(turn, done);
|
||||
}
|
||||
if (typeof done.conversation_summary === "string") {
|
||||
conversationSummary = done.conversation_summary;
|
||||
}
|
||||
@@ -2071,10 +2131,11 @@ export function initSituationalCopilot({
|
||||
}
|
||||
|
||||
const pinId = `pin-${++pinCounter}`;
|
||||
const domainMeta = WORKBENCH_DOMAIN_CONFIG[turn.domain] || WORKBENCH_DOMAIN_CONFIG.global;
|
||||
const pinTag = turn.domain === "compute"
|
||||
? (ctx.selectedCodes || ["CN", "US"]).slice(0, 2).join("/")
|
||||
: (WORKBENCH_DOMAIN_CONFIG[turn.domain]?.shortTag || "GLOBAL");
|
||||
const shortLabel = `${pinTag} · Rev.${turn.revision || 1}`;
|
||||
: text(domainMeta.shortTagZh, domainMeta.shortTag);
|
||||
const shortLabel = `${pinTag} · ${text(`第 ${turn.revision || 1} 版`, `Rev.${turn.revision || 1}`)}`;
|
||||
const snapshot = {
|
||||
pinId,
|
||||
shortLabel,
|
||||
@@ -2094,8 +2155,8 @@ export function initSituationalCopilot({
|
||||
}
|
||||
activePinnedId = pinId;
|
||||
exportNotice = canUseDualSlot()
|
||||
? text("已固定至右侧双栏对照槽(保持中央地球清晰可视)。", "Pinned to companion comparison slot.")
|
||||
: text("当前视口较窄,已收纳至顶部固定标签栏(零遮挡快速切换)。", "Docked to Pinned Tabs bar for zero-overlap switching.");
|
||||
? text("已固定至右侧对照栏。", "Pinned to comparison slot.")
|
||||
: text("已收纳至顶部固定标签栏。", "Docked to Pinned Tabs bar.");
|
||||
syncPinsToBackend();
|
||||
render();
|
||||
}
|
||||
@@ -2130,7 +2191,7 @@ export function initSituationalCopilot({
|
||||
if (watchData?.session_token) {
|
||||
sessionToken = watchData.session_token;
|
||||
}
|
||||
exportNotice = text(`已开启主动态势关注(${watchKey}),快照增量将自动入队提示。`, `Topic watch active (${watchKey}).`);
|
||||
exportNotice = text("已开启态势异动提醒,有更新时将自动提示。", "Topic alerts enabled; updates will notify automatically.");
|
||||
} catch {
|
||||
exportError = text("创建态势订阅失败,请稍后重试。", "Failed to create topic watch.");
|
||||
} finally {
|
||||
@@ -2188,7 +2249,7 @@ export function initSituationalCopilot({
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1500);
|
||||
}
|
||||
exportNotice = copied
|
||||
? text("已复制本地上下文 JSON(可在 Admin AI 参谋粘贴挂载)", "Copied local context JSON to clipboard")
|
||||
? text("已复制本地上下文 JSON", "Copied local context JSON")
|
||||
: text("已下载本地上下文 JSON 文件", "Downloaded local context JSON file");
|
||||
} catch {
|
||||
exportError = text("导出本地上下文 JSON 失败,请重试。", "Failed to export local context JSON.");
|
||||
@@ -2238,8 +2299,8 @@ export function initSituationalCopilot({
|
||||
});
|
||||
if (res.status === 409) {
|
||||
exportError = text(
|
||||
"底层态势已产生新修订版本(409 版本保护),请重新核验后再导出。",
|
||||
"Underlying posture revision updated (409 guard); refresh before exporting.",
|
||||
"态势数据已更新,请刷新后再导出。",
|
||||
"Posture data has been updated; refresh before exporting.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -2258,9 +2319,10 @@ export function initSituationalCopilot({
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1500);
|
||||
}
|
||||
const exportedRev = data.revision || expectedRev || 1;
|
||||
exportNotice = text(
|
||||
`已导出冻结修订版 Rev.${data.revision || expectedRev || 1} 简报`,
|
||||
`Exported frozen Rev.${data.revision || expectedRev || 1} brief`,
|
||||
`已导出第 ${exportedRev} 版简报`,
|
||||
`Exported Rev.${exportedRev} brief`,
|
||||
);
|
||||
} catch {
|
||||
exportError = text("导出简报失败,请重试。", "Failed to export Markdown brief.");
|
||||
@@ -2481,6 +2543,39 @@ export function initSituationalCopilot({
|
||||
return;
|
||||
}
|
||||
|
||||
const clearWfBtn = event.target.closest("[data-copilot-clear-workflow]");
|
||||
if (clearWfBtn) {
|
||||
ctx = { ...ctx, workflowId: null, workflowName: "", targets: [] };
|
||||
render();
|
||||
return;
|
||||
}
|
||||
|
||||
const quickWfBtn = event.target.closest("[data-copilot-workflow-id]");
|
||||
if (quickWfBtn) {
|
||||
const wfId = quickWfBtn.dataset.copilotWorkflowId || "";
|
||||
const wf = getCachedWorkflowBindings().find((item) => item.workflow_id === wfId);
|
||||
if (wf) {
|
||||
const b = wf.bindings || {};
|
||||
const isEn = getEarthLocale() === "en-US";
|
||||
const wfTitle = isEn
|
||||
? (b.action_label_en || wf.name_en || wf.name)
|
||||
: (b.action_label || wf.name);
|
||||
ctx = {
|
||||
...ctx,
|
||||
workflowId: wf.workflow_id,
|
||||
workflowName: wfTitle,
|
||||
};
|
||||
const q = renderBindingPromptTemplate(
|
||||
b.prompt_template || "",
|
||||
Array.isArray(ctx.targets) ? ctx.targets : [],
|
||||
suggestedPrompts()[0] || wfTitle,
|
||||
);
|
||||
render();
|
||||
if (q) void askQuestion(q);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const focusTagBtn = event.target.closest("[data-copilot-focus-tag]");
|
||||
if (focusTagBtn) {
|
||||
if (Date.now() < suppressFocusTagClickUntil) return;
|
||||
@@ -2488,6 +2583,9 @@ export function initSituationalCopilot({
|
||||
ctx = {
|
||||
...ctx,
|
||||
domain: nextDom,
|
||||
workflowId: null,
|
||||
workflowName: "",
|
||||
targets: [],
|
||||
entityId: nextDom === "compute" ? (ctx.entityId || "CN") : null,
|
||||
};
|
||||
focusTagOverridden = true;
|
||||
@@ -2586,14 +2684,26 @@ export function initSituationalCopilot({
|
||||
const { preserveActiveContext, ...incomingContext } = nextContext || {};
|
||||
const prevDomain = ctx.domain;
|
||||
const prevEntity = ctx.entityId;
|
||||
const prevWorkflowId = ctx.workflowId;
|
||||
const nextDomain = incomingContext.domain ?? prevDomain;
|
||||
if (incomingContext.newsContext === undefined && !preserveActiveContext && nextDomain !== "news") {
|
||||
incomingContext.newsContext = null;
|
||||
}
|
||||
if (incomingContext.workflowId === undefined && !preserveActiveContext) {
|
||||
incomingContext.workflowId = null;
|
||||
incomingContext.workflowName = "";
|
||||
if (incomingContext.targets === undefined) {
|
||||
incomingContext.targets = [];
|
||||
}
|
||||
}
|
||||
const entityChanged = Boolean(incomingContext.entityId && prevEntity !== incomingContext.entityId);
|
||||
const workflowChanged = Boolean(
|
||||
incomingContext.workflowId !== undefined && prevWorkflowId !== incomingContext.workflowId,
|
||||
);
|
||||
const keepSessionContext = Boolean(preserveActiveContext)
|
||||
&& turns.length > 0
|
||||
&& prevDomain === nextDomain
|
||||
&& !workflowChanged
|
||||
&& !(nextDomain === "bgp" && prevEntity !== incomingContext.entityId);
|
||||
ctx = keepSessionContext
|
||||
? {
|
||||
@@ -2608,6 +2718,7 @@ export function initSituationalCopilot({
|
||||
};
|
||||
if (
|
||||
prevDomain !== ctx.domain
|
||||
|| workflowChanged
|
||||
|| (ctx.domain === "bgp" && prevEntity !== ctx.entityId)
|
||||
|| (!keepSessionContext && entityChanged)
|
||||
) {
|
||||
|
||||
@@ -231,7 +231,7 @@ describe("Workbench 6 Registered Section Blocks", () => {
|
||||
expect(html).toContain("暂无同口径公开发布值");
|
||||
expect(html).toContain("wb-corridor__gap-marker");
|
||||
expect(html).toContain("分母数学分解");
|
||||
expect(html).toContain("未知(无独立海底光缆故障遥测");
|
||||
expect(html).toContain("未知(暂无线缆物理故障遥测)");
|
||||
expect(html).toContain("已隔离 1 份事后来源");
|
||||
expect(html).toContain("executive_onepager");
|
||||
});
|
||||
@@ -1143,7 +1143,7 @@ describe("Shared HUD Select Menu for Time Basis", () => {
|
||||
}),
|
||||
});
|
||||
await pendingAsk;
|
||||
expect(panelEl.innerHTML).toContain('<span class="wb-turn-meta__sep" aria-hidden="true">·</span><span class="wb-turn-meta__rev">Rev.4</span>');
|
||||
expect(panelEl.innerHTML).toContain('<span class="wb-turn-meta__sep" aria-hidden="true">·</span><span class="wb-turn-meta__rev">第 4 版</span>');
|
||||
copilot.destroy();
|
||||
|
||||
// 2) Transient network error retries 1/2 -> 2/2 and fails after maxRetries, with clickable retry button
|
||||
|
||||
@@ -334,7 +334,7 @@ export function initStageNarrativePlayer({
|
||||
const domainBadge = domainLabels[contract.domain] || text("全球态势导览", "Situational Tour");
|
||||
const hasLogicalArcs = Array.isArray(step.logical_arcs) && step.logical_arcs.length > 0;
|
||||
const queuePillHtml = queuedCount > 0
|
||||
? `<button type="button" class="stage-narrative-bar__queue-pill" data-stage-action="play-queued" title="${escape(text("播放队列中的最新增量态势", "Play queued posture update"))}">
|
||||
? `<button type="button" class="stage-narrative-bar__queue-pill" data-stage-action="play-queued" title="${escape(text("播放下一条待播态势", "Play queued posture update"))}">
|
||||
<span class="material-symbols-rounded" aria-hidden="true">playlist_play</span>
|
||||
<span>${escape(text(`+${queuedCount} 待播新态势`, `+${queuedCount} Queued`))}</span>
|
||||
</button>`
|
||||
@@ -343,8 +343,8 @@ export function initStageNarrativePlayer({
|
||||
bar.innerHTML = `<header class="hud-panel__header hud-panel__header--inset hud-panel-drag-handle stage-narrative-bar__top">
|
||||
<div class="stage-narrative-bar__badges">
|
||||
<span class="stage-narrative-bar__domain"><span class="material-symbols-rounded stage-narrative-bar__pin-icon" aria-hidden="true">push_pin</span><span>${escape(domainBadge)} · ${stepIndex + 1}/${steps.length}</span></span>
|
||||
${isDrill ? `<span class="stage-narrative-bar__logical-tag">${escape(text("[演练档案]", "[Drill]"))}</span>` : ""}
|
||||
${hasLogicalArcs ? `<span class="stage-narrative-bar__logical-tag">${escape(text("高空弧线 = 逻辑 AS 路由关系(非海底物理光缆)", "High Arcs = Logical AS Routes (Not Physical Cables)"))}</span>` : ""}
|
||||
${isDrill ? `<span class="stage-narrative-bar__logical-tag">${escape(text("历史演练", "Drill"))}</span>` : ""}
|
||||
${hasLogicalArcs ? `<span class="stage-narrative-bar__logical-tag">${escape(text("高空弧线表示逻辑路由关系", "High Arcs = Logical Routes"))}</span>` : ""}
|
||||
${queuePillHtml}
|
||||
${basisMenu.renderSlotHtml(timeBasis, escape(text("时间回放语义", "Time basis mode")))}
|
||||
</div>
|
||||
|
||||
@@ -61,9 +61,9 @@ const HLS_RETRY_CONFIG = {
|
||||
|
||||
const TV_SOURCE_TYPE_LABELS = {
|
||||
hls: "HLS",
|
||||
video: "Video",
|
||||
iframe: "Web",
|
||||
external: "External",
|
||||
video: "视频",
|
||||
iframe: "网页",
|
||||
external: "外链",
|
||||
youtube: "YouTube",
|
||||
};
|
||||
|
||||
@@ -89,13 +89,15 @@ function getTVSourceName(source) {
|
||||
if (!source) return translateText("暂无可用频道");
|
||||
return safeTVText(
|
||||
source.name,
|
||||
titleCaseIdentifier(source.id) || "Live Channel",
|
||||
titleCaseIdentifier(source.id) || translateText("Live 新闻频道"),
|
||||
);
|
||||
}
|
||||
|
||||
function getTVSourceTypeLabel(sourceType) {
|
||||
const normalized = String(sourceType || "").trim().toLowerCase();
|
||||
return TV_SOURCE_TYPE_LABELS[normalized] || safeTVText(sourceType, translateText("频道"));
|
||||
const mapped = TV_SOURCE_TYPE_LABELS[normalized];
|
||||
if (mapped) return translateText(mapped);
|
||||
return safeTVText(sourceType, translateText("频道"));
|
||||
}
|
||||
|
||||
function getTVSourceField(value, fallback = "") {
|
||||
@@ -103,12 +105,12 @@ function getTVSourceField(value, fallback = "") {
|
||||
}
|
||||
|
||||
function getTVCollectorLabel(value) {
|
||||
const collector = getTVSourceField(value, "Collector");
|
||||
return `${translateText("采集")}: ${collector}`;
|
||||
const collector = getTVSourceField(value, translateText("采集源"));
|
||||
return `${translateText("采集源")}: ${collector}`;
|
||||
}
|
||||
|
||||
function getTVNotes(source) {
|
||||
if (!source?.notes) return translateText("支持后台配置默认源与采集器补充源。");
|
||||
if (!source?.notes) return translateText("可在后台配置默认频道与采集源。");
|
||||
return safeTVText(source.notes, translateText("配置于控制台"));
|
||||
}
|
||||
|
||||
@@ -463,7 +465,7 @@ function showEmbeddedFallback(source, reasonMessage = TV_STATUS_MESSAGE.videoErr
|
||||
empty.hidden = true;
|
||||
}
|
||||
|
||||
setPanelMessage("直播放流不可用,已回退到官网直播页");
|
||||
setPanelMessage("直播流不可用,已切换至官方直播页");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -660,7 +662,7 @@ function syncMobileOverviewSummary(source) {
|
||||
? [
|
||||
{ label: getTVSourceTypeLabel(source.source_type), kind: "status" },
|
||||
source.collector_source ? { label: getTVCollectorLabel(source.collector_source), kind: "" } : { label: translateText("内置源"), kind: "" },
|
||||
source.region ? { label: getTVSourceField(source.region, "Global"), kind: "" } : null,
|
||||
source.region ? { label: getTVSourceField(source.region, translateText("全球")), kind: "" } : null,
|
||||
].filter(Boolean).slice(0, 3)
|
||||
: [{ label: translateText("待加载"), kind: "status" }];
|
||||
tags.replaceChildren(
|
||||
|
||||
@@ -114,6 +114,10 @@ function syncStatusMessageLocale(statusEl) {
|
||||
text.textContent = formatted;
|
||||
statusEl.dataset.i18nOriginalTitle = formatted;
|
||||
statusEl.title = formatted;
|
||||
const actionBtn = statusEl.querySelector(".earth-status-action");
|
||||
if (actionBtn instanceof HTMLElement && actionBtn.dataset.i18nActionOriginal) {
|
||||
actionBtn.textContent = translateText(actionBtn.dataset.i18nActionOriginal);
|
||||
}
|
||||
}
|
||||
|
||||
function buildStatusContent(statusEl, message, type, options = null) {
|
||||
@@ -139,7 +143,8 @@ function buildStatusContent(statusEl, message, type, options = null) {
|
||||
const actionBtn = document.createElement("button");
|
||||
actionBtn.type = "button";
|
||||
actionBtn.className = "earth-status-action";
|
||||
actionBtn.textContent = options.actionLabel;
|
||||
actionBtn.dataset.i18nActionOriginal = options.actionLabel;
|
||||
actionBtn.textContent = translateText(options.actionLabel);
|
||||
actionBtn.addEventListener("pointerdown", (event) => {
|
||||
event.stopPropagation();
|
||||
});
|
||||
|
||||
@@ -293,7 +293,7 @@ function renderTrendCorridorBlock(block, { collapsedOverride } = {}) {
|
||||
${years.length > 2 ? `<span>${escapeWorkbenchHtml(years[Math.floor(years.length / 2)] ?? "")}</span>` : ""}
|
||||
<span>${escapeWorkbenchHtml(years[years.length - 1] ?? "")}</span>
|
||||
</div>
|
||||
${hasAnyGap ? `<p class="wb-corridor-note">${escapeWorkbenchHtml(t("注:缺失年份严格中断连线并做虚线留白标记,不执行跨年线性插值。", "Note: Undisclosed years break trajectory lines explicitly; no cross-year interpolation is performed."))}</p>` : ""}
|
||||
${hasAnyGap ? `<p class="wb-corridor-note">${escapeWorkbenchHtml(t("缺失年份保持留白,不作线性插值。", "Missing years are left blank without interpolation."))}</p>` : ""}
|
||||
${innovLine ? `<div class="wb-corridor-badge"><span class="material-symbols-rounded" aria-hidden="true">auto_graph</span><span>${escapeWorkbenchHtml(innovLine)}</span></div>` : ""}`;
|
||||
|
||||
return `<section class="wb-block wb-block--corridor ${isCollapsed ? "is-collapsed" : ""}" data-block-id="${escapeWorkbenchHtml(block.block_id)}" data-block-type="trend_corridor">
|
||||
@@ -449,8 +449,17 @@ function renderImpactTopologyBlock(block) {
|
||||
const timeline = Array.isArray(data.timeline) ? data.timeline : [];
|
||||
|
||||
const cableStatusText = data.physical_cable_state === "candidate_proximity_unconfirmed"
|
||||
? t("候选邻近线索(未经独立海缆断纤/光功率告警证实)", "Candidate proximity clue (unconfirmed by optical telemetry)")
|
||||
: t("未知(无独立海底光缆故障遥测,不排除亦不直接归咎物理断缆)", "Unknown (no independent subsea cable fault telemetry)");
|
||||
? t("候选邻近线索(未经独立光功率告警证实)", "Candidate proximity clue (unconfirmed by optical telemetry)")
|
||||
: t("未知(暂无线缆物理故障遥测)", "Unknown (no physical cable fault telemetry)");
|
||||
|
||||
const severityText = t(
|
||||
data.severity || "信息",
|
||||
data.severity || "Info",
|
||||
);
|
||||
const statusText = t(
|
||||
data.status === "observed" || !data.status ? "已观测" : data.status,
|
||||
data.status || "Observed",
|
||||
);
|
||||
|
||||
return `<section class="wb-block wb-block--topology" data-block-id="${escapeWorkbenchHtml(block.block_id)}" data-block-type="impact_topology">
|
||||
<header class="wb-block__header">
|
||||
@@ -458,7 +467,7 @@ function renderImpactTopologyBlock(block) {
|
||||
<span class="material-symbols-rounded wb-block__icon" aria-hidden="true">alt_route</span>
|
||||
<h5 class="wb-block__title">${escapeWorkbenchHtml(title)}</h5>
|
||||
</div>
|
||||
<span class="wb-kpi-pill">${escapeWorkbenchHtml(data.severity || "info")} · ${escapeWorkbenchHtml(data.status || "observed")}</span>
|
||||
<span class="wb-kpi-pill">${escapeWorkbenchHtml(severityText)} · ${escapeWorkbenchHtml(statusText)}</span>
|
||||
</header>
|
||||
<div class="wb-block__body">
|
||||
<div class="wb-topology-notice wb-topology-notice--warn">
|
||||
@@ -608,7 +617,7 @@ export function renderViewSpecWorkbench(viewSpec, {
|
||||
const activePreset = viewSpec.active_preset || "default";
|
||||
|
||||
const presetBar = !compact && presets.length
|
||||
? `<div class="wb-preset-bar" role="tablist" aria-label="${escapeWorkbenchHtml(t("零 Token 视图投影切换", "Zero-token view presets"))}">
|
||||
? `<div class="wb-preset-bar" role="tablist" aria-label="${escapeWorkbenchHtml(t("视图切换", "View presets"))}">
|
||||
${presets
|
||||
.map((p) => {
|
||||
const isActive = p.id === activePreset;
|
||||
@@ -633,7 +642,7 @@ export function renderViewSpecWorkbench(viewSpec, {
|
||||
.join("");
|
||||
|
||||
return `<div class="wb-surface ${compact ? "wb-surface--compact" : ""}" data-view-id="${escapeWorkbenchHtml(viewSpec.view_id || "")}">
|
||||
${viewSpec.is_drill ? `<div class="wb-drill-banner"><span class="material-symbols-rounded" aria-hidden="true">science</span><span>${escapeWorkbenchHtml(t("[演练档案] 历史教学复盘样板 · 与实时运行态严格隔离", "[Drill Archive] Historical replay sample · Isolated from live telemetry"))}</span></div>` : ""}
|
||||
${viewSpec.is_drill ? `<div class="wb-drill-banner"><span class="material-symbols-rounded" aria-hidden="true">science</span><span>${escapeWorkbenchHtml(t("历史演练回放(非实时数据)", "Historical drill replay (non-live data)"))}</span></div>` : ""}
|
||||
${viewSpec.replay_supported === false ? `<div class="wb-replay-warning-banner" role="note"><span class="material-symbols-rounded" aria-hidden="true">warning</span><span>${escapeWorkbenchHtml(viewSpec.replay_notice || t("不支持完整重放:当前历史记录缺少冻结数据快照,仅保留原始文字结论。", "Full replay unsupported: historical data snapshot missing; narrative preserved only."))}</span></div>` : ""}
|
||||
${presetBar}
|
||||
<div class="wb-blocks">${blocksHtml}</div>
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
import { getEarthLocale, translateText } from "./i18n.js";
|
||||
|
||||
const BINDINGS_API = "/api/v1/ai/workflows/bindings";
|
||||
const CACHE_TTL_MS = 5 * 60 * 1000;
|
||||
const MAX_COMPARE_TARGETS = 6;
|
||||
|
||||
const TEMPLATE_TOKEN_RE = /\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g;
|
||||
const EARTH_INTERACTABLE_PREFIX = "earth_interactable";
|
||||
|
||||
let cachedBindings = [];
|
||||
let cacheLoadedAt = 0;
|
||||
let inFlightPromise = null;
|
||||
let compareTargets = [];
|
||||
let activeMenuEl = null;
|
||||
let activeMenuCleanup = null;
|
||||
let trayEl = null;
|
||||
|
||||
function safeFetchImpl(explicit) {
|
||||
if (typeof explicit === "function") return explicit;
|
||||
return typeof fetch === "function" ? fetch.bind(globalThis) : null;
|
||||
}
|
||||
|
||||
export function getCachedWorkflowBindings() {
|
||||
return cachedBindings;
|
||||
}
|
||||
|
||||
export function setCachedWorkflowBindingsForTest(items = []) {
|
||||
cachedBindings = Array.isArray(items) ? items : [];
|
||||
cacheLoadedAt = Date.now();
|
||||
}
|
||||
|
||||
export async function loadWorkflowBindings({ force = false, fetchImpl = null } = {}) {
|
||||
if (!force && cacheLoadedAt > 0 && Date.now() - cacheLoadedAt < CACHE_TTL_MS) {
|
||||
return cachedBindings;
|
||||
}
|
||||
if (!force && inFlightPromise) return inFlightPromise;
|
||||
const fetcher = safeFetchImpl(fetchImpl);
|
||||
if (!fetcher) return cachedBindings;
|
||||
|
||||
inFlightPromise = (async () => {
|
||||
try {
|
||||
const resp = await fetcher(BINDINGS_API, {
|
||||
method: "GET",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!resp.ok) return cachedBindings;
|
||||
const body = await resp.json();
|
||||
if (Array.isArray(body?.items)) {
|
||||
cachedBindings = body.items;
|
||||
cacheLoadedAt = Date.now();
|
||||
}
|
||||
return cachedBindings;
|
||||
} catch {
|
||||
return cachedBindings;
|
||||
} finally {
|
||||
inFlightPromise = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return inFlightPromise;
|
||||
}
|
||||
|
||||
function finiteOrNull(value) {
|
||||
const num = Number(value);
|
||||
return Number.isFinite(num) ? num : null;
|
||||
}
|
||||
|
||||
function compactProperties(raw = {}) {
|
||||
const out = {};
|
||||
if (!raw || typeof raw !== "object") return out;
|
||||
const entries = Object.entries(raw);
|
||||
for (let i = 0; i < entries.length && Object.keys(out).length < 16; i += 1) {
|
||||
const [k, v] = entries[i];
|
||||
if (v === null || v === undefined) continue;
|
||||
if (typeof v === "boolean" || typeof v === "number") {
|
||||
if (typeof v === "number" && !Number.isFinite(v)) continue;
|
||||
out[k] = v;
|
||||
} else if (typeof v === "string") {
|
||||
const trimmed = v.trim();
|
||||
if (trimmed) out[k] = trimmed.slice(0, 300);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeEarthTarget(entityType, rawData = {}) {
|
||||
const data = rawData && typeof rawData === "object" ? rawData : {};
|
||||
const type = String(entityType || data.entity_type || "global").trim() || "global";
|
||||
const label = String(
|
||||
data.label
|
||||
|| data.name
|
||||
|| data.title
|
||||
|| data.collector
|
||||
|| data.city
|
||||
|| data.anomaly_type
|
||||
|| data.country
|
||||
|| data.code
|
||||
|| type,
|
||||
).trim().slice(0, 200);
|
||||
|
||||
const entityId = String(
|
||||
data.entity_id
|
||||
|| data.incident_key
|
||||
|| data.event_key
|
||||
|| data.source_id
|
||||
|| data.norad_id
|
||||
|| data.norad_cat_id
|
||||
|| data.mmsi
|
||||
|| data.cable_id
|
||||
|| data.collector
|
||||
|| data.code
|
||||
|| data.id
|
||||
|| label,
|
||||
).trim().slice(0, 160) || null;
|
||||
|
||||
const lat = finiteOrNull(data.latitude ?? data.lat ?? data.anchor?.latitude);
|
||||
const lon = finiteOrNull(data.longitude ?? data.lon ?? data.anchor?.longitude);
|
||||
const layer = data.layer ? String(data.layer).trim().slice(0, 80) : null;
|
||||
const kind = data.kind ? String(data.kind).trim().slice(0, 80) : null;
|
||||
|
||||
return {
|
||||
entity_type: type,
|
||||
entity_id: entityId,
|
||||
label,
|
||||
latitude: lat,
|
||||
longitude: lon,
|
||||
layer,
|
||||
kind,
|
||||
properties: compactProperties(data),
|
||||
};
|
||||
}
|
||||
|
||||
export function getTargetKey(target) {
|
||||
if (!target || typeof target !== "object") return "";
|
||||
return `${target.entity_type || "entity"}:${target.entity_id || target.label || ""}`;
|
||||
}
|
||||
|
||||
export function matchWorkflowBindings({
|
||||
surface,
|
||||
targets = [],
|
||||
catalog = cachedBindings,
|
||||
} = {}) {
|
||||
if (!Array.isArray(catalog) || !catalog.length) return [];
|
||||
const cleanTargets = Array.isArray(targets) ? targets.filter((t) => t && typeof t === "object") : [];
|
||||
const targetCount = Math.max(1, cleanTargets.length);
|
||||
const effectiveTargets = cleanTargets.length
|
||||
? cleanTargets
|
||||
: [{ entity_type: "global", kind: null }];
|
||||
|
||||
const matched = [];
|
||||
for (const wf of catalog) {
|
||||
const bindings = wf?.bindings;
|
||||
if (!bindings || !bindings.enabled) continue;
|
||||
const surfaces = Array.isArray(bindings.surfaces) ? bindings.surfaces : [];
|
||||
if (surface && !surfaces.includes(surface)) continue;
|
||||
|
||||
const minTargets = Math.max(1, Number(bindings.min_targets || 1));
|
||||
const maxTargets = Math.max(minTargets, Number(bindings.max_targets || 5));
|
||||
if (cleanTargets.length > 0 && (targetCount < minTargets || targetCount > maxTargets)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const allowedTypes = Array.isArray(bindings.entity_types) ? bindings.entity_types : [];
|
||||
if (!allowedTypes.length) continue;
|
||||
|
||||
const allowedKinds = Array.isArray(bindings.interactable_kinds)
|
||||
? bindings.interactable_kinds.map((k) => String(k).trim().toLowerCase()).filter(Boolean)
|
||||
: [];
|
||||
|
||||
const allMatch = effectiveTargets.every((t) => {
|
||||
const et = String(t.entity_type || "global").trim();
|
||||
if (!allowedTypes.includes(et)) return false;
|
||||
if (et === EARTH_INTERACTABLE_PREFIX && allowedKinds.length > 0) {
|
||||
const tk = String(t.kind || "").trim().toLowerCase();
|
||||
return Boolean(tk && allowedKinds.includes(tk));
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!allMatch) continue;
|
||||
|
||||
matched.push(wf);
|
||||
}
|
||||
|
||||
matched.sort((a, b) => {
|
||||
const pDiff = Number(b?.bindings?.priority || 0) - Number(a?.bindings?.priority || 0);
|
||||
if (pDiff !== 0) return pDiff;
|
||||
if (Boolean(a?.is_builtin) !== Boolean(b?.is_builtin)) {
|
||||
return a?.is_builtin ? 1 : -1;
|
||||
}
|
||||
return String(a?.workflow_id || "").localeCompare(String(b?.workflow_id || ""));
|
||||
});
|
||||
return matched;
|
||||
}
|
||||
|
||||
export function renderBindingPromptTemplate(template, targets = [], fallbackQuestion = "") {
|
||||
const raw = String(template || "").trim();
|
||||
if (!raw) return String(fallbackQuestion || "").trim();
|
||||
const list = Array.isArray(targets) ? targets : [];
|
||||
const first = list[0] || {};
|
||||
const targetsSummary = list
|
||||
.map((item) => {
|
||||
const et = item.entity_type || "entity";
|
||||
const lbl = item.label || item.entity_id || et;
|
||||
const coord = Number.isFinite(item.latitude) && Number.isFinite(item.longitude)
|
||||
? `(${item.latitude.toFixed(2)}, ${item.longitude.toFixed(2)})`
|
||||
: "";
|
||||
return `${et}「${lbl}」${coord}`;
|
||||
})
|
||||
.join("; ");
|
||||
|
||||
return raw.replace(TEMPLATE_TOKEN_RE, (_match, key) => {
|
||||
if (key === "question") return String(fallbackQuestion || "");
|
||||
if (key === "targets_summary") return targetsSummary || first.label || "";
|
||||
if (key === "target.label") return String(first.label || "");
|
||||
if (key === "target.type") return String(first.entity_type || "");
|
||||
if (key === "target.id") return String(first.entity_id || "");
|
||||
if (key === "target.lat") return Number.isFinite(first.latitude) ? first.latitude.toFixed(4) : "";
|
||||
if (key === "target.lon") return Number.isFinite(first.longitude) ? first.longitude.toFixed(4) : "";
|
||||
if (key === "target.kind") return String(first.kind || "");
|
||||
if (key === "target.layer") return String(first.layer || "");
|
||||
return "";
|
||||
}).trim();
|
||||
}
|
||||
|
||||
export function getCompareTargets() {
|
||||
return [...compareTargets];
|
||||
}
|
||||
|
||||
export function resetCompareTargetsForTest() {
|
||||
compareTargets = [];
|
||||
trayEl = null;
|
||||
}
|
||||
|
||||
export function addTargetToCompare(target) {
|
||||
if (!target || typeof target !== "object") return compareTargets;
|
||||
const key = getTargetKey(target);
|
||||
if (!key) return compareTargets;
|
||||
if (!compareTargets.some((t) => getTargetKey(t) === key)) {
|
||||
compareTargets = [...compareTargets.slice(-(MAX_COMPARE_TARGETS - 1)), target];
|
||||
}
|
||||
renderCompareTray();
|
||||
return compareTargets;
|
||||
}
|
||||
|
||||
export function removeTargetFromCompare(targetKey) {
|
||||
compareTargets = compareTargets.filter((t) => getTargetKey(t) !== targetKey);
|
||||
renderCompareTray();
|
||||
return compareTargets;
|
||||
}
|
||||
|
||||
export function clearCompareTargets() {
|
||||
compareTargets = [];
|
||||
renderCompareTray();
|
||||
}
|
||||
|
||||
function escapeHtml(val) {
|
||||
return String(val ?? "").replace(/[&<>"']/g, (ch) => ({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
})[ch]);
|
||||
}
|
||||
|
||||
export function closeWorkflowActionPicker() {
|
||||
if (typeof activeMenuCleanup === "function") {
|
||||
activeMenuCleanup();
|
||||
activeMenuCleanup = null;
|
||||
}
|
||||
if (activeMenuEl) {
|
||||
activeMenuEl.remove();
|
||||
activeMenuEl = null;
|
||||
}
|
||||
}
|
||||
|
||||
function renderCompareTray() {
|
||||
if (
|
||||
typeof window === "undefined"
|
||||
|| typeof document === "undefined"
|
||||
|| typeof document.querySelector !== "function"
|
||||
|| typeof document.createElement !== "function"
|
||||
|| typeof document.body?.appendChild !== "function"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!compareTargets.length) {
|
||||
if (trayEl) trayEl.hidden = true;
|
||||
return;
|
||||
}
|
||||
if (!trayEl || !trayEl.isConnected) {
|
||||
trayEl = document.createElement("aside");
|
||||
trayEl.id = "earth-target-tray";
|
||||
trayEl.className = "hud-panel earth-target-tray";
|
||||
trayEl.setAttribute("aria-label", translateText("多物件联合分析对比栏"));
|
||||
document.body.appendChild(trayEl);
|
||||
trayEl.addEventListener?.("click", (event) => {
|
||||
event.stopPropagation();
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
if (!target) return;
|
||||
const removeBtn = target.closest("[data-tray-remove]");
|
||||
if (removeBtn instanceof HTMLElement) {
|
||||
removeTargetFromCompare(removeBtn.dataset.trayRemove || "");
|
||||
return;
|
||||
}
|
||||
if (target.closest("[data-tray-clear]")) {
|
||||
clearCompareTargets();
|
||||
return;
|
||||
}
|
||||
const analyzeBtn = target.closest("[data-tray-analyze]");
|
||||
if (analyzeBtn instanceof HTMLElement) {
|
||||
const snapshot = getCompareTargets();
|
||||
if (!snapshot.length) return;
|
||||
const isEn = getEarthLocale() === "en-US";
|
||||
const summary = snapshot.map((t) => `${t.label || t.entity_id || t.entity_type}`).join(isEn ? ", " : "、");
|
||||
openWorkflowActionPicker({
|
||||
anchorEl: analyzeBtn,
|
||||
surface: "multi_select",
|
||||
targets: snapshot,
|
||||
fallbackDetail: {
|
||||
domain: "global",
|
||||
entityId: snapshot[0]?.entity_id || null,
|
||||
targets: snapshot,
|
||||
initialQuestion: isEn
|
||||
? `Perform a cross-layer joint analysis on these ${snapshot.length} selected Earth objects: ${summary}`
|
||||
: `请对以下选中的 ${snapshot.length} 个地球对象进行联合分析:${summary}`,
|
||||
autoAsk: true,
|
||||
},
|
||||
onSelect: (detail) => {
|
||||
window.dispatchEvent(new CustomEvent("earth:open-workbench", { detail }));
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
trayEl.hidden = false;
|
||||
const chipsHtml = compareTargets
|
||||
.map((item) => {
|
||||
const key = getTargetKey(item);
|
||||
const label = item.label || item.entity_id || item.entity_type;
|
||||
return `<span class="earth-target-tray__chip">
|
||||
<span class="earth-target-tray__chip-label" title="${escapeHtml(label)}">${escapeHtml(label)}</span>
|
||||
<button type="button" class="earth-target-tray__chip-remove" data-tray-remove="${escapeHtml(key)}" aria-label="${escapeHtml(translateText("移出对比"))}">
|
||||
<span class="material-symbols-rounded earth-target-tray__icon" aria-hidden="true">close</span>
|
||||
</button>
|
||||
</span>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
trayEl.innerHTML = `<div class="earth-target-tray__list">${chipsHtml}</div>
|
||||
<div class="earth-target-tray__actions">
|
||||
<button type="button" class="earth-target-tray__analyze" data-tray-analyze="true">
|
||||
<span class="material-symbols-rounded earth-target-tray__icon" aria-hidden="true">hub</span>
|
||||
<span>${escapeHtml(translateText("联合分析"))} (${compareTargets.length})</span>
|
||||
</button>
|
||||
<button type="button" class="hud-panel__action" data-tray-clear="true" aria-label="${escapeHtml(translateText("清空对比栏"))}" title="${escapeHtml(translateText("清空对比栏"))}">
|
||||
<span class="material-symbols-rounded earth-target-tray__icon" aria-hidden="true">delete_sweep</span>
|
||||
</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function getLocalizedWorkflowTitle(wf) {
|
||||
const isEn = getEarthLocale() === "en-US";
|
||||
const b = wf?.bindings || {};
|
||||
if (isEn) {
|
||||
return b.action_label_en || wf?.name_en || b.action_label || wf?.name || wf?.workflow_id || "";
|
||||
}
|
||||
return b.action_label || wf?.name || wf?.workflow_id || "";
|
||||
}
|
||||
|
||||
function positionMenuNearAnchor(menu, anchorEl) {
|
||||
if (!anchorEl || typeof anchorEl.getBoundingClientRect !== "function") return;
|
||||
const rect = anchorEl.getBoundingClientRect();
|
||||
const vw = window.innerWidth || 1280;
|
||||
const vh = window.innerHeight || 800;
|
||||
const menuW = Math.min(280, Math.max(210, vw - 24));
|
||||
const left = Math.max(12, Math.min(rect.right - menuW, vw - menuW - 12));
|
||||
const openBelow = vh - rect.bottom >= 180 || vh - rect.bottom >= rect.top;
|
||||
menu.style.width = `${menuW}px`;
|
||||
menu.style.left = `${left}px`;
|
||||
if (openBelow) {
|
||||
menu.style.top = `${Math.min(vh - 180, rect.bottom + 6)}px`;
|
||||
menu.style.bottom = "auto";
|
||||
} else {
|
||||
menu.style.bottom = `${Math.max(12, vh - rect.top + 6)}px`;
|
||||
menu.style.top = "auto";
|
||||
}
|
||||
}
|
||||
|
||||
export function openWorkflowActionPicker({
|
||||
anchorEl = null,
|
||||
surface = "info_card",
|
||||
targets = [],
|
||||
fallbackDetail = {},
|
||||
onSelect = null,
|
||||
} = {}) {
|
||||
const dispatch = typeof onSelect === "function"
|
||||
? onSelect
|
||||
: (detail) => {
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(new CustomEvent("earth:open-workbench", { detail }));
|
||||
}
|
||||
};
|
||||
|
||||
// Trigger non-blocking catalog refresh in background if needed.
|
||||
if (!cacheLoadedAt) {
|
||||
void loadWorkflowBindings();
|
||||
}
|
||||
|
||||
const matches = matchWorkflowBindings({ surface, targets, catalog: cachedBindings });
|
||||
|
||||
const buildDispatchPayload = (wf) => {
|
||||
const workflowId = wf?.workflow_id || null;
|
||||
const workflowName = wf ? getLocalizedWorkflowTitle(wf) : "";
|
||||
const tmpl = wf?.bindings?.prompt_template || "";
|
||||
const question = renderBindingPromptTemplate(
|
||||
tmpl,
|
||||
targets,
|
||||
fallbackDetail.initialQuestion || "",
|
||||
);
|
||||
return {
|
||||
...fallbackDetail,
|
||||
workflowId,
|
||||
workflowName,
|
||||
targets,
|
||||
initialQuestion: question,
|
||||
autoAsk: fallbackDetail.autoAsk !== undefined ? Boolean(fallbackDetail.autoAsk) : true,
|
||||
};
|
||||
};
|
||||
|
||||
if (matches.length === 0) {
|
||||
dispatch({ ...fallbackDetail, targets });
|
||||
return;
|
||||
}
|
||||
|
||||
if (matches.length === 1 && surface === "multi_select") {
|
||||
dispatch(buildDispatchPayload(matches[0]));
|
||||
return;
|
||||
}
|
||||
|
||||
if (matches.length === 1 && surface !== "info_card") {
|
||||
dispatch(buildDispatchPayload(matches[0]));
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof document === "undefined" || !document.body || !anchorEl) {
|
||||
dispatch(buildDispatchPayload(matches[0]));
|
||||
return;
|
||||
}
|
||||
|
||||
// If clicked a second time on same trigger while open, toggle closed.
|
||||
if (activeMenuEl && activeMenuEl.dataset.anchorKey === `${surface}:${getTargetKey(targets[0])}`) {
|
||||
closeWorkflowActionPicker();
|
||||
return;
|
||||
}
|
||||
|
||||
closeWorkflowActionPicker();
|
||||
const menu = document.createElement("div");
|
||||
menu.className = "hud-panel earth-workflow-menu";
|
||||
menu.dataset.anchorKey = `${surface}:${getTargetKey(targets[0])}`;
|
||||
menu.setAttribute("role", "menu");
|
||||
|
||||
const itemsHtml = matches
|
||||
.map((wf, idx) => {
|
||||
const icon = wf?.bindings?.icon || "forum";
|
||||
const label = getLocalizedWorkflowTitle(wf);
|
||||
const isCustom = wf?.is_builtin === false;
|
||||
return `<button type="button" class="earth-workflow-menu__item" data-wf-index="${idx}" role="menuitem">
|
||||
<span class="material-symbols-rounded earth-workflow-menu__icon" aria-hidden="true">${escapeHtml(icon)}</span>
|
||||
<span class="earth-workflow-menu__label">${escapeHtml(label)}</span>
|
||||
${isCustom ? `<span class="earth-workflow-menu__tag">${escapeHtml(translateText("自定义"))}</span>` : ""}
|
||||
</button>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
const showPinCompare = surface !== "multi_select" && targets.length === 1;
|
||||
const alreadyPinned = showPinCompare && compareTargets.some((t) => getTargetKey(t) === getTargetKey(targets[0]));
|
||||
const pinHtml = showPinCompare
|
||||
? `<div class="earth-workflow-menu__sep"></div>
|
||||
<button type="button" class="earth-workflow-menu__item earth-workflow-menu__item--pin" data-wf-pin="true" role="menuitem">
|
||||
<span class="material-symbols-rounded earth-workflow-menu__icon" aria-hidden="true">${alreadyPinned ? "check_circle" : "add_circle_outline"}</span>
|
||||
<span class="earth-workflow-menu__label">${escapeHtml(alreadyPinned ? translateText("已在多物件对比栏") : translateText("加入多物件对比分析"))}</span>
|
||||
</button>`
|
||||
: "";
|
||||
|
||||
menu.innerHTML = `<div class="earth-workflow-menu__head">${escapeHtml(translateText("选择 AI 工作流"))}</div>${itemsHtml}${pinHtml}`;
|
||||
document.body.appendChild(menu);
|
||||
positionMenuNearAnchor(menu, anchorEl);
|
||||
activeMenuEl = menu;
|
||||
|
||||
menu.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
if (!target) return;
|
||||
const wfBtn = target.closest("[data-wf-index]");
|
||||
if (wfBtn instanceof HTMLElement) {
|
||||
const wf = matches[Number(wfBtn.dataset.wfIndex)];
|
||||
closeWorkflowActionPicker();
|
||||
if (wf) dispatch(buildDispatchPayload(wf));
|
||||
return;
|
||||
}
|
||||
if (target.closest("[data-wf-pin]")) {
|
||||
if (targets[0]) addTargetToCompare(targets[0]);
|
||||
closeWorkflowActionPicker();
|
||||
}
|
||||
});
|
||||
|
||||
const onOutsidePointer = (event) => {
|
||||
const t = event.target instanceof Node ? event.target : null;
|
||||
if (t && (menu.contains(t) || anchorEl.contains(t))) return;
|
||||
closeWorkflowActionPicker();
|
||||
};
|
||||
const onEscape = (event) => {
|
||||
if (event.key === "Escape") closeWorkflowActionPicker();
|
||||
};
|
||||
document.addEventListener("pointerdown", onOutsidePointer, true);
|
||||
document.addEventListener("keydown", onEscape, true);
|
||||
activeMenuCleanup = () => {
|
||||
document.removeEventListener("pointerdown", onOutsidePointer, true);
|
||||
document.removeEventListener("keydown", onEscape, true);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
addTargetToCompare,
|
||||
clearCompareTargets,
|
||||
getCompareTargets,
|
||||
matchWorkflowBindings,
|
||||
normalizeEarthTarget,
|
||||
removeTargetFromCompare,
|
||||
renderBindingPromptTemplate,
|
||||
resetCompareTargetsForTest,
|
||||
} from "./workflow-bindings.js";
|
||||
|
||||
describe("earth workflow bindings matcher, normalizer, and compare store", () => {
|
||||
it("normalizes different Earth objects into a consistent target contract", () => {
|
||||
const cable = normalizeEarthTarget("cable", {
|
||||
cable_id: "c-peace",
|
||||
name: "PEACE",
|
||||
latitude: 11.5,
|
||||
longitude: 43.1,
|
||||
owner: "PEACE Cable",
|
||||
});
|
||||
expect(cable.entity_type).toBe("cable");
|
||||
expect(cable.entity_id).toBe("c-peace");
|
||||
expect(cable.label).toBe("PEACE");
|
||||
expect(cable.latitude).toBe(11.5);
|
||||
expect(cable.longitude).toBe(43.1);
|
||||
|
||||
const customPoint = normalizeEarthTarget("earth_interactable", {
|
||||
id: "poi-99",
|
||||
label: "ALMA Observatory",
|
||||
layer: "science",
|
||||
kind: "observatory",
|
||||
lat: -23.02,
|
||||
lon: -67.75,
|
||||
});
|
||||
expect(customPoint.entity_type).toBe("earth_interactable");
|
||||
expect(customPoint.kind).toBe("observatory");
|
||||
expect(customPoint.layer).toBe("science");
|
||||
expect(customPoint.latitude).toBe(-23.02);
|
||||
});
|
||||
|
||||
it("matches bound workflows by surface, entity type, interactable kind, target count, and priority", () => {
|
||||
const catalog = [
|
||||
{
|
||||
workflow_id: "default.general",
|
||||
name: "默认通用",
|
||||
is_builtin: true,
|
||||
bindings: {
|
||||
enabled: true,
|
||||
surfaces: ["info_card", "multi_select"],
|
||||
entity_types: ["cable", "vessel", "earth_interactable"],
|
||||
interactable_kinds: [],
|
||||
min_targets: 1,
|
||||
max_targets: 5,
|
||||
priority: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
workflow_id: "custom.observatory_only",
|
||||
name: "天文台专项",
|
||||
is_builtin: false,
|
||||
bindings: {
|
||||
enabled: true,
|
||||
surfaces: ["info_card"],
|
||||
entity_types: ["earth_interactable"],
|
||||
interactable_kinds: ["observatory"],
|
||||
min_targets: 1,
|
||||
max_targets: 2,
|
||||
priority: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
workflow_id: "custom.cable_vessel_compare",
|
||||
name: "海缆+船舶联合排查",
|
||||
is_builtin: false,
|
||||
bindings: {
|
||||
enabled: true,
|
||||
surfaces: ["multi_select"],
|
||||
entity_types: ["cable", "vessel"],
|
||||
interactable_kinds: [],
|
||||
min_targets: 2,
|
||||
max_targets: 5,
|
||||
priority: 50,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const obs = normalizeEarthTarget("earth_interactable", {
|
||||
id: "obs-1",
|
||||
label: "ALMA",
|
||||
kind: "observatory",
|
||||
});
|
||||
const obsMatches = matchWorkflowBindings({ surface: "info_card", targets: [obs], catalog });
|
||||
expect(obsMatches.map((w) => w.workflow_id)).toEqual([
|
||||
"custom.observatory_only",
|
||||
"default.general",
|
||||
]);
|
||||
|
||||
const portPoi = normalizeEarthTarget("earth_interactable", {
|
||||
id: "port-1",
|
||||
label: "Suez",
|
||||
kind: "port",
|
||||
});
|
||||
const portMatches = matchWorkflowBindings({ surface: "info_card", targets: [portPoi], catalog });
|
||||
expect(portMatches.map((w) => w.workflow_id)).toEqual(["default.general"]);
|
||||
|
||||
const multiMatches = matchWorkflowBindings({
|
||||
surface: "multi_select",
|
||||
targets: [
|
||||
normalizeEarthTarget("cable", { id: "c1", name: "2Africa" }),
|
||||
normalizeEarthTarget("vessel", { mmsi: "123456", name: "MV Test" }),
|
||||
],
|
||||
catalog,
|
||||
});
|
||||
expect(multiMatches.map((w) => w.workflow_id)).toEqual([
|
||||
"custom.cable_vessel_compare",
|
||||
"default.general",
|
||||
]);
|
||||
});
|
||||
|
||||
it("renders prompt templates safely without throwing on missing fields", () => {
|
||||
const out = renderBindingPromptTemplate(
|
||||
"检查 {{targets_summary}},重点对象={{target.label}} ({{target.lat}})",
|
||||
[{ entity_type: "cable", entity_id: "c1", label: "PEACE", latitude: 10.5, longitude: 20.25 }],
|
||||
"默认问题",
|
||||
);
|
||||
expect(out).toContain("cable「PEACE」(10.50, 20.25)");
|
||||
expect(out).toContain("重点对象=PEACE (10.5000)");
|
||||
});
|
||||
|
||||
it("deduplicates and removes compare tray targets in memory", () => {
|
||||
const origDoc = globalThis.document;
|
||||
globalThis.document = undefined;
|
||||
try {
|
||||
resetCompareTargetsForTest();
|
||||
const t1 = normalizeEarthTarget("cable", { id: "c1", name: "PEACE" });
|
||||
const t2 = normalizeEarthTarget("vessel", { mmsi: "999", name: "Ship A" });
|
||||
addTargetToCompare(t1);
|
||||
addTargetToCompare(t1);
|
||||
addTargetToCompare(t2);
|
||||
expect(getCompareTargets()).toHaveLength(2);
|
||||
removeTargetFromCompare("cable:c1");
|
||||
expect(getCompareTargets()).toHaveLength(1);
|
||||
clearCompareTargets();
|
||||
expect(getCompareTargets()).toHaveLength(0);
|
||||
} finally {
|
||||
globalThis.document = origDoc;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import './styles.css'
|
||||
import { Navigate, Route, Routes } from 'react-router-dom'
|
||||
import { AdminThemeProvider } from './design/theme'
|
||||
import AdvisorPlayground from './pages/AdvisorPlayground'
|
||||
@@ -10,14 +11,12 @@ import {
|
||||
CollectionManagement,
|
||||
DataSources,
|
||||
EarthContent,
|
||||
Monitoring,
|
||||
Settings,
|
||||
} from './pages/PlainResourcePages'
|
||||
import Users from './pages/Users'
|
||||
import Logs from './pages/Logs'
|
||||
import { ToastProvider } from './components/ui/toast'
|
||||
import { AdminSearchProvider } from './search/AdminSearchContext'
|
||||
import './styles.css'
|
||||
|
||||
export default function AdminRoutes() {
|
||||
return (
|
||||
@@ -32,15 +31,15 @@ export default function AdminRoutes() {
|
||||
<Route path="/advisor/playground" element={<AdvisorPlayground />} />
|
||||
<Route path="/advisor/workflows" element={<AdvisorWorkflows />} />
|
||||
<Route path="/advisor/runs" element={<AdvisorRuns />} />
|
||||
<Route path="/ops/monitoring" element={<Monitoring />} />
|
||||
<Route path="/ai" element={<AI />} />
|
||||
<Route path="/ai/prompts" element={<Navigate to="/advisor/workflows" replace />} />
|
||||
<Route path="/ai/playground" element={<Navigate to="/advisor/playground" replace />} />
|
||||
<Route path="/bgp" element={<Navigate to="/ops/monitoring?section=bgp-incidents" replace />} />
|
||||
<Route path="/alerts" element={<Navigate to="/ops/monitoring?section=system-alerts" replace />} />
|
||||
<Route path="/alerts/system" element={<Navigate to="/ops/monitoring?section=system-alerts" replace />} />
|
||||
<Route path="/alerts/bgp" element={<Navigate to="/ops/monitoring?section=bgp-incidents" replace />} />
|
||||
<Route path="/alerts/situational" element={<Navigate to="/ops/monitoring?section=stats" replace />} />
|
||||
<Route path="/ops/monitoring" element={<Navigate to="/advisor/playground" replace />} />
|
||||
<Route path="/bgp" element={<Navigate to="/advisor/playground?workflow=brief.bgp" replace />} />
|
||||
<Route path="/alerts" element={<Navigate to="/advisor/playground?workflow=brief.alerts" replace />} />
|
||||
<Route path="/alerts/system" element={<Navigate to="/advisor/playground?workflow=brief.alerts" replace />} />
|
||||
<Route path="/alerts/bgp" element={<Navigate to="/advisor/playground?workflow=brief.bgp" replace />} />
|
||||
<Route path="/alerts/situational" element={<Navigate to="/advisor/playground?workflow=brief.alerts" replace />} />
|
||||
<Route path="/earth-content" element={<EarthContent />} />
|
||||
<Route path="/collection-management" element={<CollectionManagement />} />
|
||||
<Route path="/logs" element={<Logs />} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react'
|
||||
import i18n from '../../i18n'
|
||||
import { reportAdminRuntimeLog } from '../runtimeLogs'
|
||||
|
||||
type AdminErrorBoundaryProps = {
|
||||
@@ -21,7 +22,7 @@ export class AdminErrorBoundary extends Component<AdminErrorBoundaryProps, Admin
|
||||
level: 'error',
|
||||
category: 'react-error-boundary',
|
||||
module: 'admin',
|
||||
message: error.message || '控制台渲染错误',
|
||||
message: error.message || i18n.t('admin.runtimeErrors.renderError'),
|
||||
detail: `${error.stack || error.message}\n${errorInfo.componentStack || ''}`,
|
||||
})
|
||||
}
|
||||
@@ -30,7 +31,7 @@ export class AdminErrorBoundary extends Component<AdminErrorBoundaryProps, Admin
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div className="app-route-loading">
|
||||
<div className="app-route-loading__message">控制台发生错误,请刷新页面重试。</div>
|
||||
<div className="app-route-loading__message">{i18n.t('admin.errorBoundaryMessage')}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
Search,
|
||||
Settings,
|
||||
Sun,
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
import { type FocusEvent, type KeyboardEvent, type ReactNode, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
@@ -205,7 +204,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
title={mobile ? t('admin.closeNav') : isCollapsed ? t('admin.expandMenu') : t('admin.collapseMenu')}
|
||||
aria-label={mobile ? t('admin.closeNav') : isCollapsed ? t('admin.expandMenu') : t('admin.collapseMenu')}
|
||||
>
|
||||
{isCollapsed ? <Menu size={18} /> : <X size={18} />}
|
||||
<img className="admin__brand-logo" src="/favicon.png" alt="" aria-hidden="true" />
|
||||
</Button>
|
||||
{!isCollapsed ? (
|
||||
<div className="admin__brand-copy">
|
||||
@@ -405,7 +404,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
aria-label={t('admin.search.label')}
|
||||
autoComplete="off"
|
||||
value={searchQuery}
|
||||
placeholder={activeRouteLabel ? `${t('admin.search.placeholder')},${t('admin.search.current', { label: activeRouteLabel })}` : t('admin.search.placeholder')}
|
||||
placeholder={activeRouteLabel ? t('admin.search.placeholderWithContext', { label: activeRouteLabel }) : t('admin.search.placeholder')}
|
||||
onChange={(event) => {
|
||||
setSearchQuery(event.target.value)
|
||||
setSearchOpen(true)
|
||||
@@ -416,29 +415,31 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
/>
|
||||
{searchOpen ? (
|
||||
<div className="admin__search-results" role="listbox" aria-label={t('admin.search.results')}>
|
||||
{searchResults.length > 0 ? searchResults.map((target, index) => {
|
||||
const ResultIcon = target.icon || Search
|
||||
return (
|
||||
<button
|
||||
key={target.id}
|
||||
type="button"
|
||||
className={cn('admin__search-result', index === highlightedSearchIndex && 'is-active')}
|
||||
role="option"
|
||||
aria-selected={index === highlightedSearchIndex}
|
||||
onMouseEnter={() => setHighlightedSearchIndex(index)}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => selectSearchResult(index)}
|
||||
>
|
||||
<ResultIcon size={16} />
|
||||
<span>
|
||||
<strong>{target.label}</strong>
|
||||
<small>{target.contextLabel || [target.routeLabel, target.sectionLabel].filter(Boolean).join(' / ')}</small>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}) : (
|
||||
<div className="admin__search-empty">{adminSearch.loading ? t('admin.search.loading') : t('admin.search.empty')}</div>
|
||||
)}
|
||||
<Scrollbar className="admin__search-results__scroll" axis="y">
|
||||
{searchResults.length > 0 ? searchResults.map((target, index) => {
|
||||
const ResultIcon = target.icon || Search
|
||||
return (
|
||||
<button
|
||||
key={target.id}
|
||||
type="button"
|
||||
className={cn('admin__search-result', index === highlightedSearchIndex && 'is-active')}
|
||||
role="option"
|
||||
aria-selected={index === highlightedSearchIndex}
|
||||
onMouseEnter={() => setHighlightedSearchIndex(index)}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => selectSearchResult(index)}
|
||||
>
|
||||
<ResultIcon size={16} />
|
||||
<span>
|
||||
<strong>{target.label}</strong>
|
||||
<small>{target.contextLabel || [target.routeLabel, target.sectionLabel].filter(Boolean).join(' / ')}</small>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}) : (
|
||||
<div className="admin__search-empty">{adminSearch.loading ? t('admin.search.loading') : t('admin.search.empty')}</div>
|
||||
)}
|
||||
</Scrollbar>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,17 @@
|
||||
import axios from 'axios'
|
||||
import { FilterX, GitBranch, RefreshCw, Sparkles } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { ArrowLeft, FilterX, GitBranch, RefreshCw, Sparkles, ThumbsDown, ThumbsUp } from 'lucide-react'
|
||||
import {
|
||||
type CSSProperties,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useLocale } from '../../i18n/locale'
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { AdminLayout } from '../components/layout/AdminLayout'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { Select } from '../components/ui/select'
|
||||
@@ -22,51 +31,186 @@ interface RunItem {
|
||||
completed_at?: string
|
||||
}
|
||||
|
||||
const RUNS_DETAIL_WIDTH_KEY = 'planet_advisor_runs_detail_width_v1'
|
||||
|
||||
function readStoredRunsWidth(): number {
|
||||
try {
|
||||
const raw = localStorage.getItem(RUNS_DETAIL_WIDTH_KEY)
|
||||
const num = raw ? Number(raw) : NaN
|
||||
if (Number.isFinite(num)) return Math.min(560, Math.max(320, Math.round(num)))
|
||||
} catch {
|
||||
// Ignore storage read errors.
|
||||
}
|
||||
return 390
|
||||
}
|
||||
|
||||
function extractRunTelemetry(run: RunItem): {
|
||||
modelUsed: string
|
||||
latencyMs: number | null
|
||||
revision: number | null
|
||||
rating: -1 | 0 | 1
|
||||
feedbackNote: string
|
||||
} {
|
||||
const bu = run.budget_used || {}
|
||||
const modelUsed = String(bu.model_used || run.input_params?.model_override || '').trim()
|
||||
const rawLat = bu.latency_ms
|
||||
let latencyMs: number | null =
|
||||
typeof rawLat === 'number' && Number.isFinite(rawLat) && rawLat >= 0 ? Math.round(rawLat) : null
|
||||
if (latencyMs === null && run.started_at && run.completed_at) {
|
||||
const start = Date.parse(run.started_at)
|
||||
const end = Date.parse(run.completed_at)
|
||||
if (Number.isFinite(start) && Number.isFinite(end) && end >= start) {
|
||||
latencyMs = Math.round(end - start)
|
||||
}
|
||||
}
|
||||
const rawRev = Number(bu.workflow_revision)
|
||||
const revision = Number.isFinite(rawRev) && rawRev >= 1 ? rawRev : null
|
||||
const rawRating = Number(bu.user_rating)
|
||||
const rating: -1 | 0 | 1 = rawRating === 1 ? 1 : rawRating === -1 ? -1 : 0
|
||||
const feedbackNote = String(bu.feedback_note || '').trim()
|
||||
return { modelUsed, latencyMs, revision, rating, feedbackNote }
|
||||
}
|
||||
|
||||
function formatRunTime(raw?: string): string {
|
||||
if (!raw) return ''
|
||||
const parsed = Date.parse(raw)
|
||||
if (!Number.isFinite(parsed)) return raw
|
||||
return new Date(parsed).toLocaleString(undefined, {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
export default function AdvisorRuns() {
|
||||
const { locale } = useLocale()
|
||||
const isEn = locale === 'en-US'
|
||||
const tx = useCallback((zh: string, en: string) => (isEn ? en : zh), [isEn])
|
||||
|
||||
const [runs, setRuns] = useState<RunItem[]>([])
|
||||
const [knownWorkflowIds, setKnownWorkflowIds] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [workflowFilter, setWorkflowFilter] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState('')
|
||||
const [feedbackFilter, setFeedbackFilter] = useState('')
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const [selectedId, setSelectedId] = useState<string>('')
|
||||
const [mobileDetailOpen, setMobileDetailOpen] = useState(false)
|
||||
const [detailWidth, setDetailWidth] = useState<number>(readStoredRunsWidth)
|
||||
|
||||
const splitRef = useRef<HTMLDivElement | null>(null)
|
||||
const runsAbortRef = useRef<AbortController | null>(null)
|
||||
const runsReqSeqRef = useRef(0)
|
||||
|
||||
const startDetailResize = useCallback(
|
||||
(event: ReactPointerEvent<HTMLButtonElement>) => {
|
||||
event.preventDefault()
|
||||
const startX = event.clientX
|
||||
const startWidth = detailWidth
|
||||
let latestWidth = startWidth
|
||||
const handleMove = (moveEvent: PointerEvent) => {
|
||||
const containerW = splitRef.current?.clientWidth || window.innerWidth
|
||||
const dynamicMax = Math.min(560, Math.max(320, containerW - 360))
|
||||
latestWidth = Math.min(dynamicMax, Math.max(320, Math.round(startWidth - (moveEvent.clientX - startX))))
|
||||
setDetailWidth(latestWidth)
|
||||
}
|
||||
const stopMove = () => {
|
||||
document.body.classList.remove('an-is-resizing')
|
||||
window.removeEventListener('pointermove', handleMove)
|
||||
window.removeEventListener('pointerup', stopMove)
|
||||
try {
|
||||
localStorage.setItem(RUNS_DETAIL_WIDTH_KEY, String(latestWidth))
|
||||
} catch {
|
||||
// Ignore storage write errors.
|
||||
}
|
||||
}
|
||||
document.body.classList.add('an-is-resizing')
|
||||
window.addEventListener('pointermove', handleMove)
|
||||
window.addEventListener('pointerup', stopMove, { once: true })
|
||||
},
|
||||
[detailWidth],
|
||||
)
|
||||
|
||||
const mergeKnownWorkflowIds = useCallback((ids: string[]) => {
|
||||
setKnownWorkflowIds((prev) => {
|
||||
const merged = new Set(prev)
|
||||
let added = false
|
||||
for (const id of ids) {
|
||||
if (id && !merged.has(id)) {
|
||||
merged.add(id)
|
||||
added = true
|
||||
}
|
||||
}
|
||||
return added ? Array.from(merged).sort() : prev
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const { data } = await axios.get('/api/v1/ai/workflows')
|
||||
const items = Array.isArray(data?.items)
|
||||
? (data.items as Array<{ workflow_id?: string }>)
|
||||
: []
|
||||
mergeKnownWorkflowIds(items.map((w) => String(w.workflow_id || '')).filter(Boolean))
|
||||
} catch {
|
||||
// Ignore catalog pre-seed errors.
|
||||
}
|
||||
})()
|
||||
}, [mergeKnownWorkflowIds])
|
||||
|
||||
const loadRuns = useCallback(async () => {
|
||||
runsAbortRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
runsAbortRef.current = controller
|
||||
const seq = runsReqSeqRef.current + 1
|
||||
runsReqSeqRef.current = seq
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const { data } = await axios.get('/api/v1/ai/runs', {
|
||||
signal: controller.signal,
|
||||
params: {
|
||||
limit: 100,
|
||||
...(workflowFilter ? { workflow_id: workflowFilter } : {}),
|
||||
...(statusFilter ? { status: statusFilter } : {}),
|
||||
...(feedbackFilter ? { feedback: feedbackFilter } : {}),
|
||||
},
|
||||
})
|
||||
if (seq !== runsReqSeqRef.current || controller.signal.aborted) return
|
||||
const items = Array.isArray(data?.items) ? (data.items as RunItem[]) : []
|
||||
setRuns(items)
|
||||
if (items.length && !items.some((r) => r.id === selectedId)) {
|
||||
setSelectedId(items[0].id)
|
||||
}
|
||||
} catch {
|
||||
mergeKnownWorkflowIds(items.map((r) => r.workflow_id))
|
||||
setSelectedId((prev) => (items.some((r) => r.id === prev) ? prev : items[0]?.id || ''))
|
||||
} catch (err) {
|
||||
if (axios.isCancel(err) || controller.signal.aborted) return
|
||||
setRuns([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
if (seq === runsReqSeqRef.current) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [selectedId, statusFilter, workflowFilter])
|
||||
}, [feedbackFilter, mergeKnownWorkflowIds, statusFilter, workflowFilter])
|
||||
|
||||
useEffect(() => {
|
||||
void loadRuns()
|
||||
}, [loadRuns])
|
||||
|
||||
const workflowOptions = useMemo(() => {
|
||||
const ids = Array.from(new Set(runs.map((r) => r.workflow_id))).sort()
|
||||
return [
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
runsAbortRef.current?.abort()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const workflowOptions = useMemo(
|
||||
() => [
|
||||
{ value: '', label: tx('全部工作流', 'All workflows') },
|
||||
...ids.map((id) => ({ value: id, label: id })),
|
||||
]
|
||||
}, [runs, tx])
|
||||
...knownWorkflowIds.map((id) => ({ value: id, label: id })),
|
||||
],
|
||||
[knownWorkflowIds, tx],
|
||||
)
|
||||
|
||||
const filteredRuns = useMemo(() => {
|
||||
const q = searchText.trim().toLowerCase()
|
||||
@@ -87,19 +231,19 @@ export default function AdvisorRuns() {
|
||||
|
||||
return (
|
||||
<AdminLayout>
|
||||
<div className="an-page">
|
||||
<div className="an-page an-advisor-route">
|
||||
<div className="an-page__header">
|
||||
<div>
|
||||
<h1>{tx('AI 运行记录与轨迹', 'AI Run History & Traces')}</h1>
|
||||
<p>
|
||||
{tx(
|
||||
'审计 Playground、地球 Copilot 与位置解析 Agent 的每次工作流执行轨迹,支持一键在画布回放或发起 AI 调优。',
|
||||
'Inspect execution traces across Playground, Earth Copilot, and the Location Agent, with one-click canvas replay and AI tuning.',
|
||||
'查看各业务入口的 AI 工作流执行记录与工具调用轨迹,支持画布回放与调优。',
|
||||
'Inspect AI workflow execution traces across entry points with canvas replay and tuning.',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="an-toolbar">
|
||||
<Button variant="subtle" onClick={() => void loadRuns()} loading={loading}>
|
||||
<Button type="button" variant="subtle" onClick={() => void loadRuns()} loading={loading}>
|
||||
<RefreshCw size={15} />
|
||||
{tx('刷新', 'Refresh')}
|
||||
</Button>
|
||||
@@ -107,134 +251,259 @@ export default function AdvisorRuns() {
|
||||
</div>
|
||||
<div className="an-page__body">
|
||||
<div className="an-advisor-page">
|
||||
<div className="an-advisor-bar">
|
||||
<div className="an-advisor-bar__group">
|
||||
<div className="an-advisor-bar__select">
|
||||
<Select
|
||||
value={workflowFilter}
|
||||
ariaLabel={tx('按工作流筛选', 'Filter by workflow')}
|
||||
onValueChange={setWorkflowFilter}
|
||||
options={workflowOptions}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
value={statusFilter}
|
||||
ariaLabel={tx('按运行状态筛选', 'Filter by run status')}
|
||||
onValueChange={setStatusFilter}
|
||||
options={[
|
||||
{ value: '', label: tx('全部状态', 'All statuses') },
|
||||
{ value: 'completed', label: tx('成功 (completed)', 'completed') },
|
||||
{ value: 'failed', label: tx('失败 (failed)', 'failed') },
|
||||
]}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
className="an-advisor-bar__input"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
placeholder={tx('搜索问题 / Run ID…', 'Search question or Run ID...')}
|
||||
aria-label={tx('搜索运行记录', 'Search run history')}
|
||||
/>
|
||||
{(workflowFilter || statusFilter || searchText) ? (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
setWorkflowFilter('')
|
||||
setStatusFilter('')
|
||||
setSearchText('')
|
||||
}}
|
||||
title={tx('重置筛选', 'Reset filters')}
|
||||
aria-label={tx('重置筛选', 'Reset filters')}
|
||||
>
|
||||
<FilterX size={15} />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="an-advisor-badge">{tx(`共 ${filteredRuns.length} 条记录`, `${filteredRuns.length} runs`)}</span>
|
||||
</div>
|
||||
|
||||
<div className="an-runs-split">
|
||||
<section className="an-chat-pane">
|
||||
<div className="an-chat-messages">
|
||||
{filteredRuns.length === 0 ? (
|
||||
<div className="an-chat-empty">
|
||||
<span>{tx('暂无符合条件的工作流运行记录。', 'No workflow runs matched the active filters.')}</span>
|
||||
<div className="an-advisor-bar an-runs-filter-bar">
|
||||
<div className="an-runs-filters">
|
||||
<div className="an-advisor-bar__select">
|
||||
<Select
|
||||
value={workflowFilter}
|
||||
ariaLabel={tx('按工作流筛选', 'Filter by workflow')}
|
||||
onValueChange={setWorkflowFilter}
|
||||
options={workflowOptions}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
filteredRuns.map((run) => (
|
||||
<button
|
||||
key={run.id}
|
||||
type="button"
|
||||
className={`an-workflow-item${selectedRun?.id === run.id ? ' is-active' : ''}`}
|
||||
onClick={() => setSelectedId(run.id)}
|
||||
>
|
||||
<div className="an-rf-node__head">
|
||||
<span className="an-context-card__title">{run.workflow_id}</span>
|
||||
<span
|
||||
className={`an-advisor-badge ${run.status === 'completed' ? 'an-advisor-badge--success' : 'an-advisor-badge--danger'}`}
|
||||
>
|
||||
{run.status}
|
||||
</span>
|
||||
</div>
|
||||
<span className="an-context-card__meta">{run.question || run.id}</span>
|
||||
<div className="an-rf-node__meta">
|
||||
<span>{run.actor_key || 'system'}</span>
|
||||
<span>{(run.tool_trace || []).length} steps</span>
|
||||
<span>{run.started_at || ''}</span>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
<div className="an-advisor-bar__select an-advisor-bar__select--sm">
|
||||
<Select
|
||||
value={statusFilter}
|
||||
ariaLabel={tx('按运行状态筛选', 'Filter by run status')}
|
||||
onValueChange={setStatusFilter}
|
||||
options={[
|
||||
{ value: '', label: tx('全部状态', 'All statuses') },
|
||||
{ value: 'completed', label: tx('成功', 'Completed') },
|
||||
{ value: 'failed', label: tx('失败', 'Failed') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="an-advisor-bar__select an-advisor-bar__select--sm">
|
||||
<Select
|
||||
value={feedbackFilter}
|
||||
ariaLabel={tx('按反馈质量筛选', 'Filter by feedback')}
|
||||
onValueChange={setFeedbackFilter}
|
||||
options={[
|
||||
{ value: '', label: tx('全部评价', 'All feedback') },
|
||||
{ value: 'negative', label: tx('仅失败或差评', 'Failed / Downvoted') },
|
||||
{ value: 'positive', label: tx('仅点赞', 'Upvoted') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="an-runs-search-row">
|
||||
<input
|
||||
type="text"
|
||||
className="an-input"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
placeholder={tx('搜索问题或记录编号…', 'Search question or run ID...')}
|
||||
aria-label={tx('搜索运行记录', 'Search run history')}
|
||||
/>
|
||||
{workflowFilter || statusFilter || feedbackFilter || searchText ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
setWorkflowFilter('')
|
||||
setStatusFilter('')
|
||||
setFeedbackFilter('')
|
||||
setSearchText('')
|
||||
}}
|
||||
title={tx('重置筛选', 'Reset filters')}
|
||||
aria-label={tx('重置筛选', 'Reset filters')}
|
||||
>
|
||||
<FilterX size={15} />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<span className="an-wf-pill">
|
||||
{tx(`共 ${filteredRuns.length} 条记录`, `${filteredRuns.length} runs`)}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside className="an-drawer-pane" aria-label={tx('运行轨迹详情', 'Run trace detail')}>
|
||||
<header className="an-drawer-pane__header">
|
||||
<h3>{tx('运行轨迹详情', 'Run Trace Detail')}</h3>
|
||||
</header>
|
||||
<div className="an-drawer-pane__body">
|
||||
{selectedRun ? (
|
||||
<>
|
||||
<div className="an-context-card">
|
||||
<span className="an-context-card__title">{selectedRun.workflow_id}</span>
|
||||
<span className="an-context-card__meta">Run ID: {selectedRun.id}</span>
|
||||
<span>{selectedRun.question}</span>
|
||||
{selectedRun.error_message ? (
|
||||
<span className="an-advisor-badge an-advisor-badge--danger">{selectedRun.error_message}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="an-context-card">
|
||||
<span className="an-context-card__title">{tx('执行节点与工具轨迹', 'Node & Tool Trace')}</span>
|
||||
<div className="an-advisor-bar__group">
|
||||
{(selectedRun.tool_trace || []).map((step, idx) => (
|
||||
<span key={`${step}-${idx}`} className="an-advisor-badge an-advisor-badge--accent">
|
||||
{step}
|
||||
</span>
|
||||
))}
|
||||
<div
|
||||
ref={splitRef}
|
||||
className={`an-runs-split${mobileDetailOpen ? ' is-mobile-detail-open' : ''}`}
|
||||
style={{ '--an-runs-detail-width': `${detailWidth}px` } as CSSProperties}
|
||||
>
|
||||
<section className="an-chat-pane an-runs-list-pane" aria-label={tx('运行记录列表', 'Run history list')}>
|
||||
<Scrollbar className="an-chat-messages" axis="y">
|
||||
{filteredRuns.length === 0 ? (
|
||||
<div className="an-chat-empty">
|
||||
<span>{tx('暂无符合条件的工作流运行记录。', 'No workflow runs matched the active filters.')}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
filteredRuns.map((run) => {
|
||||
const tel = extractRunTelemetry(run)
|
||||
return (
|
||||
<button
|
||||
key={run.id}
|
||||
type="button"
|
||||
className={`an-workflow-item${selectedRun?.id === run.id ? ' is-active' : ''}`}
|
||||
onClick={() => {
|
||||
setSelectedId(run.id)
|
||||
setMobileDetailOpen(true)
|
||||
}}
|
||||
>
|
||||
<div className="an-workflow-item__head">
|
||||
<span className="an-workflow-item__title">{run.workflow_id}</span>
|
||||
<div className="an-advisor-bar__group">
|
||||
{tel.rating === 1 ? (
|
||||
<span className="an-wf-pill an-wf-pill--success" title={tx('点赞', 'Upvoted')}>
|
||||
<ThumbsUp size={10} />
|
||||
</span>
|
||||
) : null}
|
||||
{tel.rating === -1 ? (
|
||||
<span className="an-wf-pill an-wf-pill--danger" title={tx('差评', 'Downvoted')}>
|
||||
<ThumbsDown size={10} />
|
||||
</span>
|
||||
) : null}
|
||||
<span
|
||||
className={`an-wf-pill ${run.status === 'completed' ? 'an-wf-pill--success' : 'an-wf-pill--danger'}`}
|
||||
>
|
||||
{run.status === 'completed'
|
||||
? tx('成功', 'Completed')
|
||||
: run.status === 'failed'
|
||||
? tx('失败', 'Failed')
|
||||
: run.status}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="an-context-card__meta">{run.question || run.id}</span>
|
||||
<div className="an-rf-node__meta">
|
||||
<span>{run.actor_key || tx('系统', 'system')}</span>
|
||||
<span>
|
||||
{isEn
|
||||
? `${(run.tool_trace || []).length} steps`
|
||||
: `${(run.tool_trace || []).length} 步`}
|
||||
</span>
|
||||
{tel.revision ? <span>v{tel.revision}</span> : null}
|
||||
{tel.modelUsed ? <span>{tel.modelUsed}</span> : null}
|
||||
{tel.latencyMs !== null ? <span>{tel.latencyMs}ms</span> : null}
|
||||
{run.started_at ? <span>{formatRunTime(run.started_at)}</span> : null}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</Scrollbar>
|
||||
</section>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="an-detail-resizer"
|
||||
onPointerDown={startDetailResize}
|
||||
aria-label={tx('拖拽调整右侧运行详情宽度', 'Resize run detail panel')}
|
||||
title={tx('拖拽调整详情宽度', 'Resize detail panel')}
|
||||
/>
|
||||
|
||||
<aside className="an-drawer-pane an-runs-detail-pane" aria-label={tx('运行轨迹详情', 'Run trace detail')}>
|
||||
<header className="an-drawer-pane__header">
|
||||
<div className="an-advisor-bar__group">
|
||||
<Link to={`/advisor/workflows?workflow=${encodeURIComponent(selectedRun.workflow_id)}&run=${encodeURIComponent(selectedRun.id)}`}>
|
||||
<Button variant="subtle">
|
||||
<GitBranch size={14} />
|
||||
{tx('在画布回放', 'Replay on Canvas')}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to={`/advisor/workflows?workflow=${encodeURIComponent(selectedRun.workflow_id)}&run=${encodeURIComponent(selectedRun.id)}&tab=optimize`}>
|
||||
<Button variant="primary">
|
||||
<Sparkles size={14} />
|
||||
{tx('AI 调优此工作流', 'Optimize Workflow')}
|
||||
</Button>
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="an-advisor-mobile-back"
|
||||
onClick={() => setMobileDetailOpen(false)}
|
||||
>
|
||||
<ArrowLeft size={13} />
|
||||
{tx('返回列表', 'Back to Runs')}
|
||||
</button>
|
||||
<h3>{tx('运行轨迹详情', 'Run Trace Detail')}</h3>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<span className="an-context-card__meta">{tx('选择左侧任意运行记录查看节点轨迹。', 'Select a run on the left to inspect its trace.')}</span>
|
||||
)}
|
||||
</header>
|
||||
<Scrollbar className="an-drawer-pane__body" axis="y">
|
||||
{selectedRun ? (() => {
|
||||
const selectedTel = extractRunTelemetry(selectedRun)
|
||||
return (
|
||||
<>
|
||||
<div className="an-context-card">
|
||||
<span className="an-context-card__title">{selectedRun.workflow_id}</span>
|
||||
<span className="an-context-card__meta">{tx('记录编号:', 'Run ID: ')}{selectedRun.id}</span>
|
||||
{selectedRun.started_at ? (
|
||||
<span className="an-context-card__meta">
|
||||
{tx('开始时间:', 'Started: ')}
|
||||
{formatRunTime(selectedRun.started_at)}
|
||||
</span>
|
||||
) : null}
|
||||
<div className="an-advisor-bar__group">
|
||||
{selectedTel.revision ? (
|
||||
<span className="an-wf-pill an-wf-pill--rev">v{selectedTel.revision}</span>
|
||||
) : null}
|
||||
{selectedTel.modelUsed ? (
|
||||
<span className="an-wf-pill">{selectedTel.modelUsed}</span>
|
||||
) : null}
|
||||
{selectedTel.latencyMs !== null ? (
|
||||
<span className="an-wf-pill">{selectedTel.latencyMs} ms</span>
|
||||
) : null}
|
||||
{selectedTel.rating === 1 ? (
|
||||
<span className="an-wf-pill an-wf-pill--success">
|
||||
<ThumbsUp size={10} /> {tx('点赞', 'Upvoted')}
|
||||
</span>
|
||||
) : null}
|
||||
{selectedTel.rating === -1 ? (
|
||||
<span className="an-wf-pill an-wf-pill--danger">
|
||||
<ThumbsDown size={10} /> {tx('差评', 'Downvoted')}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{selectedTel.feedbackNote ? (
|
||||
<span className="an-wf-pill an-wf-pill--warning an-wf-pill--block">
|
||||
{tx('反馈备注:', 'Feedback note: ')}{selectedTel.feedbackNote}
|
||||
</span>
|
||||
) : null}
|
||||
<span>{selectedRun.question}</span>
|
||||
{selectedRun.error_message ? (
|
||||
<span className="an-wf-pill an-wf-pill--danger an-wf-pill--block">
|
||||
{selectedRun.error_message}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="an-context-card">
|
||||
<span className="an-context-card__title">
|
||||
{tx('执行节点与工具轨迹', 'Node & Tool Trace')}
|
||||
</span>
|
||||
{(selectedRun.tool_trace || []).length === 0 ? (
|
||||
<span className="an-context-card__meta">
|
||||
{tx('本次运行未记录额外工具调用。', 'No extra tool trace recorded for this run.')}
|
||||
</span>
|
||||
) : (
|
||||
<div className="an-advisor-bar__group">
|
||||
{(selectedRun.tool_trace || []).map((step, idx) => (
|
||||
<span
|
||||
key={`${step}-${idx}`}
|
||||
className="an-wf-pill an-wf-pill--accent"
|
||||
>
|
||||
{step}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="an-advisor-bar__group">
|
||||
<Link
|
||||
to={`/advisor/workflows?workflow=${encodeURIComponent(selectedRun.workflow_id)}&run=${encodeURIComponent(selectedRun.id)}`}
|
||||
>
|
||||
<Button type="button" variant="subtle">
|
||||
<GitBranch size={14} />
|
||||
{tx('在画布回放', 'Replay on Canvas')}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link
|
||||
to={`/advisor/workflows?workflow=${encodeURIComponent(selectedRun.workflow_id)}&run=${encodeURIComponent(selectedRun.id)}&tab=optimize`}
|
||||
>
|
||||
<Button type="button" variant="primary">
|
||||
<Sparkles size={14} />
|
||||
{tx('AI 调优此工作流', 'Optimize Workflow')}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
})() : (
|
||||
<span className="an-context-card__meta">
|
||||
{tx('选择任意运行记录查看节点轨迹。', 'Select a run to inspect its trace.')}
|
||||
</span>
|
||||
)}
|
||||
</Scrollbar>
|
||||
</aside>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ import axios from 'axios'
|
||||
import { Ban, Check, Copy, Download, KeyRound, Plus, RefreshCw, Trash2 } from 'lucide-react'
|
||||
import { describeApiError } from '../../i18n/api-errors'
|
||||
import { useLocale } from '../../i18n/locale'
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { Badge } from '../components/ui/badge'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { ConfirmDialog, Dialog } from '../components/ui/dialog'
|
||||
@@ -32,7 +33,7 @@ interface ApiKeyListResponse {
|
||||
}
|
||||
|
||||
const SCOPE_LABELS: Record<string, { zh: string; en: string }> = {
|
||||
'earth:all_read': { zh: 'Earth 全只读 + WS(UE5/内部推荐)', en: 'Earth all read + WS (UE5/Internal)' },
|
||||
'earth:all_read': { zh: '地球全量只读(外部接入推荐)', en: 'Earth all read (Recommended)' },
|
||||
'visualization:read': { zh: '可视化 GeoJSON / 瓦片', en: 'Visualization GeoJSON / terrain' },
|
||||
'layers:read': { zh: '分层视口快照', en: 'Viewport layers' },
|
||||
'vessels:read': { zh: '船舶 AIS 快照', en: 'AIS vessel snapshot' },
|
||||
@@ -205,7 +206,7 @@ export function ApiKeySettings({ active }: { active: boolean }) {
|
||||
|
||||
<div className="an-panel-body">
|
||||
{items.length ? (
|
||||
<div className="an-table-wrap">
|
||||
<Scrollbar className="an-table-wrap">
|
||||
<table className="an-table">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -255,11 +256,11 @@ export function ApiKeySettings({ active }: { active: boolean }) {
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Scrollbar>
|
||||
) : (
|
||||
<EmptyState
|
||||
title={tr('暂无 API 密钥', 'No API keys yet')}
|
||||
description={tr('点击右上角“新建密钥”,可为 UE5 同事或外部合作方签发长期或限时访问凭据。', 'Create an API key for UE5 clients or external services.')}
|
||||
description={tr('点击右上角“新建密钥”,为客户端或外部服务签发访问凭据。', 'Create an API key for clients or external services.')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -283,7 +284,7 @@ export function ApiKeySettings({ active }: { active: boolean }) {
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder={tr('例如:UE5-研发环境 / 合作方只读', 'e.g. UE5-Client / Partner-Read')}
|
||||
placeholder={tr('例如:外部接入 / 只读服务', 'e.g. Client-Prod / Partner-Read')}
|
||||
/>
|
||||
</label>
|
||||
|
||||
@@ -383,11 +384,11 @@ export function ApiKeySettings({ active }: { active: boolean }) {
|
||||
<Input readOnly value={createdKey.apiKey} />
|
||||
</label>
|
||||
<label className="an-field">
|
||||
<span>{tr('HTTP 调用示例(curl / UE5 Header)', 'HTTP Header Example')}</span>
|
||||
<span>{tr('HTTP 请求示例', 'HTTP Header Example')}</span>
|
||||
<pre className="an-raw-json">{`curl -H "X-API-Key: ${createdKey.apiKey}" \\\n https://api.rclaw.top/api/v1/visualization/geo/summary`}</pre>
|
||||
</label>
|
||||
<label className="an-field">
|
||||
<span>{tr('UE5 WebSocket 地址示例', 'UE5 WebSocket URL Example')}</span>
|
||||
<span>{tr('WebSocket 地址示例', 'WebSocket URL Example')}</span>
|
||||
<pre className="an-raw-json">{`wss://api.rclaw.top/ws?api_key=${createdKey.apiKey}`}</pre>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from
|
||||
import axios from 'axios'
|
||||
import { ImagePlus, Link2, Plus, RefreshCw, Save, Trash2 } from 'lucide-react'
|
||||
import { useLocale } from '../../i18n/locale'
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { ConfirmDialog } from '../components/ui/dialog'
|
||||
import { Input } from '../components/ui/input'
|
||||
@@ -130,7 +131,7 @@ export function CardImageSettings({active}:{active:boolean}) {
|
||||
{errorText?<p className="an-card-images-error" role="alert">{errorText}</p>:null}
|
||||
{message?<p className="an-card-images-message" role="status">{message}</p>:null}
|
||||
{!draft?<p className="an-card-images-message">{busy?t('加载中…','Loading…'):t('暂无可用配置','Configuration unavailable')}</p>:<fieldset disabled={busy} className="an-card-images-workspace">
|
||||
<div className="an-card-images-list">
|
||||
<Scrollbar className="an-card-images-list" axis="y">
|
||||
{view==='assets'?<>
|
||||
<div className="an-card-images-list-actions"><Button variant="subtle" disabled={busy} onClick={()=>uploadRef.current?.click()}><ImagePlus size={16}/>{t('上传','Upload')}</Button><Button size="icon" variant="subtle" title={t('添加图片地址','Add image URL')} aria-label={t('添加图片地址','Add image URL')} onClick={addUrl}><Plus size={16}/></Button></div>
|
||||
<input ref={uploadRef} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={event=>{const file=event.target.files?.[0];if(file)void upload(file)}}/>
|
||||
@@ -141,8 +142,8 @@ export function CardImageSettings({active}:{active:boolean}) {
|
||||
<Button variant="subtle" onClick={()=>{setEditingRuleId(null);setTarget('');setTargetLabel('');setSearch('');setRuleAsset('');setRuleEnabled(true)}}><Plus size={16}/>{t('新关联','New assignment')}</Button>
|
||||
{draft.rules.map(rule=><div className="an-card-images-rule-row" key={rule.id}><button type="button" onClick={()=>selectRule(rule)}><span>{rule.label || rule.value}</span><small>{types.find(item=>item.value===rule.entity_type)?.label} · {scopes.find(item=>item.value===rule.scope)?.label}{!rule.enabled?` · ${t('停用','Disabled')}`:''}</small></button><Button size="icon" variant="subtle" title={t('解除关联','Remove assignment')} aria-label={t('解除关联','Remove assignment')} onClick={()=>{edit({...draft,rules:draft.rules.filter(item=>item.id!==rule.id)});if(editingRuleId===rule.id)setEditingRuleId(null)}}><Trash2 size={14}/></Button></div>)}
|
||||
</>}
|
||||
</div>
|
||||
<div className="an-card-images-editor">
|
||||
</Scrollbar>
|
||||
<Scrollbar className="an-card-images-editor" axis="y">
|
||||
{view==='assets' && asset?<>
|
||||
<div className="an-card-images-fields">
|
||||
<Field label={t('图片名称','Image name')}><Input value={asset.title} onChange={event=>patchAsset({title:event.target.value})}/></Field>
|
||||
@@ -197,7 +198,7 @@ export function CardImageSettings({active}:{active:boolean}) {
|
||||
<Button variant="subtle" disabled={!previewTarget} onClick={()=>void preview()}>{t('检查匹配','Check match')}</Button>
|
||||
{resolution?<><p role="status">{resolution.suppressed?t('此物件已明确禁用配图','Image explicitly disabled for this object'):resolution.match?`${t('命中规则','Matched rule')}: ${scopes.find(item=>item.value===resolution.match?.scope)?.label} · ${resolution.match.value}`:t('未匹配图片,显示纯数据卡片','No image matched; showing a data-only card')}</p><CardImagePreview asset={resolution.image} title={resolution.entity.name} english={english}/></>:null}
|
||||
</>:<p>{t('选择或上传一张图片。','Select or upload an image.')}</p>}
|
||||
</div>
|
||||
</Scrollbar>
|
||||
</fieldset>}
|
||||
<ConfirmDialog open={Boolean(confirmation)} onOpenChange={open=>{if(!open)setConfirmation(null)}} title={t('确认操作','Confirm action')} description={confirmation?.label} onConfirm={()=>confirmation?.run()}/>
|
||||
</Panel>
|
||||
|
||||
@@ -50,7 +50,7 @@ function validationMessage(message: string, english: boolean) {
|
||||
'Review date must not be in the future': '核验日期不能晚于今天。',
|
||||
'Use countries from the canonical compute catalog, not regional totals': '请使用国家观测,不能直接录入区域合计。',
|
||||
'Use a report URL without credentials (maximum 2000 characters)': '报告链接不能包含账号密码,长度不能超过 2000 字符。',
|
||||
'Structure scope must be GLOBAL or a canonical country code': '算力结构范围必须为 GLOBAL 或标准国家代码。',
|
||||
'Structure scope must be GLOBAL or a canonical country code': '算力结构范围必须为全球或标准国家代码。',
|
||||
'Internal compute structure shares must total 100 percent': '智能算力与通用/超算占比之和必须等于 100%。',
|
||||
'Each scope/year may have only one structure observation': '同一范围、同一年只能保留一条算力结构观测。',
|
||||
'Milestone IDs must be unique': '历史里程碑标识不能重复。',
|
||||
@@ -259,7 +259,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
|
||||
})) || []
|
||||
|
||||
const scopeOptions = [
|
||||
{ value: 'GLOBAL', label: t('全球合计 (GLOBAL)', 'Global total (GLOBAL)') },
|
||||
{ value: 'GLOBAL', label: t('全球合计', 'Global total') },
|
||||
...(saved?.countries.map(country => ({
|
||||
value: country.code,
|
||||
label: `${english ? country.name_en : country.name} (${country.code})`,
|
||||
@@ -403,7 +403,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
|
||||
</p>
|
||||
{draft.structures.map((row, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
|
||||
<summary>
|
||||
{row.scope} · {row.period_label || row.year} · AI {row.intelligent_share}% / Gen+HPC {row.general_and_super_share}%
|
||||
{row.scope === 'GLOBAL' ? t('全球', 'GLOBAL') : row.scope} · {row.period_label || row.year} · AI {row.intelligent_share}% / {t('通用与超算', 'Gen+HPC')} {row.general_and_super_share}%
|
||||
</summary>
|
||||
<div className="an-compute-fields an-compute-fields--three">
|
||||
<Field title={t('统计范围', 'Scope')}>
|
||||
@@ -548,7 +548,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
|
||||
</details>)}
|
||||
|
||||
<div className="an-compute-section-heading">
|
||||
<span>{t('中国八大国家算力枢纽(“东数西算” 3D 下钻图层)', 'China 8 National Compute Hubs (3D East-West synergy layer)')}</span>
|
||||
<span>{t('中国八大国家算力枢纽', 'China 8 National Compute Hubs')}</span>
|
||||
</div>
|
||||
{draft.national_hubs.map((hub, index) => <details className="an-compute-row" key={hub.id || index}>
|
||||
<summary>
|
||||
@@ -615,8 +615,8 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
|
||||
</> : <>
|
||||
<p className="an-compute-lead">
|
||||
{t(
|
||||
'辅助采集待审队列:粘贴白皮书/研报摘录后自动提取国家算力份额候选,管理员人工审核通过后一键导入草稿,严禁未审直上大屏。',
|
||||
'Assisted extraction review queue: extract candidate shares from report excerpts, review manually, and import approved items into draft. Unreviewed items never go live.',
|
||||
'粘贴报告摘录后提取算力份额候选项,经人工审核后再导入草稿。',
|
||||
'Extract candidate shares from report excerpts, review manually, and import approved items into draft.',
|
||||
)}
|
||||
</p>
|
||||
<div className="an-compute-candidate-box">
|
||||
|
||||
@@ -56,11 +56,11 @@ type RestartAction = 'restart-backend' | 'restart-frontend' | 'restart-ai-provid
|
||||
type RestartStage = 'confirming' | 'waiting_for_shutdown' | 'waiting_for_recovery' | 'recovered' | 'failed' | 'timeout'
|
||||
|
||||
const RESTART_ACTION_OPTIONS: Array<{ value: RestartAction; label: string; description: string; command: string }> = [
|
||||
{ value: 'restart-backend', label: '重启后端', description: '只重启后端服务,页面通常会短暂失联后自动恢复。', command: './planet.sh restart -b' },
|
||||
{ value: 'restart-frontend', label: '重启前端', description: '只重启前端开发服务,页面会短暂不可用,恢复后自动刷新。', command: './planet.sh restart -f' },
|
||||
{ value: 'restart-ai-provider', label: '重启 AI Provider', description: '只重启 AI Provider 适配服务,前端页面通常保持在线。', command: './planet.sh restart -a' },
|
||||
{ value: 'restart-database', label: '重启数据库', description: '重启 PostgreSQL 和 Redis 容器,前端页面保持在线。', command: './planet.sh restart -d' },
|
||||
{ value: 'restart-system', label: '完全重启', description: '重启前后端和相关服务,页面会短暂不可用,恢复后自动刷新。', command: './planet.sh restart' },
|
||||
{ value: 'restart-backend', label: '重启后端', description: '重启后端服务,页面会短暂断开后自动恢复。', command: './planet.sh restart -b' },
|
||||
{ value: 'restart-frontend', label: '重启前端', description: '重启前端服务,恢复后将自动刷新页面。', command: './planet.sh restart -f' },
|
||||
{ value: 'restart-ai-provider', label: '重启 AI 服务', description: '重启 AI 适配服务。', command: './planet.sh restart -a' },
|
||||
{ value: 'restart-database', label: '重启数据库', description: '重启 PostgreSQL 和 Redis 容器。', command: './planet.sh restart -d' },
|
||||
{ value: 'restart-system', label: '完全重启', description: '重启前后端及相关服务,恢复后将自动刷新页面。', command: './planet.sh restart' },
|
||||
]
|
||||
|
||||
let cachedDashboardStats: Stats | null = null
|
||||
@@ -143,7 +143,7 @@ function DashboardContent() {
|
||||
|
||||
const handleRestartAction = async () => {
|
||||
setRestartSubmitting(true)
|
||||
setRestartLogs(['[ctl] preparing restart task'])
|
||||
setRestartLogs(['正在准备重启任务...'])
|
||||
try {
|
||||
const res = await axios.post<RestartTask>('/api/v1/system/restart-tasks', { action: restartAction })
|
||||
setRestartTaskId(res.data.task_id)
|
||||
|
||||
@@ -62,7 +62,7 @@ const DETAIL_BASE_FIELDS = ['source', 'data_type', 'source_id', 'country', 'city
|
||||
const DETAIL_FIELD_LABELS: Record<string, string> = {
|
||||
source: '数据源',
|
||||
data_type: '数据类型',
|
||||
source_id: '原始ID',
|
||||
source_id: '原始 ID',
|
||||
country: '国家',
|
||||
city: '城市',
|
||||
collected_at: '采集时间',
|
||||
@@ -119,7 +119,7 @@ function dataTypeLabel(type: string) {
|
||||
generic_records: '通用记录',
|
||||
ixp: '互联网交换点',
|
||||
news_item: '新闻条目',
|
||||
news_live_stream: '新闻直播源',
|
||||
news_live_stream: 'Live 新闻源',
|
||||
prefix_geography: '前缀地理位置',
|
||||
satellite_tle: '卫星轨道根数',
|
||||
space: '空间',
|
||||
@@ -400,8 +400,8 @@ export default function DataList() {
|
||||
<p>浏览采集结果、筛选数据源和查看原始元数据。</p>
|
||||
</div>
|
||||
<div className="an-toolbar">
|
||||
<Badge tone="blue">结果 {total.toLocaleString()} 条</Badge>
|
||||
<Badge tone="slate">筛选 {activeFilterCount} 项</Badge>
|
||||
<Badge tone="blue">{`结果 ${total.toLocaleString()} 条`}</Badge>
|
||||
<Badge tone="slate">{`筛选 ${activeFilterCount} 项`}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -437,7 +437,7 @@ export default function DataList() {
|
||||
<CardHeader className="an-data-table-card__header">
|
||||
<div>
|
||||
<CardTitle>数据列表</CardTitle>
|
||||
<p>共 {total.toLocaleString()} 条结果</p>
|
||||
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
|
||||
</div>
|
||||
<div className="an-toolbar">
|
||||
<Button size="sm" variant="subtle" onClick={handleReset}><X size={14} />清空</Button>
|
||||
|
||||
@@ -568,7 +568,7 @@ export default function Logs() {
|
||||
>
|
||||
<strong>{group.message}</strong>
|
||||
<span>{group.category || group.event || group.module || group.source}</span>
|
||||
<StatusText tone={levelTone(group.level)}>{group.count} 次</StatusText>
|
||||
<StatusText tone={levelTone(group.level)}>{`${group.count} 次`}</StatusText>
|
||||
</button>
|
||||
))}
|
||||
{!groups.length && !logLoading ? <EmptyState title="暂无重复日志" /> : null}
|
||||
@@ -600,7 +600,7 @@ export default function Logs() {
|
||||
<p>{mode === 'grouped' ? '点击左侧聚合项查看每次发生时间。' : mode === 'audit' ? '管理员敏感操作和安全审计记录。' : (selectedSourceInfo?.description || '选择日志源后读取快照。')}</p>
|
||||
</div>
|
||||
<div className="an-toolbar">
|
||||
{mode === 'grouped' ? <Badge tone="blue">{selectedGroup ? groupEvents.length : groups.length} 条</Badge> : snapshot ? <Badge tone="blue">{snapshot.line_count} 行</Badge> : null}
|
||||
{mode === 'grouped' ? <Badge tone="blue">{`${selectedGroup ? groupEvents.length : groups.length} 条`}</Badge> : snapshot ? <Badge tone="blue">{`${snapshot.line_count} 行`}</Badge> : null}
|
||||
{followEnabled ? <Badge tone={followConnected ? 'green' : 'amber'}>{followConnected ? '跟随中' : '连接中'}</Badge> : null}
|
||||
<Button size="icon" variant="subtle" onClick={copyLogs} disabled={mode === 'grouped' ? !groupEvents.length : !snapshot?.lines?.length} aria-label="复制日志" title="复制日志">
|
||||
<Copy size={15} />
|
||||
@@ -639,15 +639,15 @@ export default function Logs() {
|
||||
<div className="an-log-group-detail">
|
||||
<div className="an-log-group-summary">
|
||||
<strong>{selectedGroup.message}</strong>
|
||||
<span>指纹 {selectedGroup.fingerprint}</span>
|
||||
<span>首次 {formatDateTime(selectedGroup.first_seen_at)} · 最近 {formatDateTime(selectedGroup.last_seen_at)}</span>
|
||||
<span>{`指纹 ${selectedGroup.fingerprint}`}</span>
|
||||
<span>{`首次 ${formatDateTime(selectedGroup.first_seen_at)} · 最近 ${formatDateTime(selectedGroup.last_seen_at)}`}</span>
|
||||
</div>
|
||||
{groupEvents.map((event) => (
|
||||
<div className="an-log-occurrence" key={event.id}>
|
||||
<div>
|
||||
<strong>{formatDateTime(event.occurred_at)}</strong>
|
||||
<StatusText tone={levelTone(event.level)}>{event.level}</StatusText>
|
||||
{event.occurrence_count > 1 ? <Badge tone="blue">{event.occurrence_count} 次</Badge> : null}
|
||||
{event.occurrence_count > 1 ? <Badge tone="blue">{`${event.occurrence_count} 次`}</Badge> : null}
|
||||
</div>
|
||||
<p>{event.message}</p>
|
||||
<pre>{stringifyContext(event.context)}</pre>
|
||||
@@ -657,7 +657,7 @@ export default function Logs() {
|
||||
</div>
|
||||
</Scrollbar>
|
||||
) : mode === 'grouped' ? (
|
||||
<EmptyState title="选择一组重复日志" description="左侧展示按 fingerprint 聚合后的运行时错误。" />
|
||||
<EmptyState title="选择一组重复日志" description="点击左侧聚合项查看每次发生明细。" />
|
||||
) : snapshot?.lines?.length ? (
|
||||
<Scrollbar className="an-log-reader__scroll" viewportRef={scrollContainerRef}>
|
||||
<pre>{snapshot.lines.join('\n')}</pre>
|
||||
|
||||
@@ -22,13 +22,11 @@ import {
|
||||
ImageUp,
|
||||
Layers,
|
||||
ListChecks,
|
||||
Radio,
|
||||
Redo2,
|
||||
RefreshCw,
|
||||
Save,
|
||||
Search,
|
||||
Settings2,
|
||||
ShieldAlert,
|
||||
EyeOff,
|
||||
Sparkles,
|
||||
Square,
|
||||
@@ -41,7 +39,7 @@ import MarkdownRenderer from '../../components/MarkdownRenderer/MarkdownRenderer
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { useWebSocket } from '../../hooks/useWebSocket'
|
||||
import { describeApiError, localizeApiMessage } from '../../i18n/api-errors'
|
||||
import { legacyUiTextEnUS } from '../../i18n/legacy-ui'
|
||||
import { translateLegacyAdminText } from '../../i18n/LegacyI18nBridge'
|
||||
import { useLocale, type SupportedLocale } from '../../i18n/locale'
|
||||
import { AdminLayout } from '../components/layout/AdminLayout'
|
||||
import { DataTable } from '../components/data-table/DataTable'
|
||||
@@ -245,10 +243,6 @@ function text(value: unknown, fallback = '-') {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const legacyUiTextZhCN = Object.fromEntries(
|
||||
Object.entries(legacyUiTextEnUS).map(([source, target]) => [target, source]),
|
||||
)
|
||||
|
||||
const editableValueTextEnUS: Record<string, string> = {
|
||||
'智能星球': 'Intelligent Planet',
|
||||
'智能星球计划': 'Intelligent Planet Program',
|
||||
@@ -263,17 +257,7 @@ const editableValueTextZhCN = Object.fromEntries(
|
||||
)
|
||||
|
||||
function localizeAdminText(value: string, locale: SupportedLocale) {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return value
|
||||
const dictionary = locale === 'en-US' ? legacyUiTextEnUS : legacyUiTextZhCN
|
||||
const translated = dictionary[trimmed]
|
||||
if (translated) return value.replace(trimmed, translated)
|
||||
if (trimmed.length > 240) return value
|
||||
const entries = Object.entries(dictionary)
|
||||
.filter(([source]) => source && trimmed.includes(source))
|
||||
.sort(([left], [right]) => right.length - left.length)
|
||||
if (!entries.length) return value
|
||||
return entries.reduce((next, [source, target]) => next.split(source).join(target), value)
|
||||
return translateLegacyAdminText(value, locale)
|
||||
}
|
||||
|
||||
function localizeEditableValue(_key: string, value: unknown, locale: SupportedLocale) {
|
||||
@@ -2025,7 +2009,7 @@ function EarthBrandPreview({ record }: { record: AnyRecord }) {
|
||||
const brandVariant = locale === 'en-US' ? 'en' : 'zh'
|
||||
|
||||
return (
|
||||
<div className="an-earth-brand-preview" aria-label={localizeAdminText('Earth 左上角品牌实际渲染预览', locale)}>
|
||||
<div className="an-earth-brand-preview" aria-label={localizeAdminText('智能星球左上角品牌预览', locale)}>
|
||||
<div className="an-earth-brand-preview__space">
|
||||
<div className="earth-left-column">
|
||||
<div className="hud-panel hud-panel-brand">
|
||||
@@ -2052,6 +2036,8 @@ function EarthBrandPreview({ record }: { record: AnyRecord }) {
|
||||
}
|
||||
|
||||
function TVEarthPreview({ source, tv }: { source: AnyRecord; tv: AnyRecord }) {
|
||||
const { locale } = useLocale()
|
||||
const isEn = locale === 'en-US'
|
||||
const embeddedUrl = tvEmbeddedUrl(source)
|
||||
const videoUrl = tvProxyVideoUrl(source)
|
||||
const externalUrl = tvExternalUrl(source)
|
||||
@@ -2059,30 +2045,34 @@ function TVEarthPreview({ source, tv }: { source: AnyRecord; tv: AnyRecord }) {
|
||||
const sourceCount = Array.isArray(tv.sources) ? tv.sources.length : Number(tv.source_count || 0)
|
||||
const latestUpdatedAt = text(tv.latest_updated_at || tv.generated_at, '')
|
||||
const latestLabel = latestUpdatedAt
|
||||
? `最近同步 ${new Date(latestUpdatedAt).toLocaleString('zh-CN', { hour12: false })}`
|
||||
: '尚未同步'
|
||||
const statusLabel = playable ? '直播加载中' : externalUrl ? '当前频道仅支持外部打开' : '暂无可播放直播源'
|
||||
? `${isEn ? 'Latest sync ' : '最近同步 '}${new Date(latestUpdatedAt).toLocaleString(isEn ? 'en-US' : 'zh-CN', { hour12: false })}`
|
||||
: isEn ? 'Not synced yet' : '尚未同步'
|
||||
const statusLabel = playable
|
||||
? isEn ? 'Loading stream' : '直播加载中'
|
||||
: externalUrl
|
||||
? isEn ? 'External link only' : '当前频道仅支持外部打开'
|
||||
: isEn ? 'No playable stream' : '暂无可播放直播源'
|
||||
const statusClass = playable ? 'tv-panel-tag tv-panel-tag--status' : externalUrl ? 'tv-panel-tag tv-panel-tag--warning' : 'tv-panel-tag tv-panel-tag--error'
|
||||
|
||||
return (
|
||||
<div className="an-tv-earth-preview" aria-label="Earth TV 实际渲染预览">
|
||||
<div className="an-tv-earth-preview" aria-label={localizeAdminText('电视直播预览', locale)}>
|
||||
<div className="hud-panel hud-panel-media">
|
||||
<div className="hud-panel__header">
|
||||
<div className="hud-panel__title-group">
|
||||
<span className="hud-panel-title hud-panel__title tv-panel-header-title">Live 新闻</span>
|
||||
<span className="hud-panel-title hud-panel__title tv-panel-header-title">{isEn ? 'Live News' : 'Live 新闻'}</span>
|
||||
</div>
|
||||
<div className="tv-panel-header-controls tv-panel-header-controls--live">
|
||||
<select className="tv-panel-select" value={text(source.id, '')} aria-label="选择新闻直播源" onChange={() => undefined}>
|
||||
<select className="tv-panel-select" value={text(source.id, '')} aria-label={localizeAdminText('选择 Live 新闻源', locale)} onChange={() => undefined}>
|
||||
<option value={text(source.id, '')}>
|
||||
{text(source.name, '暂无可用频道')}
|
||||
{text(source.id, '') === text(tv.default_source_id, '') ? ' · 默认' : ''}
|
||||
{text(source.name, isEn ? 'No channel available' : '暂无可用频道')}
|
||||
{text(source.id, '') === text(tv.default_source_id, '') ? (isEn ? ' · Default' : ' · 默认') : ''}
|
||||
</option>
|
||||
</select>
|
||||
<div className="tv-panel-toolbar-actions">
|
||||
<button className="hud-panel__action hud-panel__action--refresh" type="button" title="刷新直播源" aria-label="刷新直播源">
|
||||
<button className="hud-panel__action hud-panel__action--refresh" type="button" title={localizeAdminText('刷新直播源', locale)} aria-label={localizeAdminText('刷新直播源', locale)}>
|
||||
<RefreshCw size={14} />
|
||||
</button>
|
||||
<button className="hud-panel__action hud-panel__action--external" type="button" title="访问官网" aria-label="访问官网" disabled={!externalUrl}>
|
||||
<button className="hud-panel__action hud-panel__action--external" type="button" title={localizeAdminText('访问官网', locale)} aria-label={localizeAdminText('访问官网', locale)} disabled={!externalUrl}>
|
||||
<Globe2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
@@ -2100,7 +2090,7 @@ function TVEarthPreview({ source, tv }: { source: AnyRecord; tv: AnyRecord }) {
|
||||
<div className="tv-panel-subtitle">
|
||||
{text(source.provider, '-')}{' · '}{text(source.region, '-')}{' · '}{text(source.language, '-')}{' · '}{text(source.source_type, '-')}
|
||||
</div>
|
||||
<div className="tv-panel-catalog">共 {sourceCount || 0} 个频道 · {latestLabel}</div>
|
||||
<div className="tv-panel-catalog">{`共 ${sourceCount || 0} 个频道 · ${latestLabel}`}</div>
|
||||
<div className="tv-panel-notes">{text(source.notes, '支持后台配置默认源与采集器补充源。')}</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2792,8 +2782,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
const [brandAssetUploadingTarget, setBrandAssetUploadingTarget] = useState<BrandAssetTargetKey | null>(null)
|
||||
const [newsImportFile, setNewsImportFile] = useState<File | null>(null)
|
||||
const newsImportInputRef = useRef<HTMLInputElement>(null)
|
||||
const [resolveTarget, setResolveTarget] = useState<TableRecord | null>(null)
|
||||
const [resolutionText, setResolutionText] = useState('已处理')
|
||||
const [credentialGuide, setCredentialGuide] = useState<AnyRecord | null>(null)
|
||||
const [credentialGuideOpen, setCredentialGuideOpen] = useState(false)
|
||||
const [credentialGuidePosition, setCredentialGuidePosition] = useState<{ x: number; y: number } | null>(null)
|
||||
@@ -4007,16 +3995,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
}
|
||||
}
|
||||
|
||||
const submitResolveAlert = async () => {
|
||||
if (!resolveTarget) return
|
||||
const alertId = pick(resolveTarget, ['id', 'alert_id'], '')
|
||||
if (!alertId) return
|
||||
await requestAction('解决告警', 'post', `/alerts/${encodeURIComponent(alertId)}/resolve`, {
|
||||
resolution: resolutionText.trim() || '已处理',
|
||||
})
|
||||
setResolveTarget(null)
|
||||
}
|
||||
|
||||
const uploadBrandAssetFile = async (file: File | null | undefined, target: BrandAssetTargetKey) => {
|
||||
if (!file) {
|
||||
toast({ title: '请拖入图片文件', tone: 'error' })
|
||||
@@ -4095,7 +4073,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
return
|
||||
}
|
||||
if (!newsImportFile.name.toLowerCase().endsWith('.json')) {
|
||||
toast({ title: '文件类型不支持', description: '首版只支持 JSON 数组文件。', tone: 'error' })
|
||||
toast({ title: '文件类型不支持', description: '请上传 JSON 数组文件。', tone: 'error' })
|
||||
return
|
||||
}
|
||||
const formData = new FormData()
|
||||
@@ -4370,58 +4348,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
}
|
||||
}
|
||||
|
||||
const loadBGPDetail = async (record: TableRecord) => {
|
||||
const endpointKey = record.__endpointKey
|
||||
const id = pick(record, ['id', 'event_id', 'anomaly_id', 'incident_id'], '')
|
||||
if (!id) return
|
||||
const detailPaths: Record<string, string> = {
|
||||
events: `/bgp/events/${encodeURIComponent(id)}`,
|
||||
anomalies: `/bgp/anomalies/${encodeURIComponent(id)}`,
|
||||
incidents: `/bgp/incidents/${encodeURIComponent(id)}`,
|
||||
briefs: `/ai/bgp/briefs/${encodeURIComponent(id)}`,
|
||||
}
|
||||
const path = detailPaths[endpointKey]
|
||||
if (!path) return
|
||||
setActionLoading(true)
|
||||
try {
|
||||
const response = await axios.get(apiPath(path))
|
||||
replaceSelectedWithPayload(`${endpointKey}-detail`, `${record.__endpointLabel}详情`, [{
|
||||
...response.data,
|
||||
__title: recordTitle(response.data),
|
||||
__module: `${record.__endpointLabel}详情`,
|
||||
__status: recordStatus(response.data),
|
||||
__metric: recordMetric(response.data),
|
||||
}])
|
||||
toast({ title: '详情已加载', tone: 'success' })
|
||||
} catch (error) {
|
||||
toast({ title: '详情加载失败', description: error instanceof Error ? error.message : '接口请求失败', tone: 'error' })
|
||||
} finally {
|
||||
setActionLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const collectCollectorLocation = async (record: TableRecord) => {
|
||||
const id = pick(record, ['id', 'collector_id', 'source_id', 'key', 'name'], '')
|
||||
if (!id) return
|
||||
setActionLoading(true)
|
||||
try {
|
||||
const response = await axios.post(apiPath(`/bgp/collectors/${encodeURIComponent(id)}/collect-location`))
|
||||
replaceSelectedWithPayload('collector-location', 'Collector 位置采集', [{
|
||||
...response.data,
|
||||
__title: `${recordTitle(record)} 位置采集`,
|
||||
__module: 'Collector 位置',
|
||||
__status: recordStatus(response.data) === '-' ? '已提交' : recordStatus(response.data),
|
||||
__metric: recordMetric(response.data),
|
||||
}])
|
||||
toast({ title: 'Collector 位置采集已提交', tone: 'success' })
|
||||
await load()
|
||||
} catch (error) {
|
||||
toast({ title: 'Collector 位置采集失败', description: error instanceof Error ? error.message : '接口请求失败', tone: 'error' })
|
||||
} finally {
|
||||
setActionLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadCredentialGuide = async (provider: string, action: 'read' | 'generate' | 'reset' = 'read') => {
|
||||
const guideProvider = provider.trim().toLowerCase().replace(/\s+/g, '_')
|
||||
if (!guideProvider) {
|
||||
@@ -4456,7 +4382,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
? '未生成新教程'
|
||||
: '教程已生成'
|
||||
: '教程已重置',
|
||||
description: noSearchEvidence ? '没有可用 WebSearch 证据,已保留默认/当前教程。' : undefined,
|
||||
description: noSearchEvidence ? '未检索到可用网页依据,已保留默认教程。' : undefined,
|
||||
tone: noSearchEvidence ? 'default' : 'success',
|
||||
})
|
||||
}
|
||||
@@ -4803,7 +4729,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
return {
|
||||
key: `web_search:${providerId}`,
|
||||
label: providerId,
|
||||
description: text(preset.label, 'Web Search Provider'),
|
||||
description: text(preset.label, 'Web Search 供应商'),
|
||||
status: credentialStatus({
|
||||
explicitStatus: providerConfig.status,
|
||||
configured: providerConfigured,
|
||||
@@ -5013,11 +4939,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
label: 'LLM 基础地址',
|
||||
wide: true,
|
||||
inputAction: activeGroup ? {
|
||||
title: '测试 AI Provider 连通性',
|
||||
title: '测试 AI 供应商连通性',
|
||||
icon: 'test',
|
||||
loading: actionLoading,
|
||||
onClick: () => void testConnection(
|
||||
'AI Provider',
|
||||
'AI 供应商',
|
||||
'/settings/integrations/ai-provider/connect',
|
||||
sanitizeSecretDrafts(stripInternalFields(record), activeGroup.record, ['api_key', 'service_token'], revealedFor('ai_provider')),
|
||||
),
|
||||
@@ -5048,7 +4974,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
]
|
||||
const webSearchDisabled = activeGroup?.key.startsWith('web_search:') && !Boolean(record.enabled)
|
||||
const webFields: FieldConfig[] = [
|
||||
{ key: 'enabled', label: '启用 WebSearch', type: 'boolean' },
|
||||
{ key: 'enabled', label: '启用 Web Search', type: 'boolean' },
|
||||
{ key: 'provider', label: '搜索供应商', disabled: webSearchDisabled },
|
||||
{
|
||||
key: 'base_url',
|
||||
@@ -5069,9 +4995,9 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
},
|
||||
{
|
||||
key: 'api_key',
|
||||
label: 'WebSearch API Key',
|
||||
label: 'Web Search API Key',
|
||||
type: 'secret',
|
||||
placeholder: '输入新的 WebSearch API Key',
|
||||
placeholder: '输入新的 Web Search API Key',
|
||||
disabled: webSearchDisabled,
|
||||
secretVisible: Boolean(visibleSecretFields[secretFieldKey('api_key')]),
|
||||
onToggleSecret: toggleActiveSecret('api_key', 'web_search'),
|
||||
@@ -5116,7 +5042,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
] },
|
||||
]
|
||||
const promptFields: FieldConfig[] = [
|
||||
{ key: 'system_prompt', label: 'System Prompt', type: 'textarea', wide: true },
|
||||
{ key: 'system_prompt', label: '系统提示词', type: 'textarea', wide: true },
|
||||
{ key: 'prompt', label: '任务提示词', type: 'textarea', wide: true },
|
||||
]
|
||||
const fields = activeSection.key === 'integrations'
|
||||
@@ -5187,15 +5113,15 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
return (
|
||||
<AdminSwitch
|
||||
checked={checked}
|
||||
label={checked ? '停用 WebSearch' : '启用 WebSearch'}
|
||||
label={checked ? '停用 Web Search' : '启用 Web Search'}
|
||||
onCheckedChange={(next) => {
|
||||
const firstChild = group.children?.[0]
|
||||
if (!activeGroup?.key.startsWith('web_search:') && firstChild) selectHierarchyGroup(firstChild)
|
||||
const fallback = activeGroup?.key.startsWith('web_search:') ? activeGroup.record : firstChild?.record || {}
|
||||
setHierarchyDraft(setNestedDraftField(hierarchyDraft, fallback, 'enabled', next))
|
||||
toast({
|
||||
title: next ? 'WebSearch 已在草稿中启用' : 'WebSearch 已在草稿中停用',
|
||||
description: '点击右上角“保存”后才会生效;直接刷新页面会恢复为上次保存的状态。',
|
||||
title: next ? 'Web Search 已在草稿中启用' : 'Web Search 已在草稿中停用',
|
||||
description: '点击右上角“保存”后生效。',
|
||||
tone: 'default',
|
||||
})
|
||||
}}
|
||||
@@ -5235,7 +5161,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
</div>
|
||||
<div className="an-toolbar">
|
||||
{activeSection.key === 'integrations' && activeGroup ? (
|
||||
<Button size="icon" variant="subtle" title="刷新当前 Provider 的模型配置" aria-label="刷新当前 Provider 的模型配置" onClick={() => void requestAction('刷新模型列表', 'post', `/settings/integrations/ai-provider/presets/${encodeURIComponent(text(record.provider, ''))}/refresh`, sanitizeSecretDrafts(stripInternalFields(record), activeGroup.record, ['api_key', 'service_token'], revealedFor('ai_provider')), { successDescription: '模型列表已更新,当前模型与未保存配置保持不变。' })} loading={actionLoading}><RefreshCw size={15} /></Button>
|
||||
<Button size="icon" variant="subtle" title="刷新模型配置" aria-label="刷新模型配置" onClick={() => void requestAction('刷新模型列表', 'post', `/settings/integrations/ai-provider/presets/${encodeURIComponent(text(record.provider, ''))}/refresh`, sanitizeSecretDrafts(stripInternalFields(record), activeGroup.record, ['api_key', 'service_token'], revealedFor('ai_provider')), { successDescription: '模型列表已更新。' })} loading={actionLoading}><RefreshCw size={15} /></Button>
|
||||
) : null}
|
||||
{activeGroup?.key.startsWith('web_search:') ? (
|
||||
<>
|
||||
@@ -5255,12 +5181,12 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
</>
|
||||
) : null}
|
||||
{activeGroup?.key.startsWith('prompt:') ? (
|
||||
<Button size="icon" variant="danger" title="重置 Prompt" aria-label="重置 Prompt" onClick={() => setConfirmAction({
|
||||
title: '重置 Prompt',
|
||||
<Button size="icon" variant="danger" title="重置提示词" aria-label="重置提示词" onClick={() => setConfirmAction({
|
||||
title: '重置提示词',
|
||||
description: `确认将 ${activeGroup.label} 重置为默认内容?`,
|
||||
danger: true,
|
||||
confirmLabel: '重置',
|
||||
run: () => requestAction('重置 Prompt', 'post', `/settings/ai-prompts/${encodeURIComponent(text(record.key, ''))}/reset`),
|
||||
run: () => requestAction('重置提示词', 'post', `/settings/ai-prompts/${encodeURIComponent(text(record.key, ''))}/reset`),
|
||||
})}><RefreshCw size={15} /></Button>
|
||||
) : null}
|
||||
<Button variant="primary" onClick={() => void saveCurrent()} loading={actionLoading}><Save size={15} />{localizeAdminText('保存', locale)}</Button>
|
||||
@@ -5809,7 +5735,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<section className="an-field-cluster">
|
||||
<div className="an-field-cluster__heading">
|
||||
<h3>已有新闻</h3>
|
||||
<p>{items.length} 条新闻。单条标题只在这里展示,左侧保持来源/组聚合。</p>
|
||||
<p>{`${items.length} 条新闻`}</p>
|
||||
</div>
|
||||
<div className="an-news-feed-list">
|
||||
{items.length ? items.map((item, itemIndex) => {
|
||||
@@ -5880,7 +5806,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
if (activeSection.key === 'integrations') {
|
||||
const key = text(activeGroup.record.__title || activeGroup.record.key || activeGroup.record.provider, '')
|
||||
if (key === 'ai_provider') {
|
||||
await saveHierarchyIntegrations({ ai_provider: payload }, '保存 AI Provider')
|
||||
await saveHierarchyIntegrations({ ai_provider: payload }, '保存 AI 供应商')
|
||||
return
|
||||
}
|
||||
if (key === 'web_search') {
|
||||
@@ -6269,7 +6195,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
}
|
||||
setConfirmAction({
|
||||
title: localizeAdminText('确认开启超期自动清理', locale),
|
||||
description: localizeAdminText(`开启后将按保留窗口(历史快照与日志 ${currentRetentionDays} 天、BGP 原始观测 7 天)分批清理过期历史,同时永久保留当前最新数据与算力年末里程碑。若这是包含历史资产的开发库,请确认不再需要 ${currentRetentionDays} 天前的旧快照。`, locale),
|
||||
description: localizeAdminText(`开启后将按保留周期(历史快照与日志 ${currentRetentionDays} 天、BGP 原始观测 7 天)自动清理过期历史记录,同时永久保留最新数据与年度算力里程碑。`, locale),
|
||||
danger: true,
|
||||
confirmLabel: localizeAdminText('确认开启', locale),
|
||||
run: () => updateStoragePolicy({ auto_prune_enabled: true }, '开启自动清理'),
|
||||
@@ -6487,10 +6413,10 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
</label>
|
||||
<Button size="icon" variant="subtle" title="测试 SMTP" aria-label="测试 SMTP" onClick={() => {
|
||||
if (!smtpTestEmail.trim()) {
|
||||
toast({ title: '请输入测试收件人', description: 'SMTP 测试需要 to 邮箱。', tone: 'error' })
|
||||
toast({ title: '请输入测试收件人', description: '请填写测试接收邮箱地址。', tone: 'error' })
|
||||
return
|
||||
}
|
||||
void requestAction('测试 SMTP', 'post', '/settings/smtp/test', { to: smtpTestEmail.trim(), settings: record }, { refresh: false, successDescription: '测试邮件请求已发送,未保存 SMTP 表单。' })
|
||||
void requestAction('测试 SMTP', 'post', '/settings/smtp/test', { to: smtpTestEmail.trim(), settings: record }, { refresh: false, successDescription: '测试邮件已发送。' })
|
||||
}} loading={actionLoading} icon="test" />
|
||||
</>
|
||||
) : null}
|
||||
@@ -6561,11 +6487,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<div className="an-time-capsule">
|
||||
<section className="an-field-cluster">
|
||||
<div className="an-field-cluster__heading">
|
||||
<h3>Time Capsule</h3>
|
||||
<h3>{localizeAdminText('时间胶囊', locale)}</h3>
|
||||
<p>
|
||||
{snapshotTimeline.length <= 1
|
||||
? localizeAdminText(`${snapshotTimeline.length} 个快照。单份增量模式下只维护最新 1 份,可在「采集调度」按数据源开启年末对比或历史快照。`, locale)
|
||||
: localizeAdminText(`${snapshotTimeline.length} 个历史快照,选择后查看该版本详情。`, locale)}
|
||||
? localizeAdminText('当前仅保留最新 1 份快照;可在「采集调度」中开启历史快照保留。', locale)
|
||||
: localizeAdminText(`${snapshotTimeline.length} 个历史快照,选择后查看详情。`, locale)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="an-time-capsule__controls">
|
||||
@@ -6606,7 +6532,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<section className="an-field-cluster">
|
||||
<div className="an-field-cluster__heading">
|
||||
<h3>快照摘要</h3>
|
||||
<p>采集任务写入的 summary。</p>
|
||||
<p>本次采集任务的统计摘要。</p>
|
||||
</div>
|
||||
<Scrollbar className="an-code-scroll">
|
||||
<pre className="an-json-view">{formatRaw(activeSnapshot.summary)}</pre>
|
||||
@@ -6783,7 +6709,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
) : <EmptyState title={isPlaceholderSection(activeSection.key) ? '后端能力未提供' : '暂无分组'} description={isPlaceholderSection(activeSection.key) ? '当前分区没有可用后端能力,控制台不混入其他配置或假数据。' : '当前分区没有可配置项。'} />}
|
||||
) : <EmptyState title={isPlaceholderSection(activeSection.key) ? localizeAdminText('暂未接入数据', locale) : localizeAdminText('暂无分组', locale)} description={isPlaceholderSection(activeSection.key) ? localizeAdminText('该功能模块尚未提供配置接口。', locale) : localizeAdminText('当前分区没有可配置项。', locale)} />}
|
||||
</Scrollbar>
|
||||
</div>
|
||||
</Panel>
|
||||
@@ -6857,16 +6783,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
)
|
||||
}
|
||||
|
||||
if (((config === configs.systemAlerts || config === configs.situationalAlerts) || (config === configs.monitoring && endpointKey === 'system-alerts')) && id) {
|
||||
actions.push(
|
||||
<Button key="ack" size="icon" variant="subtle" onClick={() => void requestAction('确认告警', 'post', `/alerts/${encodeURIComponent(id)}/acknowledge`)} loading={actionLoading} title="确认告警" aria-label="确认告警"><CheckCircle2 size={15} /></Button>,
|
||||
<Button key="resolve" variant="primary" onClick={() => {
|
||||
setResolutionText('已处理')
|
||||
setResolveTarget(selected)
|
||||
}} loading={actionLoading}><ShieldAlert size={15} />解决</Button>,
|
||||
)
|
||||
}
|
||||
|
||||
if (config === configs.logs && endpointKey === 'sources') {
|
||||
actions.push(<Button key="snapshot" variant="primary" onClick={fetchLogSnapshot} loading={actionLoading}><FileText size={15} />读取快照</Button>)
|
||||
}
|
||||
@@ -6946,14 +6862,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
)
|
||||
}
|
||||
|
||||
if ((config === configs.bgp && endpointKey === 'collectors' && id) || (config === configs.monitoring && endpointKey === 'bgp-collectors' && id)) {
|
||||
actions.push(<Button key="collect-location" variant="primary" icon="trigger" onClick={() => void collectCollectorLocation(selected)} loading={actionLoading}>采集位置</Button>)
|
||||
}
|
||||
|
||||
if (((config === configs.bgp || config === configs.bgpAlerts) && ['events', 'anomalies', 'incidents', 'briefs'].includes(endpointKey) && id) || (config === configs.monitoring && ['bgp-events', 'bgp-anomalies', 'bgp-incidents'].includes(endpointKey) && id)) {
|
||||
actions.push(<Button key="bgp-detail" variant="subtle" onClick={() => void loadBGPDetail(selected)} loading={actionLoading}><Eye size={15} />拉取详情</Button>)
|
||||
}
|
||||
|
||||
if ((config === configs.settings) || (config === configs.earthContent && ['brand', 'boundaries', 'tv', 'newsSources'].includes(endpointKey)) || (config === configs.ai && ['prompts', 'integrations'].includes(endpointKey))) {
|
||||
actions.push(<Button key="save-json" variant="primary" onClick={saveAdvancedJson} loading={actionLoading}><Save size={15} />保存</Button>)
|
||||
}
|
||||
@@ -7053,27 +6961,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
})} loading={actionLoading}><RefreshCw size={15} /></Button>,
|
||||
)
|
||||
}
|
||||
if (config === configs.bgp || config === configs.bgpAlerts) {
|
||||
actions.push(
|
||||
<Button key="generate-bgp-brief" variant="primary" onClick={() => void requestAction('生成 BGP 简报', 'post', '/ai/bgp/brief', { incident_limit: 5, anomaly_limit: 6, collector_limit: 5 }, { refresh: false, successDescription: 'AI 简报生成任务已提交,不会保存当前页面配置。' })} loading={actionLoading} title="生成 BGP AI 简报">
|
||||
<Sparkles size={15} />生成简报
|
||||
</Button>,
|
||||
)
|
||||
}
|
||||
if (config === configs.systemAlerts) {
|
||||
actions.push(
|
||||
<Button key="generate-alert-brief" variant="primary" onClick={() => void requestAction('生成告警简报', 'post', '/ai/alerts/brief', {}, { refresh: false, successDescription: 'AI 简报生成任务已提交,不会保存当前页面配置。' })} loading={actionLoading} title="生成系统告警 AI 简报">
|
||||
<Sparkles size={15} />AI 简报
|
||||
</Button>,
|
||||
)
|
||||
}
|
||||
if (config === configs.situationalAlerts) {
|
||||
actions.push(
|
||||
<Button key="generate-situational-brief" variant="primary" onClick={() => void requestAction('生成态势简报', 'post', '/ai/situational-alerts/brief', {}, { refresh: false, successDescription: 'AI 简报生成任务已提交,不会保存当前页面配置。' })} loading={actionLoading} title="生成态势告警 AI 简报">
|
||||
<Sparkles size={15} />AI 简报
|
||||
</Button>,
|
||||
)
|
||||
}
|
||||
if (config === configs.earthContent) {
|
||||
actions.push(
|
||||
<Button key="cache-status" size="icon" variant="subtle" onClick={() => void loadEarthLayerCacheStatus()} loading={actionLoading} title="查看智能星球图层缓存" aria-label="查看智能星球图层缓存">
|
||||
@@ -7500,44 +7387,46 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<span style={{ width: `${collectionQueueSummary.progress}%` }} />
|
||||
</div>
|
||||
{collectionQueueSummary.total ? (
|
||||
<div className="an-collection-queue__panel">
|
||||
{groups.map((group) => (
|
||||
<section key={group.key} className="an-collection-queue__group">
|
||||
<h3>{group.title}<span>{group.items.length}</span></h3>
|
||||
{group.items.length ? (
|
||||
<div className="an-collection-queue__items">
|
||||
{group.items.map((item) => (
|
||||
<article key={item.key} className={`an-collection-queue__item is-${item.status}`}>
|
||||
<div>
|
||||
<strong title={item.name}>{item.name}</strong>
|
||||
<p title={`${item.error || queuePrimaryMessage(item)}${item.taskId ? ` · task ${item.taskId}` : ''}${item.completedAt ? ` · ${formatDuration(item.createdAt, item.completedAt)}` : ''}`}>
|
||||
{item.error || queuePrimaryMessage(item)}{item.taskId ? ` · task ${item.taskId}` : ''}{item.completedAt ? ` · ${formatDuration(item.createdAt, item.completedAt)}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<span>{queueProgress(item)}%</span>
|
||||
<div className="an-collection-queue__item-actions">
|
||||
<Button size="icon" variant="subtle" title="查看数据源" aria-label="查看数据源" onClick={() => void jumpToQueueRecord(item)}>
|
||||
<Eye size={14} />
|
||||
</Button>
|
||||
<Button size="icon" variant="subtle" title="查看日志" aria-label="查看日志" onClick={() => openLogsForTask(item)}>
|
||||
<FileText size={14} />
|
||||
</Button>
|
||||
{item.status === 'failed' ? (
|
||||
<Button size="icon" variant="subtle" icon="trigger" title="重试" aria-label="重试" onClick={() => retryQueueItem(item)} />
|
||||
) : null}
|
||||
{isActiveQueueStatus(item.status) ? (
|
||||
<Button size="icon" variant="subtle" title="取消任务" aria-label="取消任务" onClick={() => void cancelQueueItem(item)}>
|
||||
<X size={14} />
|
||||
<Scrollbar className="an-collection-queue__scroll" axis="y">
|
||||
<div className="an-collection-queue__panel">
|
||||
{groups.map((group) => (
|
||||
<section key={group.key} className="an-collection-queue__group">
|
||||
<h3>{group.title}<span>{group.items.length}</span></h3>
|
||||
{group.items.length ? (
|
||||
<div className="an-collection-queue__items">
|
||||
{group.items.map((item) => (
|
||||
<article key={item.key} className={`an-collection-queue__item is-${item.status}`}>
|
||||
<div>
|
||||
<strong title={item.name}>{item.name}</strong>
|
||||
<p title={`${item.error || queuePrimaryMessage(item)}${item.taskId ? ` · task ${item.taskId}` : ''}${item.completedAt ? ` · ${formatDuration(item.createdAt, item.completedAt)}` : ''}`}>
|
||||
{item.error || queuePrimaryMessage(item)}{item.taskId ? ` · task ${item.taskId}` : ''}{item.completedAt ? ` · ${formatDuration(item.createdAt, item.completedAt)}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<span>{queueProgress(item)}%</span>
|
||||
<div className="an-collection-queue__item-actions">
|
||||
<Button size="icon" variant="subtle" title="查看数据源" aria-label="查看数据源" onClick={() => void jumpToQueueRecord(item)}>
|
||||
<Eye size={14} />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : <p className="an-collection-queue__empty">暂无{group.title}任务</p>}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
<Button size="icon" variant="subtle" title="查看日志" aria-label="查看日志" onClick={() => openLogsForTask(item)}>
|
||||
<FileText size={14} />
|
||||
</Button>
|
||||
{item.status === 'failed' ? (
|
||||
<Button size="icon" variant="subtle" icon="trigger" title="重试" aria-label="重试" onClick={() => retryQueueItem(item)} />
|
||||
) : null}
|
||||
{isActiveQueueStatus(item.status) ? (
|
||||
<Button size="icon" variant="subtle" title="取消任务" aria-label="取消任务" onClick={() => void cancelQueueItem(item)}>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : <p className="an-collection-queue__empty">暂无{group.title}任务</p>}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</Scrollbar>
|
||||
) : (
|
||||
<p className="an-collection-queue__empty an-collection-queue__empty--panel">暂无数据源任务</p>
|
||||
)}
|
||||
@@ -7625,7 +7514,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
{!isSpecialContentSection ? <SummaryStrip>
|
||||
<StatCell label={localizeAdminText('接口在线', locale)} value={`${summary.online}/${states.length || 1}`} hint={localizeAdminText('已加载分区', locale)} />
|
||||
<StatCell label={localizeAdminText('记录数', locale)} value={summary.rows} hint={localizeAdminText('已加载分区汇总', locale)} />
|
||||
<StatCell label={localizeAdminText('异常接口', locale)} value={summary.failing} hint={localizeAdminText('失败时页面仍可操作', locale)} />
|
||||
<StatCell label={localizeAdminText('异常接口', locale)} value={summary.failing} hint={localizeAdminText('当前异常数', locale)} />
|
||||
</SummaryStrip> : null}
|
||||
|
||||
<SectionTabs sections={config.sections} states={states} activeKey={activeSection?.key || ''} onChange={handleSectionChange} />
|
||||
@@ -7714,7 +7603,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState title={localizeAdminText('选择一条记录', locale)} description={localizeAdminText('详情会在右侧完整滚动显示,不会挤压主表区域。', locale)} />
|
||||
<EmptyState title={localizeAdminText('选择一条记录', locale)} description={localizeAdminText('点击左侧列表查看详细信息。', locale)} />
|
||||
)}
|
||||
</DetailPanel>
|
||||
</div>
|
||||
@@ -7730,7 +7619,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<p>{text(credentialGuide.source, 'default') === 'ai' ? 'AI 生成教程' : '默认教程'}</p>
|
||||
</div>
|
||||
<div className="an-toolbar">
|
||||
<Button size="icon" variant="subtle" title="教程不好用,重新生成" aria-label="教程不好用,重新生成" onClick={() => void loadCredentialGuide(credentialGuideProviderName, 'generate')} loading={actionLoading}><Sparkles size={15} /></Button>
|
||||
<Button size="icon" variant="subtle" title={localizeAdminText('重新生成教程', locale)} aria-label={localizeAdminText('重新生成教程', locale)} onClick={() => void loadCredentialGuide(credentialGuideProviderName, 'generate')} loading={actionLoading}><Sparkles size={15} /></Button>
|
||||
<Button size="icon" variant="subtle" title="重置为默认教程" aria-label="重置为默认教程" onClick={() => setConfirmAction({
|
||||
title: '重置凭证教程',
|
||||
description: `确认将 ${credentialGuideProviderName} 凭证教程恢复默认?`,
|
||||
@@ -7744,7 +7633,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<Scrollbar className="an-guide-modal__body">
|
||||
{text(credentialGuide.verification_status, '') === 'unverified_no_search_evidence' ? (
|
||||
<div className="an-guide-alert an-guide-alert--warning">
|
||||
<strong>没有可用 WebSearch 证据,已保留默认教程。</strong>
|
||||
<strong>未检索到可用网页依据,已保留默认教程。</strong>
|
||||
{credentialGuide.verification_error ? <p>{text(credentialGuide.verification_error, '')}</p> : null}
|
||||
</div>
|
||||
) : null}
|
||||
@@ -7752,7 +7641,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<div className="an-guide-empty">
|
||||
<FileText size={30} aria-hidden="true" />
|
||||
<h3>暂无凭证教程</h3>
|
||||
<p>当前采集器还没有可展示的凭证教程。可以在这里直接生成,生成后会保存在后端并回到这个弹窗展示。</p>
|
||||
<p>当前采集器暂无凭证教程,可点击下方按钮自动生成。</p>
|
||||
{credentialGuide.verification_error ? <span>{text(credentialGuide.verification_error, '')}</span> : null}
|
||||
<Button variant="primary" onClick={() => void loadCredentialGuide(credentialGuideProviderName, 'generate')} loading={actionLoading}>
|
||||
<Sparkles size={15} />
|
||||
@@ -7795,43 +7684,22 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Dialog
|
||||
open={Boolean(resolveTarget)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setResolveTarget(null)
|
||||
}}
|
||||
title="处理告警"
|
||||
description={resolveTarget ? `为 ${recordTitle(resolveTarget)} 填写处理说明。` : undefined}
|
||||
width={520}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="subtle" onClick={() => setResolveTarget(null)} disabled={actionLoading}>取消</Button>
|
||||
<Button variant="primary" onClick={() => void submitResolveAlert()} loading={actionLoading}><ShieldAlert size={15} />标记解决</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<label className="an-field">
|
||||
<span>处理说明</span>
|
||||
<Textarea value={resolutionText} onChange={(event) => setResolutionText(event.target.value)} />
|
||||
</label>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={newsImportDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setNewsImportDialogOpen(open)
|
||||
if (!open) setNewsImportFile(null)
|
||||
}}
|
||||
title="导入 JSON 新闻"
|
||||
description="上传 JSON 数组后,所有条目都会归入当前手动新闻组。"
|
||||
title={localizeAdminText('导入 JSON 新闻', locale)}
|
||||
description={localizeAdminText('上传 JSON 数组后,所有条目都会归入当前手动新闻组。', locale)}
|
||||
width={520}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="subtle" onClick={() => {
|
||||
setNewsImportDialogOpen(false)
|
||||
setNewsImportFile(null)
|
||||
}} disabled={actionLoading}>取消</Button>
|
||||
<Button variant="primary" onClick={() => void importManualNewsJson()} loading={actionLoading} disabled={!newsImportFile}><ImageUp size={15} />导入</Button>
|
||||
}} disabled={actionLoading}>{localizeAdminText('取消', locale)}</Button>
|
||||
<Button variant="primary" onClick={() => void importManualNewsJson()} loading={actionLoading} disabled={!newsImportFile}><ImageUp size={15} />{localizeAdminText('导入', locale)}</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
@@ -7844,10 +7712,10 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
/>
|
||||
<section className="an-field-cluster an-field-cluster--compact">
|
||||
<div className="an-field-cluster__heading">
|
||||
<h3>{newsImportFile ? newsImportFile.name : '选择 JSON 文件'}</h3>
|
||||
<p>首版只支持顶层为数组的 JSON 文件;取消不会清空当前新闻组详情。</p>
|
||||
<h3>{newsImportFile ? newsImportFile.name : localizeAdminText('选择 JSON 文件', locale)}</h3>
|
||||
<p>{localizeAdminText('请上传顶层为 JSON 数组的文件。', locale)}</p>
|
||||
</div>
|
||||
<Button variant="subtle" onClick={() => newsImportInputRef.current?.click()}><ImageUp size={15} />选择文件</Button>
|
||||
<Button variant="subtle" onClick={() => newsImportInputRef.current?.click()}><ImageUp size={15} />{localizeAdminText('选择文件', locale)}</Button>
|
||||
</section>
|
||||
</Dialog>
|
||||
|
||||
@@ -7856,10 +7724,10 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setConfirmAction(null)
|
||||
}}
|
||||
title={confirmAction?.title || '确认操作'}
|
||||
description={confirmAction?.description}
|
||||
title={localizeAdminText(confirmAction?.title || '确认操作', locale)}
|
||||
description={confirmAction?.description ? localizeAdminText(confirmAction.description, locale) : undefined}
|
||||
danger={confirmAction?.danger}
|
||||
confirmLabel={confirmAction?.confirmLabel}
|
||||
confirmLabel={confirmAction?.confirmLabel ? localizeAdminText(confirmAction.confirmLabel, locale) : undefined}
|
||||
loading={actionLoading}
|
||||
onConfirm={() => void runConfirmedAction()}
|
||||
/>
|
||||
@@ -7880,7 +7748,7 @@ const configs = {
|
||||
title: '数据源',
|
||||
description: '统一查看内置源、自定义源、实时源与任务状态,保留触发、启停和连接状态入口。',
|
||||
listTitle: '数据源列表',
|
||||
listDescription: '仅展示数据源相关接口,不混入其他设置对象。',
|
||||
listDescription: '展示已接入的数据源与实时状态。',
|
||||
sections: [
|
||||
{ key: 'builtin', label: '内置源', url: '/datasources', map: datasourceRows },
|
||||
{ key: 'custom', label: '自定义源', url: '/datasources/configs', map: (payload) => makeNamedRows(payload, '自定义源') },
|
||||
@@ -7889,79 +7757,10 @@ const configs = {
|
||||
actions: [makeAction('采集管理', <Settings2 size={15} />, '/collection-management')],
|
||||
detailTitle: '数据源详情',
|
||||
},
|
||||
bgp: {
|
||||
title: 'BGP 观测',
|
||||
description: '查看采集器、事故、异常、事件与 AI 简报;这是信息观测页,采用列表加详情。',
|
||||
listTitle: 'BGP 事件与简报',
|
||||
listDescription: '按 BGP 实体聚合展示,保留事件、异常、事故和简报语义。',
|
||||
sections: [
|
||||
{ key: 'overview', label: '概览摘要', url: '/bgp/overview/summary', map: (payload) => directObject(payload, 'BGP 概览', '概览') },
|
||||
{ key: 'collectors', label: '采集器', url: '/bgp/collectors', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Collector' })) },
|
||||
{ key: 'incidents', label: '事故', url: '/bgp/incidents', params: { page_size: 30 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Incident' })) },
|
||||
{ key: 'anomalies', label: '异常', url: '/bgp/anomalies', params: { page_size: 30 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Anomaly' })) },
|
||||
{ key: 'events', label: '事件', url: '/bgp/events', params: { page_size: 30 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Event' })) },
|
||||
{ key: 'briefs', label: 'AI 简报', url: '/ai/bgp/briefs', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'AI Brief', __status: 'brief' })) },
|
||||
],
|
||||
actions: [],
|
||||
detailTitle: 'BGP 详情',
|
||||
},
|
||||
systemAlerts: {
|
||||
title: '系统告警',
|
||||
description: '系统告警、确认处理、AI 摘要和处置状态集中到一张低噪声列表。',
|
||||
listTitle: '系统告警列表',
|
||||
listDescription: '显示系统告警记录和统计,不混入 BGP 概览以外的数据。',
|
||||
sections: [
|
||||
{ key: 'alerts', label: '系统告警', url: '/alerts', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: '系统告警' })) },
|
||||
{ key: 'stats', label: '告警统计', url: '/alerts/stats', map: (payload) => directObject(payload, '告警统计', '统计') },
|
||||
],
|
||||
actions: [makeAction('BGP 告警', <Radio size={15} />, '/alerts/bgp')],
|
||||
detailTitle: '告警详情',
|
||||
},
|
||||
bgpAlerts: {
|
||||
title: 'BGP 告警',
|
||||
description: '聚合 BGP 事故、异常和 AI 简报,突出严重度、影响范围和事件链路。',
|
||||
listTitle: 'BGP 告警列表',
|
||||
listDescription: '只展示 BGP 事故、异常与简报。',
|
||||
sections: [
|
||||
{ key: 'incidents', label: 'BGP 事故', url: '/bgp/incidents', params: { page_size: 50 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Incident' })) },
|
||||
{ key: 'anomalies', label: 'BGP 异常', url: '/bgp/anomalies', params: { page_size: 50 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Anomaly' })) },
|
||||
{ key: 'briefs', label: 'BGP 简报', url: '/ai/bgp/briefs', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'AI Brief', __status: 'brief' })) },
|
||||
],
|
||||
actions: [makeAction('观测台', <Globe2 size={15} />, '/bgp')],
|
||||
detailTitle: 'BGP 告警详情',
|
||||
},
|
||||
situationalAlerts: {
|
||||
title: '态势告警',
|
||||
description: '查看态势统计、严重度、AI 简报入口和处理状态。',
|
||||
listTitle: '态势告警列表',
|
||||
listDescription: '显示态势统计与告警记录。',
|
||||
sections: [
|
||||
{ key: 'stats', label: '态势统计', url: '/alerts/stats', map: (payload) => directObject(payload, '态势统计', '统计') },
|
||||
{ key: 'alerts', label: '告警记录', url: '/alerts', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: '态势告警' })) },
|
||||
],
|
||||
actions: [makeAction('系统告警', <ShieldAlert size={15} />, '/alerts/system')],
|
||||
detailTitle: '态势详情',
|
||||
},
|
||||
monitoring: {
|
||||
title: '告警与观测',
|
||||
description: '集中查看系统告警、BGP 事故、异常、观测事件与采集器健康度;AI 简报与推演已迁入 AI 参谋。',
|
||||
listTitle: '告警与 BGP 观测列表',
|
||||
listDescription: '按模块展示原始观测告警、事故、异常事件与采集站覆盖。',
|
||||
sections: [
|
||||
{ key: 'system-alerts', label: '系统告警', url: '/alerts', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: '系统告警' })) },
|
||||
{ key: 'bgp-incidents', label: 'BGP 事故', url: '/bgp/incidents', params: { page_size: 30 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Incident' })) },
|
||||
{ key: 'bgp-anomalies', label: 'BGP 异常', url: '/bgp/anomalies', params: { page_size: 30 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Anomaly' })) },
|
||||
{ key: 'bgp-collectors', label: 'BGP 采集器', url: '/bgp/collectors', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Collector' })) },
|
||||
{ key: 'bgp-events', label: 'BGP 观测事件', url: '/bgp/events', params: { page_size: 30 }, map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: 'Event' })) },
|
||||
{ key: 'stats', label: '告警统计', url: '/alerts/stats', map: (payload) => directObject(payload, '告警统计', '统计') },
|
||||
],
|
||||
actions: [makeAction('打开 AI 参谋', <Bot size={15} />, '/advisor/playground')],
|
||||
detailTitle: '监控详情',
|
||||
},
|
||||
ai: {
|
||||
title: 'AI 基础设施',
|
||||
description: '管理模型供应商、Web Search、OCR 等 AI 基础设施凭据;Playground 与工作流节点已迁入 AI 参谋。',
|
||||
listTitle: 'AI 基础设施配置',
|
||||
title: 'AI',
|
||||
description: '管理模型供应商、Web Search、OCR 等 AI 配置;Playground 与工作流节点在 AI 参谋中管理。',
|
||||
listTitle: 'AI 分区',
|
||||
listDescription: '配置类页面采用分层结构:先选父级,再编辑子配置。',
|
||||
viewMode: 'management',
|
||||
sections: [
|
||||
@@ -7989,7 +7788,7 @@ const configs = {
|
||||
makeAction('工作流与节点', <Sparkles size={15} />, '/advisor/workflows'),
|
||||
makeAction('Playground', <Bot size={15} />, '/advisor/playground'),
|
||||
],
|
||||
detailTitle: 'AI 基础设施详情',
|
||||
detailTitle: 'AI 配置详情',
|
||||
},
|
||||
earthContent: {
|
||||
title: '智能星球内容',
|
||||
@@ -8060,7 +7859,7 @@ const configs = {
|
||||
title: '采集管理',
|
||||
description: '管理采集器、采集调度和采集历史 / 快照。',
|
||||
listTitle: '采集配置列表',
|
||||
listDescription: '先选择采集器、采集调度或采集历史 / 快照,再编辑当前对象。',
|
||||
listDescription: '按类型选择采集器、调度策略或历史快照进行管理。',
|
||||
viewMode: 'management',
|
||||
sections: [
|
||||
{
|
||||
@@ -8103,7 +7902,7 @@ const configs = {
|
||||
},
|
||||
logs: {
|
||||
title: '日志',
|
||||
description: '查看日志源、读取快照、复制原始输出,按控制台阅读方式组织。',
|
||||
description: '查看日志源、读取快照并复制原始日志。',
|
||||
listTitle: '日志源',
|
||||
listDescription: '先选择日志源,再读取对应日志快照。',
|
||||
sections: [
|
||||
@@ -8134,10 +7933,6 @@ export function DataSources() {
|
||||
return <ModuleConsole config={configs.datasources} />
|
||||
}
|
||||
|
||||
export function Monitoring() {
|
||||
return <ModuleConsole config={configs.monitoring} />
|
||||
}
|
||||
|
||||
export function AI() {
|
||||
return <ModuleConsole config={configs.ai} />
|
||||
}
|
||||
|
||||
@@ -159,7 +159,10 @@ export default function Users() {
|
||||
accessorKey: 'role',
|
||||
header: t('users.role'),
|
||||
size: 140,
|
||||
cell: ({ row }) => <Badge tone={roleTone(row.original.role)} title={row.original.role}>{roleLabel(row.original.role)}</Badge>,
|
||||
cell: ({ row }) => {
|
||||
const label = roleLabel(row.original.role)
|
||||
return <Badge tone={roleTone(row.original.role)} title={label}>{label}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'gatekeeper_groups',
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
export interface EarthContextDetectionResult {
|
||||
isEarthContext: boolean
|
||||
title: string
|
||||
summary: string
|
||||
payload: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export interface ParsedImagePayload {
|
||||
name: string
|
||||
mime_type: 'image/jpeg' | 'image/png' | 'image/webp' | 'image/gif'
|
||||
data_base64: string
|
||||
previewUrl: string
|
||||
width: number
|
||||
height: number
|
||||
size: number
|
||||
}
|
||||
|
||||
export interface ParsedVideoPayload {
|
||||
name: string
|
||||
mime_type: string
|
||||
durationSeconds: number
|
||||
width: number
|
||||
height: number
|
||||
size: number
|
||||
frames: Array<ParsedImagePayload & { timestampSec: number }>
|
||||
}
|
||||
|
||||
const EARTH_CONTEXT_SIGNAL_KEYS = [
|
||||
'selected',
|
||||
'targets',
|
||||
'visible_layers',
|
||||
'camera',
|
||||
'domain',
|
||||
'memory_notes',
|
||||
'turns',
|
||||
'selected_codes',
|
||||
'time_basis',
|
||||
'earth_context',
|
||||
'entity_id',
|
||||
] as const
|
||||
|
||||
export type AttachmentLocale = 'zh-CN' | 'en-US'
|
||||
|
||||
/** Detect whether a parsed JSON value represents an exported Planet Earth context. */
|
||||
export function detectEarthContextJson(parsed: unknown, locale: AttachmentLocale = 'en-US'): EarthContextDetectionResult {
|
||||
const isZh = locale === 'zh-CN'
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return { isEarthContext: false, title: '', summary: '', payload: null }
|
||||
}
|
||||
const obj = parsed as Record<string, unknown>
|
||||
const schema = String(obj.schema || '').trim()
|
||||
const source = String(obj.source || '').trim()
|
||||
|
||||
let signalCount = 0
|
||||
for (const key of EARTH_CONTEXT_SIGNAL_KEYS) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] != null) {
|
||||
signalCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
const isEarth =
|
||||
schema === 'planet.earth_context.v1' ||
|
||||
schema.startsWith('planet.earth_context.') ||
|
||||
source === 'earth_indexeddb' ||
|
||||
signalCount >= 2
|
||||
|
||||
if (!isEarth) {
|
||||
return { isEarthContext: false, title: '', summary: '', payload: null }
|
||||
}
|
||||
|
||||
const selectedObj =
|
||||
obj.selected && typeof obj.selected === 'object' && !Array.isArray(obj.selected)
|
||||
? (obj.selected as Record<string, unknown>)
|
||||
: null
|
||||
const firstTarget =
|
||||
Array.isArray(obj.targets) && obj.targets[0] && typeof obj.targets[0] === 'object'
|
||||
? (obj.targets[0] as Record<string, unknown>)
|
||||
: null
|
||||
|
||||
const title = String(
|
||||
obj.title ||
|
||||
selectedObj?.label ||
|
||||
selectedObj?.name ||
|
||||
firstTarget?.label ||
|
||||
firstTarget?.name ||
|
||||
obj.domain ||
|
||||
(isZh ? '地球上下文' : 'Earth Context'),
|
||||
).trim()
|
||||
|
||||
const summaryParts: string[] = []
|
||||
if (typeof obj.domain === 'string' && obj.domain.trim()) {
|
||||
summaryParts.push(obj.domain.trim())
|
||||
}
|
||||
if (Array.isArray(obj.targets) && obj.targets.length > 0) {
|
||||
summaryParts.push(isZh ? `${obj.targets.length} 个目标` : `${obj.targets.length} targets`)
|
||||
}
|
||||
if (Array.isArray(obj.turns) && obj.turns.length > 0) {
|
||||
summaryParts.push(isZh ? `${obj.turns.length} 轮对话` : `${obj.turns.length} turns`)
|
||||
}
|
||||
if (Array.isArray(obj.memory_notes) && obj.memory_notes.length > 0) {
|
||||
summaryParts.push(isZh ? `${obj.memory_notes.length} 条备注` : `${obj.memory_notes.length} notes`)
|
||||
}
|
||||
|
||||
return {
|
||||
isEarthContext: true,
|
||||
title,
|
||||
summary: summaryParts.join(' · ') || (isZh ? '地球上下文配置' : 'Earth Context'),
|
||||
payload: obj,
|
||||
}
|
||||
}
|
||||
|
||||
export interface JsonTextParseResult {
|
||||
ok: boolean
|
||||
kind: 'json' | 'text'
|
||||
parsed?: unknown
|
||||
prettyText: string
|
||||
earthContext: EarthContextDetectionResult
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** Parse uploaded or pasted JSON / text content and classify Earth context automatically. */
|
||||
export function parseJsonOrTextContent(
|
||||
rawText: string,
|
||||
options: { forceJson?: boolean; locale?: AttachmentLocale } = {},
|
||||
): JsonTextParseResult {
|
||||
const locale = options.locale ?? 'en-US'
|
||||
const trimmed = rawText.trim()
|
||||
const looksLikeJson =
|
||||
Boolean(options.forceJson) || trimmed.startsWith('{') || trimmed.startsWith('[')
|
||||
|
||||
if (looksLikeJson) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed)
|
||||
return {
|
||||
ok: true,
|
||||
kind: 'json',
|
||||
parsed,
|
||||
prettyText: JSON.stringify(parsed, null, 2),
|
||||
earthContext: detectEarthContextJson(parsed, locale),
|
||||
}
|
||||
} catch {
|
||||
if (options.forceJson) {
|
||||
return {
|
||||
ok: false,
|
||||
kind: 'json',
|
||||
prettyText: rawText,
|
||||
earthContext: { isEarthContext: false, title: '', summary: '', payload: null },
|
||||
error: locale === 'zh-CN' ? 'JSON 格式错误' : 'JSON syntax error',
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
kind: 'text',
|
||||
prettyText: rawText,
|
||||
earthContext: { isEarthContext: false, title: '', summary: '', payload: null },
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate an external HTTP/HTTPS link before requesting backend link parsing. */
|
||||
export function validateHttpUrl(rawUrl: string): { ok: true; url: string; host: string } | { ok: false } {
|
||||
const trimmed = rawUrl.trim()
|
||||
if (!trimmed) return { ok: false }
|
||||
const candidate = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`
|
||||
try {
|
||||
const parsed = new URL(candidate)
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
return { ok: false }
|
||||
}
|
||||
if (!parsed.hostname) return { ok: false }
|
||||
return { ok: true, url: parsed.toString(), host: parsed.hostname }
|
||||
} catch {
|
||||
return { ok: false }
|
||||
}
|
||||
}
|
||||
|
||||
/** Compress/scale an image file in-browser into a bounded base64 payload for multimodal chat. */
|
||||
export async function compressImageFile(
|
||||
file: File,
|
||||
maxDim = 1600,
|
||||
quality = 0.85,
|
||||
): Promise<ParsedImagePayload> {
|
||||
if (file.size > 20 * 1024 * 1024) {
|
||||
throw new Error('Image exceeds 20MB limit')
|
||||
}
|
||||
const objectUrl = URL.createObjectURL(file)
|
||||
try {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const el = new Image()
|
||||
el.onload = () => resolve(el)
|
||||
el.onerror = () => reject(new Error('Failed to load image'))
|
||||
el.src = objectUrl
|
||||
})
|
||||
const srcW = Math.max(1, img.naturalWidth || img.width || 1)
|
||||
const srcH = Math.max(1, img.naturalHeight || img.height || 1)
|
||||
const scale = Math.min(1, maxDim / Math.max(srcW, srcH))
|
||||
const width = Math.max(1, Math.round(srcW * scale))
|
||||
const height = Math.max(1, Math.round(srcH * scale))
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Canvas unavailable')
|
||||
ctx.drawImage(img, 0, 0, width, height)
|
||||
|
||||
const preferPng = file.type === 'image/png' && file.size < 900_000 && scale === 1
|
||||
const outMime: 'image/png' | 'image/jpeg' = preferPng ? 'image/png' : 'image/jpeg'
|
||||
const dataUrl = canvas.toDataURL(outMime, outMime === 'image/jpeg' ? quality : undefined)
|
||||
const commaIdx = dataUrl.indexOf(',')
|
||||
const base64 = commaIdx >= 0 ? dataUrl.slice(commaIdx + 1) : ''
|
||||
return {
|
||||
name: file.name || 'image.jpg',
|
||||
mime_type: outMime,
|
||||
data_base64: base64,
|
||||
previewUrl: dataUrl,
|
||||
width,
|
||||
height,
|
||||
size: file.size,
|
||||
}
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
}
|
||||
|
||||
/** Extract metadata and evenly spaced JPEG keyframes from a local video file in-browser. */
|
||||
export async function extractVideoKeyframes(
|
||||
file: File,
|
||||
maxFrames = 4,
|
||||
): Promise<ParsedVideoPayload> {
|
||||
if (file.size > 150 * 1024 * 1024) {
|
||||
throw new Error('Video exceeds 150MB limit')
|
||||
}
|
||||
const objectUrl = URL.createObjectURL(file)
|
||||
const video = document.createElement('video')
|
||||
video.muted = true
|
||||
video.playsInline = true
|
||||
video.preload = 'auto'
|
||||
|
||||
try {
|
||||
video.src = objectUrl
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => reject(new Error('Video metadata timeout')), 8000)
|
||||
video.onloadedmetadata = () => {
|
||||
window.clearTimeout(timer)
|
||||
resolve()
|
||||
}
|
||||
video.onerror = () => {
|
||||
window.clearTimeout(timer)
|
||||
reject(new Error('Unsupported video format'))
|
||||
}
|
||||
})
|
||||
|
||||
const duration = Number.isFinite(video.duration) && video.duration > 0 ? video.duration : 0
|
||||
const srcW = Math.max(1, video.videoWidth || 640)
|
||||
const srcH = Math.max(1, video.videoHeight || 360)
|
||||
const scale = Math.min(1, 960 / Math.max(srcW, srcH))
|
||||
const width = Math.max(1, Math.round(srcW * scale))
|
||||
const height = Math.max(1, Math.round(srcH * scale))
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
const fractions = maxFrames <= 1 ? [0.1] : [0.1, 0.36, 0.64, 0.88].slice(0, maxFrames)
|
||||
const timestamps =
|
||||
duration > 0.4
|
||||
? fractions.map((f) => Number(Math.max(0.05, Math.min(duration - 0.05, duration * f)).toFixed(2)))
|
||||
: [0]
|
||||
|
||||
const frames: ParsedVideoPayload['frames'] = []
|
||||
if (ctx) {
|
||||
for (let i = 0; i < timestamps.length; i += 1) {
|
||||
const ts = timestamps[i]
|
||||
try {
|
||||
await new Promise<void>((resolve) => {
|
||||
const timer = window.setTimeout(resolve, 1800)
|
||||
video.onseeked = () => {
|
||||
window.clearTimeout(timer)
|
||||
resolve()
|
||||
}
|
||||
video.currentTime = ts
|
||||
})
|
||||
ctx.drawImage(video, 0, 0, width, height)
|
||||
const dataUrl = canvas.toDataURL('image/jpeg', 0.78)
|
||||
const commaIdx = dataUrl.indexOf(',')
|
||||
const base64 = commaIdx >= 0 ? dataUrl.slice(commaIdx + 1) : ''
|
||||
if (base64.length >= 16) {
|
||||
frames.push({
|
||||
name: `${file.name}#${ts}s`,
|
||||
mime_type: 'image/jpeg',
|
||||
data_base64: base64,
|
||||
previewUrl: dataUrl,
|
||||
width,
|
||||
height,
|
||||
size: Math.round((base64.length * 3) / 4),
|
||||
timestampSec: ts,
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Continue capturing remaining keyframes gracefully.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: file.name || 'video.mp4',
|
||||
mime_type: file.type || 'video/mp4',
|
||||
durationSeconds: Number(duration.toFixed(1)),
|
||||
width: srcW,
|
||||
height: srcH,
|
||||
size: file.size,
|
||||
frames,
|
||||
}
|
||||
} finally {
|
||||
video.removeAttribute('src')
|
||||
video.load()
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
export interface GraphPosition {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export interface LayoutNodeInput {
|
||||
id: string
|
||||
position?: GraphPosition
|
||||
}
|
||||
|
||||
export interface LayoutEdgeInput {
|
||||
id?: string
|
||||
source: string
|
||||
target: string
|
||||
}
|
||||
|
||||
export interface AutoLayoutOptions {
|
||||
startX?: number
|
||||
columnStep?: number
|
||||
centerY?: number
|
||||
rowStep?: number
|
||||
}
|
||||
|
||||
const DEFAULT_START_X = 40
|
||||
const DEFAULT_COLUMN_STEP = 380
|
||||
const DEFAULT_CENTER_Y = 160
|
||||
const DEFAULT_ROW_STEP = 220
|
||||
|
||||
/**
|
||||
* Computes deterministic left-to-right layered DAG positions with bypass-edge
|
||||
* lane separation and cycle-safe fallback ordering.
|
||||
*/
|
||||
export function computeAutoLayoutPositions<
|
||||
TNode extends LayoutNodeInput,
|
||||
TEdge extends LayoutEdgeInput,
|
||||
>(
|
||||
nodes: readonly TNode[],
|
||||
edges: readonly TEdge[],
|
||||
opts: AutoLayoutOptions = {},
|
||||
): Record<string, GraphPosition> {
|
||||
if (!nodes.length) return {}
|
||||
|
||||
const startX = opts.startX ?? DEFAULT_START_X
|
||||
const columnStep = opts.columnStep ?? DEFAULT_COLUMN_STEP
|
||||
const centerY = opts.centerY ?? DEFAULT_CENTER_Y
|
||||
const rowStep = opts.rowStep ?? DEFAULT_ROW_STEP
|
||||
|
||||
const indexById = new Map<string, number>()
|
||||
const nodeById = new Map<string, TNode>()
|
||||
nodes.forEach((node, index) => {
|
||||
indexById.set(node.id, index)
|
||||
nodeById.set(node.id, node)
|
||||
})
|
||||
|
||||
const outgoing = new Map<string, string[]>()
|
||||
const inDegree = new Map<string, number>()
|
||||
const seenEdges = new Set<string>()
|
||||
for (const node of nodes) {
|
||||
outgoing.set(node.id, [])
|
||||
inDegree.set(node.id, 0)
|
||||
}
|
||||
|
||||
const validEdges: Array<{ source: string; target: string }> = []
|
||||
for (const edge of edges) {
|
||||
if (!edge || edge.source === edge.target) continue
|
||||
if (!nodeById.has(edge.source) || !nodeById.has(edge.target)) continue
|
||||
const key = `${edge.source}->${edge.target}`
|
||||
if (seenEdges.has(key)) continue
|
||||
seenEdges.add(key)
|
||||
validEdges.push({ source: edge.source, target: edge.target })
|
||||
outgoing.get(edge.source)?.push(edge.target)
|
||||
inDegree.set(edge.target, (inDegree.get(edge.target) ?? 0) + 1)
|
||||
}
|
||||
|
||||
const rank = new Map<string, number>()
|
||||
for (const node of nodes) {
|
||||
rank.set(node.id, 0)
|
||||
}
|
||||
|
||||
const queue: string[] = nodes
|
||||
.filter((node) => (inDegree.get(node.id) ?? 0) === 0)
|
||||
.map((node) => node.id)
|
||||
const visited = new Set<string>()
|
||||
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift() as string
|
||||
if (visited.has(current)) continue
|
||||
visited.add(current)
|
||||
const currentRank = rank.get(current) ?? 0
|
||||
for (const nextId of outgoing.get(current) ?? []) {
|
||||
const candidateRank = currentRank + 1
|
||||
if (candidateRank > (rank.get(nextId) ?? 0)) {
|
||||
rank.set(nextId, candidateRank)
|
||||
}
|
||||
const remaining = (inDegree.get(nextId) ?? 0) - 1
|
||||
inDegree.set(nextId, remaining)
|
||||
if (remaining <= 0 && !visited.has(nextId)) {
|
||||
queue.push(nextId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (visited.size < nodes.length) {
|
||||
let fallbackRank = 0
|
||||
for (const r of rank.values()) {
|
||||
if (r > fallbackRank) fallbackRank = r
|
||||
}
|
||||
for (const node of nodes) {
|
||||
if (visited.has(node.id)) continue
|
||||
fallbackRank += 1
|
||||
rank.set(node.id, fallbackRank)
|
||||
}
|
||||
}
|
||||
|
||||
const columns = new Map<number, TNode[]>()
|
||||
for (const node of nodes) {
|
||||
const col = rank.get(node.id) ?? 0
|
||||
const bucket = columns.get(col)
|
||||
if (bucket) bucket.push(node)
|
||||
else columns.set(col, [node])
|
||||
}
|
||||
|
||||
const positions: Record<string, GraphPosition> = {}
|
||||
const sortedCols = Array.from(columns.keys()).sort((a, b) => a - b)
|
||||
|
||||
for (const col of sortedCols) {
|
||||
const colNodes = columns.get(col) ?? []
|
||||
colNodes.sort((a, b) => {
|
||||
const ay = a.position?.y ?? centerY
|
||||
const by = b.position?.y ?? centerY
|
||||
if (ay !== by) return ay - by
|
||||
return (indexById.get(a.id) ?? 0) - (indexById.get(b.id) ?? 0)
|
||||
})
|
||||
|
||||
const hasLongBypassEdge = validEdges.some((edge) => {
|
||||
const sr = rank.get(edge.source) ?? 0
|
||||
const tr = rank.get(edge.target) ?? 0
|
||||
return sr < col && tr > col
|
||||
})
|
||||
|
||||
if (colNodes.length === 1) {
|
||||
const loneNode = colNodes[0]
|
||||
const yOffset = hasLongBypassEdge ? Math.round(rowStep * 0.64) : 0
|
||||
positions[loneNode.id] = {
|
||||
x: Math.round(startX + col * columnStep),
|
||||
y: Math.round(centerY + yOffset),
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const halfSpan = (colNodes.length - 1) / 2
|
||||
colNodes.forEach((node, idx) => {
|
||||
positions[node.id] = {
|
||||
x: Math.round(startX + col * columnStep),
|
||||
y: Math.round(centerY + (idx - halfSpan) * rowStep),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return positions
|
||||
}
|
||||
|
||||
export function applyAutoLayout<
|
||||
TNode extends LayoutNodeInput,
|
||||
TEdge extends LayoutEdgeInput,
|
||||
TGraph extends { nodes: TNode[]; edges: TEdge[] },
|
||||
>(graph: TGraph, opts?: AutoLayoutOptions): TGraph {
|
||||
const positions = computeAutoLayoutPositions(graph.nodes, graph.edges, opts)
|
||||
return {
|
||||
...graph,
|
||||
nodes: graph.nodes.map((node) => ({
|
||||
...node,
|
||||
position: positions[node.id] ?? node.position ?? { x: DEFAULT_START_X, y: DEFAULT_CENTER_Y },
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export function hasCrampedOrBackwardsLayout(
|
||||
nodes: readonly LayoutNodeInput[],
|
||||
edges: readonly LayoutEdgeInput[],
|
||||
): boolean {
|
||||
const posById = new Map<string, GraphPosition>()
|
||||
for (const node of nodes) {
|
||||
if (node.position) posById.set(node.id, node.position)
|
||||
}
|
||||
for (const edge of edges) {
|
||||
if (edge.source === edge.target) continue
|
||||
const sPos = posById.get(edge.source)
|
||||
const tPos = posById.get(edge.target)
|
||||
if (!sPos || !tPos) continue
|
||||
if (tPos.x - sPos.x < 120) return true
|
||||
}
|
||||
for (let i = 0; i < nodes.length; i += 1) {
|
||||
const a = nodes[i]?.position
|
||||
if (!a) continue
|
||||
for (let j = i + 1; j < nodes.length; j += 1) {
|
||||
const b = nodes[j]?.position
|
||||
if (!b) continue
|
||||
if (Math.abs(a.x - b.x) < 260 && Math.abs(a.y - b.y) < 90) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
export interface EditableNodeDef {
|
||||
id: string
|
||||
node_type: string
|
||||
title: string
|
||||
title_en?: string
|
||||
description?: string
|
||||
position: { x: number; y: number }
|
||||
enabled: boolean
|
||||
prompt_key?: string | null
|
||||
system_prompt: string
|
||||
prompt: string
|
||||
tools: string[]
|
||||
model_override?: string | null
|
||||
thinking_enabled: boolean
|
||||
max_steps: number
|
||||
timeout_seconds: number
|
||||
native_web_search: boolean
|
||||
guardrails: Record<string, unknown>
|
||||
params: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface EditableEdgeDef {
|
||||
id: string
|
||||
source: string
|
||||
target: string
|
||||
label?: string
|
||||
label_en?: string
|
||||
condition?: string
|
||||
condition_value?: string
|
||||
}
|
||||
|
||||
export interface EditableGraphDef {
|
||||
nodes: EditableNodeDef[]
|
||||
edges: EditableEdgeDef[]
|
||||
}
|
||||
|
||||
export interface WorkflowHistoryState<T> {
|
||||
past: T[]
|
||||
future: T[]
|
||||
}
|
||||
|
||||
export interface WorkflowClipboardPayload<
|
||||
TNode extends EditableNodeDef = EditableNodeDef,
|
||||
TEdge extends EditableEdgeDef = EditableEdgeDef,
|
||||
> {
|
||||
nodes: TNode[]
|
||||
edges: TEdge[]
|
||||
}
|
||||
|
||||
export const MAX_WORKFLOW_HISTORY = 40
|
||||
|
||||
/** Deep-clone a workflow graph snapshot so undo/redo entries never alias live state. */
|
||||
export function cloneGraph<T extends EditableGraphDef>(graph: T): T {
|
||||
const cloneValue =
|
||||
typeof structuredClone === 'function'
|
||||
? structuredClone
|
||||
: <V>(v: V): V => JSON.parse(JSON.stringify(v)) as V
|
||||
return cloneValue({
|
||||
nodes: Array.isArray(graph.nodes) ? graph.nodes : [],
|
||||
edges: Array.isArray(graph.edges) ? graph.edges : [],
|
||||
}) as T
|
||||
}
|
||||
|
||||
export function createEmptyHistory<T>(): WorkflowHistoryState<T> {
|
||||
return { past: [], future: [] }
|
||||
}
|
||||
|
||||
/** Record an undoable snapshot prior to a mutation, pruning oldest entries past maxDepth. */
|
||||
export function pushHistory<T extends EditableGraphDef>(
|
||||
history: WorkflowHistoryState<T>,
|
||||
snapshot: T,
|
||||
maxDepth = MAX_WORKFLOW_HISTORY,
|
||||
): WorkflowHistoryState<T> {
|
||||
const nextPast = [...history.past, cloneGraph(snapshot)]
|
||||
if (nextPast.length > maxDepth) {
|
||||
nextPast.splice(0, nextPast.length - maxDepth)
|
||||
}
|
||||
return { past: nextPast, future: [] }
|
||||
}
|
||||
|
||||
/** Step backward in graph history and move current state onto the redo stack. */
|
||||
export function stepUndo<T extends EditableGraphDef>(
|
||||
history: WorkflowHistoryState<T>,
|
||||
currentSnapshot: T,
|
||||
): { history: WorkflowHistoryState<T>; snapshot: T } | null {
|
||||
if (!history.past.length) return null
|
||||
const previous = cloneGraph(history.past[history.past.length - 1])
|
||||
return {
|
||||
snapshot: previous,
|
||||
history: {
|
||||
past: history.past.slice(0, -1),
|
||||
future: [cloneGraph(currentSnapshot), ...history.future].slice(0, MAX_WORKFLOW_HISTORY),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Step forward in graph history and move current state back onto the undo stack. */
|
||||
export function stepRedo<T extends EditableGraphDef>(
|
||||
history: WorkflowHistoryState<T>,
|
||||
currentSnapshot: T,
|
||||
): { history: WorkflowHistoryState<T>; snapshot: T } | null {
|
||||
if (!history.future.length) return null
|
||||
const next = cloneGraph(history.future[0])
|
||||
return {
|
||||
snapshot: next,
|
||||
history: {
|
||||
past: [...history.past, cloneGraph(currentSnapshot)].slice(-MAX_WORKFLOW_HISTORY),
|
||||
future: history.future.slice(1),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Collect selected nodes and only the edges whose endpoints are both inside the selection. */
|
||||
export function extractClipboardPayload<T extends EditableGraphDef>(
|
||||
graph: T,
|
||||
selectedNodeIds: readonly string[],
|
||||
): WorkflowClipboardPayload {
|
||||
const selectedSet = new Set(selectedNodeIds.filter(Boolean))
|
||||
if (!selectedSet.size) return { nodes: [], edges: [] }
|
||||
const nodes = graph.nodes.filter((n) => selectedSet.has(n.id)).map((n) => ({
|
||||
...n,
|
||||
position: { ...(n.position || { x: 40, y: 140 }) },
|
||||
tools: [...(n.tools || [])],
|
||||
guardrails: { ...(n.guardrails || {}) },
|
||||
params: { ...(n.params || {}) },
|
||||
}))
|
||||
const edges = graph.edges
|
||||
.filter((e) => selectedSet.has(e.source) && selectedSet.has(e.target))
|
||||
.map((e) => ({ ...e }))
|
||||
return { nodes, edges }
|
||||
}
|
||||
|
||||
function generateUniqueId(prefix: string, usedIds: Set<string>): string {
|
||||
const safePrefix = (prefix || 'node').replace(/[^a-zA-Z0-9_-]/g, '_')
|
||||
for (let i = 0; i < 64; i += 1) {
|
||||
const suffix = Math.random().toString(36).slice(2, 6) || `${i}`
|
||||
const candidate = `${safePrefix}_${suffix}`
|
||||
if (!usedIds.has(candidate)) {
|
||||
usedIds.add(candidate)
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
let counter = 1
|
||||
while (usedIds.has(`${safePrefix}_${counter}`)) counter += 1
|
||||
const fallback = `${safePrefix}_${counter}`
|
||||
usedIds.add(fallback)
|
||||
return fallback
|
||||
}
|
||||
|
||||
/** Paste clipboard nodes + internal edges into graph with unique IDs, cleared prompt_key, and stepped offset. */
|
||||
export function pasteClipboardIntoGraph<T extends EditableGraphDef>(
|
||||
graph: T,
|
||||
clipboard: WorkflowClipboardPayload | null | undefined,
|
||||
options: { pasteStep?: number; maxNodes?: number } = {},
|
||||
): {
|
||||
graph: T
|
||||
pastedNodeIds: string[]
|
||||
pastedEdgeIds: string[]
|
||||
truncated: boolean
|
||||
limitReached: boolean
|
||||
} {
|
||||
if (!clipboard || !Array.isArray(clipboard.nodes) || clipboard.nodes.length === 0) {
|
||||
return {
|
||||
graph,
|
||||
pastedNodeIds: [],
|
||||
pastedEdgeIds: [],
|
||||
truncated: false,
|
||||
limitReached: false,
|
||||
}
|
||||
}
|
||||
|
||||
const maxNodes = Math.max(1, options.maxNodes ?? 12)
|
||||
const remaining = maxNodes - graph.nodes.length
|
||||
if (remaining <= 0) {
|
||||
return {
|
||||
graph,
|
||||
pastedNodeIds: [],
|
||||
pastedEdgeIds: [],
|
||||
truncated: true,
|
||||
limitReached: true,
|
||||
}
|
||||
}
|
||||
|
||||
const pasteStep = Math.max(1, options.pasteStep ?? 1)
|
||||
const offset = 40 * pasteStep
|
||||
const usedNodeIds = new Set(graph.nodes.map((n) => n.id))
|
||||
const usedEdgeIds = new Set(graph.edges.map((e) => e.id))
|
||||
|
||||
const nodesToCopy = clipboard.nodes.slice(0, remaining)
|
||||
const truncated = nodesToCopy.length < clipboard.nodes.length
|
||||
const idMap = new Map<string, string>()
|
||||
|
||||
const pastedNodes: EditableNodeDef[] = nodesToCopy.map((src) => {
|
||||
const nextId = generateUniqueId(src.node_type || 'node', usedNodeIds)
|
||||
idMap.set(src.id, nextId)
|
||||
const cloned = cloneGraph({ nodes: [src], edges: [] }).nodes[0]
|
||||
return {
|
||||
...cloned,
|
||||
id: nextId,
|
||||
// Never duplicate built-in prompt_key so pasted nodes own independent inline prompts.
|
||||
prompt_key: null,
|
||||
position: {
|
||||
x: Math.round((src.position?.x ?? 40) + offset),
|
||||
y: Math.round((src.position?.y ?? 140) + offset),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const pastedEdges: EditableEdgeDef[] = (clipboard.edges || [])
|
||||
.filter((edge) => idMap.has(edge.source) && idMap.has(edge.target))
|
||||
.map((edge) => ({
|
||||
...edge,
|
||||
id: generateUniqueId('e-copy', usedEdgeIds),
|
||||
source: idMap.get(edge.source) as string,
|
||||
target: idMap.get(edge.target) as string,
|
||||
}))
|
||||
|
||||
return {
|
||||
graph: {
|
||||
...graph,
|
||||
nodes: [...graph.nodes, ...pastedNodes],
|
||||
edges: [...graph.edges, ...pastedEdges],
|
||||
} as T,
|
||||
pastedNodeIds: pastedNodes.map((n) => n.id),
|
||||
pastedEdgeIds: pastedEdges.map((e) => e.id),
|
||||
truncated,
|
||||
limitReached: false,
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete selected nodes (and attached edges) or selected edges while preserving >= 1 node. */
|
||||
export function deleteSelectionFromGraph<T extends EditableGraphDef>(
|
||||
graph: T,
|
||||
selection: { nodeIds?: readonly string[]; edgeIds?: readonly string[] },
|
||||
): {
|
||||
graph: T
|
||||
changed: boolean
|
||||
blockedMinOne: boolean
|
||||
fallbackNodeId: string
|
||||
} {
|
||||
const nodeIdSet = new Set((selection.nodeIds || []).filter(Boolean))
|
||||
const edgeIdSet = new Set((selection.edgeIds || []).filter(Boolean))
|
||||
|
||||
if (nodeIdSet.size > 0) {
|
||||
const matchedCount = graph.nodes.filter((n) => nodeIdSet.has(n.id)).length
|
||||
if (matchedCount === 0) {
|
||||
return {
|
||||
graph,
|
||||
changed: false,
|
||||
blockedMinOne: false,
|
||||
fallbackNodeId: graph.nodes[0]?.id || '',
|
||||
}
|
||||
}
|
||||
if (graph.nodes.length - matchedCount < 1) {
|
||||
return {
|
||||
graph,
|
||||
changed: false,
|
||||
blockedMinOne: true,
|
||||
fallbackNodeId: graph.nodes[0]?.id || '',
|
||||
}
|
||||
}
|
||||
const nextNodes = graph.nodes.filter((n) => !nodeIdSet.has(n.id))
|
||||
const nextEdges = graph.edges.filter(
|
||||
(e) => !nodeIdSet.has(e.source) && !nodeIdSet.has(e.target) && !edgeIdSet.has(e.id),
|
||||
)
|
||||
return {
|
||||
graph: { ...graph, nodes: nextNodes, edges: nextEdges } as T,
|
||||
changed: true,
|
||||
blockedMinOne: false,
|
||||
fallbackNodeId: nextNodes[0]?.id || '',
|
||||
}
|
||||
}
|
||||
|
||||
if (edgeIdSet.size > 0) {
|
||||
const nextEdges = graph.edges.filter((e) => !edgeIdSet.has(e.id))
|
||||
const changed = nextEdges.length !== graph.edges.length
|
||||
return {
|
||||
graph: changed ? ({ ...graph, edges: nextEdges } as T) : graph,
|
||||
changed,
|
||||
blockedMinOne: false,
|
||||
fallbackNodeId: graph.nodes[0]?.id || '',
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
graph,
|
||||
changed: false,
|
||||
blockedMinOne: false,
|
||||
fallbackNodeId: graph.nodes[0]?.id || '',
|
||||
}
|
||||
}
|
||||
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user