Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3d2d9e9f1 | ||
|
|
6d310f4dbe | ||
|
|
2c439b7235 | ||
|
|
4b2004b7d8 | ||
|
|
41059ca42a | ||
|
|
b7772f664c | ||
|
|
352b34e7c6 | ||
|
|
1e9508f2f1 | ||
|
|
e53c3af355 |
No files matched your search
@@ -179,12 +179,28 @@ Push to remote:
|
||||
### Step 9 — Publish and verify the Gitea Release
|
||||
|
||||
When remote publication is requested, verify the remote tag points to the
|
||||
release commit. Check the tag's Gitea Actions run and its release job. A queued
|
||||
run without an online runner does not publish anything.
|
||||
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
|
||||
using the command below. The publisher inspects changed files against the previous
|
||||
stable release (`scripts/release_scope.py`), pushes OCI `release-manifest:<tag>`,
|
||||
and builds/uploads **only** the affected targets:
|
||||
- `admin` / `backend` / `aiprovider`-only changes (`client.mode == "none"`): builds/pushes only the changed
|
||||
service image(s) + OCI `release-manifest:<tag>`, **skips creating a Gitea Release**,
|
||||
skips desktop packaging and client hotfix updates, and deploys only the changed container(s) on production.
|
||||
- `frontend/public/earth/**`-only changes (`client.mode == "hotfix"`): emits only the L1 Earth hotfix bundle
|
||||
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, and creates a Gitea Release with `release-manifest.json` + hotfix bundle.
|
||||
- `client/**` changes (`client.mode == "full"`): builds cross-platform desktop installers (`--all`) plus the
|
||||
L1 hotfix bundle, and creates a Gitea Release with installers + `release-manifest.json`.
|
||||
|
||||
If the job cannot start or finish, use the packaged client artifacts for the
|
||||
exact tag. Reuse verified artifacts when available, or build with Bun from the
|
||||
tag in a clean checkout. Use an asset directory that contains only this release.
|
||||
Use `--scope auto` (default) or override explicitly with `--scope admin`,
|
||||
`--scope hotfix`, `--scope backend,admin`, or `--scope full`:
|
||||
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag vx.x.x --dry-run
|
||||
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
|
||||
```
|
||||
|
||||
When verified desktop artifacts for the exact tag already exist, pass their
|
||||
directory explicitly. A queued Gitea Actions run does not block local publication.
|
||||
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run
|
||||
|
||||
@@ -4,8 +4,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
# Tagged production releases are published on demand from the workstation.
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
@@ -17,18 +16,18 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Resolve image tags
|
||||
id: meta
|
||||
run: |
|
||||
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
|
||||
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "release_tag=" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Login to registry
|
||||
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
- name: Build and push images
|
||||
env:
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
|
||||
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
run: printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
|
||||
- name: Publish immutable production images
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
run: |
|
||||
export PLANET_RELEASE_DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
|
||||
python3 scripts/production_release.py "$GITHUB_REF_NAME"
|
||||
- name: Build and push staging images
|
||||
if: "!startsWith(github.ref, 'refs/tags/v')"
|
||||
run: |
|
||||
for service in frontend admin backend aiprovider; do
|
||||
extra_build_args=""
|
||||
@@ -52,18 +51,13 @@ jobs:
|
||||
;;
|
||||
esac
|
||||
|
||||
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}"
|
||||
image="$REGISTRY/$IMAGE_NAMESPACE/$service:$GITHUB_SHA"
|
||||
docker build $extra_build_args -t "$image" -f "$dockerfile" "$context"
|
||||
docker push "$image"
|
||||
|
||||
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
|
||||
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
|
||||
docker tag "$image" "$release_image"
|
||||
docker push "$release_image"
|
||||
fi
|
||||
done
|
||||
|
||||
client_release:
|
||||
needs: images
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -98,6 +98,12 @@ the user's login interactive shell instead of assuming a specific dotfile.
|
||||
one-screen (`一屏` / `首屏`) height chain: route roots use `height: 100%`,
|
||||
intermediate wrappers keep `min-height: 0`, and only the intended child owns
|
||||
scrolling.
|
||||
- **Admin Control Design Contract**: Inline controls in the same row must share
|
||||
a `rules.md` density tier (`--an-control-xs/sm/md/lg`, e.g., `32px` filter bar
|
||||
with `0px` height jump on filter reset), centered table selection/switch
|
||||
columns, rounded-square shadowless `.tui-switch`, labeled `操作` columns, and
|
||||
`.an-detail-link` navigation cues; enforced by
|
||||
`scripts/harness/frontend-rules-check.sh` and `scripts/harness/frontend-smoke.mjs`.
|
||||
- **Existing-UI Context Inspection Before Editing**: Whenever changing or
|
||||
extending an existing interface (any non-new screen, such as `/earth/` HUD
|
||||
overlays or existing Admin/Docs pages), inspect surrounding sibling controls,
|
||||
@@ -120,6 +126,11 @@ the user's login interactive shell instead of assuming a specific dotfile.
|
||||
committed files.
|
||||
- Backend service code must use structured logging instead of `print()` or
|
||||
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
|
||||
- **Client-Only Gitea Releases**: Releases without client updates
|
||||
(`client.mode == "none"`) push only changed container images plus OCI
|
||||
`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>`.
|
||||
|
||||
### Conflict Policy
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ AI_ANTHROPIC_VERSION=2023-06-01
|
||||
# DEEPSEEK_API_KEY=replace-with-deepseek-key
|
||||
# DASHSCOPE_API_KEY=replace-with-dashscope-key
|
||||
# MOONSHOT_API_KEY=replace-with-moonshot-key
|
||||
# ZHIPU_API_KEY=replace-with-zhipu-key
|
||||
# META_MODEL_API_KEY=replace-with-meta-key
|
||||
# GEMINI_API_KEY=replace-with-gemini-key
|
||||
# XAI_API_KEY=replace-with-xai-key
|
||||
# OPENROUTER_API_KEY=replace-with-openrouter-key
|
||||
|
||||
# OpenAI-compatible example (vLLM / LM Studio / One API / local gateway)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import hmac
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from aiprovider.config import settings
|
||||
from aiprovider.provider_service import ProviderService
|
||||
@@ -124,3 +126,35 @@ async def analyze(
|
||||
):
|
||||
response.headers["X-Request-ID"] = request.state.request_id
|
||||
return await provider_service.analyze(payload)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/v1/analyze/stream",
|
||||
dependencies=[Depends(verify_service_token)],
|
||||
)
|
||||
async def analyze_stream(
|
||||
payload: SituationalAnalysisRequest,
|
||||
request: Request,
|
||||
provider_service: ProviderService = Depends(get_provider_service),
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
async def event_generator():
|
||||
try:
|
||||
async for item in provider_service.stream_analyze(payload):
|
||||
event_name = str(item.get("event") or "message")
|
||||
yield f"event: {event_name}\ndata: {json.dumps(item, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
detail = exc.detail if isinstance(exc, HTTPException) else exc
|
||||
err_payload = {"event": "error", "detail": str(detail)}
|
||||
yield f"event: error\ndata: {json.dumps(err_payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_generator(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Accel-Buffering": "no",
|
||||
"X-Request-ID": request_id,
|
||||
},
|
||||
)
|
||||
+885
-46
File diff suppressed because it is too large.
Load diff
+23
-2
@@ -1,8 +1,22 @@
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ChatMessage(BaseModel):
|
||||
role: Literal["user", "assistant", "tool"]
|
||||
content: str = Field(default="", max_length=24000)
|
||||
tool_call_id: str | None = Field(default=None, max_length=200)
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
tool_calls: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
class ToolCallRecord(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
arguments: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class AIContentBlock(BaseModel):
|
||||
type: str
|
||||
text: str | None = None
|
||||
@@ -13,13 +27,18 @@ class AIContentBlock(BaseModel):
|
||||
|
||||
class SituationalAnalysisRequest(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
objective: str = Field(..., min_length=1, max_length=20000)
|
||||
objective: str = Field(..., min_length=1, max_length=24000)
|
||||
context: dict[str, Any] = Field(default_factory=dict)
|
||||
observations: list[str] = Field(default_factory=list)
|
||||
constraints: list[str] = Field(default_factory=list)
|
||||
system_prompt: str | None = Field(default=None, max_length=8000)
|
||||
preferred_model: str | None = Field(default=None, max_length=200)
|
||||
thinking: dict[str, Any] | None = None
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=48)
|
||||
tools: list[dict[str, Any]] | None = None
|
||||
tool_choice: str | dict[str, Any] | None = None
|
||||
response_format: dict[str, Any] | None = None
|
||||
native_web_search: bool = False
|
||||
|
||||
|
||||
class SituationalAnalysisResponse(BaseModel):
|
||||
@@ -29,6 +48,8 @@ class SituationalAnalysisResponse(BaseModel):
|
||||
content_blocks: list[AIContentBlock] = Field(default_factory=list)
|
||||
text_blocks: list[str] = Field(default_factory=list)
|
||||
thinking_blocks: list[str] = Field(default_factory=list)
|
||||
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
|
||||
stop_reason: str | None = None
|
||||
raw_response: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
|
||||
@@ -102,5 +102,21 @@
|
||||
"version": "2026-11-11.1",
|
||||
"system_prompt": "你是算力白皮书数据核验提取器。仅提取原文明确写出的国家算力份额、FP32 规模或内部结构数值,输出严格 JSON 候选数组供管理员审核,严禁估算或补齐未出现的国家。",
|
||||
"prompt": "从提供的报告摘录与来源元数据中提取待审核的算力观测候选记录。"
|
||||
},
|
||||
{
|
||||
"key": "earth.news.analysis",
|
||||
"label": "Earth 新闻深层分析",
|
||||
"group": "Earth 新闻",
|
||||
"version": "2026-11-30.1",
|
||||
"system_prompt": "你是智能星球地球热点新闻与地缘基础设施分析师。请基于新闻全文、位置上下文与基础设施邻近关系,给出客观、可溯源的深层研判(Markdown,包含事实摘要、影响范围、关联基础设施与观察建议)。",
|
||||
"prompt": "围绕选中的新闻事件与关联空间坐标展开深度分析,突出对海底光缆、算力枢纽与跨境路由的潜在影响。"
|
||||
},
|
||||
{
|
||||
"key": "memory.compact",
|
||||
"label": "Earth Copilot 会话记忆压缩",
|
||||
"group": "态势参谋",
|
||||
"version": "2026-11-30.1",
|
||||
"system_prompt": "你是对话上下文压缩器。提取已确认事实、关注实体 ID、时间范围与未决问题,输出简洁要点以供后续多轮追问继承。",
|
||||
"prompt": "将较早的多轮地球参谋对话历史压缩为高信息密度记忆摘要,保留实体键与核心结论。"
|
||||
}
|
||||
]
|
||||
@@ -124,7 +124,26 @@ async def get_effective_prompt(db: AsyncSession | None, task_key: str) -> Effect
|
||||
if db is None:
|
||||
return _effective_prompt(definition, None)
|
||||
overrides = await get_prompt_overrides(db)
|
||||
return _effective_prompt(definition, overrides.get(task_key))
|
||||
override = overrides.get(task_key)
|
||||
if not override:
|
||||
try:
|
||||
from app.services.ai.workflow_registry import resolve_prompt_override_from_workflows
|
||||
|
||||
wf_prompt = await resolve_prompt_override_from_workflows(db, task_key)
|
||||
except Exception:
|
||||
wf_prompt = None
|
||||
if wf_prompt is not None:
|
||||
sys_p, user_p = wf_prompt
|
||||
has_wf = bool((sys_p or "").strip() or (user_p or "").strip())
|
||||
if has_wf and (
|
||||
sys_p != definition.system_prompt or user_p != definition.prompt
|
||||
):
|
||||
override = {
|
||||
"system_prompt": sys_p,
|
||||
"prompt": user_p,
|
||||
"updated_at": "",
|
||||
}
|
||||
return _effective_prompt(definition, override)
|
||||
|
||||
|
||||
async def save_prompt_override(
|
||||
|
||||
@@ -2,12 +2,14 @@ from app.api.v1 import card_images
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1 import (
|
||||
ai,
|
||||
api_keys,
|
||||
auth,
|
||||
users,
|
||||
datasource_config,
|
||||
datasources,
|
||||
docs,
|
||||
earth,
|
||||
client_updates,
|
||||
tasks,
|
||||
dashboard,
|
||||
alerts,
|
||||
@@ -40,11 +42,13 @@ api_router.include_router(datasources.router, prefix="/datasources", tags=["data
|
||||
api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"])
|
||||
api_router.include_router(docs.router, prefix="/docs", tags=["docs"])
|
||||
api_router.include_router(earth.router, prefix="/earth", tags=["earth"])
|
||||
api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"])
|
||||
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
|
||||
api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboard"])
|
||||
api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"])
|
||||
api_router.include_router(settings.router, prefix="/settings", tags=["settings"])
|
||||
api_router.include_router(system_control.router, prefix="/system", tags=["system"])
|
||||
api_router.include_router(api_keys.router, prefix="/system/api-keys", tags=["api-keys"])
|
||||
api_router.include_router(data_products.router, prefix="/data-products", tags=["data-products"])
|
||||
api_router.include_router(compute_intelligence.router, prefix="/data-products/compute", tags=["compute"])
|
||||
api_router.include_router(
|
||||
|
||||
@@ -49,8 +49,10 @@ from app.services.playground_chat_service import (
|
||||
)
|
||||
from app.services.situational_alert_ai_brief import build_situational_alert_brief_request
|
||||
from app.services.business_logs import emit_business_log, exception_context
|
||||
from app.api.v1.ai_workflows import router as ai_workflows_router
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(ai_workflows_router)
|
||||
logger = get_logger(__name__, service="api")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
"""Admin AI Advisor workflow management, run history, and pure-chat Playground SSE endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.ai_tasks.prompts import reset_prompt_override
|
||||
from app.core.access_gate import require_admin_user
|
||||
from app.core.logging import get_logger
|
||||
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.services.ai.thinking_sanitizer import strip_thinking_text
|
||||
from app.services.ai.workflow_registry import (
|
||||
ensure_builtin_workflows,
|
||||
generate_workflow_optimization_proposal,
|
||||
get_workflow_detail,
|
||||
list_workflows,
|
||||
publish_workflow,
|
||||
resolve_runtime_workflow_node,
|
||||
rollback_workflow,
|
||||
save_workflow_draft,
|
||||
)
|
||||
from app.services.ai_client import get_ai_provider_client
|
||||
from app.services.alert_ai_brief import build_alert_brief_request
|
||||
from app.services.bgp_ai_brief import build_bgp_brief_request
|
||||
from app.services.compute_center_locations import build_compute_center_location_query
|
||||
from app.services.location.agent_resolver import (
|
||||
run_controlled_location_agent,
|
||||
run_l1_structured_facility_resolvers,
|
||||
)
|
||||
from app.services.situational_alert_ai_brief import build_situational_alert_brief_request
|
||||
from app.api.v1.settings import get_web_search_client
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="ai_workflows")
|
||||
|
||||
|
||||
class WorkflowDraftUpdateRequest(BaseModel):
|
||||
graph: dict[str, Any]
|
||||
|
||||
|
||||
class WorkflowPublishRequest(BaseModel):
|
||||
graph: dict[str, Any] | None = None
|
||||
change_summary: str = ""
|
||||
|
||||
|
||||
class WorkflowRollbackRequest(BaseModel):
|
||||
revision: int = Field(..., ge=1)
|
||||
|
||||
|
||||
class WorkflowOptimizeRequest(BaseModel):
|
||||
instruction: str = Field(..., min_length=1, max_length=2000)
|
||||
run_id: str | None = None
|
||||
|
||||
|
||||
class WorkflowFixtureCreateRequest(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=160)
|
||||
description: str = ""
|
||||
earth_context: dict[str, Any] = Field(default_factory=dict)
|
||||
context_json: dict[str, Any] | None = None
|
||||
sample_question: str = ""
|
||||
|
||||
|
||||
class AdvisorChatMessageInput(BaseModel):
|
||||
role: str = Field(..., pattern="^(user|assistant)$")
|
||||
content: str = Field(..., min_length=1, max_length=16000)
|
||||
|
||||
|
||||
class AdvisorPlaygroundChatRequest(BaseModel):
|
||||
workflow_id: str = "default.general"
|
||||
use_draft: bool = False
|
||||
message: str = Field(..., min_length=1, max_length=16000)
|
||||
history: list[AdvisorChatMessageInput] = Field(default_factory=list)
|
||||
earth_context: dict[str, Any] | None = None
|
||||
model_override: str | None = None
|
||||
|
||||
|
||||
def _sse_frame(event: str, payload: dict[str, Any]) -> str:
|
||||
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
|
||||
|
||||
|
||||
def _actor_label(user: User) -> str:
|
||||
return str(getattr(user, "username", None) or getattr(user, "email", None) or f"user:{user.id}")
|
||||
|
||||
|
||||
@router.get("/workflows")
|
||||
async def list_ai_workflows(
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
items = await list_workflows(db)
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
@router.get("/workflows/{workflow_id}")
|
||||
async def get_ai_workflow_detail(
|
||||
workflow_id: str,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await get_workflow_detail(db, workflow_id)
|
||||
|
||||
|
||||
@router.put("/workflows/{workflow_id}/draft")
|
||||
async def update_ai_workflow_draft(
|
||||
workflow_id: str,
|
||||
payload: WorkflowDraftUpdateRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await save_workflow_draft(
|
||||
db,
|
||||
workflow_id,
|
||||
payload.graph,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/publish")
|
||||
async def publish_ai_workflow(
|
||||
workflow_id: str,
|
||||
payload: WorkflowPublishRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
published = await publish_workflow(
|
||||
db,
|
||||
workflow_id,
|
||||
graph=payload.graph,
|
||||
change_summary=payload.change_summary,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
# Clear matching legacy SystemSetting prompt overrides so published workflow prompts win cleanly.
|
||||
for node in (published.get("published_graph") or {}).get("nodes") or []:
|
||||
prompt_key = str((node or {}).get("prompt_key") or "").strip()
|
||||
if prompt_key:
|
||||
try:
|
||||
await reset_prompt_override(db, prompt_key)
|
||||
except Exception:
|
||||
continue
|
||||
return published
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/rollback")
|
||||
async def rollback_ai_workflow(
|
||||
workflow_id: str,
|
||||
payload: WorkflowRollbackRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await rollback_workflow(
|
||||
db,
|
||||
workflow_id,
|
||||
payload.revision,
|
||||
actor=_actor_label(admin),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/optimize")
|
||||
async def optimize_ai_workflow(
|
||||
workflow_id: str,
|
||||
payload: WorkflowOptimizeRequest,
|
||||
_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 generate_workflow_optimization_proposal(
|
||||
db,
|
||||
workflow_id,
|
||||
instruction=payload.instruction,
|
||||
run_id=payload.run_id,
|
||||
ai_client=ai_client,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/fixtures")
|
||||
async def create_ai_workflow_fixture(
|
||||
workflow_id: str,
|
||||
payload: WorkflowFixtureCreateRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
await ensure_builtin_workflows(db)
|
||||
wf = (
|
||||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
|
||||
).scalar_one_or_none()
|
||||
if wf is None:
|
||||
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
|
||||
ctx_payload = dict(payload.context_json if payload.context_json is not None else payload.earth_context or {})
|
||||
if payload.description.strip() and "_description" not in ctx_payload:
|
||||
ctx_payload["_description"] = payload.description.strip()
|
||||
row = AIWorkflowFixture(
|
||||
workflow_id=workflow_id,
|
||||
name=payload.name.strip(),
|
||||
sample_question=payload.sample_question.strip(),
|
||||
context_json=ctx_payload,
|
||||
created_by=_actor_label(admin),
|
||||
)
|
||||
db.add(row)
|
||||
await db.commit()
|
||||
await db.refresh(row)
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
@router.delete("/workflows/{workflow_id}/fixtures/{fixture_id}")
|
||||
async def delete_ai_workflow_fixture(
|
||||
workflow_id: str,
|
||||
fixture_id: int,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
row = (
|
||||
await db.execute(
|
||||
select(AIWorkflowFixture)
|
||||
.where(AIWorkflowFixture.id == fixture_id)
|
||||
.where(AIWorkflowFixture.workflow_id == workflow_id)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Fixture not found")
|
||||
await db.delete(row)
|
||||
await db.commit()
|
||||
return {"deleted": True, "id": fixture_id}
|
||||
|
||||
|
||||
@router.get("/runs")
|
||||
async def list_ai_workflow_runs(
|
||||
workflow_id: str | None = None,
|
||||
status: str | 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)
|
||||
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]
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
@router.get("/runs/{run_id}")
|
||||
async def get_ai_workflow_run_detail(
|
||||
run_id: str,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
row = (
|
||||
await db.execute(select(WorkflowRun).where(WorkflowRun.id == run_id))
|
||||
).scalar_one_or_none()
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Workflow run not found")
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
async def _resolve_playground_slash_or_workflow(
|
||||
*,
|
||||
db: AsyncSession,
|
||||
workflow_id: str,
|
||||
message: str,
|
||||
use_draft: bool,
|
||||
earth_context: dict[str, Any] | None,
|
||||
) -> tuple[str, list[str], SituationalAnalysisRequest | None, dict[str, Any]]:
|
||||
"""Map slash commands or selected workflow into a runnable prompt/context bundle."""
|
||||
trimmed = message.strip()
|
||||
active_wf = workflow_id or "default.general"
|
||||
tool_trace: list[str] = ["intake"]
|
||||
extra_meta: dict[str, Any] = {}
|
||||
|
||||
if trimmed.startswith("/bgp-brief"):
|
||||
active_wf = "ops.bgp_brief"
|
||||
req, facts, ctx = await build_bgp_brief_request(db)
|
||||
tool_trace.extend(["query_bgp_incidents", "query_bgp_anomalies", "synthesize"])
|
||||
extra_meta["facts"] = facts
|
||||
extra_meta["context_keys"] = sorted((ctx or {}).keys())
|
||||
return active_wf, tool_trace, req, extra_meta
|
||||
|
||||
if trimmed.startswith("/alerts-brief"):
|
||||
active_wf = "ops.alerts_brief"
|
||||
req, facts, ctx = await build_alert_brief_request(db)
|
||||
tool_trace.extend(["query_system_alerts", "synthesize"])
|
||||
extra_meta["facts"] = facts
|
||||
extra_meta["context_keys"] = sorted((ctx or {}).keys())
|
||||
return active_wf, tool_trace, req, extra_meta
|
||||
|
||||
if trimmed.startswith("/situational-brief"):
|
||||
active_wf = "ops.situational_alerts_brief"
|
||||
req, facts, ctx = await build_situational_alert_brief_request(db)
|
||||
tool_trace.extend(["query_system_alerts", "query_bgp_incidents", "synthesize"])
|
||||
extra_meta["facts"] = facts
|
||||
extra_meta["context_keys"] = sorted((ctx or {}).keys())
|
||||
return active_wf, tool_trace, req, extra_meta
|
||||
|
||||
if trimmed.startswith("/locate"):
|
||||
active_wf = "location.resolve_unknown"
|
||||
target_name = trimmed[len("/locate") :].strip() or "Unknown Facility"
|
||||
query = build_compute_center_location_query(name=target_name)
|
||||
l1_candidates, _, _ = await run_l1_structured_facility_resolvers(query, db=db)
|
||||
tool_trace.extend(["l0_normalize", "l1_knowledge"])
|
||||
if l1_candidates:
|
||||
c0 = l1_candidates[0]
|
||||
extra_meta["direct_reply"] = (
|
||||
f"已通过 **L1 设施知识库** (`{c0.source}`) 定位到 **{c0.display_name}**:\n\n"
|
||||
f"- 国家/地区:{c0.country or '-'}\n"
|
||||
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`,置信度 `{c0.confidence:.2f}`)\n"
|
||||
f"- 说明:{c0.source_note}"
|
||||
)
|
||||
return active_wf, tool_trace, None, extra_meta
|
||||
try:
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
web_search_client = await get_web_search_client(db)
|
||||
res, term = await run_controlled_location_agent(
|
||||
provider_client=provider_client,
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
db=db,
|
||||
)
|
||||
tool_trace.extend(["l2_agent_research", "l3_geo_guardrail"])
|
||||
if res.candidates:
|
||||
c0 = res.candidates[0]
|
||||
extra_meta["direct_reply"] = (
|
||||
f"已通过 **L2/L3 位置 Agent** 核验 **{c0.display_name}**:\n\n"
|
||||
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`)\n"
|
||||
f"- 结论:{c0.source_note}"
|
||||
)
|
||||
elif term:
|
||||
extra_meta["direct_reply"] = f"位置 Agent 判定该目标属于终态 `{term}`:{res.failure_reason or ''}"
|
||||
else:
|
||||
extra_meta["direct_reply"] = f"未能定位目标「{target_name}」:{res.failure_reason or '暂无可核验公开证据'}。"
|
||||
except Exception as exc:
|
||||
extra_meta["direct_reply"] = f"位置 Agent 调试执行失败:{exc}"
|
||||
return active_wf, tool_trace, None, extra_meta
|
||||
|
||||
detail = await get_workflow_detail(db, active_wf)
|
||||
wf_obj = detail["workflow"]
|
||||
graph = (wf_obj.get("draft_graph") if use_draft and wf_obj.get("draft_graph") else wf_obj.get("published_graph")) or {}
|
||||
nodes = graph.get("nodes") or []
|
||||
llm_node = next((n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}), nodes[0] if nodes else {})
|
||||
|
||||
# Apply node configuration from graph (or fallback)
|
||||
node_cfg = await resolve_runtime_workflow_node(
|
||||
db,
|
||||
active_wf,
|
||||
str(llm_node.get("id") or "default_advisor"),
|
||||
use_draft=use_draft,
|
||||
) or llm_node
|
||||
for n in nodes:
|
||||
nid = str(n.get("id") or "")
|
||||
if nid and nid not in tool_trace:
|
||||
tool_trace.append(nid)
|
||||
|
||||
ctx_payload: dict[str, Any] = {}
|
||||
if isinstance(earth_context, dict) and earth_context:
|
||||
ctx_payload["earth_context"] = earth_context
|
||||
extra_meta["earth_context_attached"] = True
|
||||
|
||||
sys_prompt = str(node_cfg.get("system_prompt") or "").strip() or (
|
||||
"你是智能星球 AI 参谋调试助手。结合附带的地球本地上下文(如有)和用户问题给出严谨、清晰的中文回复。"
|
||||
)
|
||||
node_prompt = str(node_cfg.get("prompt") or "").strip()
|
||||
objective = f"{node_prompt}\n\n用户请求:{trimmed}" if node_prompt else trimmed
|
||||
req = SituationalAnalysisRequest(
|
||||
title=f"AI Advisor ({wf_obj.get('name') or active_wf})",
|
||||
objective=objective,
|
||||
system_prompt=sys_prompt,
|
||||
context=ctx_payload,
|
||||
preferred_model=str(node_cfg.get("model_override") or "") or None,
|
||||
thinking={"mode": "auto"} if bool(node_cfg.get("thinking_enabled", True)) else {"mode": "off"},
|
||||
native_web_search=bool(node_cfg.get("native_web_search", False)),
|
||||
)
|
||||
return active_wf, tool_trace, req, extra_meta
|
||||
|
||||
|
||||
@router.post("/playground/chat/stream")
|
||||
async def stream_advisor_playground_chat(
|
||||
payload: AdvisorPlaygroundChatRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Stream AI Advisor Playground execution over SSE (`meta`, `node`, `reasoning`, `text`, `done`, `error`)."""
|
||||
run_id = f"run_{uuid4().hex[:16]}"
|
||||
started_at = datetime.now(UTC)
|
||||
|
||||
async def event_stream():
|
||||
active_wf = payload.workflow_id or "default.general"
|
||||
tool_trace: list[str] = []
|
||||
status_value = "completed"
|
||||
error_text = ""
|
||||
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))
|
||||
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),
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
status_value = "failed"
|
||||
error_text = str(exc)
|
||||
logger.warning_event(
|
||||
"Advisor playground SSE stream failed",
|
||||
event="ai_workflows.playground.stream_failed",
|
||||
context={"run_id": run_id, "workflow_id": active_wf, "error": error_text},
|
||||
)
|
||||
yield _sse_frame("error", {"message": error_text, "run_id": run_id})
|
||||
finally:
|
||||
try:
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=run_id,
|
||||
workflow_id=active_wf,
|
||||
status=status_value,
|
||||
access_tier="admin",
|
||||
actor_key=_actor_label(admin),
|
||||
question=payload.message[:500],
|
||||
input_params={
|
||||
"use_draft": payload.use_draft,
|
||||
"model_override": payload.model_override,
|
||||
"has_earth_context": bool(payload.earth_context),
|
||||
},
|
||||
tool_trace=tool_trace,
|
||||
budget_used={"steps": len(tool_trace)},
|
||||
error_message=error_text[:500],
|
||||
started_at=started_at,
|
||||
completed_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
try:
|
||||
await db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Admin endpoints for managing internal UE5 and external partner API keys."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_admin_user
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.services.api_keys import (
|
||||
EARTH_ALL_READ_SCOPE,
|
||||
EARTH_READ_SCOPES,
|
||||
create_api_key,
|
||||
delete_api_key,
|
||||
list_api_keys,
|
||||
revoke_api_key,
|
||||
serialize_api_key,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class ApiKeyCreateRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
scopes: list[str] = Field(default_factory=lambda: [EARTH_ALL_READ_SCOPE])
|
||||
rate_limit_per_minute: Optional[int] = Field(default=None, ge=0, le=100_000)
|
||||
expires_in_days: Optional[int] = Field(default=None, ge=0, le=3650)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_api_keys(
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
items = [serialize_api_key(record) for record in await list_api_keys(db)]
|
||||
return {
|
||||
"items": items,
|
||||
"available_scopes": [EARTH_ALL_READ_SCOPE, *sorted(EARTH_READ_SCOPES)],
|
||||
}
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_new_api_key(
|
||||
payload: ApiKeyCreateRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
record, raw_key = await create_api_key(
|
||||
db,
|
||||
name=payload.name,
|
||||
scopes=payload.scopes,
|
||||
rate_limit_per_minute=payload.rate_limit_per_minute,
|
||||
expires_in_days=payload.expires_in_days,
|
||||
created_by_user_id=admin.id,
|
||||
)
|
||||
return {
|
||||
"item": serialize_api_key(record),
|
||||
"api_key": raw_key,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{key_id}/revoke")
|
||||
async def revoke_existing_api_key(
|
||||
key_id: int,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
record = await revoke_api_key(db, key_id)
|
||||
return {"item": serialize_api_key(record)}
|
||||
|
||||
|
||||
@router.delete("/{key_id}")
|
||||
async def delete_existing_api_key(
|
||||
key_id: int,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
await delete_api_key(db, key_id)
|
||||
return {"status": "deleted", "id": key_id}
|
||||
@@ -2,14 +2,23 @@ import asyncio
|
||||
from hashlib import sha256
|
||||
import ipaddress
|
||||
import time
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request, status
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.access_gate import (
|
||||
EARTH_SESSION_COOKIE,
|
||||
check_sliding_rate_limit,
|
||||
create_earth_session_token,
|
||||
verify_desktop_handshake,
|
||||
verify_turnstile_token,
|
||||
verify_web_same_origin,
|
||||
)
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import OtpPurpose, UserRole
|
||||
from app.core.logging import get_logger
|
||||
@@ -487,3 +496,66 @@ async def reset_password(payload: ResetPasswordRequest, db: AsyncSession = Depen
|
||||
)
|
||||
await db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
class EarthSessionRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
client_type: Literal["web", "desktop"] = "web"
|
||||
turnstile_token: Optional[str] = None
|
||||
|
||||
|
||||
def _is_https_request(request: Request) -> bool:
|
||||
forwarded_proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
|
||||
return forwarded_proto == "https" or request.url.scheme == "https"
|
||||
|
||||
|
||||
@router.post("/earth-session")
|
||||
async def create_earth_session(
|
||||
request: Request,
|
||||
response: Response,
|
||||
payload: EarthSessionRequest | None = Body(default=None),
|
||||
):
|
||||
"""Mint a short-lived Earth session credential for zero-login Web or Desktop Earth."""
|
||||
body = payload or EarthSessionRequest()
|
||||
client_ip = _client_ip(request)
|
||||
|
||||
if body.client_type == "desktop":
|
||||
await check_sliding_rate_limit(
|
||||
f"earth_session:desktop:{client_ip}",
|
||||
limit=120,
|
||||
window_seconds=3600,
|
||||
detail="Too many desktop Earth session requests",
|
||||
)
|
||||
client_header = await verify_desktop_handshake(request)
|
||||
token, ttl_seconds = create_earth_session_token("desktop", client_id=client_header)
|
||||
return {
|
||||
"token": token,
|
||||
"expires_in": ttl_seconds,
|
||||
"client_type": "desktop",
|
||||
}
|
||||
|
||||
await check_sliding_rate_limit(
|
||||
f"earth_session:web:{client_ip}",
|
||||
limit=60,
|
||||
window_seconds=3600,
|
||||
detail="Too many web Earth session requests",
|
||||
)
|
||||
verify_web_same_origin(request)
|
||||
await verify_turnstile_token(body.turnstile_token, client_ip)
|
||||
token, ttl_seconds = create_earth_session_token("web", client_id=client_ip)
|
||||
response.set_cookie(
|
||||
key=EARTH_SESSION_COOKIE,
|
||||
value=token,
|
||||
max_age=ttl_seconds,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
secure=_is_https_request(request),
|
||||
path="/",
|
||||
)
|
||||
return {
|
||||
"expires_in": ttl_seconds,
|
||||
"ws_token": token,
|
||||
"client_type": "web",
|
||||
"turnstile_required": bool(str(settings.TURNSTILE_SECRET_KEY or "").strip()),
|
||||
}
|
||||
@@ -5,6 +5,7 @@ from fastapi.responses import FileResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.enums import UserRole
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
@@ -57,7 +58,7 @@ async def upload_image(file: UploadFile = File(...), _actor: User = Depends(imag
|
||||
return await run_in_threadpool(store_image, content, (file.filename or "Image")[:200])
|
||||
|
||||
|
||||
@router.get("/files/{filename}")
|
||||
@router.get("/files/{filename}", dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True))])
|
||||
async def image_file(filename: str):
|
||||
path = uploaded_path(filename)
|
||||
if not path.is_file():
|
||||
@@ -83,7 +84,7 @@ async def targets(
|
||||
return {"items": await search_targets(db, entity_type, scope, q.strip(), limit)}
|
||||
|
||||
|
||||
@router.get("/resolve")
|
||||
@router.get("/resolve", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def resolve(
|
||||
response: Response,
|
||||
entity_type: EntityType,
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Client L1 Earth hot-update manifest and bundle hosting endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import tarfile
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
bearer_optional = HTTPBearer(auto_error=False)
|
||||
|
||||
DEFAULT_CLIENT_UPDATES_DIR = Path(__file__).resolve().parents[3] / "data" / "client-updates"
|
||||
MAX_HOTFIX_BUNDLE_BYTES = 32 * 1024 * 1024
|
||||
MAX_HOTFIX_FILES = 2000
|
||||
MAX_HOTFIX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
|
||||
SEMVER_PATTERN = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$")
|
||||
SAFE_BUNDLE_FILENAME_PATTERN = re.compile(r"^planet-earth-bundle-[0-9A-Za-z._-]+\.tar\.gz$")
|
||||
|
||||
|
||||
def get_client_updates_dir() -> Path:
|
||||
configured = str(settings.CLIENT_UPDATES_DIR or "").strip()
|
||||
if configured:
|
||||
return Path(configured)
|
||||
return DEFAULT_CLIENT_UPDATES_DIR
|
||||
|
||||
|
||||
def _manifest_path(updates_dir: Path) -> Path:
|
||||
return updates_dir / "manifest.json"
|
||||
|
||||
|
||||
def _atomic_write_bytes(target: Path, content: bytes) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = target.with_name(f".{target.name}.{os.getpid()}.{uuid4().hex}.tmp")
|
||||
try:
|
||||
tmp_path.write_bytes(content)
|
||||
os.replace(tmp_path, target)
|
||||
except Exception:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def _validate_hotfix_tar_gz(content: bytes) -> dict[str, int]:
|
||||
if not content:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle archive is empty")
|
||||
|
||||
file_count = 0
|
||||
total_size = 0
|
||||
has_index_html = False
|
||||
|
||||
try:
|
||||
with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as archive:
|
||||
for member in archive.getmembers():
|
||||
raw_name = member.name or ""
|
||||
if "\\" in raw_name or "\0" in raw_name:
|
||||
raise HTTPException(status_code=400, detail=f"Unsafe archive entry path: {raw_name!r}")
|
||||
if member.issym() or member.islnk() or member.isdev() or member.ischr() or member.isblk() or member.isfifo():
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported special archive entry: {raw_name!r}")
|
||||
|
||||
stripped = raw_name.lstrip("./") if raw_name.startswith("./") else raw_name
|
||||
while stripped.startswith("./"):
|
||||
stripped = stripped[2:]
|
||||
stripped = stripped.rstrip("/")
|
||||
|
||||
if raw_name.startswith("/"):
|
||||
raise HTTPException(status_code=400, detail=f"Absolute archive entry path is forbidden: {raw_name!r}")
|
||||
|
||||
if stripped in ("", "."):
|
||||
if member.isdir():
|
||||
continue
|
||||
raise HTTPException(status_code=400, detail="Empty archive file path")
|
||||
|
||||
segments = stripped.split("/")
|
||||
if any(seg in ("", ".", "..") for seg in segments):
|
||||
raise HTTPException(status_code=400, detail=f"Path traversal forbidden in archive: {raw_name!r}")
|
||||
|
||||
if member.isdir():
|
||||
continue
|
||||
if not member.isreg():
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported archive entry type: {raw_name!r}")
|
||||
|
||||
file_count += 1
|
||||
if file_count > MAX_HOTFIX_FILES:
|
||||
raise HTTPException(status_code=400, detail="Archive exceeds maximum allowed file count")
|
||||
|
||||
total_size += max(0, int(member.size))
|
||||
if total_size > MAX_HOTFIX_UNCOMPRESSED_BYTES:
|
||||
raise HTTPException(status_code=400, detail="Archive exceeds maximum uncompressed size limit")
|
||||
|
||||
if stripped == "index.html":
|
||||
has_index_html = True
|
||||
except HTTPException:
|
||||
raise
|
||||
except (tarfile.TarError, EOFError, OSError, ValueError) as exc:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid gzip tar archive: {exc}") from exc
|
||||
|
||||
if not has_index_html:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle must include index.html at root")
|
||||
|
||||
return {"filesCount": file_count, "uncompressedBytes": total_size}
|
||||
|
||||
|
||||
def _default_manifest() -> dict[str, Any]:
|
||||
return {
|
||||
"shell": {
|
||||
"version": settings.VERSION,
|
||||
"minRequired": settings.CLIENT_MIN_SHELL_VERSION,
|
||||
"downloadUrl": settings.CLIENT_RELEASE_PAGE_URL,
|
||||
"releaseNotes": "",
|
||||
},
|
||||
"bundle": None,
|
||||
}
|
||||
|
||||
|
||||
def _read_manifest(updates_dir: Path) -> dict[str, Any]:
|
||||
manifest_file = _manifest_path(updates_dir)
|
||||
if not manifest_file.is_file():
|
||||
return _default_manifest()
|
||||
try:
|
||||
payload = json.loads(manifest_file.read_text(encoding="utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
return _default_manifest()
|
||||
return payload
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return _default_manifest()
|
||||
|
||||
|
||||
async def _require_update_publisher(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_optional),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> str:
|
||||
publish_token = request.headers.get("X-Client-Update-Token")
|
||||
if publish_token is not None:
|
||||
expected = str(settings.CLIENT_UPDATE_PUBLISH_TOKEN or "").strip()
|
||||
if not expected or not hmac.compare_digest(publish_token.strip(), expected):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid client update publish token",
|
||||
)
|
||||
return "ci-token"
|
||||
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
|
||||
user = await get_current_user(credentials=credentials, db=db)
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Admin privileges required",
|
||||
)
|
||||
return f"admin:{user.username}"
|
||||
|
||||
|
||||
def _validate_semver(value: str, field_name: str) -> str:
|
||||
cleaned = str(value or "").strip().lstrip("vV")
|
||||
if not SEMVER_PATTERN.match(cleaned):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid semantic version for {field_name}: {value!r}",
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
@router.get("/update-manifest")
|
||||
async def get_client_update_manifest(
|
||||
platform: str = "",
|
||||
arch: str = "",
|
||||
shell: str = "",
|
||||
bundle: str = "",
|
||||
):
|
||||
updates_dir = get_client_updates_dir()
|
||||
manifest = _read_manifest(updates_dir)
|
||||
bundle_info = manifest.get("bundle")
|
||||
if isinstance(bundle_info, dict):
|
||||
filename = Path(str(bundle_info.get("url") or "")).name
|
||||
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename) or not (updates_dir / filename).is_file():
|
||||
manifest = {**manifest, "bundle": None}
|
||||
|
||||
logger.debug_event(
|
||||
"Served client update manifest",
|
||||
event="client_updates.manifest.read",
|
||||
context={
|
||||
"platform": platform or None,
|
||||
"arch": arch or None,
|
||||
"shell": shell or None,
|
||||
"bundle": bundle or None,
|
||||
"has_bundle": bool(manifest.get("bundle")),
|
||||
},
|
||||
)
|
||||
return JSONResponse(content=manifest, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/updates/files/{filename}")
|
||||
async def download_client_hotfix_bundle(filename: str):
|
||||
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename):
|
||||
raise HTTPException(status_code=400, detail="Invalid client hotfix bundle filename")
|
||||
|
||||
updates_dir = get_client_updates_dir().resolve()
|
||||
target = (updates_dir / filename).resolve()
|
||||
if target.parent != updates_dir or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="Client hotfix bundle not found")
|
||||
|
||||
return FileResponse(
|
||||
path=target,
|
||||
media_type="application/gzip",
|
||||
filename=filename,
|
||||
headers={"Cache-Control": "public, max-age=31536000, immutable"},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/updates/bundle")
|
||||
async def publish_client_hotfix_bundle(
|
||||
file: UploadFile = File(...),
|
||||
version: str = Form(...),
|
||||
min_shell_version: str = Form(""),
|
||||
release_notes: str = Form(""),
|
||||
shell_version: str = Form(""),
|
||||
shell_min_required: str = Form(""),
|
||||
shell_download_url: str = Form(""),
|
||||
publisher: str = Depends(_require_update_publisher),
|
||||
):
|
||||
normalized_version = _validate_semver(version, "version")
|
||||
normalized_min_shell = _validate_semver(
|
||||
min_shell_version or settings.CLIENT_MIN_SHELL_VERSION or normalized_version,
|
||||
"min_shell_version",
|
||||
)
|
||||
|
||||
content = await file.read(MAX_HOTFIX_BUNDLE_BYTES + 1)
|
||||
if len(content) > MAX_HOTFIX_BUNDLE_BYTES:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle exceeds 32 MiB limit")
|
||||
|
||||
archive_meta = _validate_hotfix_tar_gz(content)
|
||||
sha256_hex = hashlib.sha256(content).hexdigest()
|
||||
bundle_filename = f"planet-earth-bundle-{normalized_version}.tar.gz"
|
||||
updates_dir = get_client_updates_dir()
|
||||
|
||||
_atomic_write_bytes(updates_dir / bundle_filename, content)
|
||||
|
||||
existing_manifest = _read_manifest(updates_dir)
|
||||
existing_shell = existing_manifest.get("shell") if isinstance(existing_manifest.get("shell"), dict) else {}
|
||||
|
||||
resolved_shell_version = (
|
||||
_validate_semver(shell_version, "shell_version")
|
||||
if str(shell_version or "").strip()
|
||||
else str(existing_shell.get("version") or settings.VERSION)
|
||||
)
|
||||
resolved_shell_min = (
|
||||
_validate_semver(shell_min_required, "shell_min_required")
|
||||
if str(shell_min_required or "").strip()
|
||||
else str(existing_shell.get("minRequired") or settings.CLIENT_MIN_SHELL_VERSION)
|
||||
)
|
||||
resolved_shell_url = str(shell_download_url or "").strip() or str(
|
||||
existing_shell.get("downloadUrl") or settings.CLIENT_RELEASE_PAGE_URL
|
||||
)
|
||||
if not resolved_shell_url.startswith(("https://", "http://")):
|
||||
raise HTTPException(status_code=400, detail="shell_download_url must start with http:// or https://")
|
||||
|
||||
cleaned_notes = str(release_notes or "").strip()[:4000]
|
||||
manifest: dict[str, Any] = {
|
||||
"shell": {
|
||||
"version": resolved_shell_version,
|
||||
"minRequired": resolved_shell_min,
|
||||
"downloadUrl": resolved_shell_url,
|
||||
"releaseNotes": cleaned_notes or str(existing_shell.get("releaseNotes") or ""),
|
||||
},
|
||||
"bundle": {
|
||||
"version": normalized_version,
|
||||
"minShellVersion": normalized_min_shell,
|
||||
"url": f"/api/v1/client/updates/files/{bundle_filename}",
|
||||
"sha256": sha256_hex,
|
||||
"size": len(content),
|
||||
"releaseNotes": cleaned_notes,
|
||||
"publishedAt": datetime.now(UTC).isoformat(),
|
||||
**archive_meta,
|
||||
},
|
||||
}
|
||||
|
||||
_atomic_write_bytes(
|
||||
_manifest_path(updates_dir),
|
||||
(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
|
||||
)
|
||||
|
||||
logger.info_event(
|
||||
"Published client L1 hotfix bundle",
|
||||
event="client_updates.bundle_published",
|
||||
context={
|
||||
"publisher": publisher,
|
||||
"version": normalized_version,
|
||||
"min_shell_version": normalized_min_shell,
|
||||
"bytes": len(content),
|
||||
"sha256": sha256_hex,
|
||||
"files_count": archive_meta["filesCount"],
|
||||
},
|
||||
)
|
||||
return {"status": "published", "manifest": manifest}
|
||||
@@ -5,6 +5,7 @@ from typing import Literal
|
||||
|
||||
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression
|
||||
from app.api.v1.visualization import convert_compute_centers_to_geojson
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.earth_geography_policy import display_country
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
@@ -64,7 +65,7 @@ def selected_countries(countries: str) -> list[str]:
|
||||
return codes
|
||||
|
||||
|
||||
@router.get("/series")
|
||||
@router.get("/series", dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
|
||||
async def get_series(
|
||||
response: Response,
|
||||
countries: str = "CN,US",
|
||||
@@ -182,7 +183,7 @@ async def sample_query(db: AsyncSession, countries: list[str], year: int | None)
|
||||
return query
|
||||
|
||||
|
||||
@router.get("/facilities")
|
||||
@router.get("/facilities", dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
|
||||
async def get_facilities(
|
||||
countries: str = "CN,US",
|
||||
year: int | None = Query(None, ge=2000, le=2100),
|
||||
|
||||
@@ -4,10 +4,11 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.visualization import get_visualization_geo_summary
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
|
||||
|
||||
PRODUCT_DEFINITIONS: dict[str, dict] = {
|
||||
"vessels": {
|
||||
|
||||
@@ -7,7 +7,7 @@ from sqlalchemy import func, or_, select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.core.enums import JobStatus, SnapshotStatus
|
||||
from app.core.enums import JobStatus, SnapshotStatus, UserRole
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.security import get_current_user
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
@@ -39,6 +39,7 @@ from app.services.business_logs import emit_business_log
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
STALE_RUNNING_TASK_TIMEOUT_MINUTES = 90
|
||||
DATASOURCE_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
|
||||
|
||||
|
||||
PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
@@ -65,6 +66,20 @@ class DatasourceBatchTriggerRequest(BaseModel):
|
||||
q: Optional[str] = None
|
||||
|
||||
|
||||
class DatasourceBatchStatusRequest(BaseModel):
|
||||
source_ids: list[int] = Field(min_length=1, max_length=500)
|
||||
is_active: bool
|
||||
|
||||
|
||||
def _require_datasource_admin(current_user: User) -> None:
|
||||
role = getattr(current_user.role, "value", current_user.role)
|
||||
if role not in DATASOURCE_ADMIN_ROLES:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Only administrators can change datasource scheduling",
|
||||
)
|
||||
|
||||
|
||||
def format_frequency_label(minutes: int) -> str:
|
||||
if minutes % 1440 == 0:
|
||||
return f"{minutes // 1440}d"
|
||||
@@ -353,6 +368,78 @@ def serialize_datasource_row(
|
||||
return row
|
||||
|
||||
|
||||
async def _serialize_datasource_rows(
|
||||
db: AsyncSession,
|
||||
datasources: list[DataSource],
|
||||
) -> list[dict]:
|
||||
if not datasources:
|
||||
return []
|
||||
config = get_data_sources_config()
|
||||
running_tasks, latest_tasks, endpoint_overrides = await _load_datasource_list_context(
|
||||
db,
|
||||
datasources,
|
||||
include_endpoint=False,
|
||||
)
|
||||
record_counts = await _load_collected_record_counts(
|
||||
db, [datasource.source for datasource in datasources]
|
||||
)
|
||||
return [
|
||||
serialize_datasource_row(
|
||||
datasource,
|
||||
running_tasks=running_tasks,
|
||||
latest_tasks=latest_tasks,
|
||||
record_counts=record_counts,
|
||||
endpoint_overrides=endpoint_overrides,
|
||||
config=config,
|
||||
include_endpoint=False,
|
||||
)
|
||||
for datasource in datasources
|
||||
]
|
||||
|
||||
|
||||
async def _load_datasource_status_counts(db: AsyncSession) -> dict[str, int]:
|
||||
result = await db.execute(
|
||||
select(DataSource.is_active, func.count(DataSource.id)).group_by(DataSource.is_active)
|
||||
)
|
||||
active = 0
|
||||
inactive = 0
|
||||
for is_active, count in result.all():
|
||||
if is_active:
|
||||
active += int(count or 0)
|
||||
else:
|
||||
inactive += int(count or 0)
|
||||
return {"all": active + inactive, "active": active, "inactive": inactive}
|
||||
|
||||
|
||||
async def _apply_datasource_activation(
|
||||
db: AsyncSession,
|
||||
datasources: list[DataSource],
|
||||
is_active: bool,
|
||||
) -> tuple[list[DataSource], list[int]]:
|
||||
"""Persist scheduling state, then reconcile scheduler jobs for changed rows only."""
|
||||
changed = [datasource for datasource in datasources if bool(datasource.is_active) != is_active]
|
||||
for datasource in changed:
|
||||
datasource.is_active = is_active
|
||||
if changed:
|
||||
await db.commit()
|
||||
sync_failed: list[int] = []
|
||||
for datasource in changed:
|
||||
try:
|
||||
await sync_datasource_job(datasource.id)
|
||||
except Exception as exc:
|
||||
sync_failed.append(datasource.id)
|
||||
logger.warning_event(
|
||||
"Datasource scheduler sync failed",
|
||||
event="collector.schedule.sync_failed",
|
||||
context={
|
||||
"datasource_id": datasource.id,
|
||||
"source": datasource.source,
|
||||
"error_type": type(exc).__name__,
|
||||
},
|
||||
)
|
||||
return changed, sync_failed
|
||||
|
||||
|
||||
def _apply_datasource_query_filters(
|
||||
query,
|
||||
*,
|
||||
@@ -817,7 +904,55 @@ async def list_datasources(
|
||||
)
|
||||
)
|
||||
|
||||
return {"total": len(collector_list), "data": collector_list}
|
||||
return {
|
||||
"total": len(collector_list),
|
||||
"data": collector_list,
|
||||
"counts": await _load_datasource_status_counts(db),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/batch-status")
|
||||
async def update_datasource_batch_status(
|
||||
payload: DatasourceBatchStatusRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_datasource_admin(current_user)
|
||||
requested_ids = list(dict.fromkeys(payload.source_ids))
|
||||
result = await db.execute(
|
||||
select(DataSource)
|
||||
.where(DataSource.id.in_(requested_ids))
|
||||
.order_by(DataSource.module, DataSource.id)
|
||||
)
|
||||
datasources = list(result.scalars().all())
|
||||
found_ids = {datasource.id for datasource in datasources}
|
||||
changed, sync_failed = await _apply_datasource_activation(db, datasources, payload.is_active)
|
||||
changed_ids = {datasource.id for datasource in changed}
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.schedule.batch_status",
|
||||
message="Datasource scheduling batch update completed",
|
||||
category="collector",
|
||||
service="api",
|
||||
module=__name__,
|
||||
user_id=current_user.id,
|
||||
context={
|
||||
"is_active": payload.is_active,
|
||||
"requested_count": len(requested_ids),
|
||||
"updated_count": len(changed),
|
||||
"sync_failed_count": len(sync_failed),
|
||||
},
|
||||
)
|
||||
return {
|
||||
"is_active": payload.is_active,
|
||||
"updated": await _serialize_datasource_rows(db, changed),
|
||||
"unchanged": [
|
||||
datasource.id for datasource in datasources if datasource.id not in changed_ids
|
||||
],
|
||||
"not_found": [source_id for source_id in requested_ids if source_id not in found_ids],
|
||||
"sync_failed": sync_failed,
|
||||
"counts": await _load_datasource_status_counts(db),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/trigger-all")
|
||||
@@ -987,20 +1122,35 @@ async def get_datasource_row(
|
||||
}
|
||||
|
||||
|
||||
async def _set_single_datasource_active(
|
||||
db: AsyncSession,
|
||||
source_id: str,
|
||||
current_user: User,
|
||||
is_active: bool,
|
||||
) -> dict:
|
||||
_require_datasource_admin(current_user)
|
||||
datasource = await get_datasource_record(db, source_id)
|
||||
if not datasource:
|
||||
raise HTTPException(status_code=404, detail="Data source not found")
|
||||
|
||||
_changed, sync_failed = await _apply_datasource_activation(db, [datasource], is_active)
|
||||
rows = await _serialize_datasource_rows(db, [datasource])
|
||||
return {
|
||||
"status": "enabled" if is_active else "disabled",
|
||||
"source_id": datasource.id,
|
||||
"data": rows[0] if rows else None,
|
||||
"sync_failed": bool(sync_failed),
|
||||
"counts": await _load_datasource_status_counts(db),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{source_id}/enable")
|
||||
async def enable_datasource(
|
||||
source_id: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
datasource = await get_datasource_record(db, source_id)
|
||||
if not datasource:
|
||||
raise HTTPException(status_code=404, detail="Data source not found")
|
||||
|
||||
datasource.is_active = True
|
||||
await db.commit()
|
||||
await sync_datasource_job(datasource.id)
|
||||
return {"status": "enabled", "source_id": datasource.id}
|
||||
return await _set_single_datasource_active(db, source_id, current_user, True)
|
||||
|
||||
|
||||
@router.post("/{source_id}/disable")
|
||||
@@ -1009,14 +1159,7 @@ async def disable_datasource(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
datasource = await get_datasource_record(db, source_id)
|
||||
if not datasource:
|
||||
raise HTTPException(status_code=404, detail="Data source not found")
|
||||
|
||||
datasource.is_active = False
|
||||
await db.commit()
|
||||
await sync_datasource_job(datasource.id)
|
||||
return {"status": "disabled", "source_id": datasource.id}
|
||||
return await _set_single_datasource_active(db, source_id, current_user, False)
|
||||
|
||||
|
||||
@router.get("/{source_id}/stats")
|
||||
|
||||
@@ -12,6 +12,7 @@ from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, func, select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.config import settings as app_settings
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import (
|
||||
@@ -296,7 +297,7 @@ async def _broadcast_earth_config_update(layer: str) -> None:
|
||||
logger.warning("Failed to broadcast %s update: %s", layer, exc)
|
||||
|
||||
|
||||
@router.get("/brand")
|
||||
@router.get("/brand", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_brand(db: AsyncSession = Depends(get_db)):
|
||||
return await _get_earth_brand_payload(db)
|
||||
|
||||
@@ -366,7 +367,7 @@ async def upload_earth_brand_asset(
|
||||
return {"url": asset_url, "filename": safe_name, "content_type": file.content_type}
|
||||
|
||||
|
||||
@router.get("/about")
|
||||
@router.get("/about", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_about(db: AsyncSession = Depends(get_db)):
|
||||
return await _get_earth_about_payload(db)
|
||||
|
||||
@@ -401,7 +402,7 @@ async def reset_earth_about(
|
||||
return {"status": "reset", "about": _normalize_earth_about_payload(None), "is_default": True}
|
||||
|
||||
|
||||
@router.get("/news-sources")
|
||||
@router.get("/news-sources", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_news_sources(db: AsyncSession = Depends(get_db)):
|
||||
return await get_earth_news_sources_payload(db)
|
||||
|
||||
@@ -606,7 +607,7 @@ async def reprocess_earth_news_item_admin(
|
||||
return {"status": "queued" if queued else "not_queued", "queued": queued, "id": item_id}
|
||||
|
||||
|
||||
@router.get("/oobe-status")
|
||||
@router.get("/oobe-status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_oobe_status(
|
||||
current_user: User | None = Depends(_get_optional_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -671,7 +672,7 @@ async def get_earth_oobe_status(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/boundaries/status")
|
||||
@router.get("/boundaries/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_boundary_status():
|
||||
return get_boundary_status()
|
||||
|
||||
@@ -718,6 +719,6 @@ async def build_earth_boundary_assets(
|
||||
) from exc
|
||||
|
||||
|
||||
@router.get("/boundaries/build/status")
|
||||
@router.get("/boundaries/build/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_boundary_build_status():
|
||||
return get_boundary_build_status()
|
||||
@@ -9,6 +9,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.models.earth_interactable import EarthInteractable
|
||||
@@ -67,7 +68,7 @@ class InteractableUpdate(BaseModel):
|
||||
properties: dict[str, Any] | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
@router.get("", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
|
||||
async def get_interactables(
|
||||
response: Response,
|
||||
layer: str | None = Query(default=None),
|
||||
@@ -79,7 +80,7 @@ async def get_interactables(
|
||||
return {"items": [serialize_interactable(item) for item in items]}
|
||||
|
||||
|
||||
@router.get("/geojson")
|
||||
@router.get("/geojson", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
|
||||
async def get_interactables_geojson(
|
||||
response: Response,
|
||||
layer: str | None = Query(default=None),
|
||||
@@ -135,7 +136,7 @@ async def create_interactable(
|
||||
return {"item": serialize_interactable(record)}
|
||||
|
||||
|
||||
@router.get("/{interactable_id}")
|
||||
@router.get("/{interactable_id}", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
|
||||
async def get_interactable(interactable_id: str, db: AsyncSession = Depends(get_db)):
|
||||
record = await db.get(EarthInteractable, interactable_id)
|
||||
if record is None or record.is_deleted:
|
||||
|
||||
@@ -13,9 +13,10 @@ from app.api.v1.visualization import (
|
||||
get_satellites_geojson,
|
||||
)
|
||||
from app.api.v1.vessels import build_vessel_snapshot_response
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("layers:read"))])
|
||||
|
||||
DEFAULT_LAYER_LIMIT = 1000
|
||||
MAX_LAYER_LIMIT = 5000
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.access_gate import (
|
||||
EarthAccessContext,
|
||||
check_sliding_rate_limit,
|
||||
require_earth_or_api_access,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.services.earth_news import (
|
||||
ALLOWED_NEWS_CATEGORY_KEYS,
|
||||
@@ -70,7 +75,24 @@ def _parse_locale(raw: str | None) -> str:
|
||||
return requested
|
||||
|
||||
|
||||
@router.post("/refresh", status_code=status.HTTP_202_ACCEPTED)
|
||||
async def _require_news_refresh_cooldown(
|
||||
request: Request,
|
||||
access: EarthAccessContext = Depends(require_earth_or_api_access("news:read")),
|
||||
) -> None:
|
||||
peer = request.client.host if (request.client and request.client.host) else "unknown"
|
||||
await check_sliding_rate_limit(
|
||||
f"news_refresh:{access.actor_key}:{peer}",
|
||||
limit=3,
|
||||
window_seconds=60,
|
||||
detail="News refresh cooldown active; please retry shortly.",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/refresh",
|
||||
status_code=status.HTTP_202_ACCEPTED,
|
||||
dependencies=[Depends(_require_news_refresh_cooldown)],
|
||||
)
|
||||
async def request_earth_news_refresh(payload: EarthNewsRefreshRequest):
|
||||
requested_region = payload.region.strip().lower() if payload.region else None
|
||||
if requested_region and requested_region not in REGION_ANCHORS:
|
||||
@@ -97,7 +119,10 @@ async def request_earth_news_refresh(payload: EarthNewsRefreshRequest):
|
||||
) from exc
|
||||
|
||||
|
||||
@router.get("/refresh/{refresh_id}")
|
||||
@router.get(
|
||||
"/refresh/{refresh_id}",
|
||||
dependencies=[Depends(require_earth_or_api_access("news:read"))],
|
||||
)
|
||||
async def get_earth_news_refresh(refresh_id: UUID):
|
||||
from app.services.earth_news_refresh import get_earth_news_refresh_status
|
||||
|
||||
@@ -124,7 +149,10 @@ async def get_earth_news_refresh(refresh_id: UUID):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/earth-feed")
|
||||
@router.get(
|
||||
"/earth-feed",
|
||||
dependencies=[Depends(require_earth_or_api_access("news:read"))],
|
||||
)
|
||||
async def get_earth_feed(
|
||||
lat: float | None = Query(None, description="Current Earth view center latitude"),
|
||||
lon: float | None = Query(None, description="Current Earth view center longitude"),
|
||||
|
||||
@@ -66,7 +66,13 @@ from app.services.llm_provider_catalog import (
|
||||
list_fallback_llm_provider_presets,
|
||||
refresh_llm_provider_preset,
|
||||
)
|
||||
from app.services.llm_model_catalog import catalog_error_message, fetch_model_catalog
|
||||
from app.services.llm_model_catalog import (
|
||||
LLMProviderCatalogConfigError,
|
||||
can_refresh_catalog_without_api_key,
|
||||
catalog_error_message,
|
||||
catalog_requires_api_key,
|
||||
fetch_model_catalog,
|
||||
)
|
||||
from app.services.scheduler import sync_datasource_job
|
||||
from app.services.tv_streams import DEFAULT_TV_SETTINGS, get_tv_settings_payload, normalize_tv_settings
|
||||
from app.services.persistent_logs import record_audit_log
|
||||
@@ -840,7 +846,7 @@ async def _check_ai_provider_lightweight(llm_config: dict, timeout_seconds: int)
|
||||
}
|
||||
if not base_url or not model:
|
||||
return {**result, "message": "当前 provider/base_url/model 未完整配置。"}
|
||||
if provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key:
|
||||
if provider != "ollama" and provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key:
|
||||
return {**result, "message": "当前 provider 未配置 API Key。"}
|
||||
try:
|
||||
catalog = await fetch_model_catalog(
|
||||
@@ -2145,6 +2151,74 @@ async def get_ai_provider_presets(
|
||||
}
|
||||
|
||||
|
||||
async def refresh_public_llm_provider_presets(db: AsyncSession) -> dict:
|
||||
current_payload = await get_setting_payload(db, "external_integrations")
|
||||
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
|
||||
results: list[dict] = []
|
||||
for preset in list_fallback_llm_provider_presets():
|
||||
provider_id = preset["provider"]
|
||||
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
|
||||
base_url = str(provider_config.get("base_url") or preset["base_url"] or "")
|
||||
provider_api = str(provider_config.get("provider_api") or preset["provider_api"] or "")
|
||||
if not can_refresh_catalog_without_api_key(provider_id, base_url, provider_api):
|
||||
continue
|
||||
try:
|
||||
refreshed = await refresh_llm_provider_preset(
|
||||
provider_id,
|
||||
api_key="",
|
||||
base_url=base_url,
|
||||
provider_api=provider_api,
|
||||
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"LLM provider catalog refresh failed",
|
||||
extra={
|
||||
"event": "settings.ai_provider.catalog.failed",
|
||||
"context": {
|
||||
"provider": provider_id,
|
||||
"error_type": type(exc).__name__,
|
||||
},
|
||||
},
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"provider": provider_id,
|
||||
"status": "failed",
|
||||
"error": f"{catalog_error_message(exc)} 已保留上次模型列表。",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
refreshed["refreshed_at"] = to_iso8601_utc(datetime.now(UTC))
|
||||
await save_setting_payload(
|
||||
db, f"{LLM_PROVIDER_PRESET_CATEGORY_PREFIX}{provider_id}", refreshed
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"provider": provider_id,
|
||||
"status": "refreshed",
|
||||
"models_count": len(refreshed["models"]),
|
||||
"refreshed_at": refreshed["refreshed_at"],
|
||||
"source": refreshed["source"],
|
||||
}
|
||||
)
|
||||
return {
|
||||
"data": results,
|
||||
"refreshed": [item["provider"] for item in results if item["status"] == "refreshed"],
|
||||
"failed": [item["provider"] for item in results if item["status"] == "failed"],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/integrations/ai-provider/presets/refresh-public")
|
||||
async def refresh_public_ai_provider_presets(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can refresh AI provider presets")
|
||||
return await refresh_public_llm_provider_presets(db)
|
||||
|
||||
|
||||
@router.post("/integrations/ai-provider/presets/{provider}/refresh")
|
||||
async def refresh_ai_provider_preset(
|
||||
provider: str,
|
||||
@@ -2152,9 +2226,10 @@ async def refresh_ai_provider_preset(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
payload: AIProviderIntegrationUpdate | None = None,
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can refresh AI provider presets")
|
||||
try:
|
||||
provider_id = _normalize_provider_id(provider)
|
||||
get_fallback_llm_provider_preset(provider_id)
|
||||
fallback = get_fallback_llm_provider_preset(provider_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
|
||||
@@ -2166,17 +2241,25 @@ async def refresh_ai_provider_preset(
|
||||
else:
|
||||
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
|
||||
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
|
||||
resolved_base_url = str(provider_config.get("base_url") or fallback["base_url"] or "")
|
||||
resolved_api = str(provider_config.get("provider_api") or fallback["provider_api"] or "")
|
||||
api_key, _api_key_source = _resolve_provider_api_key(provider_id, provider_config)
|
||||
if not api_key and provider_id not in {"ollama", "opencode-go", "openrouter"}:
|
||||
if not api_key and not can_refresh_catalog_without_api_key(
|
||||
provider_id, resolved_base_url, resolved_api
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400, detail="请先配置当前供应商的 API Key,再刷新模型列表。",
|
||||
)
|
||||
try:
|
||||
refreshed = await refresh_llm_provider_preset(
|
||||
provider_id, api_key=api_key, base_url=provider_config.get("base_url"),
|
||||
provider_api=provider_config.get("provider_api"),
|
||||
provider_id,
|
||||
api_key=api_key,
|
||||
base_url=resolved_base_url,
|
||||
provider_api=resolved_api,
|
||||
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
|
||||
)
|
||||
except LLMProviderCatalogConfigError as exc:
|
||||
raise HTTPException(status_code=400, detail=catalog_error_message(exc)) from exc
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"LLM provider catalog refresh failed",
|
||||
|
||||
@@ -7,12 +7,14 @@ from datetime import UTC, datetime
|
||||
import uuid
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.compute_intelligence import configuration_admin, selected_countries
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.models.situational_assessment import (
|
||||
ComputeEvidenceCandidate,
|
||||
@@ -53,6 +55,7 @@ from app.services.ai.workflow_runtime import (
|
||||
get_active_run_handle,
|
||||
read_frozen_result_revision,
|
||||
)
|
||||
from app.services.ai.stream_turn import stream_session_turn
|
||||
from app.services.ai_client import AIProviderClient, get_ai_provider_client
|
||||
from app.services.compute_history import ComputeSeriesMode
|
||||
|
||||
@@ -79,6 +82,13 @@ class SessionPinUpdateRequest(BaseModel):
|
||||
pinned_items: list[dict[str, Any]] = Field(default_factory=list, max_length=12)
|
||||
|
||||
|
||||
class HistoryMessageItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
role: Literal["user", "assistant"]
|
||||
content: str = Field(min_length=1, max_length=6000)
|
||||
|
||||
|
||||
class SessionTurnRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
@@ -95,6 +105,11 @@ class SessionTurnRequest(BaseModel):
|
||||
preset: ViewPreset | None = None
|
||||
prefer_llm: bool | Literal["auto"] = False
|
||||
external_urls: list[str] = Field(default_factory=list, max_length=3)
|
||||
news_context: dict[str, Any] | None = None
|
||||
history: list[HistoryMessageItem] = Field(default_factory=list, max_length=40)
|
||||
conversation_summary: str | None = Field(default=None, max_length=2400)
|
||||
memory_notes: list[str] = Field(default_factory=list, max_length=12)
|
||||
pinned_summaries: list[str] = Field(default_factory=list, max_length=8)
|
||||
run_id: str | None = Field(default=None, min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
|
||||
|
||||
|
||||
@@ -340,6 +355,68 @@ async def create_session_turn(
|
||||
return turn_result
|
||||
|
||||
|
||||
@router.post("/sessions/{session_id}/turns/stream")
|
||||
async def stream_investigation_session_turn(
|
||||
session_id: str,
|
||||
payload: SessionTurnRequest,
|
||||
request: Request,
|
||||
response: Response,
|
||||
access: AccessContext = Depends(resolve_access_context),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
ai_client: AIProviderClient = Depends(get_ai_provider_client),
|
||||
) -> StreamingResponse:
|
||||
"""Adaptive SSE endpoint streaming LLM reasoning & answer when configured, else grounded baseline."""
|
||||
session_row: InvestigationSession | None = None
|
||||
effective_access = access
|
||||
issued_token: str | None = None
|
||||
if session_id == "stateless":
|
||||
owner_key, issued_token = ensure_session_owner_identity(access, response)
|
||||
effective_access = replace(access, actor_key=owner_key, has_session_credential=True)
|
||||
else:
|
||||
session_row = await _load_owned_session_or_fail(session_id, access, db)
|
||||
|
||||
codes = (
|
||||
selected_countries(",".join(payload.selected_codes))
|
||||
if payload.selected_codes
|
||||
else None
|
||||
)
|
||||
overrides = {
|
||||
"domain": payload.domain,
|
||||
"selected_codes": codes,
|
||||
"mode": payload.mode,
|
||||
"focus_year": payload.focus_year,
|
||||
"entity_id": payload.entity_id,
|
||||
"visible_layers": payload.visible_layers,
|
||||
"time_basis": payload.time_basis,
|
||||
"cutoff_at": payload.cutoff_at,
|
||||
"include_drill": payload.include_drill,
|
||||
}
|
||||
headers = {
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Accel-Buffering": "no",
|
||||
}
|
||||
return StreamingResponse(
|
||||
stream_session_turn(
|
||||
db,
|
||||
request=request,
|
||||
session=session_row,
|
||||
question=payload.question,
|
||||
context_override=overrides,
|
||||
news_context=payload.news_context,
|
||||
history=[item.model_dump() for item in payload.history],
|
||||
conversation_summary=payload.conversation_summary,
|
||||
memory_notes=payload.memory_notes,
|
||||
pinned_summaries=payload.pinned_summaries,
|
||||
access=effective_access,
|
||||
ai_client=ai_client,
|
||||
client_run_id=payload.run_id,
|
||||
issued_session_token=issued_token,
|
||||
),
|
||||
media_type="text/event-stream",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Group 3: WorkflowRun Inspection & Explicit Cancellation
|
||||
# ============================================================================
|
||||
@@ -418,7 +495,10 @@ async def cancel_workflow_run(
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/results/{result_id:path}/revisions/{revision}")
|
||||
@router.get(
|
||||
"/results/{result_id:path}/revisions/{revision}",
|
||||
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
||||
)
|
||||
async def get_frozen_result_revision(
|
||||
result_id: str,
|
||||
revision: int,
|
||||
@@ -442,7 +522,10 @@ async def get_frozen_result_revision(
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/presentations")
|
||||
@router.get(
|
||||
"/presentations",
|
||||
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
||||
)
|
||||
async def get_presentations(
|
||||
response: Response,
|
||||
after_cursor: int = Query(0, ge=0),
|
||||
@@ -465,7 +548,10 @@ async def get_presentations(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/presentations/{presentation_key:path}")
|
||||
@router.get(
|
||||
"/presentations/{presentation_key:path}",
|
||||
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
||||
)
|
||||
async def get_presentation_by_key(
|
||||
presentation_key: str,
|
||||
response: Response,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
@@ -12,6 +13,7 @@ from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import ROOT_DIR, settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
@@ -634,3 +636,113 @@ async def ingest_admin_client_log(
|
||||
payload=payload,
|
||||
request=request,
|
||||
)
|
||||
|
||||
|
||||
_EXTERNAL_OPENAPI_PREFIXES = (
|
||||
"/health",
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/refresh",
|
||||
"/api/v1/visualization/",
|
||||
"/api/v1/layers/",
|
||||
"/api/v1/vessels/",
|
||||
"/api/v1/news/",
|
||||
"/api/v1/data-products",
|
||||
"/api/v1/earth/",
|
||||
"/api/v1/interactables",
|
||||
"/api/v1/tv/",
|
||||
"/api/v1/client/update-manifest",
|
||||
)
|
||||
_EXTERNAL_OPENAPI_EXCLUDED_SUBSTRINGS = (
|
||||
"collect-location",
|
||||
"/location",
|
||||
"/configuration",
|
||||
"/upload",
|
||||
"/preview",
|
||||
"/targets",
|
||||
"/brand/assets",
|
||||
"/boundaries/build",
|
||||
"/boundaries/config",
|
||||
"/news-groups",
|
||||
"/news-items",
|
||||
)
|
||||
_EXTERNAL_ALLOWED_POST_PATHS = frozenset(
|
||||
{
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/refresh",
|
||||
"/api/v1/visualization/terrain/terrarium/batch",
|
||||
"/api/v1/visualization/geo/path",
|
||||
"/api/v1/news/refresh",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _require_docs_developer_or_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
role = (
|
||||
current_user.role.value
|
||||
if hasattr(current_user.role, "value")
|
||||
else str(current_user.role or "")
|
||||
)
|
||||
groups = {str(g).strip() for g in (current_user.gatekeeper_groups or []) if g}
|
||||
if (
|
||||
role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
|
||||
or "docs_developer" in groups
|
||||
or "docs_admin" in groups
|
||||
):
|
||||
return current_user
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Developer docs or administrator permission required",
|
||||
)
|
||||
|
||||
|
||||
def _build_external_openapi_schema(raw_schema: dict) -> dict:
|
||||
schema = copy.deepcopy(raw_schema)
|
||||
raw_paths = schema.get("paths") or {}
|
||||
filtered_paths: dict = {}
|
||||
for path, path_item in raw_paths.items():
|
||||
if not isinstance(path_item, dict):
|
||||
continue
|
||||
if not any(path.startswith(prefix) for prefix in _EXTERNAL_OPENAPI_PREFIXES):
|
||||
continue
|
||||
if any(sub in path for sub in _EXTERNAL_OPENAPI_EXCLUDED_SUBSTRINGS):
|
||||
continue
|
||||
allowed_methods: dict = {}
|
||||
for method, operation in path_item.items():
|
||||
lower_method = str(method).lower()
|
||||
if lower_method == "get":
|
||||
allowed_methods[method] = operation
|
||||
elif lower_method == "post" and path in _EXTERNAL_ALLOWED_POST_PATHS:
|
||||
allowed_methods[method] = operation
|
||||
if allowed_methods:
|
||||
filtered_paths[path] = allowed_methods
|
||||
|
||||
schema["paths"] = filtered_paths
|
||||
components = schema.setdefault("components", {})
|
||||
security_schemes = components.setdefault("securitySchemes", {})
|
||||
security_schemes["ApiKeyAuth"] = {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-API-Key",
|
||||
}
|
||||
schema["security"] = [{"ApiKeyAuth": []}]
|
||||
info = schema.setdefault("info", {})
|
||||
info["title"] = f"{info.get('title', 'Planet API')} (External & UE5 Read-Only)"
|
||||
return schema
|
||||
|
||||
|
||||
@router.get("/openapi.json")
|
||||
async def get_controlled_openapi_schema(
|
||||
request: Request,
|
||||
_user: User = Depends(_require_docs_developer_or_admin),
|
||||
):
|
||||
"""Return full OpenAPI schema for authenticated administrators and docs_developer users."""
|
||||
return request.app.openapi()
|
||||
|
||||
|
||||
@router.get("/openapi-external.json")
|
||||
async def get_external_openapi_schema(
|
||||
request: Request,
|
||||
_user: User = Depends(_require_docs_developer_or_admin),
|
||||
):
|
||||
"""Return curated external/UE5 OpenAPI schema excluding internal admin endpoints."""
|
||||
return _build_external_openapi_schema(request.app.openapi())
|
||||
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.services.tv_catalog import get_tv_catalog_page
|
||||
from app.services.tv_streams import get_public_tv_payload, is_allowed_tv_proxy_url
|
||||
@@ -33,7 +34,7 @@ def _should_strip_hls_metadata_line(line: str) -> bool:
|
||||
return normalized.startswith("#EXT-X-MEDIA:") and "TYPE=SUBTITLES" in normalized
|
||||
|
||||
|
||||
@router.get("/streams")
|
||||
@router.get("/streams", dependencies=[Depends(require_earth_or_api_access("tv:read"))])
|
||||
async def list_public_tv_streams(
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
@@ -44,7 +45,7 @@ async def list_public_tv_streams(
|
||||
return await get_tv_catalog_page(db, offset=offset, limit=limit, q=q, selected_id=selected_id)
|
||||
|
||||
|
||||
@router.get("/proxy")
|
||||
@router.get("/proxy", dependencies=[Depends(require_earth_or_api_access("tv:read", allow_query_api_key=True))])
|
||||
async def proxy_tv_stream(
|
||||
url: str = Query(..., description="Upstream TV stream or manifest URL"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.schemas.user import UserCreate, UserUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
VALID_GATEKEEPER_GROUPS = {"docs_user", "docs_developer", "docs_admin"}
|
||||
VALID_GATEKEEPER_GROUPS = {"docs_user", "docs_developer", "docs_admin", "api_access"}
|
||||
ADMIN_ROLES = [UserRole.SUPER_ADMIN.value, UserRole.ADMIN.value]
|
||||
SUPER_ADMIN_ROLES = [UserRole.SUPER_ADMIN.value]
|
||||
|
||||
|
||||
@@ -6,13 +6,14 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.visualization import _parse_bbox, build_vessel_snapshot_response
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.services.vessel_ais_aggregation import MAX_SNAPSHOT_LIMIT
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/snapshot")
|
||||
@router.get("/snapshot", dependencies=[Depends(require_earth_or_api_access("vessels:read"))])
|
||||
async def get_vessel_snapshot(
|
||||
bbox: Optional[str] = Query(None, description="Snapshot bbox as lon_min,lat_min,lon_max,lat_max"),
|
||||
zoom: float = Query(..., ge=1, le=20, description="Current map zoom level"),
|
||||
|
||||
+293
-106
@@ -7,16 +7,18 @@ Returns GeoJSON format compatible with Three.js, CesiumJS, and Unreal Cesium.
|
||||
import asyncio
|
||||
import base64
|
||||
from collections import OrderedDict
|
||||
from contextlib import aclosing
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import math
|
||||
import re
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query, Response
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
from app.core.access_gate import require_admin_user, require_earth_or_api_access
|
||||
from app.core.compute_types import COMPUTE_SITE_TYPES, COMPUTE_SOURCES, compute_site_type, compute_record_filter, compute_site_type_expression
|
||||
from app.core.collected_data_fields import get_record_field
|
||||
from app.core.enums import BGPStatus
|
||||
@@ -28,6 +30,7 @@ from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISSourceHealth, VesselCurrentState, VesselPosition, VesselStatic
|
||||
from app.services.bgp_collectors import build_bgp_collector_coverage
|
||||
from app.services.cable_graph import build_graph_from_data, CableGraph, haversine_distance
|
||||
@@ -36,6 +39,7 @@ from app.services.compute_center_locations import (
|
||||
ResolutionDiagnostic,
|
||||
build_compute_center_location_query,
|
||||
collect_location_candidates,
|
||||
get_compute_center_location_dict,
|
||||
refresh_compute_center_location_cache,
|
||||
resolve_compute_center_location_full,
|
||||
upsert_compute_center_location,
|
||||
@@ -47,6 +51,10 @@ from app.services.location.llm_fallback import (
|
||||
collect_llm_location_fallback_candidate,
|
||||
collect_location_search_evidence,
|
||||
)
|
||||
from app.services.location.agent_resolver import (
|
||||
run_controlled_location_agent,
|
||||
run_l1_structured_facility_resolvers,
|
||||
)
|
||||
from app.services.persistent_logs import record_system_log
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
build_field_conflict_candidates,
|
||||
@@ -63,12 +71,14 @@ from app.services.earth_layer_cache import (
|
||||
earth_layer_cache,
|
||||
format_bbox_key,
|
||||
get_or_build_layer_payload,
|
||||
get_or_build_layer_response,
|
||||
quantize_bbox,
|
||||
)
|
||||
from app.core.logging import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
_vis_read_dep = Depends(require_earth_or_api_access("visualization:read"))
|
||||
TERRAIN_TILE_URL_TEMPLATE = (
|
||||
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
|
||||
)
|
||||
@@ -278,36 +288,43 @@ def convert_landing_point_to_geojson(records: List[CollectedData], city_to_cable
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], Any, Optional[str], Optional[str], Optional[str], str] | None:
|
||||
metadata = record.extra_data or {}
|
||||
norad_id = metadata.get("norad_cat_id")
|
||||
if not norad_id:
|
||||
return None
|
||||
|
||||
tle_line1 = metadata.get("tle_line1")
|
||||
tle_line2 = metadata.get("tle_line2")
|
||||
if not tle_line1 or not tle_line2:
|
||||
tle_line1, tle_line2 = build_tle_lines_from_elements(
|
||||
norad_cat_id=norad_id,
|
||||
epoch=metadata.get("epoch"),
|
||||
inclination=metadata.get("inclination"),
|
||||
raan=metadata.get("raan"),
|
||||
eccentricity=metadata.get("eccentricity"),
|
||||
arg_of_perigee=metadata.get("arg_of_perigee"),
|
||||
mean_anomaly=metadata.get("mean_anomaly"),
|
||||
mean_motion=metadata.get("mean_motion"),
|
||||
)
|
||||
|
||||
constellation_group = _normalize_satellite_constellation_group(
|
||||
metadata.get("constellation_group"),
|
||||
record.name,
|
||||
)
|
||||
footprint_policy = _get_satellite_footprint_policy(constellation_group)
|
||||
return metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy
|
||||
|
||||
|
||||
def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]:
|
||||
"""Convert satellite TLE records to GeoJSON"""
|
||||
features = []
|
||||
|
||||
for record in records:
|
||||
metadata = record.extra_data or {}
|
||||
norad_id = metadata.get("norad_cat_id")
|
||||
|
||||
if not norad_id:
|
||||
extracted = _extract_satellite_record(record)
|
||||
if extracted is None:
|
||||
continue
|
||||
|
||||
tle_line1 = metadata.get("tle_line1")
|
||||
tle_line2 = metadata.get("tle_line2")
|
||||
if not tle_line1 or not tle_line2:
|
||||
tle_line1, tle_line2 = build_tle_lines_from_elements(
|
||||
norad_cat_id=norad_id,
|
||||
epoch=metadata.get("epoch"),
|
||||
inclination=metadata.get("inclination"),
|
||||
raan=metadata.get("raan"),
|
||||
eccentricity=metadata.get("eccentricity"),
|
||||
arg_of_perigee=metadata.get("arg_of_perigee"),
|
||||
mean_anomaly=metadata.get("mean_anomaly"),
|
||||
mean_motion=metadata.get("mean_motion"),
|
||||
)
|
||||
|
||||
constellation_group = _normalize_satellite_constellation_group(
|
||||
metadata.get("constellation_group"),
|
||||
record.name,
|
||||
)
|
||||
footprint_policy = _get_satellite_footprint_policy(constellation_group)
|
||||
metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy = extracted
|
||||
|
||||
features.append(
|
||||
{
|
||||
@@ -340,6 +357,43 @@ def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
def convert_satellite_to_compact_rows(records: List[CollectedData]) -> List[List[Any]]:
|
||||
"""Convert satellite TLE records into compact array rows while keeping full catalog fidelity."""
|
||||
rows: List[List[Any]] = []
|
||||
|
||||
for record in records:
|
||||
extracted = _extract_satellite_record(record)
|
||||
if extracted is None:
|
||||
continue
|
||||
metadata, norad_id, tle_line1, tle_line2, constellation_group, _footprint_policy = extracted
|
||||
row: List[Any] = [
|
||||
record.id,
|
||||
norad_id,
|
||||
record.name,
|
||||
constellation_group,
|
||||
tle_line1,
|
||||
tle_line2,
|
||||
]
|
||||
if not tle_line1 or not tle_line2:
|
||||
row.append(
|
||||
[
|
||||
metadata.get("inclination"),
|
||||
metadata.get("raan"),
|
||||
metadata.get("eccentricity"),
|
||||
metadata.get("arg_of_perigee"),
|
||||
metadata.get("mean_anomaly"),
|
||||
metadata.get("mean_motion"),
|
||||
metadata.get("epoch"),
|
||||
metadata.get("international_designator"),
|
||||
metadata.get("classification_type"),
|
||||
metadata.get("bstar"),
|
||||
]
|
||||
)
|
||||
rows.append(row)
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
|
||||
def _get_satellite_footprint_policy(constellation_group: Optional[str]) -> str:
|
||||
if constellation_group == "starlink":
|
||||
@@ -1546,7 +1600,7 @@ def convert_bgp_incidents_to_geojson(
|
||||
# ============== API Endpoints ==============
|
||||
|
||||
|
||||
@router.get("/geo/cables")
|
||||
@router.get("/geo/cables", dependencies=[_vis_read_dep])
|
||||
async def get_cables_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
"""获取海底电缆 GeoJSON 数据 (LineString)"""
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
@@ -1584,7 +1638,7 @@ async def _build_cables_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/geo/landing-points")
|
||||
@router.get("/geo/landing-points", dependencies=[_vis_read_dep])
|
||||
async def get_landing_points_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
return await _build_landing_points_geojson(db)
|
||||
@@ -1639,7 +1693,7 @@ async def _build_landing_points_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/terrain/terrarium/{z}/{x}/{y}.png")
|
||||
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_read_dep])
|
||||
async def get_terrarium_tile(z: int, x: int, y: int):
|
||||
"""Proxy Terrarium elevation tiles through the backend to avoid browser CORS issues."""
|
||||
if not _is_valid_terrain_tile(z, x, y):
|
||||
@@ -1729,7 +1783,7 @@ async def _fetch_terrain_tile(
|
||||
return content, content_type, dict(headers)
|
||||
|
||||
|
||||
@router.post("/terrain/terrarium/batch")
|
||||
@router.post("/terrain/terrarium/batch", dependencies=[_vis_read_dep])
|
||||
async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
|
||||
"""Fetch Terrarium elevation tiles in batches so the browser avoids many tiny requests."""
|
||||
unique_tiles: list[TerrariumTileRequest] = []
|
||||
@@ -1795,7 +1849,7 @@ async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/all")
|
||||
@router.get("/geo/all", dependencies=[_vis_read_dep])
|
||||
async def get_all_geojson(db: AsyncSession = Depends(get_db)):
|
||||
records_by_source = await _load_current_collected_data_by_sources(
|
||||
db,
|
||||
@@ -1834,34 +1888,57 @@ async def get_all_geojson(db: AsyncSession = Depends(get_db)):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/satellites")
|
||||
@router.get("/geo/satellites", dependencies=[_vis_read_dep])
|
||||
async def get_satellites_geojson(
|
||||
request: Request = None,
|
||||
limit: Optional[int] = Query(
|
||||
None,
|
||||
ge=1,
|
||||
description="Maximum number of satellites to return. Omit for no limit.",
|
||||
),
|
||||
format: Optional[str] = Query(
|
||||
None,
|
||||
pattern="^(geojson|compact)$",
|
||||
description="Response payload format: default GeoJSON or compact full-catalog rows.",
|
||||
),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
response: Response = None,
|
||||
):
|
||||
"""获取卫星 TLE GeoJSON 数据"""
|
||||
"""获取卫星 TLE 数据(支持完整 GeoJSON 与全量紧凑数组格式)"""
|
||||
compact = format == "compact"
|
||||
cache_key = (
|
||||
earth_layer_cache.key("satellites", format="compact", limit=limit or "all")
|
||||
if compact
|
||||
else earth_layer_cache.key("satellites", limit=limit or "all")
|
||||
)
|
||||
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
if compact:
|
||||
return await _build_satellites_compact(limit=limit, db=db)
|
||||
return await _build_satellites_geojson(limit=limit, db=db)
|
||||
|
||||
return await get_or_build_layer_payload(
|
||||
key=earth_layer_cache.key("satellites", limit=limit or "all"),
|
||||
if request is None:
|
||||
return await get_or_build_layer_payload(
|
||||
key=cache_key,
|
||||
policy=SATELLITE_CACHE_POLICY,
|
||||
builder=build_payload,
|
||||
response=response,
|
||||
)
|
||||
|
||||
return await get_or_build_layer_response(
|
||||
key=cache_key,
|
||||
policy=SATELLITE_CACHE_POLICY,
|
||||
builder=build_payload,
|
||||
request=request,
|
||||
response=response,
|
||||
)
|
||||
|
||||
|
||||
async def _build_satellites_geojson(
|
||||
async def _stream_satellite_batches(
|
||||
*,
|
||||
limit: int | None,
|
||||
db: AsyncSession,
|
||||
) -> dict[str, Any]:
|
||||
features: list[dict[str, Any]] = []
|
||||
):
|
||||
source = "celestrak_tle"
|
||||
for current_only in (True, False):
|
||||
if current_only:
|
||||
@@ -1887,16 +1964,53 @@ async def _build_satellites_geojson(
|
||||
try:
|
||||
async for batch in records.partitions(SATELLITE_QUERY_BATCH_SIZE):
|
||||
found_records = True
|
||||
features.extend(convert_satellite_to_geojson(batch)["features"])
|
||||
yield batch
|
||||
finally:
|
||||
await records.close()
|
||||
if found_records:
|
||||
break
|
||||
|
||||
|
||||
async def _build_satellites_geojson(
|
||||
*,
|
||||
limit: int | None,
|
||||
db: AsyncSession,
|
||||
) -> dict[str, Any]:
|
||||
features: list[dict[str, Any]] = []
|
||||
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
|
||||
async for batch in batches:
|
||||
features.extend(convert_satellite_to_geojson(batch)["features"])
|
||||
|
||||
return {"type": "FeatureCollection", "features": features, "count": len(features)}
|
||||
|
||||
|
||||
@router.get("/geo/supercomputers")
|
||||
async def _build_satellites_compact(
|
||||
*,
|
||||
limit: int | None,
|
||||
db: AsyncSession,
|
||||
) -> dict[str, Any]:
|
||||
rows: list[list[Any]] = []
|
||||
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
|
||||
async for batch in batches:
|
||||
rows.extend(convert_satellite_to_compact_rows(batch))
|
||||
|
||||
return {
|
||||
"format": "satellite_compact_v1",
|
||||
"count": len(rows),
|
||||
"fields": [
|
||||
"id",
|
||||
"norad_cat_id",
|
||||
"name",
|
||||
"constellation_group",
|
||||
"tle_line1",
|
||||
"tle_line2",
|
||||
"fallback_elements",
|
||||
],
|
||||
"satellites": rows,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/supercomputers", dependencies=[_vis_read_dep])
|
||||
async def get_supercomputers_geojson(
|
||||
limit: int = 500,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -1919,7 +2033,7 @@ async def get_supercomputers_geojson(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/gpu-clusters")
|
||||
@router.get("/geo/gpu-clusters", dependencies=[_vis_read_dep])
|
||||
async def get_gpu_clusters_geojson(
|
||||
limit: int = 100,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -1942,7 +2056,7 @@ async def get_gpu_clusters_geojson(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/compute-centers")
|
||||
@router.get("/geo/compute-centers", dependencies=[_vis_read_dep])
|
||||
async def get_compute_centers_geojson(
|
||||
limit: int = Query(200, ge=1, le=1000),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -2051,6 +2165,7 @@ class CollectComputeCenterLocationRequest(BaseModel):
|
||||
organization: Optional[str] = None
|
||||
city: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
force: bool = False
|
||||
record_id: Optional[int] = Field(default=None, alias="id")
|
||||
|
||||
model_config = {"populate_by_name": True}
|
||||
@@ -2087,12 +2202,12 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
|
||||
"reason": f"WebSearch 配置读取失败:{exc}",
|
||||
}
|
||||
provider_config = config.active_provider_config
|
||||
has_api_key = bool((provider_config.api_key or "").strip())
|
||||
has_api_key = bool((provider_config.api_key or "").strip()) or not provider_config.api_key_env
|
||||
if not config.enabled:
|
||||
return {
|
||||
"enabled": False,
|
||||
"provider": config.default_provider,
|
||||
"reason": "WebSearch 未开启,无法进行事实核查定位。",
|
||||
"reason": "WebSearch 未开启,将仅使用确定性设施知识库与地理编码。",
|
||||
}
|
||||
if not has_api_key:
|
||||
return {
|
||||
@@ -2107,7 +2222,7 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
|
||||
}
|
||||
|
||||
|
||||
@router.get("/compute-centers/location-capability")
|
||||
@router.get("/compute-centers/location-capability", dependencies=[_vis_read_dep])
|
||||
async def get_compute_center_location_capability(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
@@ -2115,27 +2230,19 @@ async def get_compute_center_location_capability(
|
||||
return await _compute_center_location_web_search_capability(db)
|
||||
|
||||
|
||||
_TERMINAL_UNLOCATABLE_STATUSES = frozenset({"undisclosed", "multi_site", "anonymous"})
|
||||
|
||||
|
||||
@router.post("/compute-centers/{source_id}/collect-location")
|
||||
async def collect_compute_center_location(
|
||||
source_id: str,
|
||||
payload: CollectComputeCenterLocationRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Run the full multi-query location collection pipeline for a record.
|
||||
|
||||
The endpoint accepts the source_id of a compute center plus contextual
|
||||
fields (name/operator/site/city/country/...) and returns ranked candidate
|
||||
locations from source coordinates, open organization lookups, and online
|
||||
geocoding combinations. The caller never has to type coordinates by hand:
|
||||
if any candidate is accepted it can be applied directly. If no candidate
|
||||
can reach city-level precision the response includes an explicit
|
||||
``failure_reason`` and the list of attempted queries.
|
||||
"""
|
||||
"""Run deterministic facility lookups, Wikidata/PeeringDB, and controlled Tool-Calling location resolution."""
|
||||
if not source_id or not source_id.strip():
|
||||
raise HTTPException(status_code=400, detail="source_id is required")
|
||||
capability = await _compute_center_location_web_search_capability(db)
|
||||
if not capability.get("enabled"):
|
||||
raise HTTPException(status_code=409, detail=capability)
|
||||
|
||||
record = await _load_compute_center_record(db, source_id)
|
||||
name = payload.name or (record.name if record else None)
|
||||
@@ -2148,8 +2255,36 @@ async def collect_compute_center_location(
|
||||
country = payload.country or (get_record_field(record, "country") if record else None)
|
||||
source = payload.source or (record.source if record else None)
|
||||
record_id = payload.record_id or (record.id if record else None)
|
||||
raw_sources = metadata.get("sources") if isinstance(metadata.get("sources"), list) else []
|
||||
source_url = metadata.get("source_url") or metadata.get("detail_url")
|
||||
builds_upon = metadata.get("builds_upon")
|
||||
source_raw_country = metadata.get("raw_country")
|
||||
|
||||
candidates, attempted_queries = collect_location_candidates(
|
||||
if not payload.force and source and source_id:
|
||||
cached = get_compute_center_location_dict(source, source_id)
|
||||
cached_status = str(cached.get("verification_status") or "").strip().lower()
|
||||
if cached_status in _TERMINAL_UNLOCATABLE_STATUSES:
|
||||
return {
|
||||
"source_id": source_id,
|
||||
"record_id": record_id,
|
||||
"name": name,
|
||||
"success": False,
|
||||
"terminal_status": cached_status,
|
||||
"failure_reason": cached.get("source_note") or f"Marked as {cached_status}",
|
||||
"candidates": [],
|
||||
"attempted_queries": [],
|
||||
"llm_failure_reason": None,
|
||||
"context": {
|
||||
"name": name,
|
||||
"operator": operator,
|
||||
"site": site,
|
||||
"city": city,
|
||||
"country": country,
|
||||
},
|
||||
}
|
||||
|
||||
candidates, attempted_queries = await asyncio.to_thread(
|
||||
collect_location_candidates,
|
||||
name=name,
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
@@ -2159,52 +2294,103 @@ async def collect_compute_center_location(
|
||||
city=city,
|
||||
country=country,
|
||||
record_id=record_id,
|
||||
sources=raw_sources,
|
||||
source_url=source_url,
|
||||
builds_upon=builds_upon,
|
||||
source_raw_country=source_raw_country,
|
||||
)
|
||||
llm_failure_reason = None
|
||||
terminal_status: str | None = None
|
||||
query = build_compute_center_location_query(
|
||||
name=name,
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
operator=operator,
|
||||
site=site,
|
||||
organization=organization,
|
||||
city=city,
|
||||
country=country,
|
||||
sources=raw_sources,
|
||||
source_url=source_url,
|
||||
builds_upon=builds_upon,
|
||||
source_raw_country=source_raw_country,
|
||||
)
|
||||
if not candidates:
|
||||
query = build_compute_center_location_query(
|
||||
name=name,
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
operator=operator,
|
||||
site=site,
|
||||
organization=organization,
|
||||
city=city,
|
||||
country=country,
|
||||
l1_candidates, l1_queries, _allow_low_short_circuit = await run_l1_structured_facility_resolvers(
|
||||
query, db=db
|
||||
)
|
||||
if l1_candidates:
|
||||
candidates = l1_candidates
|
||||
attempted_queries = [*attempted_queries, *l1_queries]
|
||||
|
||||
if not candidates:
|
||||
capability = await _compute_center_location_web_search_capability(db)
|
||||
llm_result = None
|
||||
try:
|
||||
web_search_client = await get_web_search_client(db)
|
||||
search_result = await collect_location_search_evidence(
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
)
|
||||
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
|
||||
if not search_result.evidence:
|
||||
llm_failure_reason = search_result.failure_reason
|
||||
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
llm_result = await collect_llm_location_fallback_candidate(
|
||||
provider_client=provider_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
db=db,
|
||||
attempted_queries=attempted_queries,
|
||||
search_evidence=search_result.evidence,
|
||||
)
|
||||
except Exception as exc:
|
||||
if llm_failure_reason is None:
|
||||
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
|
||||
attempted_queries = [
|
||||
*attempted_queries,
|
||||
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
|
||||
]
|
||||
if not capability.get("enabled") and not raw_sources and not source_url:
|
||||
llm_failure_reason = str(capability.get("reason") or "WebSearch unavailable")
|
||||
else:
|
||||
try:
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
web_search_client = await get_web_search_client(db)
|
||||
if hasattr(provider_client, "analyze"):
|
||||
llm_result, terminal_status = await run_controlled_location_agent(
|
||||
provider_client=provider_client,
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
db=db,
|
||||
attempted_queries=[],
|
||||
)
|
||||
else:
|
||||
search_result = await collect_location_search_evidence(
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
)
|
||||
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
|
||||
if not search_result.evidence:
|
||||
llm_failure_reason = search_result.failure_reason
|
||||
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
|
||||
llm_result = await collect_llm_location_fallback_candidate(
|
||||
provider_client=provider_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
db=db,
|
||||
attempted_queries=attempted_queries,
|
||||
search_evidence=search_result.evidence,
|
||||
)
|
||||
except Exception as exc:
|
||||
if llm_failure_reason is None:
|
||||
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
|
||||
attempted_queries = [
|
||||
*attempted_queries,
|
||||
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
|
||||
]
|
||||
if llm_result is not None:
|
||||
attempted_queries = [*attempted_queries, *llm_result.attempted_queries]
|
||||
candidates = llm_result.candidates
|
||||
llm_failure_reason = llm_result.failure_reason
|
||||
|
||||
if terminal_status in _TERMINAL_UNLOCATABLE_STATUSES:
|
||||
return {
|
||||
"source_id": source_id,
|
||||
"record_id": record_id,
|
||||
"name": name,
|
||||
"success": False,
|
||||
"terminal_status": terminal_status,
|
||||
"failure_reason": llm_failure_reason or f"Marked as {terminal_status}",
|
||||
"candidates": [],
|
||||
"attempted_queries": list(attempted_queries),
|
||||
"llm_failure_reason": llm_failure_reason,
|
||||
"context": {
|
||||
"name": name,
|
||||
"operator": operator,
|
||||
"site": site,
|
||||
"city": city,
|
||||
"country": country,
|
||||
},
|
||||
}
|
||||
|
||||
if not candidates:
|
||||
logger.warning_event(
|
||||
"Compute center location collection returned no candidates",
|
||||
@@ -2288,6 +2474,7 @@ async def collect_compute_center_location(
|
||||
async def save_compute_center_location(
|
||||
source_id: str,
|
||||
payload: SaveComputeCenterLocationRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Persist the user-selected compute-center location candidate."""
|
||||
@@ -2394,7 +2581,7 @@ async def _load_raw_vessel_snapshot_features(
|
||||
"legacy_fallback_used": False,
|
||||
}
|
||||
|
||||
@router.get("/vessels/custom-supplements")
|
||||
@router.get("/vessels/custom-supplements", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_custom_supplements(db: AsyncSession = Depends(get_db)):
|
||||
"""Group custom vessel_ais sources by their declared merge target for diagnostics."""
|
||||
|
||||
@@ -2413,7 +2600,7 @@ async def get_vessel_custom_supplements(db: AsyncSession = Depends(get_db)):
|
||||
return {"groups": list(grouped.values())}
|
||||
|
||||
|
||||
@router.get("/vessels/name-fallbacks")
|
||||
@router.get("/vessels/name-fallbacks", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_name_fallbacks(
|
||||
limit: int = Query(500, ge=0, description="Maximum fallback-name vessels to return. 0 means no limit."),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -2482,7 +2669,7 @@ async def get_vessel_name_fallbacks(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}")
|
||||
@router.get("/vessels/{mmsi}", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_detail(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
from app.services.vessel_enrichment import get_vessel_enrichment_bundle
|
||||
|
||||
@@ -2517,7 +2704,7 @@ async def get_vessel_detail(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}/track")
|
||||
@router.get("/vessels/{mmsi}/track", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_track(
|
||||
mmsi: int,
|
||||
hours: int = Query(6, ge=1, le=24),
|
||||
@@ -2584,7 +2771,7 @@ async def get_vessel_track(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}/observations")
|
||||
@router.get("/vessels/{mmsi}/observations", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_observations(
|
||||
mmsi: int,
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
@@ -2601,7 +2788,7 @@ async def get_vessel_observations(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}/conflicts")
|
||||
@router.get("/vessels/{mmsi}/conflicts", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_conflicts(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
"""Return recorded AIS conflicts plus current raw-observation candidates."""
|
||||
|
||||
@@ -2615,7 +2802,7 @@ async def get_vessel_conflicts(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/bgp-anomalies")
|
||||
@router.get("/geo/bgp-anomalies", dependencies=[_vis_read_dep])
|
||||
async def get_bgp_anomalies_geojson(
|
||||
severity: Optional[str] = Query(None),
|
||||
status: Optional[str] = Query("active"),
|
||||
@@ -2659,7 +2846,7 @@ async def _build_bgp_anomalies_geojson(
|
||||
return {**geojson, "count": len(geojson.get("features", []))}
|
||||
|
||||
|
||||
@router.get("/geo/bgp-incidents")
|
||||
@router.get("/geo/bgp-incidents", dependencies=[_vis_read_dep])
|
||||
async def get_bgp_incidents_geojson(
|
||||
severity: Optional[str] = Query(None),
|
||||
status: Optional[str] = Query("active"),
|
||||
@@ -2703,7 +2890,7 @@ async def _build_bgp_incidents_geojson(
|
||||
return {**geojson, "count": len(geojson.get("features", []))}
|
||||
|
||||
|
||||
@router.get("/geo/bgp-collectors")
|
||||
@router.get("/geo/bgp-collectors", dependencies=[_vis_read_dep])
|
||||
async def get_bgp_collectors_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
return await _build_bgp_collectors_geojson(db)
|
||||
@@ -2732,7 +2919,7 @@ async def _build_bgp_collectors_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
return {**geojson, "count": len(geojson.get("features", []))}
|
||||
|
||||
|
||||
@router.get("/geo/summary")
|
||||
@router.get("/geo/summary", dependencies=[_vis_read_dep])
|
||||
async def get_visualization_geo_summary(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
"""Return lightweight Earth HUD counts without loading layer GeoJSON payloads."""
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
@@ -2842,7 +3029,7 @@ async def _build_visualization_geo_summary(db: AsyncSession) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/all")
|
||||
@router.get("/all", dependencies=[_vis_read_dep])
|
||||
async def get_all_visualization_data(db: AsyncSession = Depends(get_db)):
|
||||
"""获取所有可视化数据的统一端点
|
||||
|
||||
@@ -2948,7 +3135,7 @@ async def get_cable_graph(db: AsyncSession) -> CableGraph:
|
||||
return _cable_graph
|
||||
|
||||
|
||||
@router.post("/geo/path")
|
||||
@router.post("/geo/path", dependencies=[_vis_read_dep])
|
||||
async def find_path(
|
||||
start: List[float],
|
||||
end: List[float],
|
||||
|
||||
@@ -4,17 +4,18 @@ import asyncio
|
||||
from datetime import UTC, datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
|
||||
from fastapi import APIRouter, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from jose import jwt, JWTError
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.access_gate import authenticate_ws_earth_or_api_key
|
||||
from app.core.config import settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import is_token_blacklisted
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.manager import manager
|
||||
from app.db.session import async_session_factory
|
||||
from app.db.session import async_session_factory, get_db
|
||||
from app.services.log_tail import LOG_TAIL_CHANNEL, log_tail_manager
|
||||
|
||||
logger = get_logger(__name__, service="api")
|
||||
@@ -74,12 +75,24 @@ async def load_websocket_user_role(user_id: str | None) -> str | None:
|
||||
async def websocket_endpoint(
|
||||
websocket: WebSocket,
|
||||
token: str | None = Query(None),
|
||||
api_key: str | None = Query(None),
|
||||
earth_token: str | None = Query(None),
|
||||
):
|
||||
"""WebSocket endpoint for real-time data"""
|
||||
logger.info_event(
|
||||
"WebSocket connection attempt",
|
||||
event="auth.websocket.connection_attempt",
|
||||
context={"token_preview": f"{token[:8]}..." if token else "anonymous"},
|
||||
context={
|
||||
"token_preview": f"{token[:8]}..." if token else (
|
||||
"api_key" if (api_key or websocket.headers.get("X-API-Key")) else (
|
||||
"earth_session" if (
|
||||
earth_token
|
||||
or websocket.headers.get("X-Planet-Earth-Token")
|
||||
or websocket.cookies.get("planet_earth_session")
|
||||
) else "anonymous"
|
||||
)
|
||||
)
|
||||
},
|
||||
)
|
||||
payload = await authenticate_token(token) if token else None
|
||||
if token and payload is None:
|
||||
@@ -90,8 +103,61 @@ async def websocket_endpoint(
|
||||
await websocket.close(code=4001)
|
||||
return
|
||||
|
||||
ws_earth_or_key_actor: str | None = None
|
||||
if payload is None:
|
||||
has_api_key = bool((api_key or "").strip() or (websocket.headers.get("X-API-Key") or "").strip())
|
||||
try:
|
||||
if has_api_key:
|
||||
override_get_db = websocket.app.dependency_overrides.get(get_db)
|
||||
if override_get_db is not None:
|
||||
db_gen = override_get_db()
|
||||
db = await anext(db_gen)
|
||||
try:
|
||||
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
|
||||
websocket,
|
||||
api_key_query=api_key,
|
||||
earth_token_query=earth_token,
|
||||
db=db,
|
||||
)
|
||||
finally:
|
||||
await db_gen.aclose()
|
||||
else:
|
||||
async with async_session_factory() as db:
|
||||
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
|
||||
websocket,
|
||||
api_key_query=api_key,
|
||||
earth_token_query=earth_token,
|
||||
db=db,
|
||||
)
|
||||
else:
|
||||
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
|
||||
websocket,
|
||||
api_key_query=None,
|
||||
earth_token_query=earth_token,
|
||||
db=None, # type: ignore[arg-type]
|
||||
)
|
||||
except HTTPException:
|
||||
logger.warning_event(
|
||||
"WebSocket API key or Earth session rejected",
|
||||
event="auth.websocket.connection_rejected",
|
||||
)
|
||||
await websocket.close(code=4001)
|
||||
return
|
||||
|
||||
if not authed and settings.effective_earth_api_auth_mode == "enforce":
|
||||
logger.warning_event(
|
||||
"Unauthenticated WebSocket connection rejected in enforce mode",
|
||||
event="auth.websocket.unauthenticated_rejected",
|
||||
)
|
||||
await websocket.close(code=4001)
|
||||
return
|
||||
|
||||
is_anonymous = payload is None
|
||||
user_id = str(payload.get("sub")) if payload else f"anonymous:{id(websocket)}"
|
||||
user_id = (
|
||||
str(payload.get("sub"))
|
||||
if payload
|
||||
else (ws_earth_or_key_actor or f"anonymous:{id(websocket)}")
|
||||
)
|
||||
user_role = await load_websocket_user_role(user_id) if payload else None
|
||||
supported_channels = ["vessels", "earth_news", EARTH_UPDATES_CHANNEL] if is_anonymous else [
|
||||
"gpu_clusters",
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
"""Unified access gate for first-party Earth sessions, API keys, and authorized JWT callers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import time
|
||||
from typing import Any, Literal
|
||||
from urllib.parse import urlsplit
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, WebSocket, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
import httpx
|
||||
from jose import JWTError, jwt
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import (
|
||||
REDIS_OP_TIMEOUT_SECONDS,
|
||||
_AsyncRedisClient,
|
||||
_load_active_user,
|
||||
decode_token,
|
||||
get_current_user,
|
||||
is_token_blacklisted,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.services.api_keys import authenticate_api_key
|
||||
|
||||
logger = get_logger(__name__, service="access_gate")
|
||||
|
||||
EARTH_SESSION_COOKIE = "planet_earth_session"
|
||||
EARTH_TOKEN_HEADER = "X-Planet-Earth-Token"
|
||||
API_KEY_HEADER = "X-API-Key"
|
||||
API_ACCESS_GROUP = "api_access"
|
||||
DESKTOP_CLIENT_PREFIX = "planet-earth-desktop/"
|
||||
TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
|
||||
|
||||
_EARTH_SESSION_TOKEN_TYPE = "earth_session"
|
||||
_MAX_DESKTOP_CLOCK_SKEW_SECONDS = 300
|
||||
_EARTH_SESSION_RATE_LIMIT_PER_MIN = 600
|
||||
_LOCAL_SLIDING_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
|
||||
_LOCAL_NONCES: dict[str, float] = {}
|
||||
_MAX_LOCAL_ENTRIES = 20_000
|
||||
|
||||
optional_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class EarthAccessContext:
|
||||
"""Resolved caller identity for Earth data and external API routes."""
|
||||
|
||||
channel: Literal["api_key", "jwt", "earth_web", "earth_desktop", "dev_open"]
|
||||
actor_key: str
|
||||
user: User | None = None
|
||||
api_key_id: int | None = None
|
||||
|
||||
|
||||
def reset_access_gate_caches() -> None:
|
||||
"""Clear in-process rate-limit and nonce caches (used by tests)."""
|
||||
_LOCAL_SLIDING_WINDOWS.clear()
|
||||
_LOCAL_NONCES.clear()
|
||||
|
||||
|
||||
def _prune_local_nonces(now: float) -> None:
|
||||
expired = [key for key, exp in _LOCAL_NONCES.items() if exp <= now]
|
||||
for key in expired:
|
||||
_LOCAL_NONCES.pop(key, None)
|
||||
while len(_LOCAL_NONCES) > _MAX_LOCAL_ENTRIES:
|
||||
_LOCAL_NONCES.pop(next(iter(_LOCAL_NONCES)), None)
|
||||
|
||||
|
||||
async def check_sliding_rate_limit(
|
||||
bucket: str,
|
||||
*,
|
||||
limit: int,
|
||||
window_seconds: int,
|
||||
detail: str = "Rate limit exceeded",
|
||||
) -> None:
|
||||
"""Enforce a bounded sliding/fixed window limit via Redis with local fallback."""
|
||||
if limit <= 0 or window_seconds <= 0:
|
||||
return
|
||||
redis_key = f"access_gate:{bucket}"
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
count = await asyncio.wait_for(
|
||||
client.incr(redis_key),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
if int(count) == 1:
|
||||
await asyncio.wait_for(
|
||||
client.expire(redis_key, window_seconds),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
if int(count) > limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=detail,
|
||||
)
|
||||
return
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
now = time.monotonic()
|
||||
dq = _LOCAL_SLIDING_WINDOWS[bucket]
|
||||
cutoff = now - float(window_seconds)
|
||||
while dq and dq[0] <= cutoff:
|
||||
dq.popleft()
|
||||
if len(dq) >= limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=detail,
|
||||
)
|
||||
dq.append(now)
|
||||
if len(_LOCAL_SLIDING_WINDOWS) > _MAX_LOCAL_ENTRIES:
|
||||
_LOCAL_SLIDING_WINDOWS.pop(next(iter(_LOCAL_SLIDING_WINDOWS)), None)
|
||||
|
||||
|
||||
async def _register_nonce_once(nonce: str, ttl_seconds: int) -> bool:
|
||||
key = f"earth_nonce:{hashlib.sha256(nonce.encode('utf-8')).hexdigest()}"
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
stored = await asyncio.wait_for(
|
||||
client.set(key, "1", ex=ttl_seconds, nx=True),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
return bool(stored)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
now = time.monotonic()
|
||||
_prune_local_nonces(now)
|
||||
if key in _LOCAL_NONCES and _LOCAL_NONCES[key] > now:
|
||||
return False
|
||||
_LOCAL_NONCES[key] = now + float(ttl_seconds)
|
||||
return True
|
||||
|
||||
|
||||
def create_earth_session_token(
|
||||
channel: Literal["web", "desktop"],
|
||||
client_id: str | None = None,
|
||||
) -> tuple[str, int]:
|
||||
"""Mint a short-lived signed JWT for Web Earth or Desktop Earth zero-login access."""
|
||||
ttl_minutes = max(5, int(settings.EARTH_SESSION_TTL_MINUTES or 30))
|
||||
ttl_seconds = ttl_minutes * 60
|
||||
expire = datetime.now(UTC) + timedelta(seconds=ttl_seconds)
|
||||
cid = (client_id or uuid4().hex[:16]).strip()[:64]
|
||||
payload = {
|
||||
"type": _EARTH_SESSION_TOKEN_TYPE,
|
||||
"channel": channel,
|
||||
"cid": cid,
|
||||
"jti": uuid4().hex,
|
||||
"exp": expire,
|
||||
}
|
||||
token = jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return token, ttl_seconds
|
||||
|
||||
|
||||
def verify_earth_session_token(token: str) -> dict[str, Any] | None:
|
||||
"""Verify a signed Earth session token and return its claims or None."""
|
||||
cleaned = str(token or "").strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
try:
|
||||
payload = jwt.decode(cleaned, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
if payload.get("type") != _EARTH_SESSION_TOKEN_TYPE:
|
||||
return None
|
||||
if payload.get("channel") not in {"web", "desktop"}:
|
||||
return None
|
||||
return payload
|
||||
|
||||
|
||||
def _extract_host_port(raw_url_or_host: str) -> str:
|
||||
value = str(raw_url_or_host or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
if "://" in value:
|
||||
parsed = urlsplit(value)
|
||||
return (parsed.netloc or "").lower()
|
||||
return value.lower()
|
||||
|
||||
|
||||
def _allowed_web_origins(request: Request) -> set[str]:
|
||||
allowed: set[str] = set()
|
||||
req_host = _extract_host_port(request.headers.get("host") or request.url.netloc or "")
|
||||
if req_host:
|
||||
allowed.add(req_host)
|
||||
for raw in [*(settings.EARTH_WEB_ALLOWED_ORIGINS or []), *(settings.CORS_ORIGINS or [])]:
|
||||
host = _extract_host_port(str(raw))
|
||||
if host and host != "*":
|
||||
allowed.add(host)
|
||||
return allowed
|
||||
|
||||
|
||||
def verify_web_same_origin(request: Request) -> None:
|
||||
"""Require first-party browser same-origin / allowed-origin headers for web session minting."""
|
||||
sec_fetch_site = (request.headers.get("sec-fetch-site") or "").strip().lower()
|
||||
if sec_fetch_site in {"cross-site"}:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Cross-site Earth session requests are forbidden",
|
||||
)
|
||||
|
||||
origin_host = _extract_host_port(request.headers.get("origin") or "")
|
||||
referer_host = _extract_host_port(request.headers.get("referer") or "")
|
||||
allowed = _allowed_web_origins(request)
|
||||
|
||||
if origin_host:
|
||||
if origin_host not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Origin not permitted for Earth web session",
|
||||
)
|
||||
return
|
||||
|
||||
if referer_host:
|
||||
if referer_host not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Referer not permitted for Earth web session",
|
||||
)
|
||||
return
|
||||
|
||||
if sec_fetch_site in {"same-origin", "same-site"}:
|
||||
return
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Same-origin browser headers required for Earth web session",
|
||||
)
|
||||
|
||||
|
||||
async def verify_turnstile_token(token: str | None, remote_ip: str) -> None:
|
||||
"""Verify Cloudflare Turnstile token when `TURNSTILE_SECRET_KEY` is configured."""
|
||||
secret = str(settings.TURNSTILE_SECRET_KEY or "").strip()
|
||||
if not secret:
|
||||
return
|
||||
cleaned = str(token or "").strip()
|
||||
if not cleaned:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Turnstile verification token is required",
|
||||
)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
resp = await client.post(
|
||||
TURNSTILE_VERIFY_URL,
|
||||
data={
|
||||
"secret": secret,
|
||||
"response": cleaned,
|
||||
"remoteip": remote_ip,
|
||||
},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning_event(
|
||||
"Turnstile verification request failed",
|
||||
event="access_gate.turnstile.error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Human verification service temporarily unavailable",
|
||||
) from exc
|
||||
|
||||
if not bool(body.get("success")):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Turnstile verification failed",
|
||||
)
|
||||
|
||||
|
||||
async def verify_desktop_handshake(request: Request) -> str:
|
||||
"""Verify Planet Earth Desktop client identity and optional HMAC handshake."""
|
||||
client_header = (request.headers.get("X-Planet-Client") or "").strip()
|
||||
if not client_header.startswith(DESKTOP_CLIENT_PREFIX) or len(client_header) <= len(
|
||||
DESKTOP_CLIENT_PREFIX
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Desktop client header is required",
|
||||
)
|
||||
|
||||
secret = str(settings.EARTH_DESKTOP_HANDSHAKE_SECRET or "").strip()
|
||||
if not secret:
|
||||
return client_header
|
||||
|
||||
ts_raw = (request.headers.get("X-Planet-Client-Timestamp") or "").strip()
|
||||
nonce = (request.headers.get("X-Planet-Client-Nonce") or "").strip()
|
||||
signature = (request.headers.get("X-Planet-Client-Signature") or "").strip().lower()
|
||||
if not ts_raw or not nonce or not signature or len(nonce) > 128:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Desktop handshake signature headers required",
|
||||
)
|
||||
|
||||
try:
|
||||
ts_val = int(ts_raw)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Invalid desktop handshake timestamp",
|
||||
) from exc
|
||||
|
||||
now_ts = int(time.time())
|
||||
if abs(now_ts - ts_val) > _MAX_DESKTOP_CLOCK_SKEW_SECONDS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Desktop handshake timestamp expired",
|
||||
)
|
||||
|
||||
expected = hmac.new(
|
||||
secret.encode("utf-8"),
|
||||
f"{ts_raw}.{nonce}.{client_header}".encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
if not hmac.compare_digest(signature, expected):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Invalid desktop handshake signature",
|
||||
)
|
||||
|
||||
fresh = await _register_nonce_once(nonce, _MAX_DESKTOP_CLOCK_SKEW_SECONDS)
|
||||
if not fresh:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Replay desktop handshake nonce rejected",
|
||||
)
|
||||
return client_header
|
||||
|
||||
|
||||
def user_has_api_access(user: User) -> bool:
|
||||
"""Return True if the authenticated user is allowed to call Earth/external APIs."""
|
||||
role = user.role.value if hasattr(user.role, "value") else str(user.role or "")
|
||||
if role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
return True
|
||||
groups = {str(g).strip() for g in (user.gatekeeper_groups or []) if g}
|
||||
return API_ACCESS_GROUP in groups
|
||||
|
||||
|
||||
async def require_admin_user(current_user: User = Depends(get_current_user)) -> User:
|
||||
"""FastAPI dependency requiring `admin` or `super_admin` role."""
|
||||
role = current_user.role.value if hasattr(current_user.role, "value") else str(current_user.role or "")
|
||||
if role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Administrator privileges required",
|
||||
)
|
||||
return current_user
|
||||
|
||||
|
||||
async def _validate_bearer_api_user(
|
||||
token: str,
|
||||
db: AsyncSession,
|
||||
) -> User:
|
||||
if await is_token_blacklisted(token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "access" or payload.get("sub") is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token",
|
||||
)
|
||||
user = await _load_active_user(str(payload["sub"]), db)
|
||||
if not user_has_api_access(user):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account lacks api_access permission",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def require_earth_or_api_access(
|
||||
scope: str,
|
||||
*,
|
||||
allow_query_api_key: bool = False,
|
||||
):
|
||||
"""Build a FastAPI dependency allowing API Keys, authorized JWT users, or Earth sessions."""
|
||||
|
||||
async def _dependency(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> EarthAccessContext:
|
||||
raw_api_key = (request.headers.get(API_KEY_HEADER) or "").strip()
|
||||
if not raw_api_key and allow_query_api_key:
|
||||
raw_api_key = (request.query_params.get("api_key") or "").strip()
|
||||
if raw_api_key:
|
||||
record = await authenticate_api_key(db, raw_api_key, scope)
|
||||
return EarthAccessContext(
|
||||
channel="api_key",
|
||||
actor_key=f"api_key:{record.id}",
|
||||
api_key_id=int(record.id),
|
||||
)
|
||||
|
||||
if credentials is not None and credentials.credentials:
|
||||
user = await _validate_bearer_api_user(credentials.credentials, db)
|
||||
return EarthAccessContext(
|
||||
channel="jwt",
|
||||
actor_key=f"user:{user.id}",
|
||||
user=user,
|
||||
)
|
||||
|
||||
earth_header = (request.headers.get(EARTH_TOKEN_HEADER) or "").strip()
|
||||
earth_cookie = (request.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
|
||||
earth_token = earth_header or earth_cookie
|
||||
if earth_token:
|
||||
claims = verify_earth_session_token(earth_token)
|
||||
if claims is not None:
|
||||
channel = "earth_desktop" if claims.get("channel") == "desktop" else "earth_web"
|
||||
cid = str(claims.get("cid") or "anon")
|
||||
await check_sliding_rate_limit(
|
||||
f"earth:{channel}:{cid}",
|
||||
limit=_EARTH_SESSION_RATE_LIMIT_PER_MIN,
|
||||
window_seconds=60,
|
||||
detail="Earth session rate limit exceeded",
|
||||
)
|
||||
return EarthAccessContext(
|
||||
channel=channel,
|
||||
actor_key=f"{channel}:{cid}",
|
||||
)
|
||||
if settings.effective_earth_api_auth_mode == "enforce":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired Earth session",
|
||||
)
|
||||
|
||||
if settings.effective_earth_api_auth_mode == "enforce":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Authentication required",
|
||||
)
|
||||
|
||||
return EarthAccessContext(channel="dev_open", actor_key="dev:open")
|
||||
|
||||
return _dependency
|
||||
|
||||
|
||||
async def authenticate_ws_earth_or_api_key(
|
||||
websocket: WebSocket,
|
||||
*,
|
||||
api_key_query: str | None,
|
||||
earth_token_query: str | None,
|
||||
db: AsyncSession,
|
||||
) -> tuple[bool, str | None]:
|
||||
"""Authenticate non-JWT WebSocket connections via API key or Earth session token.
|
||||
|
||||
Returns `(authenticated, actor_id)`. Raises HTTPException on explicit invalid credentials.
|
||||
"""
|
||||
raw_api_key = (
|
||||
(websocket.headers.get(API_KEY_HEADER) or "").strip()
|
||||
or (api_key_query or "").strip()
|
||||
)
|
||||
if raw_api_key:
|
||||
record = await authenticate_api_key(db, raw_api_key, "ws:connect")
|
||||
return True, f"api_key:{record.id}"
|
||||
|
||||
raw_earth_token = (
|
||||
(websocket.headers.get(EARTH_TOKEN_HEADER) or "").strip()
|
||||
or (earth_token_query or "").strip()
|
||||
or (websocket.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
|
||||
)
|
||||
if raw_earth_token:
|
||||
claims = verify_earth_session_token(raw_earth_token)
|
||||
if claims is None:
|
||||
if settings.effective_earth_api_auth_mode == "enforce":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired Earth WebSocket session",
|
||||
)
|
||||
return False, None
|
||||
channel = str(claims.get("channel") or "web")
|
||||
cid = str(claims.get("cid") or secrets.token_hex(4))
|
||||
return True, f"earth_{channel}:{cid}"
|
||||
|
||||
return False, None
|
||||
@@ -87,10 +87,28 @@ class Settings(BaseSettings):
|
||||
AI_PROVIDER_RETRY_ATTEMPTS: int = 2
|
||||
OBSERVABILITY_INGEST_TOKEN: str = ""
|
||||
|
||||
CLIENT_UPDATES_DIR: str = ""
|
||||
CLIENT_UPDATE_PUBLISH_TOKEN: str = ""
|
||||
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
|
||||
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
|
||||
|
||||
EARTH_API_AUTH_MODE: str = ""
|
||||
EARTH_SESSION_TTL_MINUTES: int = 30
|
||||
EARTH_WEB_ALLOWED_ORIGINS: List[str] = []
|
||||
EARTH_DESKTOP_HANDSHAKE_SECRET: str = ""
|
||||
TURNSTILE_SECRET_KEY: str = ""
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return str(self.APP_ENV or "").strip().lower() == "production"
|
||||
|
||||
@property
|
||||
def effective_earth_api_auth_mode(self) -> str:
|
||||
raw = str(self.EARTH_API_AUTH_MODE or "").strip().lower()
|
||||
if raw in {"enforce", "off"}:
|
||||
return raw
|
||||
return "enforce" if self.is_production else "off"
|
||||
|
||||
@property
|
||||
def normalized_role(self) -> str:
|
||||
role = str(self.PLANET_ROLE or "all").strip().lower()
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Create api_keys table for external and internal UE5 API key authentication."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0004"
|
||||
NAME = "add_api_keys_table"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create api_keys table and indexes idempotently across PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
key_prefix VARCHAR(32) NOT NULL,
|
||||
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
scopes JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
rate_limit_per_minute INTEGER NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_by_user_id INTEGER NULL,
|
||||
last_used_at TIMESTAMP WITH TIME ZONE NULL,
|
||||
revoked_at TIMESTAMP WITH TIME ZONE NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
key_prefix VARCHAR(32) NOT NULL,
|
||||
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
scopes JSON NOT NULL DEFAULT '[]',
|
||||
rate_limit_per_minute INTEGER NULL,
|
||||
expires_at TIMESTAMP NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_by_user_id INTEGER NULL,
|
||||
last_used_at TIMESTAMP NULL,
|
||||
revoked_at TIMESTAMP NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS ix_api_keys_key_prefix ON api_keys (key_prefix)")
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE UNIQUE INDEX IF NOT EXISTS ix_api_keys_key_hash ON api_keys (key_hash)")
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS ix_api_keys_is_active ON api_keys (is_active)")
|
||||
)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Create ai_workflows, ai_workflow_revisions, and ai_workflow_fixtures tables."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0005"
|
||||
NAME = "add_ai_workflows"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create workflow management tables and indexes idempotently across PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflows (
|
||||
id SERIAL PRIMARY KEY,
|
||||
workflow_id VARCHAR(80) NOT NULL UNIQUE,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
name_en VARCHAR(160) NOT NULL DEFAULT '',
|
||||
category VARCHAR(60) NOT NULL DEFAULT 'advisor',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
description_en TEXT NOT NULL DEFAULT '',
|
||||
is_default BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
is_builtin BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
active_revision INTEGER NOT NULL DEFAULT 1,
|
||||
published_graph JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
draft_graph JSONB NULL,
|
||||
updated_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_revisions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'published',
|
||||
graph_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
change_summary TEXT NOT NULL DEFAULT '',
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_fixtures (
|
||||
id SERIAL PRIMARY KEY,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
sample_question TEXT NOT NULL DEFAULT '',
|
||||
context_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflows (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
workflow_id VARCHAR(80) NOT NULL UNIQUE,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
name_en VARCHAR(160) NOT NULL DEFAULT '',
|
||||
category VARCHAR(60) NOT NULL DEFAULT 'advisor',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
description_en TEXT NOT NULL DEFAULT '',
|
||||
is_default BOOLEAN NOT NULL DEFAULT 0,
|
||||
is_builtin BOOLEAN NOT NULL DEFAULT 1,
|
||||
active_revision INTEGER NOT NULL DEFAULT 1,
|
||||
published_graph JSON NOT NULL DEFAULT '{}',
|
||||
draft_graph JSON NULL,
|
||||
updated_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_revisions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'published',
|
||||
graph_json JSON NOT NULL DEFAULT '{}',
|
||||
change_summary TEXT NOT NULL DEFAULT '',
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_fixtures (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
sample_question TEXT NOT NULL DEFAULT '',
|
||||
context_json JSON NOT NULL DEFAULT '{}',
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_ai_workflows_category ON ai_workflows (category)"))
|
||||
await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_ai_workflow_revisions_wf_rev ON ai_workflow_revisions (workflow_id, revision)"))
|
||||
await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_ai_workflow_fixtures_wf ON ai_workflow_fixtures (workflow_id)"))
|
||||
@@ -470,6 +470,8 @@ async def ensure_default_admin_user(session: AsyncSession):
|
||||
|
||||
async def init_db():
|
||||
import app.models.user # noqa: F401
|
||||
import app.models.api_key # noqa: F401
|
||||
import app.models.ai_workflow # noqa: F401
|
||||
import app.models.gpu_cluster # noqa: F401
|
||||
import app.models.task # noqa: F401
|
||||
import app.models.data_snapshot # noqa: F401
|
||||
@@ -1121,3 +1123,6 @@ async def _init_db_ddl_and_seed():
|
||||
await purge_legacy_earth_boundary_datasources(session)
|
||||
await ensure_default_admin_user(session)
|
||||
await ensure_default_storage_policy(session)
|
||||
from app.services.ai.workflow_registry import ensure_builtin_workflows
|
||||
|
||||
await ensure_builtin_workflows(session)
|
||||
+24
-4
@@ -5,6 +5,7 @@ from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy import text
|
||||
@@ -181,10 +182,30 @@ app = FastAPI(
|
||||
description="智能星球计划 - 态势感知系统\n\n## 功能模块\n\n- **用户认证**: JWT-based authentication\n- **数据源管理**: 多源数据采集器管理\n- **任务调度**: 定时任务调度与监控\n- **实时更新**: WebSocket实时数据推送\n- **告警系统**: 多级告警管理\n\n## 数据层级\n\n- **L1**: 核心数据 (TOP500, Epoch AI GPU)\n- **L2**: 扩展数据 (HuggingFace, PeeringDB, 海缆)\n- **L3**: 分析数据\n- **L4**: 决策支持",
|
||||
lifespan=lifespan,
|
||||
docs_url=None,
|
||||
redoc_url="/docs",
|
||||
openapi_url="/openapi.json",
|
||||
redoc_url=None if settings.is_production else "/docs",
|
||||
openapi_url=None if settings.is_production else "/openapi.json",
|
||||
)
|
||||
|
||||
class NonStreamingGZipMiddleware:
|
||||
"""Apply GZip compression while skipping SSE streaming responses so events flush immediately."""
|
||||
|
||||
def __init__(self, app, minimum_size: int = 1024) -> None:
|
||||
self.app = app
|
||||
self.gzip_app = GZipMiddleware(app, minimum_size=minimum_size)
|
||||
|
||||
async def __call__(self, scope, receive, send) -> None:
|
||||
if scope.get("type") == "http":
|
||||
path = str(scope.get("path") or "")
|
||||
headers = dict(scope.get("headers") or [])
|
||||
accept = headers.get(b"accept", b"").lower()
|
||||
if path.endswith("/stream") or b"text/event-stream" in accept:
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
await self.gzip_app(scope, receive, send)
|
||||
|
||||
|
||||
app.add_middleware(NonStreamingGZipMiddleware, minimum_size=1024)
|
||||
|
||||
configured_origins = list(settings.CORS_ORIGINS or [])
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
@@ -253,8 +274,7 @@ async def root():
|
||||
return {
|
||||
"name": settings.PROJECT_NAME,
|
||||
"version": settings.VERSION,
|
||||
"docs": "/docs",
|
||||
"redoc": "/redoc",
|
||||
"docs": None if settings.is_production else "/docs",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from app.models.user import User
|
||||
from app.models.api_key import ApiKey
|
||||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
|
||||
from app.models.gpu_cluster import GPUCluster
|
||||
from app.models.task import CollectionTask
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
@@ -29,6 +31,10 @@ from app.models.situational_assessment import (
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AIWorkflow",
|
||||
"AIWorkflowFixture",
|
||||
"AIWorkflowRevision",
|
||||
"ApiKey",
|
||||
"User",
|
||||
"GPUCluster",
|
||||
"CollectionTask",
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Persistent AI workflow definitions, versioned revisions, and local test fixtures."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class AIWorkflow(Base):
|
||||
"""Managed AI Advisor workflow graph (published + optional draft revision)."""
|
||||
|
||||
__tablename__ = "ai_workflows"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
workflow_id = Column(String(80), nullable=False, unique=True, index=True)
|
||||
name = Column(String(160), nullable=False)
|
||||
name_en = Column(String(160), nullable=False, default="")
|
||||
category = Column(String(60), nullable=False, default="advisor", index=True)
|
||||
description = Column(Text, nullable=False, default="")
|
||||
description_en = Column(Text, nullable=False, default="")
|
||||
is_default = Column(Boolean, nullable=False, default=False, index=True)
|
||||
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)
|
||||
updated_by = Column(String(120), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"name": self.name,
|
||||
"name_en": self.name_en or self.name,
|
||||
"category": self.category,
|
||||
"description": self.description or "",
|
||||
"description_en": self.description_en or self.description or "",
|
||||
"is_default": bool(self.is_default),
|
||||
"is_builtin": bool(self.is_builtin),
|
||||
"active_revision": int(self.active_revision or 1),
|
||||
"has_draft": self.draft_graph is not None,
|
||||
"published_graph": self.published_graph or {},
|
||||
"draft_graph": self.draft_graph,
|
||||
"updated_by": self.updated_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
"updated_at": to_iso8601_utc(self.updated_at),
|
||||
}
|
||||
|
||||
|
||||
class AIWorkflowRevision(Base):
|
||||
"""Immutable revision history for AI workflows enabling safe rollback."""
|
||||
|
||||
__tablename__ = "ai_workflow_revisions"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
workflow_id = Column(String(80), nullable=False, index=True)
|
||||
revision = Column(Integer, nullable=False)
|
||||
status = Column(String(24), nullable=False, default="published", index=True)
|
||||
graph_json = Column(JSON, nullable=False, default=dict)
|
||||
change_summary = Column(Text, nullable=False, default="")
|
||||
created_by = Column(String(120), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_ai_workflow_revisions_wf_rev", "workflow_id", "revision"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"revision": int(self.revision),
|
||||
"status": self.status,
|
||||
"graph_json": self.graph_json or {},
|
||||
"change_summary": self.change_summary or "",
|
||||
"created_by": self.created_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
}
|
||||
|
||||
|
||||
class AIWorkflowFixture(Base):
|
||||
"""Explicitly saved anonymized regression test fixture for an AI workflow."""
|
||||
|
||||
__tablename__ = "ai_workflow_fixtures"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
workflow_id = Column(String(80), nullable=False, index=True)
|
||||
name = Column(String(160), nullable=False)
|
||||
sample_question = Column(Text, nullable=False, default="")
|
||||
context_json = Column(JSON, nullable=False, default=dict)
|
||||
created_by = Column(String(120), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"name": self.name,
|
||||
"sample_question": self.sample_question or "",
|
||||
"context_json": self.context_json or {},
|
||||
"created_by": self.created_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Database model for internal/external API keys."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Integer, JSON, String
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class ApiKey(Base):
|
||||
"""Hashed API key for UE5, internal scripts, and external partner integrations."""
|
||||
|
||||
__tablename__ = "api_keys"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
name = Column(String(120), nullable=False)
|
||||
key_prefix = Column(String(32), nullable=False, index=True)
|
||||
key_hash = Column(String(64), nullable=False, unique=True, index=True)
|
||||
scopes = Column(JSON, nullable=False, default=list)
|
||||
rate_limit_per_minute = Column(Integer, nullable=True)
|
||||
expires_at = Column(DateTime(timezone=True), nullable=True)
|
||||
is_active = Column(Boolean, nullable=False, default=True, index=True)
|
||||
created_by_user_id = Column(Integer, nullable=True)
|
||||
last_used_at = Column(DateTime(timezone=True), nullable=True)
|
||||
revoked_at = Column(DateTime(timezone=True), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<ApiKey id={self.id} name={self.name!r} prefix={self.key_prefix!r}>"
|
||||
@@ -1,9 +1,24 @@
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.core.enums import PlaygroundMessageKind, PlaygroundMessageRole, PlaygroundMessageStatus
|
||||
|
||||
|
||||
class ChatMessage(BaseModel):
|
||||
role: Literal["user", "assistant", "tool"]
|
||||
content: str = Field(default="", max_length=24000)
|
||||
tool_call_id: str | None = Field(default=None, max_length=200)
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
tool_calls: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
class ToolCallRecord(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
arguments: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class AIContentBlock(BaseModel):
|
||||
type: str
|
||||
text: str | None = None
|
||||
@@ -14,13 +29,18 @@ class AIContentBlock(BaseModel):
|
||||
|
||||
class SituationalAnalysisRequest(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
objective: str = Field(..., min_length=1, max_length=20000)
|
||||
objective: str = Field(..., min_length=1, max_length=24000)
|
||||
context: dict[str, Any] = Field(default_factory=dict)
|
||||
observations: list[str] = Field(default_factory=list)
|
||||
constraints: list[str] = Field(default_factory=list)
|
||||
system_prompt: str | None = Field(default=None, max_length=8000)
|
||||
preferred_model: str | None = Field(default=None, max_length=200)
|
||||
thinking: dict[str, Any] | None = None
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=48)
|
||||
tools: list[dict[str, Any]] | None = None
|
||||
tool_choice: str | dict[str, Any] | None = None
|
||||
response_format: dict[str, Any] | None = None
|
||||
native_web_search: bool = False
|
||||
|
||||
|
||||
class BGPBriefRequest(BaseModel):
|
||||
@@ -49,6 +69,8 @@ class SituationalAnalysisResponse(BaseModel):
|
||||
content_blocks: list[AIContentBlock] = Field(default_factory=list)
|
||||
text_blocks: list[str] = Field(default_factory=list)
|
||||
thinking_blocks: list[str] = Field(default_factory=list)
|
||||
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
|
||||
stop_reason: str | None = None
|
||||
raw_response: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Multi-turn conversation sanitization, rolling compaction, and lightweight memory formatting."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.schemas.ai import SituationalAnalysisRequest
|
||||
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
|
||||
from app.services.ai_client import AIProviderClient
|
||||
|
||||
logger = get_logger(__name__, service="ai_memory")
|
||||
|
||||
RECENT_WINDOW_TURNS = 4
|
||||
COMPACT_TRIGGER_CHARS = 7500
|
||||
MAX_MESSAGE_CHARS = 1800
|
||||
MAX_SUMMARY_CHARS = 1600
|
||||
MAX_MEMORY_NOTES = 12
|
||||
MAX_PINNED_SUMMARIES = 8
|
||||
|
||||
|
||||
def _truncate_text(text: str, limit: int) -> str:
|
||||
cleaned = str(text or "").strip()
|
||||
if len(cleaned) <= limit:
|
||||
return cleaned
|
||||
return f"{cleaned[: max(0, limit - 1)].rstrip()}…"
|
||||
|
||||
|
||||
def sanitize_history_messages(raw_messages: list[Any] | None) -> list[dict[str, str]]:
|
||||
"""Strip inline thinking blocks, truncate extremes, and normalize alternating user/assistant turns."""
|
||||
normalized: list[dict[str, str]] = []
|
||||
for item in raw_messages or []:
|
||||
if isinstance(item, dict):
|
||||
role = str(item.get("role") or "").strip().lower()
|
||||
raw_content = item.get("content")
|
||||
else:
|
||||
role = str(getattr(item, "role", "") or "").strip().lower()
|
||||
raw_content = getattr(item, "content", "")
|
||||
if role not in {"user", "assistant"}:
|
||||
continue
|
||||
content = str(raw_content or "").strip()
|
||||
if not content:
|
||||
continue
|
||||
if role == "assistant":
|
||||
clean_content, _ = strip_thinking_text(content)
|
||||
content = clean_content or content
|
||||
content = _truncate_text(content, MAX_MESSAGE_CHARS)
|
||||
if not content:
|
||||
continue
|
||||
if not normalized and role == "assistant":
|
||||
continue
|
||||
if normalized and normalized[-1]["role"] == role:
|
||||
merged = f"{normalized[-1]['content']}\n\n{content}"
|
||||
normalized[-1]["content"] = _truncate_text(merged, MAX_MESSAGE_CHARS)
|
||||
else:
|
||||
normalized.append({"role": role, "content": content})
|
||||
return normalized
|
||||
|
||||
|
||||
def _sanitize_short_list(items: list[Any] | None, *, max_items: int, max_chars: int = 200) -> list[str]:
|
||||
result: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in items or []:
|
||||
text = _truncate_text(str(raw or "").replace("\r", " ").replace("\n", " "), max_chars)
|
||||
if not text or text in seen:
|
||||
continue
|
||||
seen.add(text)
|
||||
result.append(text)
|
||||
if len(result) >= max_items:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def sanitize_memory_notes(notes: list[Any] | None) -> list[str]:
|
||||
"""Return deduplicated short user memory notes within configured cap."""
|
||||
return _sanitize_short_list(notes, max_items=MAX_MEMORY_NOTES)
|
||||
|
||||
|
||||
def sanitize_pinned_summaries(items: list[Any] | None) -> list[str]:
|
||||
"""Return deduplicated short pinned comparison summaries within configured cap."""
|
||||
return _sanitize_short_list(items, max_items=MAX_PINNED_SUMMARIES)
|
||||
|
||||
|
||||
def build_deterministic_compaction_summary(
|
||||
existing_summary: str,
|
||||
dropped_messages: list[dict[str, str]],
|
||||
) -> str:
|
||||
"""Build a bounded structured summary when older turns overflow the active window."""
|
||||
lines: list[str] = []
|
||||
prior = str(existing_summary or "").strip()
|
||||
if prior:
|
||||
lines.append(prior)
|
||||
|
||||
pair_lines: list[str] = []
|
||||
idx = 0
|
||||
while idx < len(dropped_messages):
|
||||
msg = dropped_messages[idx]
|
||||
if msg["role"] == "user":
|
||||
q = _truncate_text(msg["content"].replace("\n", " "), 120)
|
||||
a = ""
|
||||
if idx + 1 < len(dropped_messages) and dropped_messages[idx + 1]["role"] == "assistant":
|
||||
a = _truncate_text(dropped_messages[idx + 1]["content"].replace("\n", " "), 180)
|
||||
idx += 2
|
||||
else:
|
||||
idx += 1
|
||||
pair_lines.append(f"- 问:{q}" + (f" → 结:{a}" if a else ""))
|
||||
else:
|
||||
a = _truncate_text(msg["content"].replace("\n", " "), 160)
|
||||
pair_lines.append(f"- 历史结论:{a}")
|
||||
idx += 1
|
||||
|
||||
if pair_lines:
|
||||
block = "\n".join(pair_lines)
|
||||
if prior and not prior.startswith("### 前序对话摘要"):
|
||||
lines = [f"### 前序对话摘要\n{prior}", block]
|
||||
elif prior:
|
||||
lines = [prior, block]
|
||||
else:
|
||||
lines = [f"### 前序对话摘要\n{block}"]
|
||||
|
||||
combined = "\n".join(lines).strip()
|
||||
if len(combined) > MAX_SUMMARY_CHARS:
|
||||
head = "### 前序对话摘要\n"
|
||||
tail_budget = MAX_SUMMARY_CHARS - len(head) - 2
|
||||
combined = f"{head}…{combined[-tail_budget:].lstrip()}"
|
||||
return combined
|
||||
|
||||
|
||||
async def compact_conversation_history(
|
||||
raw_messages: list[Any] | None,
|
||||
existing_summary: str = "",
|
||||
*,
|
||||
ai_client: AIProviderClient | None = None,
|
||||
ai_ready: bool = False,
|
||||
recent_window_turns: int = RECENT_WINDOW_TURNS,
|
||||
char_budget: int = COMPACT_TRIGGER_CHARS,
|
||||
) -> dict[str, Any]:
|
||||
"""Keep recent window verbatim and compact overflow turns into a rolling summary."""
|
||||
sanitized = sanitize_history_messages(raw_messages)
|
||||
summary = _truncate_text(existing_summary or "", MAX_SUMMARY_CHARS)
|
||||
|
||||
keep_limit = max(2, recent_window_turns * 2)
|
||||
split_idx = max(0, len(sanitized) - keep_limit)
|
||||
if split_idx < len(sanitized) and sanitized[split_idx]["role"] == "assistant":
|
||||
split_idx += 1
|
||||
|
||||
older = sanitized[:split_idx]
|
||||
recent = sanitized[split_idx:]
|
||||
|
||||
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
|
||||
while not older and total_chars > char_budget and len(recent) > 2:
|
||||
move_count = 2 if (len(recent) >= 4 and recent[0]["role"] == "user" and recent[1]["role"] == "assistant") else 1
|
||||
older.extend(recent[:move_count])
|
||||
recent = recent[move_count:]
|
||||
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
|
||||
|
||||
if not older:
|
||||
return {
|
||||
"summary": summary,
|
||||
"recent_messages": recent,
|
||||
"compacted": False,
|
||||
"compacted_count": 0,
|
||||
}
|
||||
|
||||
next_summary = ""
|
||||
if ai_ready and ai_client is not None:
|
||||
try:
|
||||
effective_client = ai_client
|
||||
if type(ai_client) is AIProviderClient and ai_client.llm_config:
|
||||
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=900)
|
||||
transcript = "\n".join(
|
||||
f"{'用户' if m['role'] == 'user' else 'AI 参谋'}: {m['content']}" for m in older
|
||||
)
|
||||
compact_req = SituationalAnalysisRequest(
|
||||
title="Planet 多轮对话上下文压缩摘要",
|
||||
objective=(
|
||||
"请将以下较早的多轮对话与既有摘要压缩为简明中文备忘(不超过 280 字),"
|
||||
"保留:1) 用户聚焦的图层/国家/新闻实体与口径边界;2) 已核验关键数据结论;"
|
||||
"3) 尚未完结的追问线索。严禁保留客套或编造数值。"
|
||||
),
|
||||
system_prompt="你是精准的对话上下文压缩器,只输出精炼中文要点摘要。",
|
||||
context={
|
||||
"existing_summary": summary or None,
|
||||
"archived_dialogue": transcript,
|
||||
},
|
||||
thinking=None,
|
||||
)
|
||||
resp = await asyncio.wait_for(effective_client.analyze(compact_req), timeout=12.0)
|
||||
clean_resp, _ = strip_thinking_text(str(getattr(resp, "content", "") or ""))
|
||||
next_summary = _truncate_text(clean_resp, MAX_SUMMARY_CHARS)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"LLM conversation compaction fell back to deterministic summary",
|
||||
event="ai_memory.compaction.fallback",
|
||||
context={"error": str(exc), "older_count": len(older)},
|
||||
)
|
||||
|
||||
if not next_summary:
|
||||
next_summary = build_deterministic_compaction_summary(summary, older)
|
||||
|
||||
return {
|
||||
"summary": next_summary,
|
||||
"recent_messages": recent,
|
||||
"compacted": True,
|
||||
"compacted_count": len(older),
|
||||
}
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel"]
|
||||
WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel", "news"]
|
||||
SpatialDomain = Literal["global", "cable", "satellite", "vessel"]
|
||||
ReportSubjectType = Literal[
|
||||
"global_posture",
|
||||
@@ -13,11 +13,12 @@ ReportSubjectType = Literal[
|
||||
"cable_posture",
|
||||
"satellite_posture",
|
||||
"vessel_posture",
|
||||
"news_brief",
|
||||
]
|
||||
|
||||
SPATIAL_POSTURE_DOMAINS: frozenset[str] = frozenset({"global", "cable", "satellite", "vessel"})
|
||||
SUPPORTED_WORKBENCH_DOMAINS: frozenset[str] = frozenset(
|
||||
{"global", "compute", "bgp", "cable", "satellite", "vessel"}
|
||||
{"global", "compute", "bgp", "cable", "satellite", "vessel", "news"}
|
||||
)
|
||||
|
||||
DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
|
||||
@@ -27,6 +28,7 @@ DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
|
||||
"cable": "cable_posture",
|
||||
"satellite": "satellite_posture",
|
||||
"vessel": "vessel_posture",
|
||||
"news": "news_brief",
|
||||
}
|
||||
|
||||
SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
|
||||
@@ -36,6 +38,7 @@ SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
|
||||
"cable_posture": "cable",
|
||||
"satellite_posture": "satellite",
|
||||
"vessel_posture": "vessel",
|
||||
"news_brief": "news",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -520,7 +520,7 @@ async def investigate_spatial_domain(
|
||||
timeout=35.0,
|
||||
)
|
||||
_raise_if_cancelled(cancel_event)
|
||||
raw_text = (llm_resp.answer or "").strip()
|
||||
raw_text = (llm_resp.content or "").strip()
|
||||
assert_no_thinking_leak(raw_text)
|
||||
parsed = extract_json_object(raw_text)
|
||||
if not isinstance(parsed, dict):
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
"""Adaptive SSE streaming turn orchestrator with thinking process, model attribution, and news context."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import json
|
||||
import os
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.situational_assessment import InvestigationSession
|
||||
from app.schemas.ai import ChatMessage, SituationalAnalysisRequest
|
||||
from app.services.ai.access_policy import AccessContext
|
||||
from app.services.ai.conversation_memory import (
|
||||
compact_conversation_history,
|
||||
sanitize_memory_notes,
|
||||
sanitize_pinned_summaries,
|
||||
)
|
||||
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
|
||||
from app.services.ai.tool_registry import (
|
||||
TimeBasis,
|
||||
query_global_situational_tool,
|
||||
query_recent_earth_news_tool,
|
||||
)
|
||||
from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn
|
||||
from app.services.ai_client import AIProviderClient
|
||||
|
||||
logger = get_logger(__name__, service="ai_stream")
|
||||
|
||||
_STREAM_QUOTA_WINDOW: dict[str, deque[datetime]] = defaultdict(deque)
|
||||
_GEOPOLITICAL_OR_NEWS_KEYWORDS = (
|
||||
"国际局势",
|
||||
"全球局势",
|
||||
"地缘",
|
||||
"新闻",
|
||||
"报道",
|
||||
"外交",
|
||||
"冲突",
|
||||
"制裁",
|
||||
"关税",
|
||||
"战争",
|
||||
"和平",
|
||||
"热点",
|
||||
"geopolit",
|
||||
"headline",
|
||||
"news",
|
||||
"international situation",
|
||||
"world situation",
|
||||
)
|
||||
|
||||
|
||||
def reset_stream_quota_ledger() -> None:
|
||||
"""Reset in-memory public stream rate limiter state (for deterministic tests)."""
|
||||
_STREAM_QUOTA_WINDOW.clear()
|
||||
|
||||
|
||||
def check_stream_quota(access: AccessContext) -> None:
|
||||
"""Enforce bounded hourly quota on adaptive streaming AI turns across all access tiers."""
|
||||
default_public_cap = int(os.getenv("PLANET_PUBLIC_AI_STREAM_HOURLY_QUOTA", "60"))
|
||||
limit = access.hourly_paid_quota if access.hourly_paid_quota > 0 else default_public_cap
|
||||
if limit <= 0:
|
||||
return
|
||||
|
||||
now = datetime.now(UTC)
|
||||
window_start = now - timedelta(hours=1)
|
||||
dq = _STREAM_QUOTA_WINDOW[access.actor_key]
|
||||
while dq and dq[0] < window_start:
|
||||
dq.popleft()
|
||||
if len(dq) >= limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=f"Hourly AI stream quota ({limit}) exceeded.",
|
||||
)
|
||||
dq.append(now)
|
||||
|
||||
|
||||
def build_streaming_thinking_config(ai_client: AIProviderClient) -> dict[str, Any] | None:
|
||||
"""Enable streamed reasoning tokens for MiniMax/Anthropic providers when streaming turns."""
|
||||
llm_cfg = getattr(ai_client, "llm_config", None) or {}
|
||||
provider = str(llm_cfg.get("provider") or "").strip().lower()
|
||||
provider_api = str(llm_cfg.get("provider_api") or "").strip().lower()
|
||||
model = str(llm_cfg.get("model") or "").strip().lower()
|
||||
|
||||
if "minimax-m3" in model:
|
||||
return {"type": "adaptive", "effort": "medium"}
|
||||
if provider == "minimax" or provider_api == "anthropic-messages" or "anthropic" in provider or "claude" in model:
|
||||
return {"type": "enabled", "budget_tokens": 2048}
|
||||
return None
|
||||
|
||||
|
||||
def _is_geopolitical_or_news_question(
|
||||
question: str,
|
||||
*,
|
||||
domain: str,
|
||||
news_context: dict[str, Any] | None,
|
||||
) -> bool:
|
||||
if domain == "news" or news_context:
|
||||
return True
|
||||
q = (question or "").strip().lower()
|
||||
return any(kw in q for kw in _GEOPOLITICAL_OR_NEWS_KEYWORDS)
|
||||
|
||||
|
||||
def _format_sse(event: str, payload: dict[str, Any]) -> str:
|
||||
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
|
||||
|
||||
|
||||
def _build_news_fallback_markdown(
|
||||
*,
|
||||
question: str,
|
||||
news_context: dict[str, Any] | None,
|
||||
recent_news: dict[str, Any],
|
||||
ai_configured: bool,
|
||||
fallback_reason: str | None = None,
|
||||
) -> str:
|
||||
lines: list[str] = []
|
||||
if news_context:
|
||||
title = str(news_context.get("title") or "新闻速递").strip()
|
||||
source = str(news_context.get("source") or "").strip()
|
||||
region = str(news_context.get("region") or news_context.get("region_key") or "").strip()
|
||||
published_at = str(news_context.get("published_at") or "").strip()
|
||||
summary = str(news_context.get("summary") or "").strip()
|
||||
lines.append(f"### 新闻焦点:{title}")
|
||||
meta_parts = [p for p in (source, region, published_at) if p]
|
||||
if meta_parts:
|
||||
lines.append(f"- **来源与时间**:{' · '.join(meta_parts)}")
|
||||
if summary:
|
||||
lines.append(f"- **报道摘要**:{summary}")
|
||||
else:
|
||||
lines.append("### 全球局势与新闻态势速览")
|
||||
if question:
|
||||
lines.append(f"- **当前问题**:{question}")
|
||||
|
||||
items = list(recent_news.get("items") or [])
|
||||
if items:
|
||||
lines.append("")
|
||||
lines.append("#### 近期关联动态")
|
||||
for item in items[:5]:
|
||||
item_title = str(item.get("title") or "").strip()
|
||||
item_src = str(item.get("source") or "").strip()
|
||||
item_reg = str(item.get("region") or "").strip()
|
||||
if item_title:
|
||||
meta = f"({item_src}{' · ' + item_reg if item_reg else ''})" if item_src else ""
|
||||
lines.append(f"- {item_title}{meta}")
|
||||
|
||||
if not ai_configured:
|
||||
lines.append("")
|
||||
lines.append("> 当前后台尚未接入可用 AI 大模型,以上为内置新闻与遥测结构化汇总。")
|
||||
elif fallback_reason:
|
||||
lines.append("")
|
||||
lines.append(f"> AI 流式生成暂时不可用({fallback_reason}),已自动回退为内置结构化汇总。")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def _build_news_analysis_request(
|
||||
*,
|
||||
question: str,
|
||||
news_context: dict[str, Any] | None,
|
||||
recent_news: dict[str, Any],
|
||||
global_snapshot: dict[str, Any],
|
||||
thinking_cfg: dict[str, Any] | None,
|
||||
conversation_messages: list[ChatMessage] | None = None,
|
||||
conversation_summary: str = "",
|
||||
memory_notes: list[str] | None = None,
|
||||
pinned_summaries: list[str] | None = None,
|
||||
) -> SituationalAnalysisRequest:
|
||||
context: dict[str, Any] = {
|
||||
"focused_news": news_context or None,
|
||||
"recent_news_headlines": (recent_news.get("items") or [])[:10],
|
||||
"global_infrastructure_summary": global_snapshot.get("domain_summaries") or [],
|
||||
}
|
||||
if conversation_summary:
|
||||
context["conversation_summary"] = conversation_summary
|
||||
if memory_notes:
|
||||
context["user_memory_notes"] = memory_notes
|
||||
if pinned_summaries:
|
||||
context["pinned_comparisons"] = pinned_summaries
|
||||
return SituationalAnalysisRequest(
|
||||
title="Planet 全球新闻与国际局势研判",
|
||||
objective=(
|
||||
f"用户提问:{question}\n\n"
|
||||
"请结合多轮对话延续性与记忆备忘,直接使用中文(若用户用英文提问则用英文)输出结构清晰的 Markdown 深度分析,包括:\n"
|
||||
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
|
||||
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
|
||||
"3. **后续重点观察信号与不确定边界**。\n"
|
||||
"请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。"
|
||||
),
|
||||
system_prompt=(
|
||||
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
|
||||
"如有前序对话与用户备忘录,请保持指代与口径延续。"
|
||||
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。"
|
||||
),
|
||||
context=context,
|
||||
constraints=[
|
||||
"Output clean user-facing Markdown directly (not JSON).",
|
||||
"Distinguish reported facts from analytical outlook.",
|
||||
],
|
||||
thinking=thinking_cfg,
|
||||
messages=conversation_messages or [],
|
||||
)
|
||||
|
||||
|
||||
def _build_telemetry_stream_request(
|
||||
*,
|
||||
domain: str,
|
||||
question: str,
|
||||
base_answer_md: str,
|
||||
evidence: dict[str, Any],
|
||||
view_spec: dict[str, Any] | None,
|
||||
recent_news: dict[str, Any] | None,
|
||||
thinking_cfg: dict[str, Any] | None,
|
||||
conversation_messages: list[ChatMessage] | None = None,
|
||||
conversation_summary: str = "",
|
||||
memory_notes: list[str] | None = None,
|
||||
pinned_summaries: list[str] | None = None,
|
||||
) -> SituationalAnalysisRequest:
|
||||
context: dict[str, Any] = {
|
||||
"domain": domain,
|
||||
"verified_baseline_summary": base_answer_md,
|
||||
"evidence": evidence,
|
||||
"view_headline": (view_spec or {}).get("headline"),
|
||||
}
|
||||
if recent_news and recent_news.get("items"):
|
||||
context["recent_news_headlines"] = (recent_news.get("items") or [])[:10]
|
||||
if conversation_summary:
|
||||
context["conversation_summary"] = conversation_summary
|
||||
if memory_notes:
|
||||
context["user_memory_notes"] = memory_notes
|
||||
if pinned_summaries:
|
||||
context["pinned_comparisons"] = pinned_summaries
|
||||
return SituationalAnalysisRequest(
|
||||
title=f"Planet 态势参谋分析({domain})",
|
||||
objective=(
|
||||
f"用户问题:{question}\n\n"
|
||||
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
|
||||
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。"
|
||||
),
|
||||
system_prompt=(
|
||||
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
|
||||
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。"
|
||||
),
|
||||
context=context,
|
||||
constraints=[
|
||||
"Output clean Markdown directly (not JSON).",
|
||||
"Do not invent telemetry counts or unverified outages outside context.",
|
||||
],
|
||||
thinking=thinking_cfg,
|
||||
messages=conversation_messages or [],
|
||||
)
|
||||
|
||||
|
||||
async def stream_session_turn(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
request: Request | None,
|
||||
session: InvestigationSession | None,
|
||||
question: str,
|
||||
context_override: dict[str, Any] | None,
|
||||
news_context: dict[str, Any] | None,
|
||||
access: AccessContext,
|
||||
ai_client: AIProviderClient | None,
|
||||
client_run_id: str | None = None,
|
||||
issued_session_token: str | None = None,
|
||||
history: list[dict[str, Any]] | None = None,
|
||||
conversation_summary: str | None = None,
|
||||
memory_notes: list[str] | None = None,
|
||||
pinned_summaries: list[str] | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline."""
|
||||
check_stream_quota(access)
|
||||
|
||||
session_id_val = str(session.id) if session is not None else "stateless"
|
||||
run_id = client_run_id or f"run-{uuid.uuid4().hex[:12]}"
|
||||
|
||||
merged_ctx: dict[str, Any] = {}
|
||||
if session is not None and isinstance(session.context_state, dict):
|
||||
merged_ctx.update(session.context_state)
|
||||
if context_override:
|
||||
for k, v in context_override.items():
|
||||
if v is not None:
|
||||
merged_ctx[k] = v
|
||||
|
||||
raw_history = history if history else merged_ctx.get("recent_messages")
|
||||
existing_summary = str(
|
||||
conversation_summary
|
||||
if conversation_summary is not None
|
||||
else merged_ctx.get("conversation_summary") or ""
|
||||
)
|
||||
clean_memory_notes = sanitize_memory_notes(memory_notes)
|
||||
clean_pinned_summaries = sanitize_pinned_summaries(
|
||||
pinned_summaries
|
||||
if pinned_summaries is not None
|
||||
else [
|
||||
f"{p.get('pin_id', 'PIN')}: {p.get('title', '')}"
|
||||
for p in ((getattr(session, "pinned_items", None) or []) if session is not None else [])
|
||||
if isinstance(p, dict) and p.get("title")
|
||||
]
|
||||
)
|
||||
|
||||
routed = classify_turn_intent(question, merged_ctx)
|
||||
explicit_domain = str((context_override or {}).get("domain") or "").strip().lower()
|
||||
domain = "news" if news_context or explicit_domain == "news" else str(routed.get("domain") or "global")
|
||||
is_pure_view = bool(routed.get("is_pure_projection") or routed.get("auto_play_presentation"))
|
||||
geo_or_news_query = _is_geopolitical_or_news_question(
|
||||
question,
|
||||
domain=domain,
|
||||
news_context=news_context,
|
||||
)
|
||||
|
||||
time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective"
|
||||
cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at")
|
||||
codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"])
|
||||
visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {})
|
||||
|
||||
ai_ready = False
|
||||
provider_name = ""
|
||||
model_name = ""
|
||||
if ai_client is not None:
|
||||
ai_ready, provider_name, model_name = await ai_client.is_ready()
|
||||
|
||||
compaction = await compact_conversation_history(
|
||||
raw_history,
|
||||
existing_summary,
|
||||
ai_client=ai_client,
|
||||
ai_ready=ai_ready,
|
||||
)
|
||||
compacted_summary = str(compaction.get("summary") or "")
|
||||
recent_history = list(compaction.get("recent_messages") or [])
|
||||
compacted_flag = bool(compaction.get("compacted"))
|
||||
memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries)
|
||||
|
||||
view_spec: dict[str, Any] | None = None
|
||||
scene_spec: dict[str, Any] | None = None
|
||||
evidence: dict[str, Any] = {}
|
||||
subject_key = "global"
|
||||
revision = 1
|
||||
base_answer_md = ""
|
||||
context_state: dict[str, Any] = {**merged_ctx, "domain": domain}
|
||||
recent_news: dict[str, Any] = {"items": [], "evidence": {}}
|
||||
|
||||
if news_context or domain == "news":
|
||||
news_region = str((news_context or {}).get("region_key") or "").strip() or None
|
||||
recent_news = await query_recent_earth_news_tool(db, region=news_region, limit=10)
|
||||
global_snap = await query_global_situational_tool(
|
||||
db,
|
||||
selected_codes=codes,
|
||||
visible_layers=visible_layers,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
evidence = {**(recent_news.get("evidence") or {}), **(global_snap.get("evidence") or {})}
|
||||
if news_context and news_context.get("url"):
|
||||
evidence["ev-news-focus"] = {
|
||||
"id": "ev-news-focus",
|
||||
"title": str(news_context.get("title") or "聚焦新闻"),
|
||||
"publisher": str(news_context.get("source") or "Planet News"),
|
||||
"url": str(news_context.get("url") or ""),
|
||||
"published_at": str(news_context.get("published_at") or ""),
|
||||
"locator": str(news_context.get("region") or news_context.get("region_key") or "news"),
|
||||
}
|
||||
subject_key = f"news:{(news_context or {}).get('id') or news_region or 'global'}"
|
||||
base_answer_md = _build_news_fallback_markdown(
|
||||
question=question,
|
||||
news_context=news_context,
|
||||
recent_news=recent_news,
|
||||
ai_configured=ai_ready,
|
||||
)
|
||||
else:
|
||||
base_turn = await execute_session_turn(
|
||||
db,
|
||||
session=session,
|
||||
question=question,
|
||||
context_override=context_override,
|
||||
prefer_llm=False,
|
||||
access=access,
|
||||
ai_client=None,
|
||||
client_run_id=None,
|
||||
)
|
||||
view_spec = base_turn.get("view_spec")
|
||||
scene_spec = base_turn.get("scene_spec")
|
||||
evidence = base_turn.get("evidence") or {}
|
||||
subject_key = str(base_turn.get("subject_key") or domain)
|
||||
revision = int(base_turn.get("revision") or 1)
|
||||
base_answer_md = str((base_turn.get("reply") or {}).get("answer_markdown") or "")
|
||||
if isinstance(base_turn.get("context_state"), dict):
|
||||
context_state = base_turn["context_state"]
|
||||
if domain == "global" and (geo_or_news_query or ai_ready):
|
||||
recent_news = await query_recent_earth_news_tool(db, limit=10)
|
||||
evidence = {**evidence, **(recent_news.get("evidence") or {})}
|
||||
if geo_or_news_query and not is_pure_view:
|
||||
# Conversational international/news questions should focus on the narrative, not a static bar chart.
|
||||
view_spec = None
|
||||
scene_spec = None
|
||||
if not ai_ready:
|
||||
base_answer_md = _build_news_fallback_markdown(
|
||||
question=question,
|
||||
news_context=None,
|
||||
recent_news=recent_news,
|
||||
ai_configured=False,
|
||||
)
|
||||
|
||||
meta_payload: dict[str, Any] = {
|
||||
"session_id": session_id_val,
|
||||
"run_id": run_id,
|
||||
"domain": domain,
|
||||
"subject_key": subject_key,
|
||||
"revision": revision,
|
||||
"ai_enabled": ai_ready and not is_pure_view,
|
||||
"provider": provider_name if (ai_ready and not is_pure_view) else None,
|
||||
"model": model_name if (ai_ready and not is_pure_view) else None,
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"view_spec": view_spec,
|
||||
"scene_spec": scene_spec,
|
||||
"evidence": evidence,
|
||||
"context_state": context_state,
|
||||
}
|
||||
if issued_session_token:
|
||||
meta_payload["session_token"] = issued_session_token
|
||||
yield _format_sse("meta", meta_payload)
|
||||
|
||||
def _persist_session_memory(answer_text: str) -> None:
|
||||
if session is None or not isinstance(session.context_state, dict):
|
||||
return
|
||||
updated_recent = [*recent_history, {"role": "user", "content": question}]
|
||||
if answer_text:
|
||||
updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
|
||||
session.context_state = {
|
||||
**session.context_state,
|
||||
"conversation_summary": compacted_summary,
|
||||
"recent_messages": updated_recent[-8:],
|
||||
}
|
||||
|
||||
if not ai_ready or is_pure_view or ai_client is None:
|
||||
_persist_session_memory(base_answer_md)
|
||||
if base_answer_md:
|
||||
yield _format_sse("text", {"delta": base_answer_md})
|
||||
yield _format_sse(
|
||||
"done",
|
||||
{
|
||||
"status": "completed",
|
||||
"generation_mode": "deterministic_baseline",
|
||||
"zero_token": True,
|
||||
"provider": None,
|
||||
"model": None,
|
||||
"usage": {},
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"answer_markdown": base_answer_md,
|
||||
"reasoning_markdown": "",
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
conversation_messages = [
|
||||
ChatMessage(role=m["role"], content=m["content"]) for m in recent_history
|
||||
]
|
||||
thinking_cfg = build_streaming_thinking_config(ai_client)
|
||||
effective_client = ai_client
|
||||
current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0)
|
||||
if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200:
|
||||
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
|
||||
analysis_req = (
|
||||
_build_news_analysis_request(
|
||||
question=question,
|
||||
news_context=news_context,
|
||||
recent_news=recent_news,
|
||||
global_snapshot=await query_global_situational_tool(
|
||||
db,
|
||||
selected_codes=codes,
|
||||
visible_layers=visible_layers,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
),
|
||||
thinking_cfg=thinking_cfg,
|
||||
conversation_messages=conversation_messages,
|
||||
conversation_summary=compacted_summary,
|
||||
memory_notes=clean_memory_notes,
|
||||
pinned_summaries=clean_pinned_summaries,
|
||||
)
|
||||
if (news_context or domain == "news")
|
||||
else _build_telemetry_stream_request(
|
||||
domain=domain,
|
||||
question=question,
|
||||
base_answer_md=base_answer_md,
|
||||
evidence=evidence,
|
||||
view_spec=view_spec,
|
||||
recent_news=recent_news if domain == "global" else None,
|
||||
thinking_cfg=thinking_cfg,
|
||||
conversation_messages=conversation_messages,
|
||||
conversation_summary=compacted_summary,
|
||||
memory_notes=clean_memory_notes,
|
||||
pinned_summaries=clean_pinned_summaries,
|
||||
)
|
||||
)
|
||||
|
||||
text_chunks: list[str] = []
|
||||
reasoning_chunks: list[str] = []
|
||||
resolved_provider = provider_name
|
||||
resolved_model = model_name
|
||||
final_usage: dict[str, Any] = {}
|
||||
|
||||
try:
|
||||
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
|
||||
if request is not None and await request.is_disconnected():
|
||||
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":
|
||||
delta = ev.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
reasoning_chunks.append(delta)
|
||||
yield _format_sse("reasoning", {"delta": delta})
|
||||
elif ev_type == "text":
|
||||
delta = ev.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
text_chunks.append(delta)
|
||||
yield _format_sse("text", {"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"]
|
||||
if isinstance(ev.get("usage"), dict):
|
||||
final_usage = ev["usage"]
|
||||
elif ev_type == "error":
|
||||
raise RuntimeError(str(ev.get("detail") or "AI stream error"))
|
||||
|
||||
combined_text = "".join(text_chunks).strip()
|
||||
if not combined_text:
|
||||
raise RuntimeError("AI provider stream returned empty response")
|
||||
|
||||
clean_text, inline_thoughts = strip_thinking_text(combined_text)
|
||||
combined_reasoning = "".join(reasoning_chunks).strip()
|
||||
if inline_thoughts:
|
||||
extra_thought = "\n\n".join(inline_thoughts)
|
||||
combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
|
||||
|
||||
final_answer_md = clean_text or combined_text
|
||||
_persist_session_memory(final_answer_md)
|
||||
if hasattr(db, "commit"):
|
||||
try:
|
||||
await db.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
yield _format_sse(
|
||||
"done",
|
||||
{
|
||||
"status": "completed",
|
||||
"generation_mode": "llm_verified",
|
||||
"zero_token": False,
|
||||
"provider": resolved_provider,
|
||||
"model": resolved_model,
|
||||
"usage": final_usage,
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"answer_markdown": final_answer_md,
|
||||
"reasoning_markdown": combined_reasoning,
|
||||
},
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"AI stream turn failed",
|
||||
event="ai_stream.llm.fallback",
|
||||
context={"domain": domain, "emitted_text": bool(text_chunks), "error": str(exc)},
|
||||
)
|
||||
if text_chunks:
|
||||
yield _format_sse("error", {"detail": str(exc), "partial": True})
|
||||
return
|
||||
|
||||
fallback_md = (
|
||||
_build_news_fallback_markdown(
|
||||
question=question,
|
||||
news_context=news_context,
|
||||
recent_news=recent_news,
|
||||
ai_configured=True,
|
||||
fallback_reason=str(exc),
|
||||
)
|
||||
if (news_context or domain == "news" or geo_or_news_query)
|
||||
else f"{base_answer_md}\n\n> AI 流式研判暂时回退:{exc}".strip()
|
||||
)
|
||||
if fallback_md:
|
||||
yield _format_sse("text", {"delta": fallback_md})
|
||||
yield _format_sse(
|
||||
"done",
|
||||
{
|
||||
"status": "completed",
|
||||
"generation_mode": "deterministic_fallback",
|
||||
"zero_token": True,
|
||||
"provider": None,
|
||||
"model": None,
|
||||
"usage": {},
|
||||
"answer_markdown": fallback_md,
|
||||
"reasoning_markdown": "".join(reasoning_chunks).strip(),
|
||||
"fallback_reason": str(exc),
|
||||
},
|
||||
)
|
||||
@@ -11,11 +11,13 @@ from urllib.parse import urljoin, urlparse
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import desc, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.schemas.compute_configuration import ComputeConfiguration
|
||||
from app.services.ai_tools.schemas import FetchedEvidence
|
||||
from app.services.compute_configuration import read_configuration
|
||||
@@ -610,7 +612,20 @@ async def query_satellite_posture_tool(
|
||||
|
||||
safe_limit = max(50, min(int(limit or 1200), 3000))
|
||||
features: list[dict[str, Any]] = []
|
||||
catalog_total: int | None = None
|
||||
limitations: list[str] = []
|
||||
try:
|
||||
count_stmt = select(func.count(CollectedData.id)).where(
|
||||
CollectedData.source == "celestrak_tle",
|
||||
CollectedData.is_current.is_(True),
|
||||
CollectedData.name != "Unknown",
|
||||
)
|
||||
counted = (await db.execute(count_stmt)).scalar_one_or_none()
|
||||
if isinstance(counted, int) and counted > 0:
|
||||
catalog_total = counted
|
||||
except Exception:
|
||||
catalog_total = None
|
||||
|
||||
try:
|
||||
sat_fc = await _build_satellites_geojson(limit=safe_limit, db=db)
|
||||
features = list(sat_fc.get("features") or [])
|
||||
@@ -622,6 +637,8 @@ async def query_satellite_posture_tool(
|
||||
)
|
||||
limitations.append("内置卫星 TLE 查询受限")
|
||||
|
||||
effective_total = catalog_total if catalog_total is not None and catalog_total >= len(features) else len(features)
|
||||
|
||||
by_constellation: dict[str, int] = {}
|
||||
by_orbit_regime: dict[str, int] = {}
|
||||
sample_satellites: list[dict[str, Any]] = []
|
||||
@@ -657,15 +674,18 @@ async def query_satellite_posture_tool(
|
||||
sorted_constellations = dict(
|
||||
sorted(by_constellation.items(), key=lambda kv: kv[1], reverse=True)[:10]
|
||||
)
|
||||
if len(features) >= safe_limit:
|
||||
limitations.append(f"本次卫星样本按性能上限截取前 {safe_limit} 颗轨道目标,不代表全库总编目。")
|
||||
if effective_total > len(features):
|
||||
limitations.append(
|
||||
f"在轨卫星全库共 {effective_total} 颗;星座/轨道分布基于最新 {len(features)} 颗样本统计。"
|
||||
)
|
||||
if time_basis == "as_known_then":
|
||||
limitations.append("在轨星历基于最新同步批次(celestrak_tle),未按历史截点回卷旧 TLE。")
|
||||
|
||||
return {
|
||||
"domain": "satellite",
|
||||
"available": len(features) > 0,
|
||||
"satellites_total": len(features),
|
||||
"available": effective_total > 0,
|
||||
"satellites_total": effective_total,
|
||||
"sampled_count": len(features),
|
||||
"sample_limit": safe_limit,
|
||||
"by_constellation": sorted_constellations,
|
||||
"by_orbit_regime": by_orbit_regime,
|
||||
@@ -678,6 +698,74 @@ async def query_satellite_posture_tool(
|
||||
}
|
||||
|
||||
|
||||
async def query_recent_earth_news_tool(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
region: str | None = None,
|
||||
limit: int = 12,
|
||||
) -> dict[str, Any]:
|
||||
"""Read-only built-in snapshot of recent global/regional Earth news items for geopolitical & news copilot turns."""
|
||||
base_ev_id = "ev-news-1"
|
||||
evidence = {
|
||||
base_ev_id: {
|
||||
"id": base_ev_id,
|
||||
"title": "Planet 全球态势新闻聚合快照(earth_news_items)",
|
||||
"publisher": "Planet Global News Monitor",
|
||||
"url": "/api/v1/earth/news",
|
||||
"published_at": datetime.now(UTC).date().isoformat(),
|
||||
"locator": f"builtin:earth_news:{region or 'global'}:limit={limit}",
|
||||
}
|
||||
}
|
||||
if not hasattr(db, "execute"):
|
||||
return {"domain": "news", "available": False, "items": [], "evidence": evidence}
|
||||
|
||||
safe_limit = max(1, min(int(limit or 12), 25))
|
||||
items: list[dict[str, Any]] = []
|
||||
try:
|
||||
stmt = (
|
||||
select(EarthNewsItem)
|
||||
.where(EarthNewsItem.resolved_at.is_(None))
|
||||
.order_by(desc(EarthNewsItem.published_at), desc(EarthNewsItem.last_seen_at))
|
||||
.limit(safe_limit)
|
||||
)
|
||||
if region:
|
||||
stmt = stmt.where(EarthNewsItem.region == region)
|
||||
rows = (await db.execute(stmt)).scalars().all()
|
||||
for row in rows:
|
||||
loc_meta = dict(row.location_meta or {})
|
||||
news_meta = loc_meta.get("news_meta") if isinstance(loc_meta.get("news_meta"), dict) else {}
|
||||
localizations = row.localizations if isinstance(row.localizations, dict) else {}
|
||||
zh_loc = localizations.get("zh-CN") if isinstance(localizations.get("zh-CN"), dict) else {}
|
||||
items.append(
|
||||
{
|
||||
"id": row.id,
|
||||
"title": zh_loc.get("title") or row.title,
|
||||
"summary": (zh_loc.get("summary") or row.summary or "")[:400],
|
||||
"source": row.source or row.feed_name,
|
||||
"region": row.region,
|
||||
"location_label": row.location_label,
|
||||
"category": news_meta.get("category") or "other",
|
||||
"breaking_level": news_meta.get("breaking_level") or "none",
|
||||
"published_at": row.published_at.isoformat() if row.published_at else None,
|
||||
"url": row.url,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Recent earth news query degraded",
|
||||
event="ai_tool.earth_news.degraded",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
return {
|
||||
"domain": "news",
|
||||
"available": len(items) > 0,
|
||||
"count": len(items),
|
||||
"items": items,
|
||||
"evidence": evidence,
|
||||
}
|
||||
|
||||
|
||||
async def query_vessel_posture_tool(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
import json
|
||||
from time import perf_counter
|
||||
|
||||
@@ -45,6 +46,82 @@ class AIProviderClient:
|
||||
)
|
||||
self.llm_config = llm_config or {}
|
||||
|
||||
async def is_ready(self) -> tuple[bool, str, str]:
|
||||
"""Return `(configured_and_enabled, provider, model)` without calling LLM inference."""
|
||||
if not self.service_url:
|
||||
return False, "unconfigured", ""
|
||||
if isinstance(self.llm_config, dict) and self.llm_config:
|
||||
provider = str(self.llm_config.get("provider") or "").strip().lower()
|
||||
provider_api = str(self.llm_config.get("provider_api") or "").strip().lower()
|
||||
base_url = str(self.llm_config.get("base_url") or "").strip()
|
||||
model = str(self.llm_config.get("model") or "").strip()
|
||||
api_key = str(self.llm_config.get("api_key") or "").strip()
|
||||
if not provider or provider == "disabled":
|
||||
return False, provider or "disabled", model
|
||||
needs_key = provider != "ollama" and provider_api != "ollama-generate"
|
||||
configured = bool(base_url and model and (api_key or not needs_key))
|
||||
return configured, provider, model
|
||||
try:
|
||||
status_resp = await self.get_status()
|
||||
return (
|
||||
bool(status_resp.enabled and status_resp.configured),
|
||||
str(status_resp.provider or ""),
|
||||
str(status_resp.model or ""),
|
||||
)
|
||||
except Exception:
|
||||
return False, "unavailable", ""
|
||||
|
||||
async def stream_analyze(
|
||||
self,
|
||||
payload: SituationalAnalysisRequest,
|
||||
request_id: str | None = None,
|
||||
) -> AsyncIterator[dict]:
|
||||
"""Stream structured SSE events (`start`, `reasoning`, `text`, `done`, `error`) from aiprovider."""
|
||||
if not self.service_url:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="AI provider service URL is not configured.",
|
||||
)
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{self.service_url}/v1/analyze/stream",
|
||||
headers=self._headers(request_id),
|
||||
json=payload.model_dump(),
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
detail = (await response.aread()).decode("utf-8", errors="replace")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"AI provider service request failed: {detail or response.status_code}",
|
||||
)
|
||||
event_name = ""
|
||||
data_lines: list[str] = []
|
||||
async for raw_line in response.aiter_lines():
|
||||
line = raw_line.rstrip("\r")
|
||||
if line == "":
|
||||
if data_lines:
|
||||
raw_json = "\n".join(data_lines)
|
||||
event_name_cur = event_name
|
||||
event_name = ""
|
||||
data_lines = []
|
||||
parsed = json.loads(raw_json)
|
||||
if isinstance(parsed, dict):
|
||||
parsed.setdefault("event", event_name_cur or "message")
|
||||
yield parsed
|
||||
continue
|
||||
if line.startswith(":"):
|
||||
continue
|
||||
if line.startswith("event:"):
|
||||
event_name = line[6:].strip()
|
||||
elif line.startswith("data:"):
|
||||
data_lines.append(line[5:].lstrip())
|
||||
if data_lines:
|
||||
parsed = json.loads("\n".join(data_lines))
|
||||
if isinstance(parsed, dict):
|
||||
parsed.setdefault("event", event_name or "message")
|
||||
yield parsed
|
||||
|
||||
def _headers(self, request_id: str | None = None) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.service_token:
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
"""API key lifecycle, scope evaluation, hashing, and rate-limited validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import secrets
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import REDIS_OP_TIMEOUT_SECONDS, _AsyncRedisClient
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.models.api_key import ApiKey
|
||||
|
||||
logger = get_logger(__name__, service="api_keys")
|
||||
|
||||
API_KEY_PREFIX = "plt_live_"
|
||||
EARTH_ALL_READ_SCOPE = "earth:all_read"
|
||||
|
||||
EARTH_READ_SCOPES: frozenset[str] = frozenset(
|
||||
{
|
||||
"visualization:read",
|
||||
"layers:read",
|
||||
"vessels:read",
|
||||
"news:read",
|
||||
"data_products:read",
|
||||
"situational:read",
|
||||
"earth:read",
|
||||
"interactables:read",
|
||||
"tv:read",
|
||||
"ws:connect",
|
||||
}
|
||||
)
|
||||
|
||||
VALID_API_KEY_SCOPES: frozenset[str] = frozenset({EARTH_ALL_READ_SCOPE, *EARTH_READ_SCOPES})
|
||||
|
||||
_LAST_USED_TOUCH_CACHE: dict[int, float] = {}
|
||||
_LOCAL_KEY_RATE_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
|
||||
_LAST_USED_MIN_INTERVAL_SECONDS = 60.0
|
||||
|
||||
|
||||
def reset_api_key_runtime_caches() -> None:
|
||||
"""Clear in-process caches (intended for deterministic tests)."""
|
||||
_LAST_USED_TOUCH_CACHE.clear()
|
||||
_LOCAL_KEY_RATE_WINDOWS.clear()
|
||||
|
||||
|
||||
def hash_api_key(raw_key: str) -> str:
|
||||
"""Compute SHA-256 hex digest of a raw API key."""
|
||||
return hashlib.sha256(raw_key.strip().encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def mask_api_key_prefix(raw_key: str) -> str:
|
||||
"""Return a short non-sensitive prefix for UI display and logging."""
|
||||
cleaned = raw_key.strip()
|
||||
return f"{cleaned[:16]}..." if len(cleaned) > 16 else f"{cleaned[:8]}..."
|
||||
|
||||
|
||||
def normalize_api_key_scopes(scopes: list[str] | None) -> list[str]:
|
||||
"""Validate and deduplicate requested API key scopes."""
|
||||
if not scopes:
|
||||
return [EARTH_ALL_READ_SCOPE]
|
||||
normalized: list[str] = []
|
||||
seen: set[str] = set()
|
||||
invalid: list[str] = []
|
||||
for raw in scopes:
|
||||
scope = str(raw or "").strip()
|
||||
if not scope:
|
||||
continue
|
||||
if scope not in VALID_API_KEY_SCOPES:
|
||||
invalid.append(scope)
|
||||
continue
|
||||
if scope not in seen:
|
||||
seen.add(scope)
|
||||
normalized.append(scope)
|
||||
if invalid:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Unsupported API key scope(s): {', '.join(invalid)}",
|
||||
)
|
||||
if not normalized:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="At least one valid scope is required",
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def api_key_allows_scope(key_scopes: list[str] | None, required_scope: str) -> bool:
|
||||
"""Return True if the key scopes authorize `required_scope`."""
|
||||
scopes = {str(item).strip() for item in (key_scopes or []) if item}
|
||||
if required_scope in scopes:
|
||||
return True
|
||||
if EARTH_ALL_READ_SCOPE in scopes and required_scope in EARTH_READ_SCOPES:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_utc(dt: datetime | None) -> datetime | None:
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=UTC)
|
||||
return dt.astimezone(UTC)
|
||||
|
||||
|
||||
def serialize_api_key(record: ApiKey) -> dict[str, Any]:
|
||||
"""Serialize ApiKey metadata safely without exposing key_hash or raw secret."""
|
||||
now = datetime.now(UTC)
|
||||
expires_at = _ensure_utc(record.expires_at)
|
||||
is_expired = bool(expires_at is not None and expires_at <= now)
|
||||
status_label = "revoked" if not record.is_active else ("expired" if is_expired else "active")
|
||||
return {
|
||||
"id": record.id,
|
||||
"name": record.name,
|
||||
"key_prefix": record.key_prefix,
|
||||
"scopes": list(record.scopes or []),
|
||||
"rate_limit_per_minute": record.rate_limit_per_minute,
|
||||
"expires_at": to_iso8601_utc(expires_at),
|
||||
"is_active": bool(record.is_active),
|
||||
"is_expired": is_expired,
|
||||
"status": status_label,
|
||||
"created_by_user_id": record.created_by_user_id,
|
||||
"last_used_at": to_iso8601_utc(_ensure_utc(record.last_used_at)),
|
||||
"revoked_at": to_iso8601_utc(_ensure_utc(record.revoked_at)),
|
||||
"created_at": to_iso8601_utc(_ensure_utc(record.created_at)),
|
||||
}
|
||||
|
||||
|
||||
async def _enforce_api_key_rate_limit(key_id: int, limit_per_minute: int | None) -> None:
|
||||
if limit_per_minute is None or int(limit_per_minute) <= 0:
|
||||
return
|
||||
limit = int(limit_per_minute)
|
||||
window = 60
|
||||
bucket = f"rate:api_key:{key_id}"
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
current_count = await asyncio.wait_for(
|
||||
client.incr(bucket),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
if int(current_count) == 1:
|
||||
await asyncio.wait_for(client.expire(bucket, window), timeout=REDIS_OP_TIMEOUT_SECONDS)
|
||||
if int(current_count) > limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="API key rate limit exceeded",
|
||||
)
|
||||
return
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
now = time.monotonic()
|
||||
dq = _LOCAL_KEY_RATE_WINDOWS[bucket]
|
||||
cutoff = now - float(window)
|
||||
while dq and dq[0] <= cutoff:
|
||||
dq.popleft()
|
||||
if len(dq) >= limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="API key rate limit exceeded",
|
||||
)
|
||||
dq.append(now)
|
||||
|
||||
|
||||
async def create_api_key(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
name: str,
|
||||
scopes: list[str] | None,
|
||||
rate_limit_per_minute: int | None,
|
||||
expires_in_days: int | None,
|
||||
created_by_user_id: int | None,
|
||||
) -> tuple[ApiKey, str]:
|
||||
"""Create and persist a new API key, returning `(record, raw_plaintext_once)`."""
|
||||
cleaned_name = str(name or "").strip()
|
||||
if not cleaned_name:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="API key name is required",
|
||||
)
|
||||
normalized_scopes = normalize_api_key_scopes(scopes)
|
||||
normalized_limit = (
|
||||
int(rate_limit_per_minute)
|
||||
if rate_limit_per_minute is not None and int(rate_limit_per_minute) > 0
|
||||
else None
|
||||
)
|
||||
expires_at: datetime | None = None
|
||||
if expires_in_days is not None and int(expires_in_days) > 0:
|
||||
expires_at = datetime.now(UTC) + timedelta(days=int(expires_in_days))
|
||||
|
||||
raw_key = f"{API_KEY_PREFIX}{secrets.token_urlsafe(32)}"
|
||||
record = ApiKey(
|
||||
name=cleaned_name[:120],
|
||||
key_prefix=mask_api_key_prefix(raw_key),
|
||||
key_hash=hash_api_key(raw_key),
|
||||
scopes=normalized_scopes,
|
||||
rate_limit_per_minute=normalized_limit,
|
||||
expires_at=expires_at,
|
||||
is_active=True,
|
||||
created_by_user_id=created_by_user_id,
|
||||
)
|
||||
db.add(record)
|
||||
await db.commit()
|
||||
await db.refresh(record)
|
||||
logger.info_event(
|
||||
"Created API key",
|
||||
event="api_key.created",
|
||||
context={
|
||||
"key_id": record.id,
|
||||
"key_prefix": record.key_prefix,
|
||||
"scopes": normalized_scopes,
|
||||
"has_expiry": expires_at is not None,
|
||||
"rate_limit_per_minute": normalized_limit,
|
||||
"created_by_user_id": created_by_user_id,
|
||||
},
|
||||
)
|
||||
return record, raw_key
|
||||
|
||||
|
||||
async def list_api_keys(db: AsyncSession) -> list[ApiKey]:
|
||||
result = await db.execute(select(ApiKey).order_by(ApiKey.created_at.desc(), ApiKey.id.desc()))
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def revoke_api_key(db: AsyncSession, key_id: int) -> ApiKey:
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
|
||||
if record.is_active:
|
||||
record.is_active = False
|
||||
record.revoked_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.refresh(record)
|
||||
logger.info_event(
|
||||
"Revoked API key",
|
||||
event="api_key.revoked",
|
||||
context={"key_id": record.id, "key_prefix": record.key_prefix},
|
||||
)
|
||||
return record
|
||||
|
||||
|
||||
async def delete_api_key(db: AsyncSession, key_id: int) -> None:
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
|
||||
prefix = record.key_prefix
|
||||
await db.delete(record)
|
||||
await db.commit()
|
||||
logger.info_event(
|
||||
"Deleted API key",
|
||||
event="api_key.deleted",
|
||||
context={"key_id": key_id, "key_prefix": prefix},
|
||||
)
|
||||
|
||||
|
||||
async def authenticate_api_key(
|
||||
db: AsyncSession,
|
||||
raw_key: str,
|
||||
required_scope: str,
|
||||
) -> ApiKey:
|
||||
"""Validate an incoming raw API key for active status, expiration, scope, and rate limit."""
|
||||
cleaned = str(raw_key or "").strip()
|
||||
if not cleaned:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid API key",
|
||||
)
|
||||
|
||||
digest = hash_api_key(cleaned)
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.key_hash == digest))
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None or not record.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or revoked API key",
|
||||
)
|
||||
|
||||
expires_at = _ensure_utc(record.expires_at)
|
||||
if expires_at is not None and expires_at <= datetime.now(UTC):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="API key has expired",
|
||||
)
|
||||
|
||||
if not api_key_allows_scope(list(record.scopes or []), required_scope):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"API key lacks required scope: {required_scope}",
|
||||
)
|
||||
|
||||
await _enforce_api_key_rate_limit(int(record.id), record.rate_limit_per_minute)
|
||||
|
||||
now_mono = time.monotonic()
|
||||
last_touched = _LAST_USED_TOUCH_CACHE.get(int(record.id), 0.0)
|
||||
if now_mono - last_touched >= _LAST_USED_MIN_INTERVAL_SECONDS:
|
||||
_LAST_USED_TOUCH_CACHE[int(record.id)] = now_mono
|
||||
try:
|
||||
record.last_used_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
|
||||
return record
|
||||
@@ -276,6 +276,66 @@ def _organization_label(organization: dict[str, Any], fallback: str) -> str:
|
||||
return fallback
|
||||
|
||||
|
||||
_COMMERCIAL_HYPERSCALER_TOKENS = frozenset(
|
||||
{
|
||||
"amazon",
|
||||
"aws",
|
||||
"microsoft",
|
||||
"azure",
|
||||
"google",
|
||||
"alphabet",
|
||||
"meta",
|
||||
"facebook",
|
||||
"openai",
|
||||
"xai",
|
||||
"oracle",
|
||||
"alibaba",
|
||||
"tencent",
|
||||
"bytedance",
|
||||
"nvidia",
|
||||
"apple",
|
||||
"coreweave",
|
||||
"lambda",
|
||||
}
|
||||
)
|
||||
_ROR_SIMILARITY_STOPWORDS = frozenset({"the", "of", "for", "and", "inc", "ltd", "corp", "llc", "co"})
|
||||
|
||||
|
||||
def _ror_is_plausible_facility_match(
|
||||
ror_query: str,
|
||||
organization: dict[str, Any],
|
||||
display_name: str,
|
||||
) -> bool:
|
||||
query_norm = normalize_text(ror_query)
|
||||
if not query_norm:
|
||||
return False
|
||||
query_tokens = {
|
||||
tok
|
||||
for tok in query_norm.split()
|
||||
if len(tok) >= 3 and tok not in _ROR_SIMILARITY_STOPWORDS
|
||||
}
|
||||
org_types = {str(t).strip().lower() for t in (organization.get("types") or []) if t}
|
||||
is_commercial = "company" in org_types or any(
|
||||
tok in query_tokens for tok in _COMMERCIAL_HYPERSCALER_TOKENS
|
||||
)
|
||||
if is_commercial:
|
||||
return False
|
||||
|
||||
candidate_labels = [display_name]
|
||||
for entry in organization.get("names") or []:
|
||||
if isinstance(entry, dict) and entry.get("value"):
|
||||
candidate_labels.append(str(entry["value"]))
|
||||
combined_norm = normalize_text(" ".join(candidate_labels))
|
||||
if not combined_norm:
|
||||
return False
|
||||
if query_norm in combined_norm or combined_norm in query_norm:
|
||||
return True
|
||||
if not query_tokens:
|
||||
return False
|
||||
label_tokens = set(combined_norm.split())
|
||||
return bool(query_tokens & label_tokens)
|
||||
|
||||
|
||||
class ROROrganizationResolver:
|
||||
"""Resolve source-provided organization/site text through the open ROR API."""
|
||||
|
||||
@@ -308,6 +368,9 @@ class ROROrganizationResolver:
|
||||
continue
|
||||
if not isinstance(organization, dict):
|
||||
continue
|
||||
display_name = _organization_label(organization, ror_query)
|
||||
if not _ror_is_plausible_facility_match(ror_query, organization, display_name):
|
||||
continue
|
||||
locations = organization.get("locations")
|
||||
if not isinstance(locations, list) or not locations:
|
||||
continue
|
||||
@@ -328,7 +391,6 @@ class ROROrganizationResolver:
|
||||
|
||||
city = coerce_str(details.get("name")) or None
|
||||
region = coerce_str(details.get("country_subdivision_name")) or None
|
||||
display_name = _organization_label(organization, ror_query)
|
||||
ror_id = coerce_str(organization.get("id"))
|
||||
geonames_id = location.get("geonames_id")
|
||||
source_note = (
|
||||
@@ -551,6 +613,9 @@ def _record_context(record: Any, metadata: dict[str, Any]) -> dict[str, Any]:
|
||||
"organization": coerce_str(metadata.get("organization")),
|
||||
"source_location": metadata.get("location"),
|
||||
"source_raw_country": metadata.get("raw_country"),
|
||||
"sources": metadata.get("sources") if isinstance(metadata.get("sources"), list) else [],
|
||||
"source_url": coerce_str(metadata.get("source_url") or metadata.get("detail_url")),
|
||||
"builds_upon": coerce_str(metadata.get("builds_upon")),
|
||||
}
|
||||
|
||||
|
||||
@@ -580,6 +645,9 @@ def _context_to_query(
|
||||
"organization": context.get("organization") or "",
|
||||
"source_location": context.get("source_location"),
|
||||
"source_raw_country": context.get("source_raw_country"),
|
||||
"sources": list(context.get("sources") or []),
|
||||
"source_url": context.get("source_url") or "",
|
||||
"builds_upon": context.get("builds_upon") or "",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -656,6 +724,61 @@ def _compute_center_candidate_sort_key(candidate: LocationCandidate) -> tuple[in
|
||||
return (source_rank, precision_rank, -float(candidate.confidence or 0))
|
||||
|
||||
|
||||
class BuildsUponComputeCenterResolver:
|
||||
"""Inherit coordinates from a previously resolved parent cluster via `builds_upon`."""
|
||||
|
||||
name = "inherited"
|
||||
|
||||
def resolve(self, query: LocationQuery) -> ResolverOutput:
|
||||
extra = query.extra or {}
|
||||
parent_ref = coerce_str(extra.get("builds_upon"))
|
||||
if not parent_ref:
|
||||
return ResolverOutput()
|
||||
|
||||
parent_norm = normalize_text(parent_ref)
|
||||
candidates: list[LocationCandidate] = []
|
||||
seen_coords: set[tuple[str, str]] = set()
|
||||
for entry in COMPUTE_CENTER_LOCATION_CACHE.values():
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
prec = coerce_str(entry.get("precision"))
|
||||
if prec not in RENDERABLE_PRECISIONS:
|
||||
continue
|
||||
lat = parse_float(entry.get("latitude"))
|
||||
lon = parse_float(entry.get("longitude"))
|
||||
if lat in (None, 0.0) or lon in (None, 0.0):
|
||||
continue
|
||||
entry_id = normalize_text(entry.get("source_id"))
|
||||
entry_name = normalize_text(entry.get("name"))
|
||||
if parent_norm not in {entry_id, entry_name}:
|
||||
continue
|
||||
coord_key = (f"{lat:.4f}", f"{lon:.4f}")
|
||||
if coord_key in seen_coords:
|
||||
continue
|
||||
seen_coords.add(coord_key)
|
||||
candidates.append(
|
||||
LocationCandidate(
|
||||
latitude=lat,
|
||||
longitude=lon,
|
||||
display_name=coerce_str(entry.get("name")) or parent_ref,
|
||||
precision="site" if prec == "precise" else prec,
|
||||
confidence=0.82 if not entry.get("needs_confirmation") else 0.72,
|
||||
query=f"builds_upon:{parent_ref}",
|
||||
source=self.name,
|
||||
source_note=f"Inherited from parent cluster '{coerce_str(entry.get('name')) or parent_ref}' via builds_upon",
|
||||
matched_fields=("builds_upon",),
|
||||
needs_confirmation=True,
|
||||
city=coerce_str(entry.get("city")) or None,
|
||||
country=coerce_str(entry.get("country")) or query.country,
|
||||
matched_location_name=coerce_str(entry.get("name")) or parent_ref,
|
||||
)
|
||||
)
|
||||
return ResolverOutput(
|
||||
candidates=tuple(candidates),
|
||||
attempted_queries=(f"builds_upon:{parent_ref}",),
|
||||
)
|
||||
|
||||
|
||||
COMPUTE_CENTER_PIPELINE = LocationPipeline(
|
||||
[
|
||||
ComputeCenterSourceCoordinatesResolver(),
|
||||
@@ -673,6 +796,7 @@ COMPUTE_CENTER_COLLECTION_PIPELINE = LocationPipeline(
|
||||
[
|
||||
ComputeCenterSourceCoordinatesResolver(),
|
||||
VerifiedComputeSiteResolver(),
|
||||
BuildsUponComputeCenterResolver(),
|
||||
ROROrganizationResolver(),
|
||||
NominatimResolver(
|
||||
query_plan_builder=_compute_center_query_plan,
|
||||
@@ -871,12 +995,12 @@ def collect_location_candidates(
|
||||
country: str | None = None,
|
||||
organization: str | None = None,
|
||||
record_id: int | None = None,
|
||||
sources: list[str] | None = None,
|
||||
source_url: str | None = None,
|
||||
builds_upon: str | None = None,
|
||||
source_raw_country: str | None = None,
|
||||
) -> tuple[list[LocationCandidate], list[str]]:
|
||||
"""Run the full resolution chain and return ranked candidates with attempted queries.
|
||||
|
||||
The unused ``source`` / ``source_id`` / ``record_id`` arguments are kept
|
||||
for backward compatibility with the API handler that calls this function.
|
||||
"""
|
||||
"""Run the full resolution chain and return ranked candidates with attempted queries."""
|
||||
query = build_compute_center_location_query(
|
||||
name=name,
|
||||
source=source,
|
||||
@@ -886,6 +1010,10 @@ def collect_location_candidates(
|
||||
city=city,
|
||||
country=country,
|
||||
organization=organization,
|
||||
sources=sources,
|
||||
source_url=source_url,
|
||||
builds_upon=builds_upon,
|
||||
source_raw_country=source_raw_country,
|
||||
)
|
||||
return COMPUTE_CENTER_COLLECTION_PIPELINE.collect_candidates(query)
|
||||
|
||||
@@ -900,6 +1028,10 @@ def build_compute_center_location_query(
|
||||
city: str | None = None,
|
||||
country: str | None = None,
|
||||
organization: str | None = None,
|
||||
sources: list[str] | None = None,
|
||||
source_url: str | None = None,
|
||||
builds_upon: str | None = None,
|
||||
source_raw_country: str | None = None,
|
||||
) -> LocationQuery:
|
||||
name_value = coerce_str(name)
|
||||
context: dict[str, Any] = {
|
||||
@@ -912,6 +1044,10 @@ def build_compute_center_location_query(
|
||||
"site": coerce_str(site or organization),
|
||||
"operator": coerce_str(operator or organization),
|
||||
"organization": coerce_str(organization),
|
||||
"sources": [str(item).strip() for item in (sources or []) if item],
|
||||
"source_url": coerce_str(source_url),
|
||||
"builds_upon": coerce_str(builds_upon),
|
||||
"source_raw_country": coerce_str(source_raw_country),
|
||||
}
|
||||
return _context_to_query(context)
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ DOCS_METADATA: tuple[DocsMetadata, ...] = (
|
||||
DocsMetadata("location-pipeline-development.md", "location-pipeline-development", "docs_developer", "Backend", 35, "通用位置估算管线开发说明", "Shared Location Resolution Pipeline Development Guide"),
|
||||
DocsMetadata("earth-news-live-streams-collector-format.md", "earth-news-live-streams-collector-format", "docs_developer", "Backend", 36, "新闻直播采集格式", "News Live Streams Collector Format"),
|
||||
DocsMetadata("docs-gatekeeper-development.md", "docs-gatekeeper-development", "docs_developer", "Backend", 37, "Docs Gatekeeper 开发说明", "Docs Gatekeeper Development Guide"),
|
||||
DocsMetadata("api-integration-guide.md", "api-integration-guide", "docs_developer", "Backend", 38, "API 接入与鉴权指南", "API Integration and Authentication Guide"),
|
||||
DocsMetadata("agents-aiprovider.md", "agents-aiprovider", "docs_developer", "Agents", 40, "AI Provider 指南", "AI Provider Guide"),
|
||||
DocsMetadata("ops-runbook.md", "ops-runbook", "docs_admin", "Ops", 49, "智能星球运维手册", "Intelligent Planet Ops Runbook"),
|
||||
DocsMetadata("ops-docker-compose-buildx-upgrade.md", "ops-docker-compose-buildx-upgrade", "docs_admin", "Ops", 50, "Docker + Compose + Buildx 升级", "Docker + Compose + Buildx Upgrade"),
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, replace
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import HTTPException, Response
|
||||
from fastapi import HTTPException, Request, Response
|
||||
|
||||
from app.core.cache import _RedisClient
|
||||
from app.core.config import settings
|
||||
@@ -27,6 +29,8 @@ DEFAULT_MAX_FEATURES = 5000
|
||||
DEFAULT_MAX_BYTES = 5 * 1024 * 1024
|
||||
DEFAULT_BBOX_PRECISION_DEGREES = 0.1
|
||||
DEV_CACHE_KEY_HEADER = {"development", "dev", "test", "testing", "local"}
|
||||
ENCODED_ARTIFACT_CACHE_MAX_ENTRIES = 8
|
||||
GZIP_COMPRESS_LEVEL = 5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -49,6 +53,25 @@ class EarthLayerCacheResult:
|
||||
bytes: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _EncodedLayerArtifact:
|
||||
raw_bytes: bytes
|
||||
gzip_bytes: bytes
|
||||
etag: str
|
||||
features: int
|
||||
byte_length: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EarthLayerEncodedResult:
|
||||
artifact: _EncodedLayerArtifact
|
||||
state: str
|
||||
key: str
|
||||
|
||||
|
||||
_ENCODED_ARTIFACT_CACHE: OrderedDict[tuple[str, str], _EncodedLayerArtifact] = OrderedDict()
|
||||
|
||||
|
||||
class EarthLayerCache:
|
||||
def __init__(self) -> None:
|
||||
self._client = None
|
||||
@@ -81,6 +104,16 @@ class EarthLayerCache:
|
||||
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:32]
|
||||
return f"{EARTH_LAYER_LOCK_PREFIX}:{digest}"
|
||||
|
||||
def get_raw(self, key: str) -> bytes | None:
|
||||
raw = self.client.get(key)
|
||||
if not raw:
|
||||
return None
|
||||
if isinstance(raw, bytes):
|
||||
return raw
|
||||
if isinstance(raw, str):
|
||||
return raw.encode("utf-8")
|
||||
return None
|
||||
|
||||
def get_json(self, key: str) -> dict[str, Any] | None:
|
||||
raw = self.client.get(key)
|
||||
if not raw:
|
||||
@@ -191,15 +224,143 @@ def format_bbox_key(bbox: tuple[float, float, float, float]) -> str:
|
||||
return ",".join(f"{value:.1f}" for value in bbox)
|
||||
|
||||
|
||||
def apply_cache_headers(response: Response | None, result: EarthLayerCacheResult) -> None:
|
||||
if response is None:
|
||||
return
|
||||
response.headers["X-Planet-Cache"] = result.state
|
||||
response.headers["X-Planet-Cache-Features"] = str(result.features)
|
||||
response.headers["X-Planet-Cache-Bytes"] = str(result.bytes)
|
||||
def _cache_headers(
|
||||
result: EarthLayerCacheResult | EarthLayerEncodedResult,
|
||||
) -> dict[str, str]:
|
||||
if isinstance(result, EarthLayerEncodedResult):
|
||||
features, byte_length = result.artifact.features, result.artifact.byte_length
|
||||
else:
|
||||
features, byte_length = result.features, result.bytes
|
||||
headers = {
|
||||
"X-Planet-Cache": result.state,
|
||||
"X-Planet-Cache-Features": str(features),
|
||||
"X-Planet-Cache-Bytes": str(byte_length),
|
||||
}
|
||||
env_name = str(getattr(settings, "ENVIRONMENT", "") or "development").lower()
|
||||
if env_name in DEV_CACHE_KEY_HEADER:
|
||||
response.headers["X-Planet-Cache-Key"] = result.key
|
||||
headers["X-Planet-Cache-Key"] = result.key
|
||||
return headers
|
||||
|
||||
|
||||
def apply_cache_headers(
|
||||
response: Response | None,
|
||||
result: EarthLayerCacheResult | EarthLayerEncodedResult,
|
||||
) -> None:
|
||||
if response is not None:
|
||||
response.headers.update(_cache_headers(result))
|
||||
|
||||
|
||||
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
|
||||
if not if_none_match:
|
||||
return False
|
||||
normalized_target = etag.strip()
|
||||
if normalized_target.startswith("W/"):
|
||||
normalized_target = normalized_target[2:].strip()
|
||||
for candidate in if_none_match.split(","):
|
||||
token = candidate.strip()
|
||||
if token == "*":
|
||||
return True
|
||||
if token.startswith("W/"):
|
||||
token = token[2:].strip()
|
||||
if token == normalized_target:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _encode_layer_bytes(
|
||||
key: str,
|
||||
raw_bytes: bytes,
|
||||
*,
|
||||
features: int | None = None,
|
||||
) -> _EncodedLayerArtifact:
|
||||
etag = f'"{hashlib.sha256(raw_bytes).hexdigest()[:24]}"'
|
||||
cache_key = (key, etag)
|
||||
cached = _ENCODED_ARTIFACT_CACHE.get(cache_key)
|
||||
if cached is not None:
|
||||
_ENCODED_ARTIFACT_CACHE.move_to_end(cache_key)
|
||||
return cached
|
||||
|
||||
resolved_features = features
|
||||
if resolved_features is None:
|
||||
parsed = json.loads(raw_bytes)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("Earth layer cache payload must be a JSON object")
|
||||
resolved_features = _feature_count(parsed)
|
||||
|
||||
gzip_bytes = gzip.compress(raw_bytes, compresslevel=GZIP_COMPRESS_LEVEL)
|
||||
artifact = _EncodedLayerArtifact(
|
||||
raw_bytes=raw_bytes,
|
||||
gzip_bytes=gzip_bytes,
|
||||
etag=etag,
|
||||
features=resolved_features,
|
||||
byte_length=len(raw_bytes),
|
||||
)
|
||||
_ENCODED_ARTIFACT_CACHE[cache_key] = artifact
|
||||
while len(_ENCODED_ARTIFACT_CACHE) > ENCODED_ARTIFACT_CACHE_MAX_ENTRIES:
|
||||
_ENCODED_ARTIFACT_CACHE.popitem(last=False)
|
||||
return artifact
|
||||
|
||||
|
||||
async def resolve_layer_encoded_payload(
|
||||
*,
|
||||
key: str,
|
||||
policy: EarthLayerCachePolicy,
|
||||
builder: Callable[[], Awaitable[dict[str, Any]]],
|
||||
) -> EarthLayerEncodedResult:
|
||||
flight_key = (asyncio.get_running_loop(), key)
|
||||
if flight_key not in earth_layer_cache._inflight:
|
||||
cached_raw = None
|
||||
with suppress(Exception):
|
||||
cached_raw = earth_layer_cache.get_raw(key)
|
||||
if cached_raw is not None:
|
||||
try:
|
||||
artifact = _encode_layer_bytes(key, cached_raw)
|
||||
return EarthLayerEncodedResult(artifact=artifact, state="hit", key=key)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Invalid raw earth layer cache payload; falling back to standard resolver",
|
||||
event="earth_layer_cache.raw_decode_failed",
|
||||
context={"key": key, "error": str(exc)},
|
||||
)
|
||||
|
||||
result = await resolve_layer_payload(key=key, policy=policy, builder=builder)
|
||||
raw_bytes = json.dumps(result.payload, ensure_ascii=False, default=str).encode("utf-8")
|
||||
artifact = _encode_layer_bytes(key, raw_bytes, features=result.features)
|
||||
return EarthLayerEncodedResult(artifact=artifact, state=result.state, key=result.key)
|
||||
|
||||
|
||||
async def get_or_build_layer_response(
|
||||
*,
|
||||
key: str,
|
||||
policy: EarthLayerCachePolicy,
|
||||
builder: Callable[[], Awaitable[dict[str, Any]]],
|
||||
request: Request,
|
||||
response: Response | None = None,
|
||||
) -> Response:
|
||||
result = await resolve_layer_encoded_payload(key=key, policy=policy, builder=builder)
|
||||
headers = _cache_headers(result)
|
||||
if response is not None:
|
||||
response.headers.update(headers)
|
||||
headers.update({
|
||||
"ETag": result.artifact.etag,
|
||||
"Cache-Control": "private, no-cache",
|
||||
"Vary": "Accept-Encoding",
|
||||
})
|
||||
if _etag_matches(request.headers.get("if-none-match"), result.artifact.etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
|
||||
accept_encoding = (request.headers.get("accept-encoding") or "").lower()
|
||||
if "gzip" in accept_encoding:
|
||||
return Response(
|
||||
content=result.artifact.gzip_bytes,
|
||||
media_type="application/json",
|
||||
headers={**headers, "Content-Encoding": "gzip"},
|
||||
)
|
||||
return Response(
|
||||
content=result.artifact.raw_bytes,
|
||||
media_type="application/json",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
async def get_or_build_layer_payload(
|
||||
@@ -262,9 +423,11 @@ async def _resolve_layer_payload(
|
||||
try:
|
||||
async with asyncio.timeout(policy.build_wait_seconds):
|
||||
while True:
|
||||
cached = earth_layer_cache.get_json(key)
|
||||
if cached is not None:
|
||||
return _result(cached, state="hit", key=key)
|
||||
cached_raw = earth_layer_cache.get_raw(key)
|
||||
if cached_raw is not None:
|
||||
cached = json.loads(cached_raw)
|
||||
if isinstance(cached, dict):
|
||||
return _result(cached, state="hit", key=key, byte_length=len(cached_raw))
|
||||
token = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds)
|
||||
if token is not None:
|
||||
break
|
||||
@@ -454,13 +617,19 @@ def _with_budget_diagnostics(
|
||||
return {**payload, "diagnostics": diagnostics}
|
||||
|
||||
|
||||
def _result(payload: dict[str, Any], *, state: str, key: str) -> EarthLayerCacheResult:
|
||||
def _result(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
state: str,
|
||||
key: str,
|
||||
byte_length: int | None = None,
|
||||
) -> EarthLayerCacheResult:
|
||||
return EarthLayerCacheResult(
|
||||
payload=payload,
|
||||
state=state,
|
||||
key=key,
|
||||
features=_feature_count(payload),
|
||||
bytes=_payload_size(payload),
|
||||
bytes=_payload_size(payload) if byte_length is None else byte_length,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
import time
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -14,32 +16,117 @@ CATALOG_MAX_PAGES = 100
|
||||
CATALOG_PAGE_SIZE = 100
|
||||
CATALOG_REQUEST_ATTEMPTS = 2
|
||||
CATALOG_RETRY_DELAY_SECONDS = 0.2
|
||||
MODELS_DEV_CATALOG_URL = "https://models.dev/api.json"
|
||||
OPENROUTER_CATALOG_URL = "https://openrouter.ai/api/v1/models"
|
||||
AGGREGATOR_CACHE_TTL_SECONDS = 300
|
||||
SUPPORTED_PROVIDER_APIS = {
|
||||
"openai-completions",
|
||||
"openai-responses",
|
||||
"anthropic-messages",
|
||||
"ollama-generate",
|
||||
}
|
||||
OFFICIAL_PUBLIC_CATALOG_HOSTS: dict[str, frozenset[str]] = {
|
||||
"openrouter": frozenset({"openrouter.ai"}),
|
||||
"opencode-go": frozenset({"opencode.ai"}),
|
||||
}
|
||||
OFFICIAL_PROVIDER_HOSTS: dict[str, frozenset[str]] = {
|
||||
"minimax": frozenset({"api.minimaxi.com", "api.minimax.cn", "api.minimax.io"}),
|
||||
"openai": frozenset({"api.openai.com"}),
|
||||
"anthropic": frozenset({"api.anthropic.com"}),
|
||||
"deepseek": frozenset({"api.deepseek.com"}),
|
||||
"alibaba": frozenset({"dashscope.aliyuncs.com", "dashscope-intl.aliyuncs.com"}),
|
||||
"moonshotai": frozenset({"api.moonshot.ai", "api.moonshot.cn"}),
|
||||
"glm": frozenset({"open.bigmodel.cn", "api.z.ai"}),
|
||||
"meta": frozenset({"api.meta.ai", "api.llama.com"}),
|
||||
"gemini": frozenset({"generativelanguage.googleapis.com"}),
|
||||
"grok": frozenset({"api.x.ai"}),
|
||||
**OFFICIAL_PUBLIC_CATALOG_HOSTS,
|
||||
}
|
||||
AGGREGATOR_OPENROUTER_PREFIXES: dict[str, str] = {
|
||||
"minimax": "minimax/",
|
||||
"openai": "openai/",
|
||||
"anthropic": "anthropic/",
|
||||
"deepseek": "deepseek/",
|
||||
"alibaba": "qwen/",
|
||||
"moonshotai": "moonshotai/",
|
||||
"glm": "z-ai/",
|
||||
"meta": "meta-llama/",
|
||||
"gemini": "google/",
|
||||
"grok": "x-ai/",
|
||||
}
|
||||
_AGGREGATOR_CACHE: dict[str, tuple[float, object]] = {}
|
||||
_AGGREGATOR_LOOP_LOCKS: WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = WeakKeyDictionary()
|
||||
|
||||
|
||||
class LLMProviderCatalogError(RuntimeError):
|
||||
"""A safe, user-facing catalog failure with no upstream response or credentials."""
|
||||
|
||||
|
||||
class LLMProviderCatalogConfigError(LLMProviderCatalogError):
|
||||
"""Invalid local catalog configuration or missing required credentials."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelCatalog:
|
||||
url: str
|
||||
models: list[str]
|
||||
|
||||
|
||||
def is_official_public_catalog(provider: str, base_url: str) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
||||
return host in OFFICIAL_PUBLIC_CATALOG_HOSTS.get(provider_key, frozenset())
|
||||
|
||||
|
||||
def is_official_provider_host(provider: str, base_url: str) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
||||
if not host:
|
||||
return False
|
||||
if host in OFFICIAL_PROVIDER_HOSTS.get(provider_key, frozenset()):
|
||||
return True
|
||||
return provider_key == "alibaba" and (host == "aliyuncs.com" or host.endswith(".aliyuncs.com"))
|
||||
|
||||
|
||||
def catalog_requires_api_key(provider: str, base_url: str, provider_api: str) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
if provider_key == "ollama" or provider_api == "ollama-generate":
|
||||
return False
|
||||
return not is_official_public_catalog(provider_key, base_url)
|
||||
|
||||
|
||||
def catalog_supports_aggregator_fallback(
|
||||
provider: str, base_url: str, provider_api: str
|
||||
) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
return (
|
||||
provider_key in AGGREGATOR_OPENROUTER_PREFIXES
|
||||
and provider_api in SUPPORTED_PROVIDER_APIS
|
||||
and provider_api != "ollama-generate"
|
||||
and is_official_provider_host(provider_key, base_url)
|
||||
)
|
||||
|
||||
|
||||
def can_refresh_catalog_without_api_key(
|
||||
provider: str, base_url: str, provider_api: str
|
||||
) -> bool:
|
||||
return not catalog_requires_api_key(
|
||||
provider, base_url, provider_api
|
||||
) or catalog_supports_aggregator_fallback(provider, base_url, provider_api)
|
||||
|
||||
|
||||
def clear_aggregator_catalog_cache() -> None:
|
||||
_AGGREGATOR_CACHE.clear()
|
||||
|
||||
|
||||
def model_catalog_url(provider: str, base_url: str, provider_api: str) -> str:
|
||||
parts = urlsplit(base_url.strip())
|
||||
if parts.scheme not in {"http", "https"} or not parts.hostname:
|
||||
raise LLMProviderCatalogError("请填写有效的 HTTP(S) 模型基础地址。")
|
||||
raise LLMProviderCatalogConfigError("请填写有效的 HTTP(S) 模型基础地址。")
|
||||
if parts.username or parts.password or parts.query or parts.fragment:
|
||||
raise LLMProviderCatalogError("模型基础地址不能包含账号、密码、查询参数或片段。")
|
||||
raise LLMProviderCatalogConfigError("模型基础地址不能包含账号、密码、查询参数或片段。")
|
||||
if provider_api not in SUPPORTED_PROVIDER_APIS:
|
||||
raise LLMProviderCatalogError("当前接口协议不支持模型目录查询。")
|
||||
raise LLMProviderCatalogConfigError("当前接口协议不支持模型目录查询。")
|
||||
path = parts.path.rstrip("/")
|
||||
if provider_api == "ollama-generate":
|
||||
path = path.removesuffix("/api").removesuffix("/v1") + "/api/tags"
|
||||
@@ -85,11 +172,14 @@ def _model_rows(payload: object) -> tuple[list[dict[str, object]], dict[str, obj
|
||||
return rows, envelope
|
||||
|
||||
|
||||
def _model_id(row: dict[str, object]) -> str:
|
||||
def _model_id(row: dict[str, object], provider: str = "") -> str:
|
||||
value = row.get("id") or row.get("model") or row.get("name")
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise LLMProviderCatalogError("供应商返回了缺少 ID 的模型条目。")
|
||||
return value.strip()
|
||||
normalized = value.strip()
|
||||
if provider.strip().lower() == "gemini" and normalized.startswith("models/"):
|
||||
normalized = normalized.removeprefix("models/")
|
||||
return normalized
|
||||
|
||||
|
||||
def _model_date(row: dict[str, object]) -> float:
|
||||
@@ -132,21 +222,23 @@ async def fetch_model_catalog(
|
||||
api_key: str = "",
|
||||
anthropic_version: str = "2023-06-01",
|
||||
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
|
||||
*,
|
||||
include_auth: bool = True,
|
||||
) -> ModelCatalog:
|
||||
url = model_catalog_url(provider, base_url, provider_api)
|
||||
public_catalog = provider in {"opencode-go", "openrouter"}
|
||||
if not api_key and provider_api != "ollama-generate" and not public_catalog:
|
||||
raise LLMProviderCatalogError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
||||
if not api_key and catalog_requires_api_key(provider, base_url, provider_api):
|
||||
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
||||
headers = {"User-Agent": "Planet/1.0", "Accept": "application/json"}
|
||||
if provider_api == "anthropic-messages" and provider not in {
|
||||
"opencode-go",
|
||||
"openrouter",
|
||||
"alibaba",
|
||||
"moonshotai",
|
||||
}:
|
||||
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
|
||||
elif api_key:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
if include_auth and api_key:
|
||||
if provider_api == "anthropic-messages" and provider not in {
|
||||
"opencode-go",
|
||||
"openrouter",
|
||||
"alibaba",
|
||||
"moonshotai",
|
||||
}:
|
||||
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
|
||||
else:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
native_dashscope = provider == "alibaba" and urlsplit(url).hostname.endswith(".aliyuncs.com")
|
||||
params: dict[str, str | int] = {}
|
||||
if native_dashscope:
|
||||
@@ -160,7 +252,7 @@ async def fetch_model_catalog(
|
||||
rows, envelope = _model_rows(payload)
|
||||
previous_count = len(rows_by_id)
|
||||
for row in rows:
|
||||
rows_by_id[_model_id(row)] = row
|
||||
rows_by_id[_model_id(row, provider)] = row
|
||||
has_more = envelope.get("has_more") is True
|
||||
if native_dashscope:
|
||||
total = envelope.get("total")
|
||||
@@ -179,8 +271,205 @@ async def fetch_model_catalog(
|
||||
)
|
||||
# An empty Ollama catalog is valid: no models have been installed yet.
|
||||
if not models and provider_api != "ollama-generate":
|
||||
raise LLMProviderCatalogError("供应商返回了空模型目录,已保留上次模型列表。")
|
||||
raise LLMProviderCatalogError("供应商返回了空模型目录。")
|
||||
return ModelCatalog(url=url, models=models)
|
||||
if len(rows_by_id) == previous_count:
|
||||
raise LLMProviderCatalogError("供应商模型目录分页没有进展,已保留上次模型列表。")
|
||||
raise LLMProviderCatalogError("供应商模型目录分页超过限制,已保留上次模型列表。")
|
||||
raise LLMProviderCatalogError("供应商模型目录分页没有进展。")
|
||||
raise LLMProviderCatalogError("供应商模型目录分页超过限制。")
|
||||
|
||||
|
||||
def _aggregator_lock() -> asyncio.Lock:
|
||||
loop = asyncio.get_running_loop()
|
||||
lock = _AGGREGATOR_LOOP_LOCKS.get(loop)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
_AGGREGATOR_LOOP_LOCKS[loop] = lock
|
||||
return lock
|
||||
|
||||
|
||||
async def _fetch_aggregator_json(url: str, timeout_seconds: int) -> object:
|
||||
now = time.monotonic()
|
||||
cached = _AGGREGATOR_CACHE.get(url)
|
||||
if cached is not None and cached[0] > now:
|
||||
return cached[1]
|
||||
async with _aggregator_lock():
|
||||
now = time.monotonic()
|
||||
cached = _AGGREGATOR_CACHE.get(url)
|
||||
if cached is not None and cached[0] > now:
|
||||
return cached[1]
|
||||
timeout = max(1, min(timeout_seconds, CATALOG_TIMEOUT_SECONDS))
|
||||
headers = {
|
||||
"User-Agent": "Planet/1.0",
|
||||
"Accept": "application/json",
|
||||
"Accept-Encoding": "gzip",
|
||||
}
|
||||
async with asyncio.timeout(timeout), httpx.AsyncClient(timeout=timeout) as client:
|
||||
payload = await _get_catalog_page(client, url, headers, {})
|
||||
_AGGREGATOR_CACHE[url] = (time.monotonic() + AGGREGATOR_CACHE_TTL_SECONDS, payload)
|
||||
return payload
|
||||
|
||||
|
||||
def _models_dev_candidate_keys(provider: str, base_url: str) -> tuple[str, ...]:
|
||||
provider_key = provider.strip().lower()
|
||||
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
||||
if provider_key == "minimax":
|
||||
if host in {"api.minimaxi.com", "api.minimax.cn"}:
|
||||
return ("minimax-cn", "minimax")
|
||||
return ("minimax", "minimax-cn")
|
||||
if provider_key == "alibaba":
|
||||
if "intl" in host:
|
||||
return ("alibaba", "alibaba-cn")
|
||||
return ("alibaba-cn", "alibaba")
|
||||
if provider_key == "moonshotai":
|
||||
if host.endswith(".cn"):
|
||||
return ("moonshotai-cn", "moonshotai")
|
||||
return ("moonshotai", "moonshotai-cn")
|
||||
fixed: dict[str, tuple[str, ...]] = {
|
||||
"glm": ("zhipuai",),
|
||||
"meta": ("meta",),
|
||||
"gemini": ("google",),
|
||||
"grok": ("xai",),
|
||||
"openai": ("openai",),
|
||||
"anthropic": ("anthropic",),
|
||||
"deepseek": ("deepseek",),
|
||||
}
|
||||
return fixed.get(provider_key, (provider_key,))
|
||||
|
||||
|
||||
def _is_aggregator_chat_model(model_id: str, output_modalities: object = None) -> bool:
|
||||
"""Exclude embeddings, image/audio/video generators, and consumer chat aliases."""
|
||||
lower = model_id.strip().lower()
|
||||
if not lower:
|
||||
return False
|
||||
if isinstance(output_modalities, list) and output_modalities:
|
||||
mods = {str(item).strip().lower() for item in output_modalities if str(item).strip()}
|
||||
if "text" not in mods or (mods & {"image", "video", "audio"}):
|
||||
return False
|
||||
if "embedding" in lower:
|
||||
return False
|
||||
if lower.startswith(
|
||||
(
|
||||
"chatgpt-",
|
||||
"dall-e",
|
||||
"whisper",
|
||||
"tts-",
|
||||
"gpt-image",
|
||||
"gpt-audio",
|
||||
"gpt-realtime",
|
||||
"grok-imagine",
|
||||
"qwen-mt-",
|
||||
)
|
||||
):
|
||||
return False
|
||||
if lower == "gpt-chat-latest" or (lower.startswith("gpt-") and lower.endswith("-chat")):
|
||||
return False
|
||||
if any(token in lower for token in ("-image", "-tts", "-asr", "-live-", "-realtime", "-video")):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_general_aggregator_model(model_id: str) -> bool:
|
||||
"""Rank general-purpose flagship chat models ahead of vertical or experimental variants."""
|
||||
lower = model_id.strip().lower()
|
||||
if lower.startswith(("gpt-daybreak-", "deep-research-")):
|
||||
return False
|
||||
if lower.endswith(("-healthcare", "-legal", "-contributor", "-exp")):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _extract_models_dev_models(
|
||||
payload: object, provider: str, base_url: str
|
||||
) -> ModelCatalog | None:
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
for key in _models_dev_candidate_keys(provider, base_url):
|
||||
entry = payload.get(key)
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
raw_models = entry.get("models")
|
||||
if not isinstance(raw_models, dict):
|
||||
continue
|
||||
candidates: list[tuple[bool, bool, str, str]] = []
|
||||
for model_id, meta in raw_models.items():
|
||||
if not isinstance(model_id, str) or not model_id.strip() or not isinstance(meta, dict):
|
||||
continue
|
||||
modalities = meta.get("modalities")
|
||||
output_mods = modalities.get("output") if isinstance(modalities, dict) else None
|
||||
if not _is_aggregator_chat_model(model_id, output_mods):
|
||||
continue
|
||||
active = str(meta.get("status") or "").strip().lower() != "deprecated"
|
||||
release_date = str(meta.get("release_date") or "")
|
||||
candidates.append(
|
||||
(active, _is_general_aggregator_model(model_id), release_date, model_id.strip())
|
||||
)
|
||||
if candidates:
|
||||
candidates.sort(key=lambda item: (item[0], item[1], item[2], item[3]), reverse=True)
|
||||
return ModelCatalog(
|
||||
url=f"{MODELS_DEV_CATALOG_URL}#{key}",
|
||||
models=[item[3] for item in candidates],
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _extract_openrouter_models(payload: object, provider: str) -> ModelCatalog | None:
|
||||
provider_key = provider.strip().lower()
|
||||
prefix = AGGREGATOR_OPENROUTER_PREFIXES.get(provider_key, "")
|
||||
if not prefix:
|
||||
return None
|
||||
try:
|
||||
rows, _ = _model_rows(payload)
|
||||
except LLMProviderCatalogError:
|
||||
return None
|
||||
dated: list[tuple[bool, float, str]] = []
|
||||
seen: set[str] = set()
|
||||
for row in rows:
|
||||
raw_id = row.get("id")
|
||||
if not isinstance(raw_id, str) or not raw_id.startswith(prefix):
|
||||
continue
|
||||
model_id = raw_id[len(prefix) :].strip()
|
||||
if not model_id or ":" in model_id or model_id in seen:
|
||||
continue
|
||||
arch = row.get("architecture")
|
||||
output_mods = arch.get("output_modalities") if isinstance(arch, dict) else None
|
||||
if not _is_aggregator_chat_model(model_id, output_mods):
|
||||
continue
|
||||
seen.add(model_id)
|
||||
dated.append((_is_general_aggregator_model(model_id), _model_date(row), model_id))
|
||||
if not dated:
|
||||
return None
|
||||
dated.sort(key=lambda item: (item[0], item[1], item[2]), reverse=True)
|
||||
return ModelCatalog(
|
||||
url=f"{OPENROUTER_CATALOG_URL}#{provider_key}",
|
||||
models=[item[2] for item in dated],
|
||||
)
|
||||
|
||||
|
||||
async def fetch_aggregator_model_catalog(
|
||||
provider: str,
|
||||
base_url: str,
|
||||
provider_api: str,
|
||||
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
|
||||
) -> ModelCatalog:
|
||||
"""Fetch public model catalog for a keyless official-host provider via aggregators."""
|
||||
model_catalog_url(provider, base_url, provider_api)
|
||||
if not catalog_supports_aggregator_fallback(provider, base_url, provider_api):
|
||||
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
||||
|
||||
try:
|
||||
models_dev_payload = await _fetch_aggregator_json(MODELS_DEV_CATALOG_URL, timeout_seconds)
|
||||
catalog = _extract_models_dev_models(models_dev_payload, provider, base_url)
|
||||
if catalog is not None and catalog.models:
|
||||
return catalog
|
||||
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
|
||||
pass
|
||||
|
||||
try:
|
||||
openrouter_payload = await _fetch_aggregator_json(OPENROUTER_CATALOG_URL, timeout_seconds)
|
||||
catalog = _extract_openrouter_models(openrouter_payload, provider)
|
||||
if catalog is not None and catalog.models:
|
||||
return catalog
|
||||
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
|
||||
pass
|
||||
|
||||
raise LLMProviderCatalogError("公共聚合模型目录暂不可用,请稍后重试或配置 API Key。")
|
||||
@@ -2,10 +2,21 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from app.services.llm_model_catalog import fetch_model_catalog
|
||||
import httpx
|
||||
|
||||
from app.services.llm_model_catalog import (
|
||||
catalog_requires_api_key,
|
||||
catalog_supports_aggregator_fallback,
|
||||
fetch_aggregator_model_catalog,
|
||||
fetch_model_catalog,
|
||||
is_official_public_catalog,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
OPENCODE_GO_MODEL_PROVIDER_APIS = {
|
||||
"minimax-m3": "anthropic-messages",
|
||||
@@ -22,30 +33,44 @@ OPENCODE_GO_MODEL_PROVIDER_APIS = {
|
||||
"minimax-m2.5": "anthropic-messages",
|
||||
}
|
||||
OPENCODE_GO_FALLBACK_MODELS = [
|
||||
"minimax-m3",
|
||||
"kimi-k3",
|
||||
"glm-5.3",
|
||||
"qwen3.8-max",
|
||||
"gpt-5.6-luna",
|
||||
"minimax-m2.7",
|
||||
"minimax-m2.5",
|
||||
"kimi-k2.6",
|
||||
"kimi-k2.5",
|
||||
"glm-5.1",
|
||||
"glm-5",
|
||||
"glm-5.3-flash",
|
||||
"deepseek-v4.1-flash",
|
||||
"deepseek-v4-pro",
|
||||
"deepseek-v4-flash",
|
||||
"qwen3.6-plus",
|
||||
"qwen3.5-plus",
|
||||
"mimo-v2.5-pro",
|
||||
"mimo-v2.5",
|
||||
"kimi-k3.1-pro",
|
||||
"kimi-k3",
|
||||
"kimi-k2.7-code",
|
||||
"minimax-m3",
|
||||
"minimax-m3.1-flash",
|
||||
"qwen4-max",
|
||||
"qwen3.8-max",
|
||||
"qwen3.8-flash",
|
||||
"qwen3.7-plus",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6-luna",
|
||||
"grok-4.7",
|
||||
"claude-haiku-5-5",
|
||||
"gemini-4-argon",
|
||||
"mimo-v2.6-pro",
|
||||
"mimo-v2.6-flash",
|
||||
"hy4",
|
||||
"hy4-flash-free",
|
||||
"step-5-preview",
|
||||
"muse-spark-1.3-contributor",
|
||||
"muse-spark-1.2-contributor",
|
||||
]
|
||||
|
||||
|
||||
OPENAI_MODEL_PROVIDER_APIS = {
|
||||
model: "openai-responses"
|
||||
for model in [
|
||||
"gpt-6.2-astra",
|
||||
"gpt-6.2-sol",
|
||||
"gpt-6.1-terra",
|
||||
"gpt-6.1-sol",
|
||||
"gpt-6-astra",
|
||||
"gpt-6-sol",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
"gpt-5.6-luna",
|
||||
@@ -80,8 +105,18 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
|
||||
"label": "OpenAI",
|
||||
"provider_api": "openai-responses",
|
||||
"base_url": "https://api.openai.com/v1",
|
||||
"model": "gpt-6-astra",
|
||||
"models": ["gpt-6-astra", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-4.1"],
|
||||
"model": "gpt-6.2-astra",
|
||||
"models": [
|
||||
"gpt-6.2-astra",
|
||||
"gpt-6.2-sol",
|
||||
"gpt-6.1-terra",
|
||||
"gpt-6.1-sol",
|
||||
"gpt-6-astra",
|
||||
"gpt-6-sol",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-4.1",
|
||||
],
|
||||
"model_provider_apis": OPENAI_MODEL_PROVIDER_APIS,
|
||||
"api_key_env": "OPENAI_API_KEY",
|
||||
"source": "fallback",
|
||||
@@ -126,13 +161,66 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
|
||||
"api_key_env": "MOONSHOT_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"glm": {
|
||||
"provider": "glm",
|
||||
"label": "Zhipu AI / GLM (CN)",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://open.bigmodel.cn/api/paas/v4",
|
||||
"model": "glm-5.3",
|
||||
"models": ["glm-5.3", "glm-5.3-flash", "glm-5.3-flashx", "glm-5.2", "glm-5.1", "glm-5"],
|
||||
"api_key_env": "ZHIPU_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"meta": {
|
||||
"provider": "meta",
|
||||
"label": "Meta AI",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.meta.ai/v1",
|
||||
"model": "muse-ember-1.0",
|
||||
"models": ["muse-ember-1.0", "muse-wonder-1.0", "muse-spark-1.3", "muse-spark-1.2", "muse-spark-1.1"],
|
||||
"api_key_env": "META_MODEL_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"gemini": {
|
||||
"provider": "gemini",
|
||||
"label": "Google Gemini",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai",
|
||||
"model": "gemini-4-neon",
|
||||
"models": [
|
||||
"gemini-4-neon",
|
||||
"gemini-4-hydrogen",
|
||||
"gemini-4-carbon",
|
||||
"gemini-4-argon",
|
||||
"gemini-3.8-flash",
|
||||
"gemini-2.5-flash",
|
||||
],
|
||||
"api_key_env": "GEMINI_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"grok": {
|
||||
"provider": "grok",
|
||||
"label": "xAI Grok",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.x.ai/v1",
|
||||
"model": "grok-4.7",
|
||||
"models": ["grok-4.7", "grok-4.6", "grok-4.5", "grok-4.3", "grok-4.20-0309-reasoning"],
|
||||
"api_key_env": "XAI_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"openrouter": {
|
||||
"provider": "openrouter",
|
||||
"label": "OpenRouter",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://openrouter.ai/api/v1",
|
||||
"model": "openai/gpt-5.1",
|
||||
"models": ["openai/gpt-5.1", "anthropic/claude-sonnet-4.5", "qwen/qwen3-max"],
|
||||
"model": "openai/gpt-6.2-astra",
|
||||
"models": [
|
||||
"openai/gpt-6.2-astra",
|
||||
"openai/gpt-6.2-sol",
|
||||
"google/gemini-4-neon",
|
||||
"qwen/qwen4-max",
|
||||
"anthropic/claude-sonnet-4.5",
|
||||
],
|
||||
"api_key_env": "OPENROUTER_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
@@ -141,7 +229,7 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
|
||||
"label": "OpenCode Go",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://opencode.ai/zen/go/v1",
|
||||
"model": "glm-5.1",
|
||||
"model": "glm-5.3",
|
||||
"models": OPENCODE_GO_FALLBACK_MODELS,
|
||||
"model_provider_apis": OPENCODE_GO_MODEL_PROVIDER_APIS,
|
||||
"api_key_env": "OPENCODE_GO_API_KEY",
|
||||
@@ -178,6 +266,15 @@ def _opencode_go_model_provider_apis(model_ids: list[str]) -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
def _openai_model_provider_apis(model_ids: list[str]) -> dict[str, str]:
|
||||
mapping: dict[str, str] = {}
|
||||
for model_id in model_ids:
|
||||
lower = model_id.strip().lower()
|
||||
if model_id in OPENAI_MODEL_PROVIDER_APIS or lower.startswith(("gpt-6", "gpt-5", "o3", "o4")):
|
||||
mapping[model_id] = OPENAI_MODEL_PROVIDER_APIS.get(model_id, "openai-responses")
|
||||
return mapping
|
||||
|
||||
|
||||
async def refresh_llm_provider_preset(
|
||||
provider: str,
|
||||
api_key: str | None = None,
|
||||
@@ -189,23 +286,69 @@ async def refresh_llm_provider_preset(
|
||||
fallback = get_fallback_llm_provider_preset(provider)
|
||||
resolved_base_url = base_url or fallback["base_url"]
|
||||
resolved_api = provider_api or fallback["provider_api"]
|
||||
catalog = await fetch_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
api_key or "",
|
||||
anthropic_version,
|
||||
)
|
||||
model_provider_apis = (
|
||||
_opencode_go_model_provider_apis(catalog.models)
|
||||
if fallback["provider"] == "opencode-go"
|
||||
else fallback.get("model_provider_apis", {})
|
||||
resolved_api_key = (api_key or "").strip()
|
||||
supports_aggregator = catalog_supports_aggregator_fallback(
|
||||
fallback["provider"], resolved_base_url, resolved_api
|
||||
)
|
||||
if (
|
||||
fallback["provider"] == "openai"
|
||||
and urlsplit(resolved_base_url).hostname != "api.openai.com"
|
||||
not resolved_api_key
|
||||
and catalog_requires_api_key(fallback["provider"], resolved_base_url, resolved_api)
|
||||
and supports_aggregator
|
||||
):
|
||||
model_provider_apis = {}
|
||||
catalog = await fetch_aggregator_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
catalog = await fetch_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
resolved_api_key,
|
||||
anthropic_version,
|
||||
include_auth=not is_official_public_catalog(
|
||||
fallback["provider"], resolved_base_url
|
||||
),
|
||||
)
|
||||
except (httpx.HTTPError, TimeoutError) as official_exc:
|
||||
if not resolved_api_key or not supports_aggregator:
|
||||
raise
|
||||
logger.warning(
|
||||
"Official LLM catalog request failed; falling back to public aggregator",
|
||||
extra={
|
||||
"event": "settings.ai_provider.catalog.official_fallback",
|
||||
"context": {
|
||||
"provider": fallback["provider"],
|
||||
"error_type": type(official_exc).__name__,
|
||||
"status_code": (
|
||||
official_exc.response.status_code
|
||||
if isinstance(official_exc, httpx.HTTPStatusError)
|
||||
else None
|
||||
),
|
||||
},
|
||||
},
|
||||
)
|
||||
try:
|
||||
catalog = await fetch_aggregator_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
)
|
||||
except Exception:
|
||||
# Preserve the original official error (e.g. 401 invalid API key) if public aggregators also fail.
|
||||
raise official_exc from None
|
||||
if fallback["provider"] == "opencode-go":
|
||||
model_provider_apis = _opencode_go_model_provider_apis(catalog.models)
|
||||
elif fallback["provider"] == "openai":
|
||||
model_provider_apis = (
|
||||
{}
|
||||
if urlsplit(resolved_base_url).hostname != "api.openai.com"
|
||||
else _openai_model_provider_apis(catalog.models)
|
||||
)
|
||||
else:
|
||||
model_provider_apis = fallback.get("model_provider_apis", {})
|
||||
return {
|
||||
**fallback,
|
||||
"base_url": resolved_base_url,
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
"""Controlled multi-step Tool-Calling agent & L1 resolvers for unknown facility locations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.compute_center_location import ComputeCenterLocationRecord
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.schemas.ai import SituationalAnalysisRequest
|
||||
from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch
|
||||
from app.services.ai.workflow_registry import resolve_runtime_workflow_node
|
||||
from app.services.location.llm_fallback import (
|
||||
DEFAULT_MIN_CONFIDENCE,
|
||||
LocationLLMFallbackResult,
|
||||
collect_llm_location_fallback_candidate,
|
||||
)
|
||||
from app.services.location.models import LocationCandidate, LocationQuery
|
||||
from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder
|
||||
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
|
||||
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
|
||||
from app.services.location.text import coerce_str, normalize_country_text, normalize_text, parse_float
|
||||
|
||||
logger = get_logger(__name__, service="location_agent")
|
||||
|
||||
TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset({"undisclosed", "multi_site", "anonymous"})
|
||||
_agent_geocoder = build_default_nominatim_geocoder()
|
||||
|
||||
LOCATION_AGENT_TOOLS: list[dict[str, Any]] = [
|
||||
{
|
||||
"name": "fetch_source_url",
|
||||
"description": "Fetch and read a primary source webpage (especially Epoch Source 1..5 or TOP500 detail URL) cleanly with prompt-injection isolation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"url": {"type": "string", "description": "Public http/https URL"}},
|
||||
"required": ["url"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "web_search",
|
||||
"description": "Search the web using concise English or local-language queries (do not chain long hardware suffixes).",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"query": {"type": "string", "description": "Concise search query"}},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "geocode_verify",
|
||||
"description": "Verify a physical facility address or city via geocoder and receive a verified geocode_candidate_id with coordinates and country.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"place_query": {"type": "string", "description": "Address, campus, or city + country"},
|
||||
"country": {"type": "string", "description": "Expected country name"},
|
||||
},
|
||||
"required": ["place_query"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "submit_location_result",
|
||||
"description": "Finalize location verification using a geocode_candidate_id from geocode_verify, or report a terminal status (undisclosed/multi_site/anonymous/unresolved).",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["located", "undisclosed", "multi_site", "anonymous", "unresolved"],
|
||||
},
|
||||
"facility_name": {"type": "string"},
|
||||
"address": {"type": "string"},
|
||||
"city": {"type": "string"},
|
||||
"region": {"type": "string"},
|
||||
"country": {"type": "string"},
|
||||
"precision": {"type": "string", "enum": ["precise", "site", "city"]},
|
||||
"geocode_candidate_id": {"type": "string"},
|
||||
"citations": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "URLs directly observed in fetch_source_url or web_search outputs",
|
||||
},
|
||||
"confidence": {"type": "number"},
|
||||
"reasoning": {"type": "string"},
|
||||
},
|
||||
"required": ["status", "reasoning"],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
async def run_l1_structured_facility_resolvers(
|
||||
query: LocationQuery,
|
||||
*,
|
||||
db: AsyncSession | None = None,
|
||||
) -> tuple[list[LocationCandidate], list[str], bool]:
|
||||
"""Run async L1 Wikidata & PeeringDB lookups respecting `location.resolve_unknown` config."""
|
||||
l1_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l1_knowledge")
|
||||
params = (l1_node or {}).get("params") or {}
|
||||
enabled_tools = set((l1_node or {}).get("tools") or [])
|
||||
allow_low_short_circuit = bool(params.get("allow_low_confidence_short_circuit", False))
|
||||
|
||||
tasks = []
|
||||
if params.get("wikidata_enabled", True) and (not enabled_tools or "wikidata_lookup" in enabled_tools):
|
||||
tasks.append(lookup_wikidata_facility(query))
|
||||
if params.get("peeringdb_enabled", True) and (not enabled_tools or "peeringdb_fac_lookup" in enabled_tools):
|
||||
tasks.append(lookup_peeringdb_facility(query))
|
||||
|
||||
candidates: list[LocationCandidate] = []
|
||||
attempted: list[str] = []
|
||||
if tasks:
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for out in results:
|
||||
if isinstance(out, Exception):
|
||||
continue
|
||||
attempted.extend(out.attempted_queries)
|
||||
candidates.extend(out.candidates)
|
||||
return candidates, attempted, allow_low_short_circuit
|
||||
|
||||
|
||||
async def _persist_terminal_location_status(
|
||||
db: AsyncSession | None,
|
||||
*,
|
||||
query: LocationQuery,
|
||||
terminal_status: str,
|
||||
reasoning: str,
|
||||
) -> None:
|
||||
if db is None or not hasattr(db, "execute"):
|
||||
return
|
||||
extra = query.extra or {}
|
||||
source = coerce_str(extra.get("source"))
|
||||
source_id = coerce_str(extra.get("source_id"))
|
||||
if not source or not source_id:
|
||||
return
|
||||
try:
|
||||
from app.services.compute_center_locations import refresh_compute_center_location_cache
|
||||
|
||||
existing = await db.scalar(
|
||||
select(ComputeCenterLocationRecord)
|
||||
.where(ComputeCenterLocationRecord.source == source)
|
||||
.where(ComputeCenterLocationRecord.source_id == source_id)
|
||||
)
|
||||
if existing is None:
|
||||
existing = ComputeCenterLocationRecord(
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
name=query.name,
|
||||
operator=coerce_str(extra.get("operator")) or None,
|
||||
site=coerce_str(extra.get("site")) or None,
|
||||
city=query.city,
|
||||
country=query.country,
|
||||
latitude=None,
|
||||
longitude=None,
|
||||
precision="unknown",
|
||||
confidence=0.0,
|
||||
location_source=f"agent_terminal_{terminal_status}",
|
||||
source_note=reasoning[:500] or f"Marked {terminal_status} by location agent",
|
||||
needs_confirmation=False,
|
||||
verification_status=terminal_status,
|
||||
verified_at=datetime.now(UTC),
|
||||
)
|
||||
db.add(existing)
|
||||
else:
|
||||
existing.precision = "unknown"
|
||||
existing.latitude = None
|
||||
existing.longitude = None
|
||||
existing.verification_status = terminal_status
|
||||
existing.location_source = f"agent_terminal_{terminal_status}"
|
||||
existing.source_note = reasoning[:500] or existing.source_note
|
||||
existing.verified_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await refresh_compute_center_location_cache(db)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to persist terminal unlocatable status",
|
||||
event="location.agent.persist_terminal_failed",
|
||||
context={"source_id": source_id, "status": terminal_status, "error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
async def _record_location_workflow_run(
|
||||
db: AsyncSession | None,
|
||||
*,
|
||||
question: str,
|
||||
status_value: str,
|
||||
tool_trace: list[str],
|
||||
steps_used: int,
|
||||
error_message: str = "",
|
||||
) -> None:
|
||||
if db is None or not hasattr(db, "add"):
|
||||
return
|
||||
try:
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"run_{uuid4().hex[:16]}",
|
||||
workflow_id="location.resolve_unknown",
|
||||
status=status_value,
|
||||
access_tier="admin",
|
||||
actor_key="admin:collect-location",
|
||||
question=question[:500],
|
||||
tool_trace=tool_trace,
|
||||
budget_used={"steps": steps_used},
|
||||
error_message=error_message[:500],
|
||||
completed_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
try:
|
||||
await db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def run_controlled_location_agent(
|
||||
*,
|
||||
provider_client: Any,
|
||||
web_search_client: Any | None,
|
||||
query: LocationQuery,
|
||||
entity_type: str = "compute_center",
|
||||
db: AsyncSession | None = None,
|
||||
attempted_queries: list[str] | None = None,
|
||||
) -> tuple[LocationLLMFallbackResult, str | None]:
|
||||
"""Run the 3-4 step Tool-Calling location agent and return `(result, terminal_status)`."""
|
||||
extra = query.extra or {}
|
||||
l2_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l2_agent_research")
|
||||
l3_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l3_geo_guardrail")
|
||||
if l2_node and not l2_node.get("enabled", True):
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=list(attempted_queries or []),
|
||||
failure_reason="Location agent node is disabled by workflow configuration.",
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
max_steps = max(1, min(int((l2_node or {}).get("max_steps") or 4), 6))
|
||||
allowed_tool_names = set((l2_node or {}).get("tools") or [t["name"] for t in LOCATION_AGENT_TOOLS])
|
||||
min_confidence = float(((l3_node or {}).get("guardrails") or {}).get("min_confidence") or DEFAULT_MIN_CONFIDENCE)
|
||||
require_tool_urls = bool(((l3_node or {}).get("guardrails") or {}).get("require_tool_cited_urls", True))
|
||||
|
||||
active_tools = [t for t in LOCATION_AGENT_TOOLS if t["name"] in allowed_tool_names]
|
||||
if not any(t["name"] == "submit_location_result" for t in active_tools):
|
||||
active_tools.append(LOCATION_AGENT_TOOLS[-1])
|
||||
|
||||
observed_urls: set[str] = set()
|
||||
geocode_candidates: dict[str, dict[str, Any]] = {}
|
||||
tool_trace: list[str] = ["l0_normalize", "l1_knowledge"]
|
||||
agent_attempts: list[str] = []
|
||||
source_urls = [
|
||||
str(u).strip()
|
||||
for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])]
|
||||
if str(u or "").strip().startswith(("http://", "https://"))
|
||||
]
|
||||
|
||||
system_prompt = (l2_node or {}).get("system_prompt") or (
|
||||
"你是算力与网络基础设施物理位置查证 Agent。严禁编造经纬度!"
|
||||
"1) 若存在 primary_source_urls,优先调用 fetch_source_url;"
|
||||
"2) 否则调用 web_search 查询物理地址;"
|
||||
"3) 将查到的物理地址/城市传入 geocode_verify 获取 candidate_id;"
|
||||
"4) 最后调用 submit_location_result 提交结果。"
|
||||
)
|
||||
user_objective = (l2_node or {}).get("prompt") or (
|
||||
f"请查证目标设施 {query.name or extra.get('source_id')} 的物理所在城市或园区。"
|
||||
)
|
||||
context_payload = {
|
||||
"name": query.name,
|
||||
"name_short": query.aliases[0] if query.aliases else query.name,
|
||||
"operator": extra.get("operator") or None,
|
||||
"site": extra.get("site") or None,
|
||||
"city": query.city,
|
||||
"country": query.country,
|
||||
"raw_country": extra.get("source_raw_country"),
|
||||
"primary_source_urls": source_urls[:5],
|
||||
}
|
||||
|
||||
messages: list[dict[str, Any]] = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
f"{user_objective}\n\n目标上下文 JSON:\n"
|
||||
f"{json.dumps(context_payload, ensure_ascii=False)}"
|
||||
),
|
||||
}
|
||||
]
|
||||
submitted_payload: dict[str, Any] | None = None
|
||||
last_text_response = ""
|
||||
steps_taken = 0
|
||||
|
||||
for step in range(1, max_steps + 1):
|
||||
steps_taken = step
|
||||
req = SituationalAnalysisRequest(
|
||||
title=f"Location agent step {step}",
|
||||
objective=user_objective,
|
||||
system_prompt=system_prompt,
|
||||
context=context_payload,
|
||||
preferred_model=(l2_node or {}).get("model_override"),
|
||||
messages=messages,
|
||||
tools=active_tools,
|
||||
tool_choice="auto" if step < max_steps else {"type": "function", "name": "submit_location_result"},
|
||||
native_web_search=bool((l2_node or {}).get("native_web_search", False)),
|
||||
)
|
||||
try:
|
||||
resp = await provider_client.analyze(req)
|
||||
except Exception as exc:
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=str(exc),
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=f"Location agent failed: {exc}",
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
last_text_response = str(getattr(resp, "content", "") or "")
|
||||
tool_calls = list(getattr(resp, "tool_calls", None) or [])
|
||||
if not tool_calls:
|
||||
# Provider returned plain text (no tool calling support); break cleanly into deterministic fallback.
|
||||
break
|
||||
|
||||
messages.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": last_text_response,
|
||||
"tool_calls": [
|
||||
{"id": tc.id, "name": tc.name, "arguments": tc.arguments}
|
||||
for tc in tool_calls
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
for tc in tool_calls:
|
||||
raw_args = tc.arguments
|
||||
if isinstance(raw_args, str):
|
||||
try:
|
||||
raw_args = json.loads(raw_args)
|
||||
except json.JSONDecodeError:
|
||||
raw_args = {}
|
||||
args = raw_args if isinstance(raw_args, dict) else {}
|
||||
tool_trace.append(f"l2_agent_research:{tc.name}")
|
||||
if tc.name == "fetch_source_url":
|
||||
target_url = coerce_str(args.get("url"))
|
||||
agent_attempts.append(f"fetch_url:{target_url}")
|
||||
try:
|
||||
fetched = await asyncio.wait_for(safe_web_fetch(target_url, timeout_seconds=8), timeout=10.0)
|
||||
final_url = (
|
||||
coerce_str(fetched.get("final_url") or fetched.get("url"))
|
||||
if isinstance(fetched, dict)
|
||||
else coerce_str(getattr(fetched, "final_url", None) or getattr(fetched, "url", None))
|
||||
) or target_url
|
||||
title = fetched.get("title", "") if isinstance(fetched, dict) else getattr(fetched, "title", "")
|
||||
text = fetched.get("content", "") if isinstance(fetched, dict) else getattr(fetched, "text", "")
|
||||
observed_urls.add(target_url)
|
||||
observed_urls.add(final_url)
|
||||
tool_output = isolate_untrusted_external_text(final_url, title, text, max_chars=2400)
|
||||
except Exception as exc:
|
||||
tool_output = {"error": f"fetch failed: {exc}", "url": target_url}
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps(tool_output, ensure_ascii=False),
|
||||
}
|
||||
)
|
||||
elif tc.name == "web_search":
|
||||
q_str = coerce_str(args.get("query"))
|
||||
agent_attempts.append(f"web_search:{q_str}")
|
||||
if web_search_client is None:
|
||||
tool_output = {"error": "WebSearch is not enabled or missing API key"}
|
||||
else:
|
||||
try:
|
||||
evidences = await web_search_client.search(q_str, max_results=5)
|
||||
items = []
|
||||
for ev in evidences:
|
||||
u = coerce_str(getattr(ev, "url", ""))
|
||||
if u:
|
||||
observed_urls.add(u)
|
||||
items.append(
|
||||
{
|
||||
"title": getattr(ev, "title", ""),
|
||||
"url": u,
|
||||
"snippet": getattr(ev, "snippet", "")[:400],
|
||||
}
|
||||
)
|
||||
tool_output = {"results": items}
|
||||
except Exception as exc:
|
||||
tool_output = {"error": str(exc)}
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps(tool_output, ensure_ascii=False),
|
||||
}
|
||||
)
|
||||
elif tc.name == "geocode_verify":
|
||||
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):
|
||||
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"))
|
||||
lon = parse_float(geo_res.get("lon") if geo_res.get("lon") is not None else geo_res.get("longitude"))
|
||||
addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {}
|
||||
res_country = normalize_country_text(addr.get("country") or geo_res.get("country"))
|
||||
if (
|
||||
lat in (None, 0.0)
|
||||
or lon in (None, 0.0)
|
||||
or not (-90.0 <= lat <= 90.0)
|
||||
or not (-180.0 <= lon <= 180.0)
|
||||
):
|
||||
tool_output = {"found": False, "reason": "Invalid geocoder coordinates"}
|
||||
elif expected_c and res_country and normalize_text(res_country) != normalize_text(expected_c):
|
||||
tool_output = {
|
||||
"found": False,
|
||||
"reason": f"Country mismatch: got {res_country}, expected {expected_c}",
|
||||
}
|
||||
else:
|
||||
cid = f"geo_{len(geocode_candidates) + 1}"
|
||||
geocode_candidates[cid] = {
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"display_name": coerce_str(geo_res.get("display_name")) or place_q,
|
||||
"city": coerce_str(
|
||||
addr.get("city")
|
||||
or addr.get("town")
|
||||
or addr.get("village")
|
||||
or addr.get("municipality")
|
||||
or geo_res.get("city")
|
||||
),
|
||||
"region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")),
|
||||
"country": res_country or expected_c or query.country,
|
||||
}
|
||||
tool_output = {"found": True, "geocode_candidate_id": cid, **geocode_candidates[cid]}
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps(tool_output, ensure_ascii=False),
|
||||
}
|
||||
)
|
||||
elif tc.name == "submit_location_result":
|
||||
submitted_payload = dict(args)
|
||||
tool_trace.append("l3_geo_guardrail")
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps({"accepted": True}),
|
||||
}
|
||||
)
|
||||
if submitted_payload is not None:
|
||||
break
|
||||
|
||||
if submitted_payload is None:
|
||||
# Fallback for providers/mocks without tool_calls support
|
||||
evidence_list = []
|
||||
if web_search_client is not None:
|
||||
from app.services.location.llm_fallback import collect_location_search_evidence
|
||||
|
||||
search_res = await collect_location_search_evidence(
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type=entity_type,
|
||||
)
|
||||
agent_attempts.extend(search_res.attempted_queries)
|
||||
evidence_list = search_res.evidence
|
||||
if evidence_list or last_text_response:
|
||||
fallback_res = await collect_llm_location_fallback_candidate(
|
||||
provider_client=provider_client,
|
||||
query=query,
|
||||
entity_type=entity_type,
|
||||
db=db,
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
search_evidence=evidence_list,
|
||||
min_confidence=min_confidence,
|
||||
)
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="completed" if fallback_res.candidates else "failed",
|
||||
tool_trace=[*tool_trace, "llm_fallback"],
|
||||
steps_used=steps_taken,
|
||||
error_message=fallback_res.failure_reason or "",
|
||||
)
|
||||
return fallback_res, None
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message="Agent did not submit location result",
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason="Location agent reached step budget without submitting a verified location.",
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
sub_status = str(submitted_payload.get("status") or "unresolved").strip().lower()
|
||||
reasoning = coerce_str(submitted_payload.get("reasoning"))
|
||||
if sub_status in TERMINAL_UNLOCATABLE_STATUSES:
|
||||
await _persist_terminal_location_status(
|
||||
db,
|
||||
query=query,
|
||||
terminal_status=sub_status,
|
||||
reasoning=reasoning,
|
||||
)
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="completed",
|
||||
tool_trace=[*tool_trace, f"l4_persist_outcome:{sub_status}"],
|
||||
steps_used=steps_taken,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reasoning or f"Facility confirmed as {sub_status}.",
|
||||
),
|
||||
sub_status,
|
||||
)
|
||||
|
||||
geo_cid = coerce_str(submitted_payload.get("geocode_candidate_id"))
|
||||
geo_entry = geocode_candidates.get(geo_cid)
|
||||
if sub_status != "located" or geo_entry is None:
|
||||
reason = reasoning or "Submitted result missing verified geocode_candidate_id"
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=reason,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reason,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
citations = [
|
||||
str(c).strip()
|
||||
for c in (submitted_payload.get("citations") or [])
|
||||
if str(c or "").strip()
|
||||
]
|
||||
verified_citations = [c for c in citations if c in observed_urls]
|
||||
if require_tool_urls and not verified_citations:
|
||||
reason = "No verified citation URLs observed in tool outputs"
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=reason,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reason,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
expected_country = normalize_country_text(query.country)
|
||||
resolved_country = normalize_country_text(submitted_payload.get("country") or geo_entry.get("country"))
|
||||
if expected_country and resolved_country and normalize_text(resolved_country) != normalize_text(expected_country):
|
||||
reason = f"Country mismatch ({resolved_country} != {expected_country})"
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=reason,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reason,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
confidence = min(max(parse_float(submitted_payload.get("confidence")) or 0.78, 0.0), 1.0)
|
||||
raw_precision = coerce_str(submitted_payload.get("precision")).lower()
|
||||
precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city"
|
||||
facility_label = coerce_str(submitted_payload.get("facility_name")) or coerce_str(geo_entry.get("display_name")) or coerce_str(query.name)
|
||||
candidate = LocationCandidate(
|
||||
latitude=float(geo_entry["latitude"]),
|
||||
longitude=float(geo_entry["longitude"]),
|
||||
display_name=facility_label,
|
||||
precision=precision,
|
||||
confidence=max(confidence, min_confidence),
|
||||
query=f"location_agent:{entity_type}:{query.name or extra.get('source_id') or 'unknown'}",
|
||||
source="llm_location_factcheck",
|
||||
source_note=reasoning or f"Verified via tool-calling agent ({len(verified_citations)} citations)",
|
||||
matched_fields=("name", "tool_calling_agent"),
|
||||
needs_confirmation=True,
|
||||
city=coerce_str(submitted_payload.get("city")) or geo_entry.get("city") or query.city or None,
|
||||
region=coerce_str(submitted_payload.get("region")) or geo_entry.get("region") or query.region or None,
|
||||
country=resolved_country or expected_country or query.country,
|
||||
matched_location_name=facility_label,
|
||||
raw_payload={"citations": verified_citations or citations, "geocode_candidate_id": geo_cid},
|
||||
)
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="completed",
|
||||
tool_trace=[*tool_trace, "l4_persist_outcome:located"],
|
||||
steps_used=steps_taken,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[candidate],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=None,
|
||||
),
|
||||
None,
|
||||
)
|
||||
@@ -266,7 +266,14 @@ def _detect_country_in_text(text: str) -> str:
|
||||
variants = [canonical, *aliases]
|
||||
for variant in variants:
|
||||
normalized_variant = normalize_text(variant)
|
||||
if normalized_variant and normalized_variant in normalized_text:
|
||||
if not normalized_variant:
|
||||
continue
|
||||
if normalized_variant.isascii():
|
||||
if len(normalized_variant) < 4:
|
||||
continue
|
||||
if re.search(rf"\b{re.escape(normalized_variant)}\b", normalized_text):
|
||||
return canonical
|
||||
elif normalized_variant in normalized_text:
|
||||
return canonical
|
||||
return ""
|
||||
|
||||
@@ -488,6 +495,7 @@ def _fill_city_coordinates_from_geocoder(
|
||||
|
||||
if not geocode_queries:
|
||||
return payload, None
|
||||
expected_country = normalize_text(normalize_country_text(country or query.country))
|
||||
failures: list[str] = []
|
||||
geocode_query = ""
|
||||
result: dict[str, Any] | None = None
|
||||
@@ -503,9 +511,19 @@ def _fill_city_coordinates_from_geocoder(
|
||||
continue
|
||||
latitude = parse_float(maybe_result.get("lat"))
|
||||
longitude = parse_float(maybe_result.get("lon"))
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
if (
|
||||
latitude in (None, 0.0)
|
||||
or longitude in (None, 0.0)
|
||||
or not (-90.0 <= latitude <= 90.0)
|
||||
or not (-180.0 <= longitude <= 180.0)
|
||||
):
|
||||
failures.append(f"{geocode_query}: invalid coordinates")
|
||||
continue
|
||||
cand_addr = maybe_result.get("address") if isinstance(maybe_result.get("address"), dict) else {}
|
||||
cand_country = normalize_text(normalize_country_text(cand_addr.get("country")))
|
||||
if expected_country and cand_country and cand_country != expected_country:
|
||||
failures.append(f"{geocode_query}: country mismatch ({cand_country} != {expected_country})")
|
||||
continue
|
||||
result = maybe_result
|
||||
break
|
||||
if result is None:
|
||||
@@ -514,7 +532,12 @@ def _fill_city_coordinates_from_geocoder(
|
||||
|
||||
latitude = parse_float(result.get("lat"))
|
||||
longitude = parse_float(result.get("lon"))
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
if (
|
||||
latitude in (None, 0.0)
|
||||
or longitude in (None, 0.0)
|
||||
or not (-90.0 <= latitude <= 90.0)
|
||||
or not (-180.0 <= longitude <= 180.0)
|
||||
):
|
||||
return payload, f"city geocode fallback returned invalid coordinates for '{geocode_query}'"
|
||||
address = result.get("address") if isinstance(result.get("address"), dict) else {}
|
||||
city = (
|
||||
@@ -527,9 +550,11 @@ def _fill_city_coordinates_from_geocoder(
|
||||
)
|
||||
country = country or address.get("country")
|
||||
try:
|
||||
precision = _normalize_llm_precision(payload.get("precision")) or "city"
|
||||
raw_precision = _normalize_llm_precision(payload.get("precision")) or "city"
|
||||
except Exception:
|
||||
precision = "city"
|
||||
raw_precision = "city"
|
||||
# City-level geocoder fallback must never keep inflated site/precise claims.
|
||||
precision = "city" if raw_precision in {"precise", "site", "city"} else raw_precision
|
||||
filled = {
|
||||
**payload,
|
||||
"latitude": latitude,
|
||||
@@ -665,7 +690,15 @@ def _ambiguity_text(payload: dict[str, Any], evidence_items: list[dict[str, Any]
|
||||
def _conflict_penalty(payload: dict[str, Any], evidence_items: list[dict[str, Any]]) -> float:
|
||||
penalty = 0.0
|
||||
ambiguity_text = _ambiguity_text(payload, evidence_items)
|
||||
if any(token in ambiguity_text for token in ("conflict", "contradict", "inconsistent")):
|
||||
cleaned_text = re.sub(
|
||||
r"\b(?:no|without|not|zero)\s+(?:conflict|contradiction|ambiguity)s?\b|无冲突|未见矛盾",
|
||||
" ",
|
||||
ambiguity_text,
|
||||
)
|
||||
if any(
|
||||
token in cleaned_text
|
||||
for token in ("conflict", "contradict", "inconsistent", "冲突", "矛盾", "不一致")
|
||||
):
|
||||
penalty += 0.35
|
||||
if any(
|
||||
_truthy_evidence_field(item, "has_conflict", "conflicting")
|
||||
@@ -685,8 +718,12 @@ def _weak_evidence_penalty(
|
||||
conflict_penalty: float,
|
||||
) -> float:
|
||||
ambiguity_text = _ambiguity_text(payload, evidence_items)
|
||||
cleaned_text = re.sub(r"\b(?:no|without|not)\s+ambiguity\b|无歧义", " ", ambiguity_text)
|
||||
penalty = 0.0
|
||||
if any(token in ambiguity_text for token in ("ambiguous", "unclear", "weak", "guess")):
|
||||
if any(
|
||||
token in cleaned_text
|
||||
for token in ("ambiguous", "unclear", "weak", "guess", "存疑", "不确定", "猜测", "无法确认")
|
||||
):
|
||||
penalty += 0.20
|
||||
if any(_truthy_evidence_field(item, "ambiguous") for item in evidence_items):
|
||||
penalty += 0.15
|
||||
@@ -762,7 +799,12 @@ def _candidate_from_payload(
|
||||
min_confidence: float,
|
||||
) -> tuple[LocationCandidate | None, str | None]:
|
||||
latitude, longitude = _extract_llm_coordinates(payload)
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
if (
|
||||
latitude in (None, 0.0)
|
||||
or longitude in (None, 0.0)
|
||||
or not (-90.0 <= latitude <= 90.0)
|
||||
or not (-180.0 <= longitude <= 180.0)
|
||||
):
|
||||
return None, "missing, invalid, or zero latitude/longitude"
|
||||
|
||||
precision = _normalize_llm_precision(payload.get("precision"))
|
||||
@@ -770,11 +812,11 @@ def _candidate_from_payload(
|
||||
return None, f"precision '{payload.get('precision')}' is not precise/site/city"
|
||||
|
||||
city = coerce_str(payload.get("city")) or query.city or None
|
||||
country = (
|
||||
normalize_country_text(payload.get("country"))
|
||||
or normalize_country_text(query.country)
|
||||
or query.country
|
||||
)
|
||||
payload_country = normalize_country_text(payload.get("country"))
|
||||
expected_country = normalize_country_text(query.country)
|
||||
if payload_country and expected_country and normalize_text(payload_country) != normalize_text(expected_country):
|
||||
return None, f"country '{payload_country}' contradicts expected '{expected_country}'"
|
||||
country = payload_country or expected_country or query.country
|
||||
evidence_score = _score_llm_location_payload(payload, query=query, precision=precision)
|
||||
if evidence_score.score < min_confidence:
|
||||
return None, (
|
||||
@@ -1230,20 +1272,25 @@ async def collect_llm_location_fallback_candidate(
|
||||
if search_evidence:
|
||||
payload["search_evidence"] = search_evidence
|
||||
existing_evidence = _evidence_items(payload.get("evidence"))
|
||||
payload["evidence"] = [
|
||||
*existing_evidence,
|
||||
*[
|
||||
{
|
||||
"source": item.get("title") or item.get("url"),
|
||||
"url": item.get("url"),
|
||||
"text": item.get("snippet") or item.get("content"),
|
||||
"source_type": "web_search",
|
||||
"entity_match": _search_evidence_entity_match(item, query),
|
||||
}
|
||||
for item in search_evidence
|
||||
if isinstance(item, dict)
|
||||
],
|
||||
]
|
||||
search_by_url = {
|
||||
str(item.get("url")).strip(): item
|
||||
for item in search_evidence
|
||||
if isinstance(item, dict) and item.get("url")
|
||||
}
|
||||
enriched_evidence = []
|
||||
for item in existing_evidence:
|
||||
url = coerce_str(item.get("url"))
|
||||
matched_search = search_by_url.get(url)
|
||||
if matched_search is not None:
|
||||
enriched_evidence.append(
|
||||
{
|
||||
**item,
|
||||
"entity_match": item.get("entity_match") or _search_evidence_entity_match(matched_search, query),
|
||||
}
|
||||
)
|
||||
else:
|
||||
enriched_evidence.append(item)
|
||||
payload["evidence"] = enriched_evidence
|
||||
latitude, longitude = _extract_llm_coordinates(payload)
|
||||
city_geocode_failure = None
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""PeeringDB Facility (/api/fac) resolver for commercial datacenter compute sites."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..models import LocationCandidate, LocationQuery, ResolverOutput
|
||||
from ..text import coerce_str, normalize_country_text, normalize_text, parse_float
|
||||
|
||||
PEERINGDB_FAC_URL = "https://www.peeringdb.com/api/fac"
|
||||
PEERINGDB_USER_AGENT = "Planet-Intelligence-System/1.0"
|
||||
PEERINGDB_TIMEOUT_SECONDS = 6.0
|
||||
|
||||
|
||||
async def lookup_peeringdb_facility(
|
||||
query: LocationQuery,
|
||||
*,
|
||||
timeout_seconds: float = PEERINGDB_TIMEOUT_SECONDS,
|
||||
) -> ResolverOutput:
|
||||
"""Query PeeringDB facilities matching the target site/operator/name."""
|
||||
extra = query.extra or {}
|
||||
search_terms: list[str] = []
|
||||
for raw in [
|
||||
extra.get("site"),
|
||||
extra.get("operator"),
|
||||
*(query.aliases or ()),
|
||||
query.name,
|
||||
]:
|
||||
cleaned = coerce_str(raw)
|
||||
if cleaned and len(cleaned) >= 3 and cleaned not in search_terms:
|
||||
search_terms.append(cleaned)
|
||||
if not search_terms:
|
||||
return ResolverOutput()
|
||||
|
||||
attempted: list[str] = []
|
||||
candidates: list[LocationCandidate] = []
|
||||
expected_country = normalize_text(normalize_country_text(query.country))
|
||||
headers = {"User-Agent": PEERINGDB_USER_AGENT, "Accept": "application/json"}
|
||||
api_key = os.environ.get("PEERINGDB_API_KEY", "").strip()
|
||||
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
|
||||
for term in search_terms[:2]:
|
||||
attempted.append(f"peeringdb_fac:{term}")
|
||||
params: dict[str, Any] = {"name__icontains": term, "limit": 4}
|
||||
if api_key:
|
||||
params["key"] = api_key
|
||||
try:
|
||||
resp = await client.get(PEERINGDB_FAC_URL, params=params)
|
||||
resp.raise_for_status()
|
||||
rows = (resp.json() or {}).get("data") or []
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
term_norm = normalize_text(term)
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
lat = parse_float(item.get("latitude"))
|
||||
lon = parse_float(item.get("longitude"))
|
||||
if (
|
||||
lat in (None, 0.0)
|
||||
or lon in (None, 0.0)
|
||||
or not (-90.0 <= lat <= 90.0)
|
||||
or not (-180.0 <= lon <= 180.0)
|
||||
):
|
||||
continue
|
||||
item_country = normalize_country_text(item.get("country"))
|
||||
if expected_country and item_country and normalize_text(item_country) != expected_country:
|
||||
continue
|
||||
fac_name = coerce_str(item.get("name")) or term
|
||||
if term_norm and term_norm not in normalize_text(fac_name):
|
||||
# Require meaningful overlap when fuzzy matched
|
||||
fac_tokens = set(normalize_text(fac_name).split())
|
||||
if not (set(term_norm.split()) & fac_tokens):
|
||||
continue
|
||||
city = coerce_str(item.get("city")) or None
|
||||
addr = coerce_str(item.get("address1"))
|
||||
candidates.append(
|
||||
LocationCandidate(
|
||||
latitude=lat,
|
||||
longitude=lon,
|
||||
display_name=fac_name,
|
||||
precision="precise" if addr else "site",
|
||||
confidence=0.80,
|
||||
query=f"peeringdb_fac:{term}",
|
||||
source="peeringdb_facility",
|
||||
source_note=f"PeeringDB facility #{item.get('id')}: {fac_name}" + (f" ({addr})" if addr else ""),
|
||||
matched_fields=("site", "peeringdb"),
|
||||
needs_confirmation=True,
|
||||
city=city,
|
||||
region=coerce_str(item.get("state")) or None,
|
||||
country=item_country or query.country,
|
||||
matched_location_name=fac_name,
|
||||
raw_payload={"peeringdb_fac_id": item.get("id"), "address": addr},
|
||||
)
|
||||
)
|
||||
|
||||
return ResolverOutput(candidates=tuple(candidates), attempted_queries=tuple(attempted))
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Wikidata structured entity lookup for compute-center / facility coordinates (P625 / P276)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..models import LocationCandidate, LocationQuery, ResolverOutput
|
||||
from ..text import coerce_str, normalize_country_text, normalize_text, parse_float
|
||||
|
||||
WIKIDATA_API_URL = "https://www.wikidata.org/w/api.php"
|
||||
WIKIDATA_USER_AGENT = "planet-earth-location-resolver/1.0"
|
||||
WIKIDATA_TIMEOUT_SECONDS = 6.0
|
||||
|
||||
|
||||
async def lookup_wikidata_facility(
|
||||
query: LocationQuery,
|
||||
*,
|
||||
timeout_seconds: float = WIKIDATA_TIMEOUT_SECONDS,
|
||||
) -> ResolverOutput:
|
||||
"""Query Wikidata entities for facility-level P625 coordinate claims."""
|
||||
extra = query.extra or {}
|
||||
terms: list[str] = []
|
||||
for raw in [
|
||||
*(query.aliases or ()),
|
||||
query.name,
|
||||
extra.get("site"),
|
||||
]:
|
||||
cleaned = coerce_str(raw)
|
||||
if cleaned and cleaned not in terms:
|
||||
terms.append(cleaned)
|
||||
if not terms:
|
||||
return ResolverOutput()
|
||||
|
||||
attempted: list[str] = []
|
||||
candidates: list[LocationCandidate] = []
|
||||
seen_qids: set[str] = set()
|
||||
headers = {"User-Agent": WIKIDATA_USER_AGENT, "Accept": "application/json"}
|
||||
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
|
||||
for term in terms[:2]:
|
||||
attempted.append(f"wikidata:{term}")
|
||||
try:
|
||||
search_resp = await client.get(
|
||||
WIKIDATA_API_URL,
|
||||
params={
|
||||
"action": "wbsearchentities",
|
||||
"search": term,
|
||||
"language": "en",
|
||||
"format": "json",
|
||||
"limit": 4,
|
||||
},
|
||||
)
|
||||
search_resp.raise_for_status()
|
||||
search_items = (search_resp.json() or {}).get("search") or []
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
qids = [
|
||||
str(item.get("id"))
|
||||
for item in search_items
|
||||
if isinstance(item, dict) and item.get("id") and item.get("id") not in seen_qids
|
||||
]
|
||||
if not qids:
|
||||
continue
|
||||
seen_qids.update(qids)
|
||||
try:
|
||||
ent_resp = await client.get(
|
||||
WIKIDATA_API_URL,
|
||||
params={
|
||||
"action": "wbgetentities",
|
||||
"ids": "|".join(qids[:4]),
|
||||
"props": "labels|descriptions|claims",
|
||||
"languages": "en|zh",
|
||||
"format": "json",
|
||||
},
|
||||
)
|
||||
ent_resp.raise_for_status()
|
||||
entities = (ent_resp.json() or {}).get("entities") or {}
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
term_tokens = set(normalize_text(term).split())
|
||||
for qid, entity in entities.items():
|
||||
if not isinstance(entity, dict):
|
||||
continue
|
||||
labels = entity.get("labels") or {}
|
||||
label = coerce_str((labels.get("en") or {}).get("value") or (labels.get("zh") or {}).get("value"))
|
||||
desc = coerce_str(((entity.get("descriptions") or {}).get("en") or {}).get("value")).lower()
|
||||
if label:
|
||||
label_tokens = set(normalize_text(label).split())
|
||||
if term_tokens and not (term_tokens & label_tokens):
|
||||
continue
|
||||
if desc and not any(
|
||||
kw in desc
|
||||
for kw in ("supercomputer", "data center", "datacenter", "computer", "cluster", "laboratory", "facility", "campus")
|
||||
):
|
||||
continue
|
||||
|
||||
claims = entity.get("claims") or {}
|
||||
coord_claims = claims.get("P625") or []
|
||||
for claim in coord_claims:
|
||||
mainsnak = claim.get("mainsnak") if isinstance(claim, dict) else None
|
||||
datavalue = (mainsnak or {}).get("datavalue") or {}
|
||||
val = datavalue.get("value") if isinstance(datavalue, dict) else None
|
||||
if not isinstance(val, dict):
|
||||
continue
|
||||
lat = parse_float(val.get("latitude"))
|
||||
lon = parse_float(val.get("longitude"))
|
||||
if (
|
||||
lat in (None, 0.0)
|
||||
or lon in (None, 0.0)
|
||||
or not (-90.0 <= lat <= 90.0)
|
||||
or not (-180.0 <= lon <= 180.0)
|
||||
):
|
||||
continue
|
||||
country = normalize_country_text(query.country)
|
||||
candidates.append(
|
||||
LocationCandidate(
|
||||
latitude=lat,
|
||||
longitude=lon,
|
||||
display_name=label or term,
|
||||
precision="site",
|
||||
confidence=0.84,
|
||||
query=f"wikidata:{term}",
|
||||
source="wikidata_facility",
|
||||
source_note=f"Wikidata entity {qid} P625 coordinates ({desc or label})",
|
||||
matched_fields=("name", "wikidata"),
|
||||
needs_confirmation=True,
|
||||
city=query.city or None,
|
||||
country=country or query.country,
|
||||
matched_location_name=label or term,
|
||||
raw_payload={"wikidata_qid": qid, "description": desc},
|
||||
)
|
||||
)
|
||||
break
|
||||
|
||||
return ResolverOutput(candidates=tuple(candidates), attempted_queries=tuple(attempted))
|
||||
@@ -0,0 +1,279 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.api.v1 import situational_awareness
|
||||
from app.schemas.ai import SituationalAnalysisResponse
|
||||
from app.services.ai import spatial_domain_agent
|
||||
from app.services.ai.stream_turn import reset_stream_quota_ledger
|
||||
from app.services.ai_client import AIProviderClient, get_ai_provider_client
|
||||
|
||||
|
||||
def _parse_sse_text(raw: str) -> list[tuple[str, dict]]:
|
||||
events: list[tuple[str, dict]] = []
|
||||
for block in raw.replace("\r\n", "\n").split("\n\n"):
|
||||
if not block.strip():
|
||||
continue
|
||||
ev_name = "message"
|
||||
data_lines: list[str] = []
|
||||
for line in block.split("\n"):
|
||||
if line.startswith("event:"):
|
||||
ev_name = line[6:].strip()
|
||||
elif line.startswith("data:"):
|
||||
data_lines.append(line[5:].lstrip())
|
||||
if data_lines:
|
||||
events.append((ev_name, json.loads("\n".join(data_lines))))
|
||||
return events
|
||||
|
||||
|
||||
class _StubDb:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spatial_domain_agent_reads_content_attribute(monkeypatch):
|
||||
class _FakeClient:
|
||||
service_url = "http://aiprovider.test"
|
||||
llm_config = {"provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
|
||||
async def analyze(self, _req):
|
||||
return SituationalAnalysisResponse(
|
||||
provider="minimax",
|
||||
model="MiniMax-M2.7",
|
||||
content=json.dumps(
|
||||
{
|
||||
"domain": "global",
|
||||
"subject_key": "global:test",
|
||||
"title": "全球多图层态势",
|
||||
"executive_assertion": "已成功读取大模型合成内容。",
|
||||
"confirmed_facts": [{"statement": "全网多图层数据在线。", "evidence_ids": ["ev-global-1"]}],
|
||||
"analytical_notes": [{"statement": "LLM 输出字段匹配成功。", "evidence_ids": ["ev-global-1"]}],
|
||||
"open_gaps": ["示例口径边界。"],
|
||||
"evidence_ids": ["ev-global-1"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "global",
|
||||
"available": True,
|
||||
"domain_summaries": [],
|
||||
"bgp_summary": {"active_count": 0},
|
||||
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Snapshot"}},
|
||||
"limitations": [],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(spatial_domain_agent, "query_global_situational_tool", fake_global_tool)
|
||||
|
||||
result = await spatial_domain_agent.investigate_spatial_domain(
|
||||
_StubDb(),
|
||||
domain="global",
|
||||
question="分析全球态势",
|
||||
persist=False,
|
||||
ai_client=_FakeClient(),
|
||||
)
|
||||
|
||||
assert result["generation_mode"] == "llm_verified"
|
||||
assert result["payload"]["executive_assertion"] == "已成功读取大模型合成内容。"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_turn_adapts_between_configured_minimax_and_disabled_ai(monkeypatch):
|
||||
reset_stream_quota_ledger()
|
||||
|
||||
async def fake_recent_news(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "news",
|
||||
"available": True,
|
||||
"count": 1,
|
||||
"items": [{"id": "n1", "title": "全球海缆路由测试头条", "source": "Reuters", "region": "global"}],
|
||||
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Planet News"}},
|
||||
}
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "global",
|
||||
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
||||
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
||||
|
||||
class _ConfiguredClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "secret-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
},
|
||||
)
|
||||
|
||||
async def stream_analyze(self, payload, request_id=None):
|
||||
assert payload.thinking == {"type": "enabled", "budget_tokens": 2048}
|
||||
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
yield {"event": "reasoning", "delta": "先梳理新闻核心矛盾。"}
|
||||
yield {"event": "text", "delta": "### 新闻深度分析\n\n- **要点**:供应链与光缆关注升温。"}
|
||||
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 42}}
|
||||
|
||||
class _DisabledClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={"provider": "disabled"},
|
||||
)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
||||
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _ConfiguredClient()
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
# 1. Anonymous Earth/desktop caller uses MiniMax automatically when configured
|
||||
res_ai = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
||||
"domain": "news",
|
||||
"news_context": {
|
||||
"id": "n1",
|
||||
"title": "全球海缆路由测试头条",
|
||||
"summary": "测试新闻摘要",
|
||||
"source": "Reuters",
|
||||
"region": "全球",
|
||||
},
|
||||
},
|
||||
)
|
||||
assert res_ai.status_code == 200
|
||||
assert "text/event-stream" in res_ai.headers["content-type"]
|
||||
ai_events = _parse_sse_text(res_ai.text)
|
||||
ai_names = [name for name, _ in ai_events]
|
||||
assert ai_names == ["meta", "reasoning", "text", "done"]
|
||||
assert ai_events[0][1]["ai_enabled"] is True
|
||||
assert ai_events[0][1]["model"] == "MiniMax-M2.7"
|
||||
assert ai_events[1][1]["delta"] == "先梳理新闻核心矛盾。"
|
||||
assert "新闻深度分析" in ai_events[2][1]["delta"]
|
||||
assert ai_events[3][1]["zero_token"] is False
|
||||
assert ai_events[3][1]["generation_mode"] == "llm_verified"
|
||||
assert ai_events[3][1]["model"] == "MiniMax-M2.7"
|
||||
|
||||
# 2. Switching provider to disabled adapts seamlessly back to deterministic baseline
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _DisabledClient()
|
||||
res_no_ai = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
||||
"domain": "news",
|
||||
"news_context": {"id": "n1", "title": "全球海缆路由测试头条", "summary": "测试新闻摘要"},
|
||||
},
|
||||
)
|
||||
assert res_no_ai.status_code == 200
|
||||
no_ai_events = _parse_sse_text(res_no_ai.text)
|
||||
assert no_ai_events[0][1]["ai_enabled"] is False
|
||||
assert no_ai_events[0][1]["model"] is None
|
||||
assert no_ai_events[-1][0] == "done"
|
||||
assert no_ai_events[-1][1]["zero_token"] is True
|
||||
assert no_ai_events[-1][1]["model"] is None
|
||||
assert no_ai_events[-1][1]["generation_mode"] == "deterministic_baseline"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
|
||||
reset_stream_quota_ledger()
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "global",
|
||||
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
||||
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
||||
}
|
||||
|
||||
async def fake_recent_news(*_args, **_kwargs):
|
||||
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
|
||||
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
||||
|
||||
captured_analyze_reqs = []
|
||||
captured_stream_reqs = []
|
||||
|
||||
class _CompactingClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "secret-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
},
|
||||
)
|
||||
|
||||
async def analyze(self, payload, request_id=None):
|
||||
captured_analyze_reqs.append(payload)
|
||||
return SituationalAnalysisResponse(
|
||||
provider="minimax",
|
||||
model="MiniMax-M2.7",
|
||||
content="<think>internal</think>前序关注中美算力与亚太海缆冗余,已核验 343 条骨干海缆。",
|
||||
)
|
||||
|
||||
async def stream_analyze(self, payload, request_id=None):
|
||||
captured_stream_reqs.append(payload)
|
||||
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
yield {"event": "text", "delta": "结合前文 343 条海缆与您的亚太聚焦偏好,补充说明如下。"}
|
||||
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 55}}
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
||||
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _CompactingClient()
|
||||
|
||||
long_history = []
|
||||
for idx in range(1, 7):
|
||||
long_history.append({"role": "user", "content": f"第 {idx} 轮提问"})
|
||||
long_history.append({"role": "assistant", "content": f"<think>thought-{idx}</think>第 {idx} 轮结论"})
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
res = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "基于前面总结继续追问亚太海缆脆弱点",
|
||||
"domain": "global",
|
||||
"history": long_history,
|
||||
"memory_notes": ["优先给出亚太海缆冗余与算力口径边界"],
|
||||
"pinned_summaries": ["GLOBAL · Rev.1: 全球综合态势"],
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
events = _parse_sse_text(res.text)
|
||||
meta_ev = events[0][1]
|
||||
done_ev = events[-1][1]
|
||||
|
||||
assert meta_ev["compacted"] is True
|
||||
assert "343 条骨干海缆" in meta_ev["conversation_summary"]
|
||||
assert "<think>" not in meta_ev["conversation_summary"]
|
||||
assert meta_ev["memory_used"] is True
|
||||
assert done_ev["compacted"] is True
|
||||
assert done_ev["conversation_summary"] == meta_ev["conversation_summary"]
|
||||
|
||||
assert len(captured_analyze_reqs) == 1
|
||||
assert len(captured_stream_reqs) == 1
|
||||
sent_payload = captured_stream_reqs[0]
|
||||
# Recent window preserves latest 4 turns (8 messages), with <think> stripped
|
||||
assert len(sent_payload.messages) == 8
|
||||
assert sent_payload.messages[0].content == "第 3 轮提问"
|
||||
assert sent_payload.messages[1].content == "第 3 轮结论"
|
||||
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
|
||||
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
|
||||
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Tests for Admin AI Advisor workflows, versioning, fixtures, optimization diff, and Playground SSE."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.ai_tasks.prompts import get_effective_prompt
|
||||
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.situational_assessment import WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS
|
||||
|
||||
|
||||
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():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
AIWorkflow.__table__,
|
||||
AIWorkflowRevision.__table__,
|
||||
AIWorkflowFixture.__table__,
|
||||
WorkflowRun.__table__,
|
||||
SystemSetting.__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_ai_workflows_seed_draft_publish_rollback_and_fixtures(monkeypatch):
|
||||
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:
|
||||
list_resp = await client.get("/api/v1/ai/workflows")
|
||||
assert list_resp.status_code == 200
|
||||
body = list_resp.json()
|
||||
assert body["total"] == len(BUILTIN_WORKFLOWS)
|
||||
ids = {item["workflow_id"] for item in body["items"]}
|
||||
assert "default.general" in ids
|
||||
assert "location.resolve_unknown" in ids
|
||||
assert "earth.news.analysis" in ids
|
||||
assert any(item["is_default"] for item in body["items"])
|
||||
|
||||
detail_resp = await client.get("/api/v1/ai/workflows/earth.news.analysis")
|
||||
assert detail_resp.status_code == 200
|
||||
detail = detail_resp.json()
|
||||
assert len(detail["tool_catalog"]) >= 10
|
||||
graph = detail["workflow"]["published_graph"]
|
||||
target_node = next(n for n in graph["nodes"] if n.get("prompt_key") == "earth.news.analysis")
|
||||
target_node["system_prompt"] = "自定义新闻参谋系统提示词"
|
||||
target_node["tools"] = ["query_recent_earth_news", "invalid_unknown_tool"]
|
||||
|
||||
draft_resp = await client.put(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/draft",
|
||||
json={"graph": graph},
|
||||
)
|
||||
assert draft_resp.status_code == 200
|
||||
draft_body = draft_resp.json()
|
||||
assert draft_body["has_draft"] is True
|
||||
draft_node = next(
|
||||
n for n in draft_body["draft_graph"]["nodes"] if n["id"] == target_node["id"]
|
||||
)
|
||||
# Invalid tool id must be stripped cleanly by whitelist validation
|
||||
assert draft_node["tools"] == ["query_recent_earth_news"]
|
||||
|
||||
pub_resp = await client.post(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/publish",
|
||||
json={"change_summary": "Enable custom news system prompt"},
|
||||
)
|
||||
assert pub_resp.status_code == 200
|
||||
pub_body = pub_resp.json()
|
||||
assert pub_body["active_revision"] == 2
|
||||
assert pub_body["has_draft"] is False
|
||||
|
||||
# Runtime effective prompt must pick up the published workflow node prompt
|
||||
async with factory() as session:
|
||||
eff = await get_effective_prompt(session, "earth.news.analysis")
|
||||
assert eff.system_prompt == "自定义新闻参谋系统提示词"
|
||||
|
||||
# Rollback back to v1 -> creates v3 with v1 graph
|
||||
rb_resp = await client.post(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/rollback",
|
||||
json={"revision": 1},
|
||||
)
|
||||
assert rb_resp.status_code == 200
|
||||
assert rb_resp.json()["active_revision"] == 3
|
||||
|
||||
# Explicit fixture create + delete
|
||||
fix_resp = await client.post(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/fixtures",
|
||||
json={
|
||||
"name": "Red Sea Cable News Sample",
|
||||
"description": "Anonymized local Earth context export",
|
||||
"earth_context": {"schema": "planet.earth_context.v1", "selected": {"id": "news-1"}},
|
||||
"sample_question": "分析影响",
|
||||
},
|
||||
)
|
||||
assert fix_resp.status_code == 200
|
||||
fixture_id = fix_resp.json()["id"]
|
||||
del_resp = await client.delete(
|
||||
f"/api/v1/ai/workflows/earth.news.analysis/fixtures/{fixture_id}"
|
||||
)
|
||||
assert del_resp.status_code == 200
|
||||
assert del_resp.json()["deleted"] is True
|
||||
finally:
|
||||
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()
|
||||
|
||||
class _FakeAIClient:
|
||||
async def is_ready(self):
|
||||
return True, "openai", "gpt-test"
|
||||
|
||||
async def analyze(self, _req):
|
||||
return SimpleNamespace(
|
||||
content=json.dumps(
|
||||
{
|
||||
"summary": "Add fetch tool & block bad tool",
|
||||
"node_patches": [
|
||||
{
|
||||
"node_id": "l2_agent_research",
|
||||
"field": "tools",
|
||||
"after": ["fetch_source_url", "evil_rm_rf_tool"],
|
||||
"reason": "Keep only whitelisted tool",
|
||||
},
|
||||
{
|
||||
"node_id": "l2_agent_research",
|
||||
"field": "max_steps",
|
||||
"after": 5,
|
||||
"reason": "Allow 5 steps",
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
async def stream_analyze(self, _req, request_id=None):
|
||||
yield {"event": "reasoning", "delta": "Checking local earth context..."}
|
||||
yield {"event": "text", "delta": "已结合地球本地上下文完成分析。"}
|
||||
|
||||
from app.api.v1 import ai_workflows as ai_workflows_api
|
||||
|
||||
async def _fake_get_ai_client(_db):
|
||||
return _FakeAIClient()
|
||||
|
||||
monkeypatch.setattr(ai_workflows_api, "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:
|
||||
opt_resp = await client.post(
|
||||
"/api/v1/ai/workflows/location.resolve_unknown/optimize",
|
||||
json={"instruction": "允许抓取一手页面并屏蔽非法工具"},
|
||||
)
|
||||
assert opt_resp.status_code == 200
|
||||
opt_body = opt_resp.json()
|
||||
assert opt_body["base_revision"] == 1
|
||||
tools_patch = next(c for c in opt_body["changes"] if c["field"] == "tools")
|
||||
assert tools_patch["after"] == ["fetch_source_url"]
|
||||
assert "evil_rm_rf_tool" not in tools_patch["after"]
|
||||
|
||||
# Live workflow must remain untouched (no draft, revision=1) until admin clicks Apply
|
||||
detail = (await client.get("/api/v1/ai/workflows/location.resolve_unknown")).json()
|
||||
assert detail["workflow"]["has_draft"] is False
|
||||
assert detail["workflow"]["active_revision"] == 1
|
||||
|
||||
# Stream Playground chat with portable planet.earth_context.v1
|
||||
sse_resp = await client.post(
|
||||
"/api/v1/ai/playground/chat/stream",
|
||||
json={
|
||||
"workflow_id": "default.general",
|
||||
"message": "结合我刚导出的地球上下文说明重点风险",
|
||||
"earth_context": {
|
||||
"schema": "planet.earth_context.v1",
|
||||
"selected": {"type": "compute_center", "name": "Colossus"},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert sse_resp.status_code == 200
|
||||
raw_sse = sse_resp.text
|
||||
assert "event: meta" in raw_sse
|
||||
assert "event: reasoning" in raw_sse
|
||||
assert "已结合地球本地上下文完成分析。" in raw_sse
|
||||
assert "event: done" in raw_sse
|
||||
|
||||
# WorkflowRun must be persisted cleanly in /runs
|
||||
runs_resp = await client.get("/api/v1/ai/runs?workflow_id=default.general")
|
||||
assert runs_resp.status_code == 200
|
||||
runs = runs_resp.json()["items"]
|
||||
assert len(runs) == 1
|
||||
assert runs[0]["status"] == "completed"
|
||||
assert runs[0]["input_params"]["has_earth_context"] is True
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Tests for client L1 hot-update manifest and bundle hosting APIs."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import tarfile
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token
|
||||
from app.db.session import get_db
|
||||
from app.main import app
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class _DummyDbSession:
|
||||
pass
|
||||
|
||||
|
||||
class _ScalarResult:
|
||||
def __init__(self, user: User):
|
||||
self._user = user
|
||||
|
||||
def scalar_one_or_none(self):
|
||||
return self._user
|
||||
|
||||
|
||||
class _UserLookupSession:
|
||||
def __init__(self, user: User):
|
||||
self._user = user
|
||||
|
||||
async def execute(self, _stmt):
|
||||
return _ScalarResult(self._user)
|
||||
|
||||
|
||||
def _make_tar_gz(entries: dict[str, bytes], *, prefix: str = "") -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||
for name, data in entries.items():
|
||||
info = tarfile.TarInfo(name=f"{prefix}{name}")
|
||||
info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_client_updates_dir(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "CLIENT_UPDATES_DIR", str(tmp_path))
|
||||
monkeypatch.setattr(settings, "CLIENT_UPDATE_PUBLISH_TOKEN", "ci-publish-secret-token")
|
||||
monkeypatch.setattr("app.core.security.redis_client", type("NoRedis", (), {"sismember": staticmethod(lambda *_a, **_k: False)})())
|
||||
yield
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_manifest_before_any_hotfix_published():
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
res = await client.get("/api/v1/client/update-manifest?shell=0.78.0&bundle=0.78.0")
|
||||
assert res.status_code == 200
|
||||
assert res.headers["cache-control"] == "no-store"
|
||||
data = res.json()
|
||||
assert data["shell"]["version"] == settings.VERSION
|
||||
assert data["bundle"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_bundle_auth_validation_and_download():
|
||||
valid_tar = _make_tar_gz(
|
||||
{
|
||||
"index.html": b"<!doctype html><html><body>updated</body></html>",
|
||||
"js/main.js": b"console.log('hotfix');",
|
||||
}
|
||||
)
|
||||
expected_sha = hashlib.sha256(valid_tar).hexdigest()
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# Unauthenticated rejected
|
||||
unauth = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert unauth.status_code == 401
|
||||
|
||||
# Wrong CI publish token rejected
|
||||
bad_token = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "wrong-token"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert bad_token.status_code == 401
|
||||
|
||||
# Non-admin JWT rejected
|
||||
async def _non_admin_db():
|
||||
yield _UserLookupSession(User(id=2, username="viewer", email="v@example.com", role="viewer", is_active=True))
|
||||
|
||||
app.dependency_overrides[get_db] = _non_admin_db
|
||||
viewer_jwt = create_access_token({"sub": "2", "username": "viewer"})
|
||||
forbidden = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"Authorization": f"Bearer {viewer_jwt}"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
# Malicious path traversal archive rejected
|
||||
evil_tar = _make_tar_gz({"../evil.js": b"alert(1)", "index.html": b"ok"})
|
||||
evil_res = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("evil.tar.gz", evil_tar, "application/gzip")},
|
||||
)
|
||||
assert evil_res.status_code == 400
|
||||
|
||||
# Valid publish via CI token succeeds and updates manifest
|
||||
pub = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
|
||||
data={
|
||||
"version": "0.78.1",
|
||||
"min_shell_version": "0.78.0",
|
||||
"release_notes": "Fix WebGL recovery",
|
||||
"shell_version": "0.78.1",
|
||||
"shell_min_required": "0.78.0",
|
||||
"shell_download_url": "https://gitea.rclaw.top/linkong/planet/releases/tag/v0.78.1",
|
||||
},
|
||||
files={"file": ("planet-earth-bundle-0.78.1.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert pub.status_code == 200
|
||||
pub_data = pub.json()
|
||||
assert pub_data["status"] == "published"
|
||||
assert pub_data["manifest"]["bundle"]["version"] == "0.78.1"
|
||||
assert pub_data["manifest"]["bundle"]["sha256"] == expected_sha
|
||||
assert pub_data["manifest"]["bundle"]["size"] == len(valid_tar)
|
||||
assert pub_data["manifest"]["bundle"]["filesCount"] == 2
|
||||
|
||||
# Manifest reflects published bundle
|
||||
manifest_res = await client.get("/api/v1/client/update-manifest")
|
||||
assert manifest_res.status_code == 200
|
||||
bundle = manifest_res.json()["bundle"]
|
||||
assert bundle["version"] == "0.78.1"
|
||||
assert bundle["url"] == "/api/v1/client/updates/files/planet-earth-bundle-0.78.1.tar.gz"
|
||||
|
||||
# Download serves exact archive bytes
|
||||
dl = await client.get(bundle["url"])
|
||||
assert dl.status_code == 200
|
||||
assert dl.content == valid_tar
|
||||
|
||||
# Admin JWT publish also works cleanly
|
||||
missing_index_tar = _make_tar_gz({"js/main.js": b"console.log(1)"})
|
||||
|
||||
async def _admin_db():
|
||||
yield _UserLookupSession(User(id=1, username="admin", email="a@example.com", role="admin", is_active=True))
|
||||
|
||||
app.dependency_overrides[get_db] = _admin_db
|
||||
admin_jwt = create_access_token({"sub": "1", "username": "admin"})
|
||||
no_idx = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"Authorization": f"Bearer {admin_jwt}"},
|
||||
data={"version": "0.78.2"},
|
||||
files={"file": ("no-index.tar.gz", missing_index_tar, "application/gzip")},
|
||||
)
|
||||
assert no_idx.status_code == 400
|
||||
|
||||
# Invalid download filename rejected
|
||||
bad_dl = await client.get("/api/v1/client/updates/files/not-allowed.txt")
|
||||
assert bad_dl.status_code == 400
|
||||
@@ -1,6 +1,10 @@
|
||||
import asyncio
|
||||
import inspect
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.api.v1 import datasources as datasources_api
|
||||
from app.models.datasource import DataSource
|
||||
@@ -219,3 +223,128 @@ def test_trigger_datasource_batch_skips_disabled_and_frequency_window(monkeypatc
|
||||
assert queued_sources == ["ris_live_bgp"]
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class _CommitDb:
|
||||
def __init__(self, datasources=None):
|
||||
self.commits = 0
|
||||
self.datasources = list(datasources or [])
|
||||
|
||||
async def commit(self):
|
||||
self.commits += 1
|
||||
|
||||
async def execute(self, _query):
|
||||
datasources = self.datasources
|
||||
|
||||
class _Result:
|
||||
def scalars(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return datasources
|
||||
|
||||
return _Result()
|
||||
|
||||
|
||||
def _patch_row_helpers(monkeypatch, synced: list[int]):
|
||||
async def fake_sync(datasource_id):
|
||||
synced.append(datasource_id)
|
||||
|
||||
async def fake_rows(_db, datasources):
|
||||
return [{"id": item.id, "source": item.source, "is_active": item.is_active} for item in datasources]
|
||||
|
||||
async def fake_counts(_db):
|
||||
return {"all": 3, "active": 2, "inactive": 1}
|
||||
|
||||
monkeypatch.setattr(datasources_api, "sync_datasource_job", fake_sync)
|
||||
monkeypatch.setattr(datasources_api, "_serialize_datasource_rows", fake_rows)
|
||||
monkeypatch.setattr(datasources_api, "_load_datasource_status_counts", fake_counts)
|
||||
|
||||
|
||||
def test_activation_only_commits_and_syncs_changed_sources(monkeypatch):
|
||||
async def run():
|
||||
synced: list[int] = []
|
||||
_patch_row_helpers(monkeypatch, synced)
|
||||
db = _CommitDb()
|
||||
enabled = make_datasource(1, "arcgis_cables", is_active=True)
|
||||
disabled = make_datasource(2, "ris_live_bgp", is_active=False)
|
||||
|
||||
changed, failed = await datasources_api._apply_datasource_activation(db, [enabled, disabled], True)
|
||||
|
||||
assert [item.id for item in changed] == [2]
|
||||
assert disabled.is_active is True
|
||||
assert failed == []
|
||||
assert synced == [2]
|
||||
assert db.commits == 1
|
||||
|
||||
unchanged, _ = await datasources_api._apply_datasource_activation(db, [enabled], True)
|
||||
assert unchanged == []
|
||||
assert db.commits == 1
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_batch_status_reports_updated_unchanged_and_missing(monkeypatch):
|
||||
async def run():
|
||||
synced: list[int] = []
|
||||
_patch_row_helpers(monkeypatch, synced)
|
||||
already = make_datasource(1, "arcgis_cables", is_active=True)
|
||||
target = make_datasource(2, "ris_live_bgp", is_active=False)
|
||||
db = _CommitDb([already, target])
|
||||
admin = SimpleNamespace(id=9, role="admin")
|
||||
|
||||
result = await datasources_api.update_datasource_batch_status(
|
||||
datasources_api.DatasourceBatchStatusRequest(source_ids=[1, 2, 2, 99], is_active=True),
|
||||
current_user=admin,
|
||||
db=db,
|
||||
)
|
||||
|
||||
assert [row["id"] for row in result["updated"]] == [2]
|
||||
assert result["updated"][0]["is_active"] is True
|
||||
assert result["unchanged"] == [1]
|
||||
assert result["not_found"] == [99]
|
||||
assert result["sync_failed"] == []
|
||||
assert result["counts"] == {"all": 3, "active": 2, "inactive": 1}
|
||||
assert synced == [2]
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_scheduling_changes_require_admin(monkeypatch):
|
||||
async def run():
|
||||
_patch_row_helpers(monkeypatch, [])
|
||||
viewer = SimpleNamespace(id=5, role="viewer")
|
||||
with pytest.raises(HTTPException) as batch_error:
|
||||
await datasources_api.update_datasource_batch_status(
|
||||
datasources_api.DatasourceBatchStatusRequest(source_ids=[1], is_active=False),
|
||||
current_user=viewer,
|
||||
db=_CommitDb(),
|
||||
)
|
||||
with pytest.raises(HTTPException) as single_error:
|
||||
await datasources_api.enable_datasource("1", current_user=viewer, db=_CommitDb())
|
||||
assert batch_error.value.status_code == 403
|
||||
assert single_error.value.status_code == 403
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_single_toggle_returns_row_and_counts(monkeypatch):
|
||||
async def run():
|
||||
synced: list[int] = []
|
||||
_patch_row_helpers(monkeypatch, synced)
|
||||
datasource = make_datasource(4, "ris_live_bgp", is_active=False)
|
||||
|
||||
async def fake_record(_db, _source_id):
|
||||
return datasource
|
||||
|
||||
monkeypatch.setattr(datasources_api, "get_datasource_record", fake_record)
|
||||
result = await datasources_api.enable_datasource(
|
||||
"4", current_user=SimpleNamespace(id=1, role="super_admin"), db=_CommitDb()
|
||||
)
|
||||
|
||||
assert result["status"] == "enabled"
|
||||
assert result["data"] == {"id": 4, "source": "ris_live_bgp", "is_active": True}
|
||||
assert result["counts"]["active"] == 2
|
||||
assert synced == [4]
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,618 @@
|
||||
"""Tests for zero-login Earth sessions, permanent/scoped API keys, anti-scraping gate, and controlled OpenAPI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import hmac
|
||||
import importlib.util
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from app import main as main_module
|
||||
from app.core import access_gate
|
||||
from app.core.access_gate import (
|
||||
EARTH_SESSION_COOKIE,
|
||||
EARTH_TOKEN_HEADER,
|
||||
reset_access_gate_caches,
|
||||
)
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token, get_password_hash
|
||||
from app.db.session import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.api_key import ApiKey
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.user import User
|
||||
from app.services.api_keys import hash_api_key, reset_api_key_runtime_caches
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
"""Minimal async wrapper around sync SQLAlchemy Session for fast isolated tests."""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def add(self, instance: Any) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances: list[Any]) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def delete(self, instance: Any) -> None:
|
||||
self._session.delete(instance)
|
||||
|
||||
async def get(self, entity: Any, ident: Any) -> Any:
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement: Any, params: dict[str, Any] | None = None):
|
||||
if params is not None:
|
||||
return self._session.execute(statement, params)
|
||||
return self._session.execute(statement)
|
||||
|
||||
async def scalar(self, statement: Any):
|
||||
return self._session.scalar(statement)
|
||||
|
||||
async def scalars(self, statement: Any):
|
||||
return self._session.scalars(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
async def rollback(self) -> None:
|
||||
self._session.rollback()
|
||||
|
||||
async def refresh(self, instance: Any) -> None:
|
||||
self._session.refresh(instance)
|
||||
|
||||
|
||||
class _NoRedisClient:
|
||||
def sismember(self, *_args, **_kwargs):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def get_client():
|
||||
raise RuntimeError("Redis disabled in unit test")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_gate_and_redis(monkeypatch):
|
||||
reset_access_gate_caches()
|
||||
reset_api_key_runtime_caches()
|
||||
monkeypatch.setattr("app.core.security.redis_client", _NoRedisClient())
|
||||
monkeypatch.setattr("app.core.security._AsyncRedisClient", _NoRedisClient)
|
||||
monkeypatch.setattr("app.core.access_gate._AsyncRedisClient", _NoRedisClient)
|
||||
monkeypatch.setattr("app.services.api_keys._AsyncRedisClient", _NoRedisClient)
|
||||
yield
|
||||
app.dependency_overrides.clear()
|
||||
reset_access_gate_caches()
|
||||
reset_api_key_runtime_caches()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def access_db():
|
||||
engine = create_engine(
|
||||
"sqlite://",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
User.__table__,
|
||||
ApiKey.__table__,
|
||||
SystemSetting.__table__,
|
||||
CollectedData.__table__,
|
||||
],
|
||||
)
|
||||
with Session(engine) as session:
|
||||
admin = User(
|
||||
id=1,
|
||||
username="admin-user",
|
||||
email="admin@example.invalid",
|
||||
password_hash=get_password_hash("AdminPass!123"),
|
||||
role="admin",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=[],
|
||||
)
|
||||
viewer = User(
|
||||
id=2,
|
||||
username="plain-viewer",
|
||||
email="viewer@example.invalid",
|
||||
password_hash=get_password_hash("ViewerPass!123"),
|
||||
role="viewer",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=[],
|
||||
)
|
||||
partner = User(
|
||||
id=3,
|
||||
username="partner-api",
|
||||
email="partner@example.invalid",
|
||||
password_hash=get_password_hash("PartnerPass!123"),
|
||||
role="viewer",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=["api_access"],
|
||||
)
|
||||
docs_dev = User(
|
||||
id=4,
|
||||
username="docs-dev",
|
||||
email="docsdev@example.invalid",
|
||||
password_hash=get_password_hash("DocsDevPass!123"),
|
||||
role="viewer",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=["docs_developer"],
|
||||
)
|
||||
session.add_all([admin, viewer, partner, docs_dev])
|
||||
session.commit()
|
||||
|
||||
async_session = _AsyncSQLiteSession(session)
|
||||
|
||||
async def _override_get_db():
|
||||
yield async_session
|
||||
|
||||
app.dependency_overrides[get_db] = _override_get_db
|
||||
yield async_session
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _bearer_headers(user_id: int, username: str) -> dict[str, str]:
|
||||
token = create_access_token({"sub": str(user_id), "username": username})
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enforce_mode_blocks_anonymous_endpoints_and_allows_public_exemptions(
|
||||
monkeypatch, access_db
|
||||
):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
|
||||
class _ReadyDbContext:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
async def execute(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
class _ReadyRedis:
|
||||
class _Client:
|
||||
async def ping(self):
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_client():
|
||||
return _ReadyRedis._Client()
|
||||
|
||||
monkeypatch.setattr(main_module, "async_session_factory", lambda: _ReadyDbContext())
|
||||
monkeypatch.setattr(main_module, "_AsyncRedisClient", _ReadyRedis)
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
for protected_path in [
|
||||
"/api/v1/visualization/geo/summary",
|
||||
"/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5",
|
||||
"/api/v1/vessels/snapshot?bbox=-10,-10,10,10&zoom=5",
|
||||
"/api/v1/news/earth-feed",
|
||||
"/api/v1/data-products/compute/configuration",
|
||||
"/api/v1/earth/brand",
|
||||
"/api/v1/tv/streams",
|
||||
]:
|
||||
resp = await client.get(protected_path)
|
||||
assert resp.status_code == 401, f"{protected_path} returned {resp.status_code}"
|
||||
|
||||
assert (await client.get("/health")).status_code == 200
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
health_resp = await client.get("/health/ready")
|
||||
assert health_resp.status_code == 200
|
||||
manifest_resp = await client.get("/api/v1/client/update-manifest")
|
||||
assert manifest_resp.status_code == 200
|
||||
docs_resp = await client.get("/api/v1/docs/catalog")
|
||||
assert docs_resp.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with pytest.raises(WebSocketDisconnect) as exc_info:
|
||||
with tc.websocket_connect("/ws"):
|
||||
pass
|
||||
assert exc_info.value.code == 4001
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_web_earth_session_zero_login_origin_cookie_ws_and_turnstile(
|
||||
monkeypatch, access_db
|
||||
):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "")
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
no_origin = await client.post("/api/v1/auth/earth-session", json={"client_type": "web"})
|
||||
assert no_origin.status_code == 403
|
||||
|
||||
cross_site = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web"},
|
||||
headers={"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"},
|
||||
)
|
||||
assert cross_site.status_code == 403
|
||||
|
||||
ok = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web"},
|
||||
headers={"Origin": "http://test", "Sec-Fetch-Site": "same-origin"},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
body = ok.json()
|
||||
assert body["client_type"] == "web"
|
||||
assert body["ws_token"]
|
||||
assert body["turnstile_required"] is False
|
||||
set_cookie = ok.headers.get("set-cookie", "")
|
||||
assert EARTH_SESSION_COOKIE in set_cookie
|
||||
assert "HttpOnly" in set_cookie
|
||||
assert "samesite=strict" in set_cookie.lower()
|
||||
|
||||
authed_brand = await client.get("/api/v1/earth/brand")
|
||||
assert authed_brand.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with tc.websocket_connect(f"/ws?earth_token={body['ws_token']}") as ws:
|
||||
hello = ws.receive_json()
|
||||
assert hello["type"] == "connection_established"
|
||||
|
||||
monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "ts-secret")
|
||||
|
||||
class _MockTurnstileClient:
|
||||
def __init__(self, success: bool):
|
||||
self._success = success
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
async def post(self, *_args, **_kwargs):
|
||||
class _Resp:
|
||||
def __init__(self, success_flag: bool):
|
||||
self._success_flag = success_flag
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return {"success": self._success_flag}
|
||||
|
||||
return _Resp(self._success)
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
missing_ts = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web"},
|
||||
headers={"Origin": "http://test"},
|
||||
)
|
||||
assert missing_ts.status_code == 403
|
||||
|
||||
monkeypatch.setattr(
|
||||
access_gate.httpx,
|
||||
"AsyncClient",
|
||||
lambda **_kw: _MockTurnstileClient(False),
|
||||
)
|
||||
failed_ts = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web", "turnstile_token": "bad-token"},
|
||||
headers={"Origin": "http://test"},
|
||||
)
|
||||
assert failed_ts.status_code == 403
|
||||
|
||||
monkeypatch.setattr(
|
||||
access_gate.httpx,
|
||||
"AsyncClient",
|
||||
lambda **_kw: _MockTurnstileClient(True),
|
||||
)
|
||||
ok_ts = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web", "turnstile_token": "good-token"},
|
||||
headers={"Origin": "http://test"},
|
||||
)
|
||||
assert ok_ts.status_code == 200
|
||||
assert ok_ts.json()["turnstile_required"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_desktop_earth_handshake_hmac_replay_and_token_access(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
secret = "desktop-shared-hmac-secret"
|
||||
monkeypatch.setattr(settings, "EARTH_DESKTOP_HANDSHAKE_SECRET", secret)
|
||||
|
||||
client_header = "planet-earth-desktop/0.82.0"
|
||||
ts = str(int(time.time()))
|
||||
nonce = "nonce-unique-123"
|
||||
sig = hmac.new(
|
||||
secret.encode("utf-8"),
|
||||
f"{ts}.{nonce}.{client_header}".encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
missing_hdr = await client.post("/api/v1/auth/earth-session", json={"client_type": "desktop"})
|
||||
assert missing_hdr.status_code == 403
|
||||
|
||||
bad_sig = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "desktop"},
|
||||
headers={
|
||||
"X-Planet-Client": client_header,
|
||||
"X-Planet-Client-Timestamp": ts,
|
||||
"X-Planet-Client-Nonce": nonce,
|
||||
"X-Planet-Client-Signature": "0" * 64,
|
||||
},
|
||||
)
|
||||
assert bad_sig.status_code == 403
|
||||
|
||||
ok = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "desktop"},
|
||||
headers={
|
||||
"X-Planet-Client": client_header,
|
||||
"X-Planet-Client-Timestamp": ts,
|
||||
"X-Planet-Client-Nonce": nonce,
|
||||
"X-Planet-Client-Signature": sig,
|
||||
},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
desktop_token = ok.json()["token"]
|
||||
|
||||
replay = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "desktop"},
|
||||
headers={
|
||||
"X-Planet-Client": client_header,
|
||||
"X-Planet-Client-Timestamp": ts,
|
||||
"X-Planet-Client-Nonce": nonce,
|
||||
"X-Planet-Client-Signature": sig,
|
||||
},
|
||||
)
|
||||
assert replay.status_code == 403
|
||||
|
||||
brand_resp = await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers={EARTH_TOKEN_HEADER: desktop_token},
|
||||
)
|
||||
assert brand_resp.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with tc.websocket_connect("/ws", headers={EARTH_TOKEN_HEADER: desktop_token}) as ws:
|
||||
hello = ws.receive_json()
|
||||
assert hello["type"] == "connection_established"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_key_lifecycle_permanent_scopes_rate_limit_revocation_and_ws(
|
||||
monkeypatch, access_db
|
||||
):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
admin_hdrs = _bearer_headers(1, "admin-user")
|
||||
viewer_hdrs = _bearer_headers(2, "plain-viewer")
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
denied_create = await client.post(
|
||||
"/api/v1/system/api-keys",
|
||||
json={"name": "unauthorized"},
|
||||
headers=viewer_hdrs,
|
||||
)
|
||||
assert denied_create.status_code == 403
|
||||
|
||||
created = await client.post(
|
||||
"/api/v1/system/api-keys",
|
||||
json={
|
||||
"name": "ue5-permanent",
|
||||
"scopes": ["earth:all_read"],
|
||||
"rate_limit_per_minute": None,
|
||||
"expires_in_days": None,
|
||||
},
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert created.status_code == 201
|
||||
created_data = created.json()
|
||||
raw_perm_key = created_data["api_key"]
|
||||
perm_item = created_data["item"]
|
||||
assert raw_perm_key.startswith("plt_live_")
|
||||
assert perm_item["expires_at"] is None
|
||||
assert perm_item["rate_limit_per_minute"] is None
|
||||
|
||||
listing = await client.get("/api/v1/system/api-keys", headers=admin_hdrs)
|
||||
assert listing.status_code == 200
|
||||
listed_item = listing.json()["items"][0]
|
||||
assert listed_item["key_prefix"] == perm_item["key_prefix"]
|
||||
assert raw_perm_key not in listing.text
|
||||
|
||||
ok_http = await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key})
|
||||
assert ok_http.status_code == 200
|
||||
|
||||
ok_tv_query = await client.get(f"/api/v1/tv/streams?api_key={raw_perm_key}")
|
||||
# /tv/streams intentionally requires header X-API-Key (not query), whereas /tv/proxy allows query
|
||||
assert ok_tv_query.status_code == 401
|
||||
ok_tv_header = await client.get("/api/v1/tv/streams", headers={"X-API-Key": raw_perm_key})
|
||||
assert ok_tv_header.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with tc.websocket_connect(f"/ws?api_key={raw_perm_key}") as ws:
|
||||
hello = ws.receive_json()
|
||||
assert hello["type"] == "connection_established"
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
scoped_created = await client.post(
|
||||
"/api/v1/system/api-keys",
|
||||
json={
|
||||
"name": "earth-only-limited",
|
||||
"scopes": ["earth:read"],
|
||||
"rate_limit_per_minute": 2,
|
||||
"expires_in_days": 30,
|
||||
},
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert scoped_created.status_code == 201
|
||||
scoped_key = scoped_created.json()["api_key"]
|
||||
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
|
||||
).status_code == 429
|
||||
|
||||
out_of_scope = await client.get(
|
||||
"/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5",
|
||||
headers={"X-API-Key": scoped_key},
|
||||
)
|
||||
assert out_of_scope.status_code == 403
|
||||
|
||||
revoked = await client.post(
|
||||
f"/api/v1/system/api-keys/{perm_item['id']}/revoke",
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert revoked.status_code == 200
|
||||
assert revoked.json()["item"]["status"] == "revoked"
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key})
|
||||
).status_code == 401
|
||||
|
||||
deleted = await client.delete(
|
||||
f"/api/v1/system/api-keys/{scoped_created.json()['item']['id']}",
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert deleted.status_code == 200
|
||||
|
||||
expired_raw = "plt_live_expired_unit_test_key"
|
||||
expired_row = ApiKey(
|
||||
name="expired-key",
|
||||
key_prefix="plt_live_exp...",
|
||||
key_hash=hash_api_key(expired_raw),
|
||||
scopes=["earth:all_read"],
|
||||
is_active=True,
|
||||
expires_at=datetime.now(UTC) - timedelta(days=1),
|
||||
)
|
||||
access_db.add(expired_row)
|
||||
await access_db.commit()
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
exp_resp = await client.get("/api/v1/earth/brand", headers={"X-API-Key": expired_raw})
|
||||
assert exp_resp.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jwt_api_access_group_enforcement(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers=_bearer_headers(1, "admin-user"),
|
||||
)
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers=_bearer_headers(3, "partner-api"),
|
||||
)
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers=_bearer_headers(2, "plain-viewer"),
|
||||
)
|
||||
).status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_news_refresh_requires_auth_and_enforces_cooldown(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
from app.services import scheduler as scheduler_service
|
||||
|
||||
monkeypatch.setattr(
|
||||
scheduler_service,
|
||||
"request_earth_news_region_refresh",
|
||||
lambda region: {"refresh_id": "11111111111111111111111111111111", "region": region, "status": "queued"},
|
||||
)
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
anon = await client.post("/api/v1/news/refresh", json={"region": "global"})
|
||||
assert anon.status_code == 401
|
||||
|
||||
hdrs = _bearer_headers(3, "partner-api")
|
||||
for _ in range(3):
|
||||
ok = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs)
|
||||
assert ok.status_code == 202
|
||||
limited = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs)
|
||||
assert limited.status_code == 429
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_controlled_openapi_and_production_mode_defaults(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "APP_ENV", "production")
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "")
|
||||
assert settings.effective_earth_api_auth_mode == "enforce"
|
||||
|
||||
spec = importlib.util.spec_from_file_location("app_main_prod_probe", main_module.__file__)
|
||||
assert spec is not None and spec.loader is not None
|
||||
prod_main = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(prod_main)
|
||||
assert prod_main.app.docs_url is None
|
||||
assert prod_main.app.redoc_url is None
|
||||
assert prod_main.app.openapi_url is None
|
||||
|
||||
monkeypatch.setattr(settings, "APP_ENV", "development")
|
||||
assert settings.effective_earth_api_auth_mode == "off"
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
assert settings.effective_earth_api_auth_mode == "enforce"
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
assert (await client.get("/api/v1/system/openapi.json")).status_code == 401
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/system/openapi.json",
|
||||
headers=_bearer_headers(2, "plain-viewer"),
|
||||
)
|
||||
).status_code == 403
|
||||
|
||||
full_resp = await client.get(
|
||||
"/api/v1/system/openapi.json",
|
||||
headers=_bearer_headers(4, "docs-dev"),
|
||||
)
|
||||
assert full_resp.status_code == 200
|
||||
assert "/api/v1/users" in full_resp.json()["paths"]
|
||||
|
||||
ext_resp = await client.get(
|
||||
"/api/v1/system/openapi-external.json",
|
||||
headers=_bearer_headers(1, "admin-user"),
|
||||
)
|
||||
assert ext_resp.status_code == 200
|
||||
ext = ext_resp.json()
|
||||
assert "ApiKeyAuth" in ext["components"]["securitySchemes"]
|
||||
assert "/api/v1/visualization/geo/summary" in ext["paths"]
|
||||
assert "/api/v1/users" not in ext["paths"]
|
||||
assert "/api/v1/settings/integrations" not in ext["paths"]
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
|
||||
import httpx
|
||||
@@ -9,6 +10,7 @@ from fastapi import FastAPI, HTTPException, Response
|
||||
|
||||
from app.api.v1 import visualization
|
||||
from app.services.earth_layer_cache import (
|
||||
_ENCODED_ARTIFACT_CACHE,
|
||||
EarthLayerCachePolicy,
|
||||
apply_payload_budget,
|
||||
earth_layer_cache,
|
||||
@@ -81,9 +83,11 @@ def fake_cache_client():
|
||||
previous = earth_layer_cache._client
|
||||
fake = FakeRedis()
|
||||
earth_layer_cache._client = fake
|
||||
_ENCODED_ARTIFACT_CACHE.clear()
|
||||
try:
|
||||
yield fake
|
||||
finally:
|
||||
_ENCODED_ARTIFACT_CACHE.clear()
|
||||
earth_layer_cache._client = previous
|
||||
|
||||
|
||||
@@ -566,3 +570,99 @@ def test_invalidate_earth_layer_cache_for_source_degrades_gracefully_on_redis_fa
|
||||
assert invalidate_earth_layer_cache_for_source("ris_live_bgp") == 0
|
||||
finally:
|
||||
earth_layer_cache._client = previous
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_satellites_endpoint_supports_compact_gzip_and_etag_304(
|
||||
fake_cache_client,
|
||||
monkeypatch,
|
||||
):
|
||||
geojson_calls = 0
|
||||
compact_calls = 0
|
||||
|
||||
async def fake_build_satellites_geojson(*, limit, db):
|
||||
nonlocal geojson_calls
|
||||
geojson_calls += 1
|
||||
return {
|
||||
"type": "FeatureCollection",
|
||||
"features": [{"type": "Feature", "id": 25544, "properties": {"id": 1}}],
|
||||
"count": 1,
|
||||
}
|
||||
|
||||
async def fake_build_satellites_compact(*, limit, db):
|
||||
nonlocal compact_calls
|
||||
compact_calls += 1
|
||||
return {
|
||||
"format": "satellite_compact_v1",
|
||||
"count": 1,
|
||||
"fields": [
|
||||
"id",
|
||||
"norad_cat_id",
|
||||
"name",
|
||||
"constellation_group",
|
||||
"tle_line1",
|
||||
"tle_line2",
|
||||
"fallback_elements",
|
||||
],
|
||||
"satellites": [[1, 25544, "ISS (ZARYA)", "leo", "1 25544U ...", "2 25544 ..."]],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(visualization, "_build_satellites_geojson", fake_build_satellites_geojson)
|
||||
monkeypatch.setattr(visualization, "_build_satellites_compact", fake_build_satellites_compact)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(visualization.router, prefix="/api/v1/visualization")
|
||||
app.dependency_overrides[visualization.get_db] = lambda: object()
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app),
|
||||
base_url="http://test",
|
||||
) as client:
|
||||
first_compact = await client.get(
|
||||
"/api/v1/visualization/geo/satellites?format=compact",
|
||||
headers={"Accept-Encoding": "gzip"},
|
||||
)
|
||||
assert first_compact.status_code == 200
|
||||
assert first_compact.headers["X-Planet-Cache"] == "refresh"
|
||||
assert first_compact.headers["X-Planet-Cache-Features"] == "1"
|
||||
assert first_compact.headers["Content-Encoding"] == "gzip"
|
||||
etag = first_compact.headers["ETag"]
|
||||
assert etag
|
||||
assert first_compact.json()["format"] == "satellite_compact_v1"
|
||||
assert first_compact.json()["satellites"][0][1] == 25544
|
||||
|
||||
second_compact = await client.get(
|
||||
"/api/v1/visualization/geo/satellites?format=compact",
|
||||
headers={"Accept-Encoding": "gzip"},
|
||||
)
|
||||
assert second_compact.status_code == 200
|
||||
assert second_compact.headers["X-Planet-Cache"] == "hit"
|
||||
assert second_compact.headers["ETag"] == etag
|
||||
assert second_compact.headers["Content-Encoding"] == "gzip"
|
||||
|
||||
not_modified = await client.get(
|
||||
"/api/v1/visualization/geo/satellites?format=compact",
|
||||
headers={"If-None-Match": etag, "Accept-Encoding": "gzip"},
|
||||
)
|
||||
assert not_modified.status_code == 304
|
||||
assert not_modified.content == b""
|
||||
assert not_modified.headers["ETag"] == etag
|
||||
|
||||
plain_geo = await client.get(
|
||||
"/api/v1/visualization/geo/satellites",
|
||||
headers={"Accept-Encoding": "identity"},
|
||||
)
|
||||
assert plain_geo.status_code == 200
|
||||
assert "content-encoding" not in {k.lower() for k in plain_geo.headers.keys()}
|
||||
assert plain_geo.json()["type"] == "FeatureCollection"
|
||||
assert geojson_calls == 1
|
||||
assert compact_calls == 1
|
||||
|
||||
# Verify raw bytes cached cleanly match uncompressed response and encoded artifact gzip round-trips
|
||||
raw_cached = fake_cache_client.store[
|
||||
earth_layer_cache.key("satellites", format="compact", limit="all")
|
||||
]
|
||||
assert json.loads(raw_cached)["count"] == 1
|
||||
assert second_compact.json()["count"] == 1
|
||||
artifact = next(iter(_ENCODED_ARTIFACT_CACHE.values()))
|
||||
assert gzip.decompress(artifact.gzip_bytes) == artifact.raw_bytes
|
||||
@@ -9,6 +9,13 @@ from app.services import llm_provider_catalog as catalog
|
||||
REAL_CLIENT = httpx.AsyncClient
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_aggregator_cache():
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
yield
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
|
||||
def mock_http(monkeypatch, handler):
|
||||
transport = httpx.MockTransport(handler)
|
||||
monkeypatch.setattr(
|
||||
@@ -26,8 +33,12 @@ def mock_http(monkeypatch, handler):
|
||||
("deepseek", "/v1/models", "authorization"),
|
||||
("alibaba", "/api/v1/models", "authorization"),
|
||||
("moonshotai", "/v1/models", "authorization"),
|
||||
("openrouter", "/api/v1/models", "authorization"),
|
||||
("opencode-go", "/zen/go/v1/models", "authorization"),
|
||||
("glm", "/api/paas/v4/models", "authorization"),
|
||||
("meta", "/v1/models", "authorization"),
|
||||
("gemini", "/v1beta/openai/models", "authorization"),
|
||||
("grok", "/v1/models", "authorization"),
|
||||
("openrouter", "/api/v1/models", None),
|
||||
("opencode-go", "/zen/go/v1/models", None),
|
||||
("ollama", "/api/tags", "authorization"),
|
||||
],
|
||||
)
|
||||
@@ -37,7 +48,13 @@ async def test_official_catalog_requests(monkeypatch, provider, path, auth):
|
||||
def handle(request):
|
||||
assert request.url.path == path
|
||||
assert request.url.host == httpx.URL(preset["base_url"]).host
|
||||
assert request.headers[auth] == ("test-key" if auth == "x-api-key" else "Bearer test-key")
|
||||
if auth is None:
|
||||
assert "authorization" not in request.headers
|
||||
assert "x-api-key" not in request.headers
|
||||
else:
|
||||
assert request.headers[auth] == (
|
||||
"test-key" if auth == "x-api-key" else "Bearer test-key"
|
||||
)
|
||||
if provider == "alibaba":
|
||||
assert request.url.params["capabilities"] == "TG"
|
||||
return httpx.Response(
|
||||
@@ -45,6 +62,8 @@ async def test_official_catalog_requests(monkeypatch, provider, path, auth):
|
||||
)
|
||||
if provider == "ollama":
|
||||
return httpx.Response(200, json={"models": [{"name": "latest:7b"}]})
|
||||
if provider == "gemini":
|
||||
return httpx.Response(200, json={"data": [{"id": "models/latest"}]})
|
||||
return httpx.Response(200, json={"data": [{"id": "latest"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
@@ -214,6 +233,304 @@ async def test_retry_transient_error_only(monkeypatch):
|
||||
|
||||
mock_http(monkeypatch, unauthorized)
|
||||
with pytest.raises(httpx.HTTPStatusError) as error:
|
||||
await catalog.refresh_llm_provider_preset("minimax", "test-key")
|
||||
await discovery.fetch_model_catalog(
|
||||
"minimax",
|
||||
"https://api.minimaxi.com/anthropic",
|
||||
"anthropic-messages",
|
||||
"test-key",
|
||||
)
|
||||
assert len(calls) == 1
|
||||
assert "secret-upstream-text" not in discovery.catalog_error_message(error.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"provider,custom_base",
|
||||
[
|
||||
("openrouter", "https://proxy.test/api/v1"),
|
||||
("opencode-go", "https://proxy.test/zen/go/v1"),
|
||||
],
|
||||
)
|
||||
async def test_custom_gateway_for_public_provider_requires_and_sends_key(
|
||||
monkeypatch, provider, custom_base
|
||||
):
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
await catalog.refresh_llm_provider_preset(provider, base_url=custom_base)
|
||||
|
||||
def handle(request):
|
||||
assert request.url.host == "proxy.test"
|
||||
assert request.headers["authorization"] == "Bearer custom-key"
|
||||
return httpx.Response(200, json={"data": [{"id": "proxy-model"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await catalog.refresh_llm_provider_preset(
|
||||
provider, api_key="custom-key", base_url=custom_base
|
||||
)
|
||||
assert result["models"] == ["proxy-model"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_model_catalog_include_auth_for_connectivity_check(monkeypatch):
|
||||
def handle(request):
|
||||
assert request.headers["authorization"] == "Bearer check-key"
|
||||
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await discovery.fetch_model_catalog(
|
||||
"opencode-go",
|
||||
"https://opencode.ai/zen/go/v1",
|
||||
"openai-completions",
|
||||
api_key="check-key",
|
||||
include_auth=True,
|
||||
)
|
||||
assert result.models == ["glm-5.3"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ollama_openai_completions_refreshes_without_key(monkeypatch):
|
||||
def handle(request):
|
||||
assert request.url.path == "/v1/models"
|
||||
assert "authorization" not in request.headers
|
||||
return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await catalog.refresh_llm_provider_preset(
|
||||
"ollama", provider_api="openai-completions"
|
||||
)
|
||||
assert result["models"] == ["qwen2.5:7b"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_error_type_and_clean_upstream_error_messages(monkeypatch):
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
discovery.model_catalog_url("openai", "not-a-url", "openai-responses")
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
discovery.model_catalog_url("openai", "https://api.openai.com/v1", "unsupported-api")
|
||||
|
||||
mock_http(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
|
||||
with pytest.raises(discovery.LLMProviderCatalogError) as exc:
|
||||
await catalog.refresh_llm_provider_preset("openai", "test-key")
|
||||
assert not isinstance(exc.value, discovery.LLMProviderCatalogConfigError)
|
||||
assert "已保留上次模型列表" not in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_official_providers_use_models_dev_cache_and_filter_non_text(monkeypatch):
|
||||
calls = []
|
||||
models_dev_payload = {
|
||||
"minimax-cn": {"models": {"MiniMax-M3.1-Flash": {"release_date": "2026-10-19", "modalities": {"output": ["text"]}}}},
|
||||
"openai": {"models": {"gpt-6.2-astra": {"release_date": "2026-11-17", "modalities": {"output": ["text"]}}}},
|
||||
"anthropic": {"models": {"claude-fable-5-2": {"release_date": "2026-11-09", "modalities": {"output": ["text"]}}}},
|
||||
"deepseek": {"models": {"deepseek-v4-pro": {"release_date": "2026-08-13", "modalities": {"output": ["text"]}}}},
|
||||
"alibaba-cn": {"models": {"qwen4-max": {"release_date": "2026-11-16", "modalities": {"output": ["text"]}}}},
|
||||
"moonshotai": {"models": {"kimi-k3.1-pro": {"release_date": "2026-10-23", "modalities": {"output": ["text"]}}}},
|
||||
"zhipuai": {"models": {"glm-5.3": {"release_date": "2026-08-14", "modalities": {"output": ["text"]}}}},
|
||||
"meta": {"models": {"muse-ember-1.0": {"release_date": "2026-11-09", "modalities": {"output": ["text"]}}}},
|
||||
"google": {"models": {"gemini-4-neon": {"release_date": "2026-11-18", "modalities": {"output": ["text"]}}}},
|
||||
"xai": {
|
||||
"models": {
|
||||
"grok-imagine-video": {"release_date": "2026-10-01", "modalities": {"output": ["video"]}},
|
||||
"grok-4.6": {"release_date": "2026-08-12", "modalities": {"output": ["text"]}},
|
||||
"grok-4.7": {"release_date": "2026-09-21", "modalities": {"output": ["text"]}},
|
||||
"grok-legacy": {"release_date": "2026-11-01", "status": "deprecated", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
calls.append(str(request.url))
|
||||
assert str(request.url) == discovery.MODELS_DEV_CATALOG_URL
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
expected = {
|
||||
"minimax": ["MiniMax-M3.1-Flash"],
|
||||
"openai": ["gpt-6.2-astra"],
|
||||
"anthropic": ["claude-fable-5-2"],
|
||||
"deepseek": ["deepseek-v4-pro"],
|
||||
"alibaba": ["qwen4-max"],
|
||||
"moonshotai": ["kimi-k3.1-pro"],
|
||||
"glm": ["glm-5.3"],
|
||||
"meta": ["muse-ember-1.0"],
|
||||
"gemini": ["gemini-4-neon"],
|
||||
"grok": ["grok-4.7", "grok-4.6", "grok-legacy"],
|
||||
}
|
||||
for provider, models in expected.items():
|
||||
result = await catalog.refresh_llm_provider_preset(provider)
|
||||
assert result["models"] == models
|
||||
assert result["source"].startswith(discovery.MODELS_DEV_CATALOG_URL)
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_aggregator_falls_back_to_openrouter_when_models_dev_fails(monkeypatch):
|
||||
seen_urls = []
|
||||
|
||||
def handle(request):
|
||||
seen_urls.append(str(request.url))
|
||||
if str(request.url) == discovery.MODELS_DEV_CATALOG_URL:
|
||||
return httpx.Response(503, text="models.dev down")
|
||||
if str(request.url) == discovery.OPENROUTER_CATALOG_URL:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"data": [
|
||||
{"id": "moonshotai/kimi-k3:batch", "created": 300},
|
||||
{"id": "moonshotai/kimi-k3.1-pro", "created": 200},
|
||||
{"id": "moonshotai/kimi-k3", "created": 100},
|
||||
{"id": "z-ai/glm-5.3", "created": 150},
|
||||
]
|
||||
},
|
||||
)
|
||||
pytest.fail(f"unexpected URL {request.url}")
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await catalog.refresh_llm_provider_preset("moonshotai")
|
||||
assert result["models"] == ["kimi-k3.1-pro", "kimi-k3"]
|
||||
assert result["source"] == f"{discovery.OPENROUTER_CATALOG_URL}#moonshotai"
|
||||
assert discovery.MODELS_DEV_CATALOG_URL in seen_urls
|
||||
assert discovery.OPENROUTER_CATALOG_URL in seen_urls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_aggregator_fails_cleanly_and_official_vs_gateway_keyed_fallback(monkeypatch):
|
||||
mock_http(monkeypatch, lambda request: httpx.Response(503, text="secret-upstream-error"))
|
||||
with pytest.raises(discovery.LLMProviderCatalogError) as agg_exc:
|
||||
await catalog.refresh_llm_provider_preset("glm")
|
||||
assert not isinstance(agg_exc.value, discovery.LLMProviderCatalogConfigError)
|
||||
|
||||
# Keyed official host falling back to models.dev when official /models returns 401
|
||||
seen_hosts = []
|
||||
|
||||
def deepseek_401_then_aggregator(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
if request.url.host == "api.deepseek.com":
|
||||
return httpx.Response(401, text="bad-key")
|
||||
if str(request.url) == discovery.MODELS_DEV_CATALOG_URL:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"deepseek": {
|
||||
"models": {
|
||||
"deepseek-chat": {"release_date": "2026-01-01"},
|
||||
"deepseek-v4-flash": {"release_date": "2026-10-17"},
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
pytest.fail(f"unexpected URL {request.url}")
|
||||
|
||||
mock_http(monkeypatch, deepseek_401_then_aggregator)
|
||||
ds_result = await catalog.refresh_llm_provider_preset("deepseek", api_key="stale-key")
|
||||
assert seen_hosts == ["api.deepseek.com", "models.dev"]
|
||||
assert ds_result["models"] == ["deepseek-v4-flash", "deepseek-chat"]
|
||||
assert ds_result["source"] == f"{discovery.MODELS_DEV_CATALOG_URL}#deepseek"
|
||||
|
||||
# Keyed official host where both aggregators also fail preserves original 401 HTTPStatusError
|
||||
seen_hosts.clear()
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
def official_and_aggregators_fail(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
if request.url.host == "api.moonshot.ai":
|
||||
return httpx.Response(401, text="bad-key")
|
||||
return httpx.Response(503, text="aggregator-down")
|
||||
|
||||
mock_http(monkeypatch, official_and_aggregators_fail)
|
||||
with pytest.raises(httpx.HTTPStatusError) as official_err:
|
||||
await catalog.refresh_llm_provider_preset("moonshotai", api_key="invalid-key")
|
||||
assert official_err.value.response.status_code == 401
|
||||
assert seen_hosts[0] == "api.moonshot.ai"
|
||||
|
||||
# Keyed custom gateway never falls back to public aggregators
|
||||
seen_hosts.clear()
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
def custom_gateway_bad_key(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
return httpx.Response(401, text="bad-gateway-key")
|
||||
|
||||
mock_http(monkeypatch, custom_gateway_bad_key)
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
await catalog.refresh_llm_provider_preset(
|
||||
"moonshotai",
|
||||
api_key="invalid-key",
|
||||
base_url="https://proxy.example.test/v1",
|
||||
)
|
||||
assert seen_hosts == ["proxy.example.test"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_6_2_defaults_and_aggregator_chat_filtering_demotion(monkeypatch):
|
||||
preset = catalog.get_fallback_llm_provider_preset("openai")
|
||||
assert preset["model"] == "gpt-6.2-astra"
|
||||
assert {"gpt-6.2-astra", "gpt-6.2-sol"}.issubset(set(preset["models"]))
|
||||
assert preset["model_provider_apis"]["gpt-6.2-astra"] == "openai-responses"
|
||||
assert preset["model_provider_apis"]["gpt-6.2-sol"] == "openai-responses"
|
||||
|
||||
models_dev_payload = {
|
||||
"openai": {
|
||||
"models": {
|
||||
"gpt-6.2-sol-healthcare": {"release_date": "2026-11-24", "modalities": {"output": ["text"]}},
|
||||
"gpt-daybreak-red-latest": {"release_date": "2026-11-24", "modalities": {"output": ["text"]}},
|
||||
"gpt-6.2-sol": {"release_date": "2026-11-17", "modalities": {"output": ["text"]}},
|
||||
"gpt-6.2-astra": {"release_date": "2026-11-17", "modalities": {"output": ["text"]}},
|
||||
"gpt-chat-latest": {"release_date": "2026-11-20", "modalities": {"output": ["text"]}},
|
||||
"text-embedding-3-small": {"release_date": "2026-11-20", "modalities": {"output": ["text"]}},
|
||||
"chatgpt-image-latest": {"release_date": "2026-11-20", "modalities": {"output": ["text", "image"]}},
|
||||
"gpt-image-1.5": {"release_date": "2026-11-20", "modalities": {"output": ["text", "image"]}},
|
||||
"gpt-audio": {"release_date": "2026-11-20", "modalities": {"output": ["text", "audio"]}},
|
||||
}
|
||||
},
|
||||
"zhipuai": {
|
||||
"models": {
|
||||
"glm-5.3-flashx-legal": {"release_date": "2026-11-24", "modalities": {"output": ["text"]}},
|
||||
"glm-5.3": {"release_date": "2026-08-14", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
},
|
||||
"deepseek": {
|
||||
"models": {
|
||||
"deepseek-v4-flash": {"release_date": "2026-10-17", "modalities": {"output": ["text"]}},
|
||||
"deepseek-chat": {"release_date": "2026-01-01", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
},
|
||||
}
|
||||
mock_http(monkeypatch, lambda request: httpx.Response(200, json=models_dev_payload))
|
||||
|
||||
oai = await catalog.refresh_llm_provider_preset("openai")
|
||||
assert oai["models"] == [
|
||||
"gpt-6.2-sol",
|
||||
"gpt-6.2-astra",
|
||||
"gpt-daybreak-red-latest",
|
||||
"gpt-6.2-sol-healthcare",
|
||||
]
|
||||
assert oai["model"] == "gpt-6.2-sol"
|
||||
assert oai["model_provider_apis"]["gpt-6.2-sol"] == "openai-responses"
|
||||
assert oai["model_provider_apis"]["gpt-6.2-astra"] == "openai-responses"
|
||||
|
||||
glm = await catalog.refresh_llm_provider_preset("glm")
|
||||
assert glm["models"] == ["glm-5.3", "glm-5.3-flashx-legal"]
|
||||
assert glm["model"] == "glm-5.3"
|
||||
|
||||
ds = await catalog.refresh_llm_provider_preset("deepseek")
|
||||
assert ds["models"] == ["deepseek-v4-flash", "deepseek-chat"]
|
||||
|
||||
mock_http(
|
||||
monkeypatch,
|
||||
lambda request: httpx.Response(200, json={"data": [{"id": "gpt-6.2-astra"}, {"id": "gpt-6.2-sol"}]}),
|
||||
)
|
||||
gw = await catalog.refresh_llm_provider_preset(
|
||||
"openai",
|
||||
api_key="gw-key",
|
||||
base_url="https://gateway.test/v1",
|
||||
)
|
||||
assert gw["model_provider_apis"] == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_custom_gateway_still_requires_api_key(monkeypatch):
|
||||
mock_http(monkeypatch, lambda request: pytest.fail("must not call aggregator or proxy"))
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
await catalog.refresh_llm_provider_preset(
|
||||
"moonshotai", base_url="https://proxy.example.test/v1"
|
||||
)
|
||||
@@ -13,6 +13,15 @@ from app.services import llm_model_catalog as discovery
|
||||
from app.services.llm_provider_catalog import list_fallback_llm_provider_presets
|
||||
|
||||
REAL_CLIENT = httpx.AsyncClient
|
||||
ADMIN_USER = SimpleNamespace(role="admin")
|
||||
VIEWER_USER = SimpleNamespace(role="viewer")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_aggregator_cache():
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
yield
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -44,7 +53,9 @@ def use_upstream(monkeypatch, handler):
|
||||
@pytest.mark.asyncio
|
||||
async def test_fresh_database_lists_all_builtin_presets(settings_db):
|
||||
result = await api.get_ai_provider_presets(current_user=None, db=settings_db)
|
||||
assert len(result["data"]) == 9
|
||||
assert len(result["data"]) == 13
|
||||
providers = {row["provider"] for row in result["data"]}
|
||||
assert {"moonshotai", "glm", "meta", "gemini", "grok"}.issubset(providers)
|
||||
assert all(row["models"] for row in result["data"])
|
||||
assert "MiniMax-M3" in result["data"][0]["models"]
|
||||
|
||||
@@ -82,7 +93,7 @@ async def test_refresh_commits_reloads_and_preserves_runtime_and_draft(settings_
|
||||
api_key="draft-secret",
|
||||
service_token="unsaved-service-token",
|
||||
)
|
||||
refreshed = await api.refresh_ai_provider_preset("minimax", None, settings_db, draft)
|
||||
refreshed = await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db, draft)
|
||||
result = await api.get_ai_provider_presets(None, settings_db)
|
||||
preset = next(row for row in result["data"] if row["provider"] == "minimax")
|
||||
assert len(seen) == 1
|
||||
@@ -108,7 +119,7 @@ async def test_failed_refresh_preserves_stored_catalog_and_sanitizes_errors(
|
||||
use_upstream(monkeypatch, lambda request: httpx.Response(401, text="private-upstream-secret"))
|
||||
commits = settings_db.commit.await_count
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("openrouter", None, settings_db)
|
||||
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db)
|
||||
assert error.value.status_code == 502
|
||||
assert "private-upstream-secret" not in error.value.detail
|
||||
assert settings_db.commit.await_count == commits
|
||||
@@ -123,12 +134,296 @@ async def test_missing_key_is_actionable_and_does_not_request_upstream(settings_
|
||||
pytest.fail("must not query a private catalog without credentials")
|
||||
|
||||
use_upstream(monkeypatch, fail_request)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="minimax",
|
||||
base_url="https://proxy.example.test/anthropic",
|
||||
model="MiniMax-M3",
|
||||
)
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("minimax", None, settings_db)
|
||||
await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db, draft)
|
||||
assert error.value.status_code == 400
|
||||
assert "API Key" in error.value.detail
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_key_on_official_host_refreshes_via_aggregator(settings_db, monkeypatch):
|
||||
seen_urls = []
|
||||
models_dev_payload = {
|
||||
"moonshotai": {"models": {"kimi-k3.1-pro": {"release_date": "2026-10-23"}}},
|
||||
"zhipuai": {"models": {"glm-5.3": {"release_date": "2026-08-14"}}},
|
||||
"meta": {"models": {"muse-ember-1.0": {"release_date": "2026-11-09"}}},
|
||||
"google": {"models": {"gemini-4-neon": {"release_date": "2026-11-18"}}},
|
||||
"xai": {"models": {"grok-4.7": {"release_date": "2026-09-21"}}},
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
seen_urls.append(str(request.url))
|
||||
assert str(request.url) == discovery.MODELS_DEV_CATALOG_URL
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
for provider_id, expected_model in (
|
||||
("moonshotai", "kimi-k3.1-pro"),
|
||||
("glm", "glm-5.3"),
|
||||
("meta", "muse-ember-1.0"),
|
||||
("gemini", "gemini-4-neon"),
|
||||
("grok", "grok-4.7"),
|
||||
):
|
||||
refreshed = await api.refresh_ai_provider_preset(provider_id, ADMIN_USER, settings_db)
|
||||
assert refreshed["data"]["models"] == [expected_model]
|
||||
assert refreshed["data"]["source"].startswith(discovery.MODELS_DEV_CATALOG_URL)
|
||||
stored = await api.get_setting_payload(settings_db, f"llm_provider_preset:{provider_id}")
|
||||
assert stored["models"] == [expected_model]
|
||||
assert seen_urls == [discovery.MODELS_DEV_CATALOG_URL]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_requires_admin_role(settings_db):
|
||||
with pytest.raises(api.HTTPException) as single_err:
|
||||
await api.refresh_ai_provider_preset("openrouter", VIEWER_USER, settings_db)
|
||||
assert single_err.value.status_code == 403
|
||||
|
||||
with pytest.raises(api.HTTPException) as bulk_err:
|
||||
await api.refresh_public_ai_provider_presets(VIEWER_USER, settings_db)
|
||||
assert bulk_err.value.status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_opencode_go_refreshes_ignoring_invalid_saved_and_draft_keys(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
await api.save_setting_payload(
|
||||
settings_db,
|
||||
"external_integrations",
|
||||
{
|
||||
"ai_provider": {
|
||||
"default_provider": "opencode-go",
|
||||
"providers": {
|
||||
"opencode-go": {
|
||||
"base_url": "https://opencode.ai/zen/go/v1",
|
||||
"model": "glm-5.3",
|
||||
"api_key": "stale-invalid-key",
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
def handle(request):
|
||||
assert "authorization" not in request.headers
|
||||
assert "x-api-key" not in request.headers
|
||||
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "deepseek-v4.1-flash"}]})
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="opencode-go",
|
||||
base_url="https://opencode.ai/zen/go/v1",
|
||||
model="glm-5.3",
|
||||
api_key="bad-draft-key",
|
||||
)
|
||||
refreshed = await api.refresh_ai_provider_preset("opencode-go", ADMIN_USER, settings_db, draft)
|
||||
assert refreshed["data"]["models"] == ["glm-5.3", "deepseek-v4.1-flash"]
|
||||
stored = await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go")
|
||||
assert stored["models"] == ["glm-5.3", "deepseek-v4.1-flash"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ollama_openai_completions_works_without_key(settings_db, monkeypatch):
|
||||
def handle(request):
|
||||
assert request.url.path == "/v1/models"
|
||||
assert "authorization" not in request.headers
|
||||
return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]})
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="ollama",
|
||||
provider_api="openai-completions",
|
||||
base_url="http://127.0.0.1:11434/v1",
|
||||
model="qwen2.5:7b",
|
||||
)
|
||||
refreshed = await api.refresh_ai_provider_preset("ollama", ADMIN_USER, settings_db, draft)
|
||||
assert refreshed["data"]["models"] == ["qwen2.5:7b"]
|
||||
|
||||
check = await api._check_ai_provider_lightweight(
|
||||
{
|
||||
"provider": "ollama",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "http://127.0.0.1:11434/v1",
|
||||
"model": "qwen2.5:7b",
|
||||
"api_key": "",
|
||||
},
|
||||
5,
|
||||
)
|
||||
assert check["success"] is True
|
||||
assert check["connected"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_draft_base_url_returns_400_without_calling_upstream(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
use_upstream(
|
||||
monkeypatch,
|
||||
lambda request: pytest.fail("must not query upstream when draft base_url is invalid"),
|
||||
)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="openrouter",
|
||||
base_url="not-a-valid-url",
|
||||
model="openai/gpt-6.2-astra",
|
||||
)
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db, draft)
|
||||
assert error.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_catalog_error_does_not_duplicate_retention_suffix(settings_db, monkeypatch):
|
||||
use_upstream(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db)
|
||||
assert error.value.status_code == 502
|
||||
assert error.value.detail.count("已保留上次模型列表") == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_public_presets_updates_credential_free_and_isolates_failures(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
await api.save_setting_payload(
|
||||
settings_db,
|
||||
"external_integrations",
|
||||
{
|
||||
"ai_provider": {
|
||||
"default_provider": "openrouter",
|
||||
"providers": {
|
||||
"openrouter": {
|
||||
"base_url": "https://proxy.test/api/v1",
|
||||
"model": "custom-model",
|
||||
"api_key": "",
|
||||
},
|
||||
"opencode-go": {
|
||||
"base_url": "https://opencode.ai/zen/go/v1",
|
||||
"model": "glm-5.3",
|
||||
"api_key": "stale-key",
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
await api.save_setting_payload(
|
||||
settings_db, "llm_provider_preset:ollama", {"models": ["kept-local-model"]}
|
||||
)
|
||||
|
||||
seen_hosts = []
|
||||
models_dev_payload = {
|
||||
"minimax-cn": {"models": {"MiniMax-M3": {"release_date": "2026-06-01"}}},
|
||||
"openai": {"models": {"gpt-6.2-astra": {"release_date": "2026-11-17"}}},
|
||||
"anthropic": {"models": {"claude-fable-5-2": {"release_date": "2026-11-09"}}},
|
||||
"deepseek": {"models": {"deepseek-v4-pro": {"release_date": "2026-08-13"}}},
|
||||
"alibaba-cn": {"models": {"qwen4-max": {"release_date": "2026-11-16"}}},
|
||||
"moonshotai": {"models": {"kimi-k3.1-pro": {"release_date": "2026-10-23"}}},
|
||||
"zhipuai": {"models": {"glm-5.3": {"release_date": "2026-08-14"}}},
|
||||
"meta": {"models": {"muse-ember-1.0": {"release_date": "2026-11-09"}}},
|
||||
"google": {"models": {"gemini-4-neon": {"release_date": "2026-11-18"}}},
|
||||
"xai": {"models": {"grok-4.7": {"release_date": "2026-09-21"}}},
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
assert "authorization" not in request.headers
|
||||
if request.url.host == "models.dev":
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
if request.url.host == "opencode.ai":
|
||||
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "qwen4-max"}]})
|
||||
raise httpx.ConnectError("local ollama offline", request=request)
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
summary = await api.refresh_public_ai_provider_presets(ADMIN_USER, settings_db)
|
||||
assert seen_hosts.count("models.dev") == 1
|
||||
assert "opencode.ai" in seen_hosts
|
||||
assert "127.0.0.1" in seen_hosts
|
||||
assert "proxy.test" not in seen_hosts
|
||||
assert "opencode-go" in summary["refreshed"]
|
||||
assert "glm" in summary["refreshed"]
|
||||
assert "moonshotai" in summary["refreshed"]
|
||||
assert summary["failed"] == ["ollama"]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go"))[
|
||||
"models"
|
||||
] == ["glm-5.3", "qwen4-max"]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:glm"))["models"] == [
|
||||
"glm-5.3"
|
||||
]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:ollama"))[
|
||||
"models"
|
||||
] == ["kept-local-model"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deepseek_stale_saved_key_refreshes_via_aggregator_but_connect_fails(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
await api.save_setting_payload(
|
||||
settings_db,
|
||||
"external_integrations",
|
||||
{
|
||||
"ai_provider": {
|
||||
"default_provider": "deepseek",
|
||||
"providers": {
|
||||
"deepseek": {
|
||||
"base_url": "https://api.deepseek.com/v1",
|
||||
"provider_api": "openai-completions",
|
||||
"model": "deepseek-chat",
|
||||
"api_key": "sk-stale-deepseek-key",
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
seen_hosts = []
|
||||
models_dev_payload = {
|
||||
"deepseek": {
|
||||
"models": {
|
||||
"deepseek-v4-flash": {"release_date": "2026-10-17", "modalities": {"output": ["text"]}},
|
||||
"deepseek-v4-pro": {"release_date": "2026-08-13", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
if request.url.host == "api.deepseek.com":
|
||||
return httpx.Response(401, text="secret-upstream-auth-error")
|
||||
if str(request.url) == discovery.MODELS_DEV_CATALOG_URL:
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
pytest.fail(f"unexpected URL {request.url}")
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
refreshed = await api.refresh_ai_provider_preset("deepseek", ADMIN_USER, settings_db)
|
||||
assert seen_hosts == ["api.deepseek.com", "models.dev"]
|
||||
assert refreshed["data"]["models"] == ["deepseek-v4-flash", "deepseek-v4-pro"]
|
||||
assert refreshed["data"]["source"] == f"{discovery.MODELS_DEV_CATALOG_URL}#deepseek"
|
||||
assert "sk-stale-deepseek-key" not in str(refreshed)
|
||||
stored = await api.get_setting_payload(settings_db, "llm_provider_preset:deepseek")
|
||||
assert stored["models"] == ["deepseek-v4-flash", "deepseek-v4-pro"]
|
||||
|
||||
# Connectivity test with stale key must still fail strictly without hitting aggregator
|
||||
seen_hosts.clear()
|
||||
check = await api._check_ai_provider_lightweight(
|
||||
{
|
||||
"provider": "deepseek",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.deepseek.com/v1",
|
||||
"model": "deepseek-v4-flash",
|
||||
"api_key": "sk-stale-deepseek-key",
|
||||
},
|
||||
5,
|
||||
)
|
||||
assert check["success"] is False
|
||||
assert check["connected"] is False
|
||||
assert seen_hosts == ["api.deepseek.com"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"preset", list_fallback_llm_provider_presets(), ids=lambda p: p["provider"]
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
"""Tests for Wikidata/PeeringDB L1 resolvers and Tool-Calling Location Agent."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.db.session import Base
|
||||
from app.models.compute_center_location import ComputeCenterLocationRecord
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.services.location.agent_resolver import run_controlled_location_agent
|
||||
from app.services.location.models import LocationQuery
|
||||
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
|
||||
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
|
||||
|
||||
|
||||
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 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_sync_db():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[ComputeCenterLocationRecord.__table__, WorkflowRun.__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_wikidata_and_peeringdb_resolvers_parse_coordinates(monkeypatch):
|
||||
class _FakeResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
class _FakeAsyncClient:
|
||||
def __init__(self, **_kwargs):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
async def get(self, url, params=None):
|
||||
if "wikidata.org" in url and (params or {}).get("action") == "wbsearchentities":
|
||||
return _FakeResponse({"search": [{"id": "Q123456"}]})
|
||||
if "wikidata.org" in url and (params or {}).get("action") == "wbgetentities":
|
||||
return _FakeResponse(
|
||||
{
|
||||
"entities": {
|
||||
"Q123456": {
|
||||
"labels": {"en": {"value": "Memphis Supercluster Facility"}},
|
||||
"descriptions": {"en": {"value": "data center campus in Memphis, Tennessee"}},
|
||||
"claims": {
|
||||
"P625": [
|
||||
{
|
||||
"mainsnak": {
|
||||
"datavalue": {
|
||||
"value": {"latitude": 35.0612, "longitude": -90.1511}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
if "peeringdb.com" in url:
|
||||
return _FakeResponse(
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 9901,
|
||||
"name": "Equinix NY5 Secaucus",
|
||||
"city": "Secaucus",
|
||||
"state": "NJ",
|
||||
"country": "US",
|
||||
"address1": "800 Secaucus Rd",
|
||||
"latitude": 40.7831,
|
||||
"longitude": -74.0725,
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
return _FakeResponse({})
|
||||
|
||||
from app.services.location.resolvers import peeringdb_facility, wikidata
|
||||
|
||||
monkeypatch.setattr(wikidata.httpx, "AsyncClient", _FakeAsyncClient)
|
||||
monkeypatch.setattr(peeringdb_facility.httpx, "AsyncClient", _FakeAsyncClient)
|
||||
|
||||
wd_out = await lookup_wikidata_facility(
|
||||
LocationQuery(name="Memphis Supercluster Facility", country="United States")
|
||||
)
|
||||
assert len(wd_out.candidates) == 1
|
||||
assert wd_out.candidates[0].source == "wikidata_facility"
|
||||
assert wd_out.candidates[0].latitude == pytest.approx(35.0612, abs=1e-4)
|
||||
|
||||
pdb_out = await lookup_peeringdb_facility(
|
||||
LocationQuery(name="Equinix NY5 Secaucus", country="United States")
|
||||
)
|
||||
assert len(pdb_out.candidates) == 1
|
||||
assert pdb_out.candidates[0].source == "peeringdb_facility"
|
||||
assert pdb_out.candidates[0].precision == "precise"
|
||||
assert pdb_out.candidates[0].city == "Secaucus"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_calling_location_agent_loop_and_guardrails(monkeypatch):
|
||||
from app.services.location import agent_resolver
|
||||
|
||||
async def _fake_safe_fetch(url, **_kwargs):
|
||||
return {
|
||||
"url": url,
|
||||
"status_code": 200,
|
||||
"content": "The Colossus supercomputer operates at 5420 Tulane Rd, Memphis, TN, USA.",
|
||||
}
|
||||
|
||||
def _fake_geocode(place_query, country_hint=""):
|
||||
return {
|
||||
"latitude": 35.0612,
|
||||
"longitude": -90.1511,
|
||||
"display_name": "5420 Tulane Rd, Memphis, Shelby County, Tennessee, United States",
|
||||
"city": "Memphis",
|
||||
"region": "Tennessee",
|
||||
"country": "美国",
|
||||
"precision": "precise",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(agent_resolver, "safe_web_fetch", _fake_safe_fetch)
|
||||
monkeypatch.setattr(agent_resolver, "_agent_geocoder", _fake_geocode)
|
||||
|
||||
class _StepProvider:
|
||||
def __init__(self):
|
||||
self.turn = 0
|
||||
|
||||
async def analyze(self, req):
|
||||
self.turn += 1
|
||||
if self.turn == 1:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="call_1",
|
||||
name="fetch_source_url",
|
||||
arguments=json.dumps({"url": "https://epoch.ai/colossus-source"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
if self.turn == 2:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="call_2",
|
||||
name="geocode_verify",
|
||||
arguments=json.dumps({"place_query": "5420 Tulane Rd, Memphis, USA", "country": "United States"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="call_3",
|
||||
name="submit_location_result",
|
||||
arguments=json.dumps(
|
||||
{
|
||||
"status": "located",
|
||||
"facility_name": "Colossus Memphis Campus",
|
||||
"city": "Memphis",
|
||||
"region": "Tennessee",
|
||||
"country": "United States",
|
||||
"precision": "precise",
|
||||
"geocode_candidate_id": "geo_1",
|
||||
"citations": ["https://epoch.ai/colossus-source"],
|
||||
"confidence": 0.91,
|
||||
"reasoning": "Epoch source confirms 5420 Tulane Rd in Memphis.",
|
||||
}
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
engine, factory = _make_sync_db()
|
||||
|
||||
try:
|
||||
async with factory() as session:
|
||||
result, term = await run_controlled_location_agent(
|
||||
provider_client=_StepProvider(),
|
||||
web_search_client=None,
|
||||
query=LocationQuery(
|
||||
name="Colossus",
|
||||
country="United States",
|
||||
extra={"source": "epoch_ai_gpu", "source_id": "epoch-colossus", "source_url": "https://epoch.ai/colossus-source"},
|
||||
),
|
||||
db=session,
|
||||
)
|
||||
assert term is None
|
||||
assert len(result.candidates) == 1
|
||||
cand = result.candidates[0]
|
||||
assert cand.precision == "precise"
|
||||
assert cand.city == "Memphis"
|
||||
assert cand.raw_payload["citations"] == ["https://epoch.ai/colossus-source"]
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_calling_agent_rejects_unobserved_citations_and_persists_terminal(monkeypatch):
|
||||
from app.services.location import agent_resolver
|
||||
|
||||
monkeypatch.setattr(agent_resolver, "_agent_geocoder", lambda _q, _c="": {
|
||||
"latitude": 35.0612,
|
||||
"longitude": -90.1511,
|
||||
"display_name": "Memphis, TN, USA",
|
||||
"city": "Memphis",
|
||||
"country": "美国",
|
||||
"precision": "city",
|
||||
})
|
||||
|
||||
class _FabricatedCitationProvider:
|
||||
def __init__(self):
|
||||
self.turn = 0
|
||||
|
||||
async def analyze(self, _req):
|
||||
self.turn += 1
|
||||
if self.turn == 1:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="g1",
|
||||
name="geocode_verify",
|
||||
arguments=json.dumps({"place_query": "Memphis, USA", "country": "United States"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="s1",
|
||||
name="submit_location_result",
|
||||
arguments=json.dumps(
|
||||
{
|
||||
"status": "located",
|
||||
"geocode_candidate_id": "geo_1",
|
||||
"citations": ["https://madeup.example.com/fake-url"],
|
||||
"country": "United States",
|
||||
"reasoning": "Made up citation test",
|
||||
}
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
res_bad, _ = await run_controlled_location_agent(
|
||||
provider_client=_FabricatedCitationProvider(),
|
||||
web_search_client=None,
|
||||
query=LocationQuery(name="FakeCitedCluster", country="United States"),
|
||||
)
|
||||
assert res_bad.candidates == []
|
||||
assert "No verified citation URLs" in (res_bad.failure_reason or "")
|
||||
|
||||
class _TerminalProvider:
|
||||
async def analyze(self, _req):
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="t1",
|
||||
name="submit_location_result",
|
||||
arguments=json.dumps(
|
||||
{
|
||||
"status": "undisclosed",
|
||||
"reasoning": "Customer confidential cluster location is undisclosed.",
|
||||
}
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
engine, factory = _make_sync_db()
|
||||
|
||||
from app.services import compute_center_locations
|
||||
|
||||
monkeypatch.setattr(
|
||||
compute_center_locations,
|
||||
"refresh_compute_center_location_cache",
|
||||
lambda _db: _noop(),
|
||||
)
|
||||
|
||||
async def _noop():
|
||||
return None
|
||||
|
||||
try:
|
||||
async with factory() as session:
|
||||
res_term, term = await run_controlled_location_agent(
|
||||
provider_client=_TerminalProvider(),
|
||||
web_search_client=None,
|
||||
query=LocationQuery(
|
||||
name="Undisclosed Customer",
|
||||
extra={"source": "epoch_ai_gpu", "source_id": "epoch-undisclosed"},
|
||||
),
|
||||
db=session,
|
||||
)
|
||||
assert term == "undisclosed"
|
||||
assert res_term.candidates == []
|
||||
saved = await session.get(ComputeCenterLocationRecord, 1)
|
||||
assert saved is not None
|
||||
assert saved.verification_status == "undisclosed"
|
||||
finally:
|
||||
engine.dispose()
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from unittest.mock import patch
|
||||
@@ -175,3 +176,269 @@ async def test_minimax_m31_flash_forces_adaptive_thinking_and_effort(monkeypatch
|
||||
assert payloads[0]["output_config"] == {"effort": "low"}
|
||||
assert payloads[1]["thinking"] == {"type": "adaptive"}
|
||||
assert payloads[1]["output_config"] == {"effort": "medium"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_analyze_anthropic_emits_thinking_text_and_done(monkeypatch):
|
||||
client_type = httpx.AsyncClient
|
||||
sse_bytes = (
|
||||
b'event: message_start\n'
|
||||
b'data: {"type":"message_start","message":{"model":"MiniMax-M2.7","usage":{"input_tokens":12}}}\n\n'
|
||||
b'event: content_block_delta\n'
|
||||
b'data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"step-1 "}}\n\n'
|
||||
b'event: content_block_delta\n'
|
||||
b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hello "}}\n\n'
|
||||
b'event: message_delta\n'
|
||||
b'data: {"type":"message_delta","usage":{"output_tokens":7}}\n\n'
|
||||
b'event: message_stop\n'
|
||||
b'data: {"type":"message_stop"}\n\n'
|
||||
)
|
||||
|
||||
def handle(_request):
|
||||
return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"})
|
||||
|
||||
transport = httpx.MockTransport(handle)
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "test-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
}
|
||||
)
|
||||
|
||||
events = []
|
||||
async for ev in service.stream_analyze(
|
||||
SituationalAnalysisRequest(title="news", objective="analyze", thinking={"type": "enabled", "budget_tokens": 1024})
|
||||
):
|
||||
events.append(ev)
|
||||
|
||||
assert events[0] == {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
assert {"event": "reasoning", "delta": "step-1 "} in events
|
||||
assert {"event": "text", "delta": "hello "} in events
|
||||
assert events[-1]["event"] == "done"
|
||||
assert events[-1]["model"] == "MiniMax-M2.7"
|
||||
assert events[-1]["usage"]["output_tokens"] == 7
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_analyze_openai_emits_reasoning_and_text(monkeypatch):
|
||||
client_type = httpx.AsyncClient
|
||||
sse_bytes = (
|
||||
b'data: {"model":"gpt-5.6","choices":[{"delta":{"reasoning_content":"check cables"}}]}\n\n'
|
||||
b'data: {"model":"gpt-5.6","choices":[{"delta":{"content":"summary ok"}}],"usage":{"total_tokens":20}}\n\n'
|
||||
b'data: [DONE]\n\n'
|
||||
)
|
||||
|
||||
def handle(_request):
|
||||
return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"})
|
||||
|
||||
transport = httpx.MockTransport(handle)
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "openai",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.openai.test/v1",
|
||||
"api_key": "test-key",
|
||||
"model": "gpt-5.6",
|
||||
}
|
||||
)
|
||||
|
||||
events = []
|
||||
async for ev in service.stream_analyze(SituationalAnalysisRequest(title="global", objective="analyze")):
|
||||
events.append(ev)
|
||||
|
||||
assert {"event": "reasoning", "delta": "check cables"} in events
|
||||
assert {"event": "text", "delta": "summary ok"} in events
|
||||
assert events[-1]["event"] == "done"
|
||||
assert events[-1]["usage"]["total_tokens"] == 20
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_analyze_forwards_normalized_multi_turn_messages(monkeypatch):
|
||||
client_type = httpx.AsyncClient
|
||||
captured_bodies = []
|
||||
|
||||
def handle(request):
|
||||
captured_bodies.append(json.loads(request.content.decode("utf-8")))
|
||||
sse = (
|
||||
b'event: content_block_delta\n'
|
||||
b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"multi-turn ok"}}\n\n'
|
||||
b'event: message_stop\n'
|
||||
b'data: {"type":"message_stop"}\n\n'
|
||||
)
|
||||
return httpx.Response(200, content=sse, headers={"content-type": "text/event-stream"})
|
||||
|
||||
transport = httpx.MockTransport(handle)
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "test-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
}
|
||||
)
|
||||
|
||||
events = []
|
||||
async for ev in service.stream_analyze(
|
||||
SituationalAnalysisRequest(
|
||||
title="follow-up",
|
||||
objective="继续追问第二点",
|
||||
messages=[
|
||||
{"role": "assistant", "content": "leading assistant ignored"},
|
||||
{"role": "user", "content": "第一轮问题"},
|
||||
{"role": "assistant", "content": "第一轮回答"},
|
||||
],
|
||||
)
|
||||
):
|
||||
events.append(ev)
|
||||
|
||||
assert len(captured_bodies) == 1
|
||||
sent_msgs = captured_bodies[0]["messages"]
|
||||
assert [m["role"] for m in sent_msgs] == ["user", "assistant", "user"]
|
||||
assert sent_msgs[0]["content"][0]["text"] == "第一轮问题"
|
||||
assert sent_msgs[1]["content"][0]["text"] == "第一轮回答"
|
||||
assert "继续追问第二点" in sent_msgs[2]["content"][0]["text"]
|
||||
assert {"event": "text", "delta": "multi-turn ok"} in events
|
||||
|
||||
|
||||
def test_anthropic_request_omits_temperature_and_bumps_max_tokens_when_thinking_enabled():
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "test-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
"max_tokens": 1200,
|
||||
}
|
||||
)
|
||||
|
||||
_, _, enabled_body = service._build_anthropic_request(
|
||||
"MiniMax-M2.7",
|
||||
"analyze",
|
||||
thinking={"type": "enabled", "budget_tokens": 2048},
|
||||
stream=True,
|
||||
)
|
||||
assert "temperature" not in enabled_body
|
||||
assert enabled_body["max_tokens"] == 3072
|
||||
assert enabled_body["thinking"] == {"type": "enabled", "budget_tokens": 2048}
|
||||
|
||||
_, _, adaptive_body = service._build_anthropic_request(
|
||||
"MiniMax-M3.1",
|
||||
"analyze",
|
||||
thinking=None,
|
||||
stream=True,
|
||||
)
|
||||
assert "temperature" not in adaptive_body
|
||||
assert adaptive_body["thinking"] == {"type": "adaptive"}
|
||||
|
||||
_, _, disabled_body = service._build_anthropic_request(
|
||||
"MiniMax-M2.7",
|
||||
"analyze",
|
||||
thinking=None,
|
||||
stream=False,
|
||||
)
|
||||
assert disabled_body["temperature"] == 0.2
|
||||
assert disabled_body["thinking"] == {"type": "disabled"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_protocol_tools_structured_output_and_json_context(monkeypatch):
|
||||
service_openai = ProviderService(
|
||||
{
|
||||
"provider": "openai",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.openai.test/v1",
|
||||
"api_key": "test-key",
|
||||
"model": "gpt-6-astra",
|
||||
}
|
||||
)
|
||||
tools_spec = [
|
||||
{
|
||||
"name": "web_search",
|
||||
"description": "Search web",
|
||||
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]},
|
||||
}
|
||||
]
|
||||
req = SituationalAnalysisRequest(
|
||||
title="locate",
|
||||
objective="find location",
|
||||
context={"country": "中国", "sources": ["https://example.invalid/a"]},
|
||||
tools=tools_spec,
|
||||
tool_choice="auto",
|
||||
response_format={"type": "json_schema", "json_schema": {"name": "loc", "schema": {"type": "object"}}},
|
||||
)
|
||||
prompt = service_openai._build_prompt(req)
|
||||
assert '"country": "中国"' in prompt
|
||||
|
||||
captured_openai = []
|
||||
|
||||
async def fake_post_openai(**kwargs):
|
||||
captured_openai.append(kwargs["request_body"])
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"finish_reason": "tool_calls",
|
||||
"message": {
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"id": "call_1", "type": "function", "function": {"name": "web_search", "arguments": '{"query":"Frontier ORNL"}'}}
|
||||
],
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
monkeypatch.setattr(service_openai, "_post", fake_post_openai)
|
||||
resp = await service_openai.analyze(req)
|
||||
assert captured_openai[0]["tools"][0]["function"]["name"] == "web_search"
|
||||
assert captured_openai[0]["response_format"]["type"] == "json_schema"
|
||||
assert resp.stop_reason == "tool_calls"
|
||||
assert len(resp.tool_calls) == 1
|
||||
assert resp.tool_calls[0].name == "web_search"
|
||||
assert resp.tool_calls[0].arguments == {"query": "Frontier ORNL"}
|
||||
|
||||
service_anthropic = ProviderService(
|
||||
{
|
||||
"provider": "anthropic",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.anthropic.test/v1",
|
||||
"api_key": "test-key",
|
||||
"model": "claude-sonnet",
|
||||
}
|
||||
)
|
||||
captured_anth = []
|
||||
|
||||
async def fake_post_anth(**kwargs):
|
||||
captured_anth.append(kwargs["request_body"])
|
||||
return {
|
||||
"stop_reason": "tool_use",
|
||||
"content": [
|
||||
{"type": "tool_use", "id": "tu_1", "name": "web_search", "input": {"query": "Oak Ridge"}}
|
||||
],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(service_anthropic, "_post", fake_post_anth)
|
||||
anth_req = SituationalAnalysisRequest(
|
||||
title="locate",
|
||||
objective="continue",
|
||||
tools=tools_spec,
|
||||
native_web_search=True,
|
||||
messages=[
|
||||
{"role": "user", "content": "find Frontier"},
|
||||
{"role": "assistant", "content": "", "tool_calls": [{"id": "tu_0", "name": "web_search", "arguments": {"query": "Frontier"}}]},
|
||||
{"role": "tool", "tool_call_id": "tu_0", "content": '{"results": []}'},
|
||||
],
|
||||
)
|
||||
anth_resp = await service_anthropic.analyze(anth_req)
|
||||
assert any(t.get("type") == "web_search_20250305" for t in captured_anth[0]["tools"])
|
||||
assert captured_anth[0]["messages"][1]["content"][0]["type"] == "tool_use"
|
||||
assert captured_anth[0]["messages"][2]["content"][0]["type"] == "tool_result"
|
||||
assert anth_resp.tool_calls[0].id == "tu_1"
|
||||
assert anth_resp.tool_calls[0].arguments == {"query": "Oak Ridge"}
|
||||
@@ -37,6 +37,10 @@ def isolated_ai_provider_env_file(monkeypatch, tmp_path):
|
||||
"DEEPSEEK_API_KEY",
|
||||
"DASHSCOPE_API_KEY",
|
||||
"MOONSHOT_API_KEY",
|
||||
"ZHIPU_API_KEY",
|
||||
"META_MODEL_API_KEY",
|
||||
"GEMINI_API_KEY",
|
||||
"XAI_API_KEY",
|
||||
"OPENROUTER_API_KEY",
|
||||
"OPENCODE_GO_API_KEY",
|
||||
):
|
||||
@@ -108,13 +112,27 @@ def test_opencode_go_provider_preset_is_openai_compatible():
|
||||
assert preset["label"] == "OpenCode Go"
|
||||
assert preset["provider_api"] == "openai-completions"
|
||||
assert preset["base_url"] == "https://opencode.ai/zen/go/v1"
|
||||
assert preset["model"] == "glm-5.1"
|
||||
assert "glm-5.1" in preset["models"]
|
||||
assert "deepseek-v4-flash" in preset["models"]
|
||||
assert preset["model"] == "glm-5.3"
|
||||
assert "glm-5.3" in preset["models"]
|
||||
assert "deepseek-v4.1-flash" in preset["models"]
|
||||
assert preset["model_provider_apis"]["minimax-m2.7"] == "anthropic-messages"
|
||||
assert preset["api_key_env"] == "OPENCODE_GO_API_KEY"
|
||||
|
||||
|
||||
def test_glm_meta_gemini_and_grok_default_presets():
|
||||
assert get_fallback_llm_provider_preset("glm")["base_url"] == "https://open.bigmodel.cn/api/paas/v4"
|
||||
assert get_fallback_llm_provider_preset("glm")["api_key_env"] == "ZHIPU_API_KEY"
|
||||
assert get_fallback_llm_provider_preset("meta")["base_url"] == "https://api.meta.ai/v1"
|
||||
assert get_fallback_llm_provider_preset("meta")["api_key_env"] == "META_MODEL_API_KEY"
|
||||
assert (
|
||||
get_fallback_llm_provider_preset("gemini")["base_url"]
|
||||
== "https://generativelanguage.googleapis.com/v1beta/openai"
|
||||
)
|
||||
assert get_fallback_llm_provider_preset("gemini")["api_key_env"] == "GEMINI_API_KEY"
|
||||
assert get_fallback_llm_provider_preset("grok")["base_url"] == "https://api.x.ai/v1"
|
||||
assert get_fallback_llm_provider_preset("grok")["api_key_env"] == "XAI_API_KEY"
|
||||
|
||||
|
||||
def test_mask_secret_without_prefix_is_fully_masked():
|
||||
assert _mask_secret("plainsecret")["preview"] == "***********"
|
||||
assert _mask_secret("sk-prefixed")["preview"] == "sk-********"
|
||||
|
||||
@@ -10,9 +10,19 @@ from app.api.v1.visualization import (
|
||||
convert_compute_centers_to_geojson,
|
||||
)
|
||||
import app.services.compute_center_locations as compute_center_locations
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.main import app
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
def _override_admin_user() -> User:
|
||||
return User(id=1, username="test-admin", email="admin@example.invalid", role="admin", is_active=True)
|
||||
|
||||
|
||||
def _override_viewer_user() -> User:
|
||||
return User(id=2, username="test-viewer", email="viewer@example.invalid", role="viewer", is_active=True)
|
||||
|
||||
|
||||
def _build_record(
|
||||
@@ -1158,6 +1168,7 @@ async def test_collect_location_endpoint_returns_candidates_for_known_record(mon
|
||||
yield _FakeSession()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
app.dependency_overrides[get_current_user] = _override_admin_user
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
@@ -1213,6 +1224,7 @@ async def test_collect_location_endpoint_returns_failure_reason(monkeypatch):
|
||||
yield _FakeSession()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
app.dependency_overrides[get_current_user] = _override_admin_user
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
@@ -1292,6 +1304,7 @@ async def test_save_location_endpoint_upserts_and_geojson_can_render():
|
||||
yield fake_session
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
app.dependency_overrides[get_current_user] = _override_admin_user
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
@@ -1411,3 +1424,51 @@ def test_infrastructure_type_is_preserved_in_geojson_and_image_classification(ki
|
||||
record.extra_data = {**record.extra_data, "site_type": kind, "location": "Tokyo, Japan"}
|
||||
assert compute_site_type(record) == kind
|
||||
assert convert_compute_centers_to_geojson([record])["features"][0]["properties"]["site_type"] == kind
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compute_center_location_write_endpoints_require_admin():
|
||||
collect_payload = {
|
||||
"name": "Frontier",
|
||||
"operator": "Oak Ridge National Laboratory",
|
||||
"country": "United States",
|
||||
}
|
||||
save_payload = {
|
||||
"source": "epoch_ai_gpu",
|
||||
"name": "Saved Cluster",
|
||||
"latitude": 35.1495,
|
||||
"longitude": -90.049,
|
||||
"precision": "city",
|
||||
"confidence": 0.72,
|
||||
"location_source": "ror_organization_registry",
|
||||
}
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
app.dependency_overrides.clear()
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
r1 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/top500-42/collect-location",
|
||||
json=collect_payload,
|
||||
)
|
||||
r2 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/epoch_ai_gpu-52/location",
|
||||
json=save_payload,
|
||||
)
|
||||
assert r1.status_code == 401
|
||||
assert r2.status_code == 401
|
||||
|
||||
app.dependency_overrides[get_current_user] = _override_viewer_user
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
r3 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/top500-42/collect-location",
|
||||
json=collect_payload,
|
||||
)
|
||||
r4 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/epoch_ai_gpu-52/location",
|
||||
json=save_payload,
|
||||
)
|
||||
assert r3.status_code == 403
|
||||
assert r4.status_code == 403
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -154,3 +154,50 @@ async def test_satellite_cursor_closes_if_conversion_fails(
|
||||
await visualization._build_satellites_geojson(limit=None, db=satellite_db)
|
||||
|
||||
assert satellite_db.streams[0].closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compact_satellite_builder_emits_compact_rows_and_fallback_elements(
|
||||
satellite_db: SatelliteSession,
|
||||
) -> None:
|
||||
with_tle = satellite(10)
|
||||
without_tle = CollectedData(
|
||||
id=11,
|
||||
source="celestrak_tle",
|
||||
source_id="11",
|
||||
data_type="satellite_tle",
|
||||
name="NO-TLE-SAT",
|
||||
is_current=True,
|
||||
task_id=1,
|
||||
collected_at=datetime(2026, 1, 1, tzinfo=UTC),
|
||||
extra_data={
|
||||
"norad_cat_id": 51000,
|
||||
"inclination": 53.2,
|
||||
"raan": 120.5,
|
||||
"eccentricity": 0.00012,
|
||||
"arg_of_perigee": 90.0,
|
||||
"mean_anomaly": 45.0,
|
||||
"mean_motion": 15.1,
|
||||
"international_designator": "24001A",
|
||||
"classification_type": "U",
|
||||
"bstar": 0.0001,
|
||||
},
|
||||
)
|
||||
starlink = satellite(12, name="STARLINK-1234")
|
||||
satellite_db.session.add_all([with_tle, without_tle, starlink])
|
||||
satellite_db.session.commit()
|
||||
|
||||
payload = await visualization._build_satellites_compact(limit=None, db=satellite_db)
|
||||
|
||||
assert payload["format"] == "satellite_compact_v1"
|
||||
assert payload["count"] == 3
|
||||
rows_by_id = {row[0]: row for row in payload["satellites"]}
|
||||
assert len(rows_by_id[10]) == 6
|
||||
assert rows_by_id[10][:4] == [10, 40010, "SAT-10", None]
|
||||
assert rows_by_id[10][4:6] == ["line-1-10", "line-2-10"]
|
||||
assert rows_by_id[12][:4] == [12, 40012, "STARLINK-1234", "starlink"]
|
||||
assert len(rows_by_id[11]) == 7
|
||||
assert rows_by_id[11][4] is None
|
||||
assert isinstance(rows_by_id[11][5], str) and rows_by_id[11][5].startswith("2 51000 ")
|
||||
assert rows_by_id[11][6][:2] == [53.2, 120.5]
|
||||
assert all(stream.closed for stream in satellite_db.streams)
|
||||
@@ -56,6 +56,8 @@ linux:
|
||||
mac:
|
||||
icon: resources/icon.png
|
||||
category: public.app-category.utilities
|
||||
extendInfo:
|
||||
NSCameraUsageDescription: Planet Earth uses your camera locally for motion gesture control.
|
||||
target:
|
||||
- target: dmg
|
||||
arch:
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.78.0",
|
||||
"version": "0.81.0",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
@@ -37,6 +37,7 @@
|
||||
"start": "bun run build && bun ./scripts/launch-electron.mjs",
|
||||
"dev": "bun run build && bun ./scripts/launch-electron.mjs --devtools",
|
||||
"dist:dir": "bun run build && bun ./scripts/dist-target.mjs --dir",
|
||||
"dist:hotfix": "bun run build:earth",
|
||||
"dist:win": "bun run build && bun ./scripts/dist-target.mjs --win",
|
||||
"dist:linux": "bun run build && bun ./scripts/dist-target.mjs --linux",
|
||||
"dist:mac": "bun run build && bun ./scripts/dist-target.mjs --mac",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs'
|
||||
import { createTarGz } from '../src/main/tar-gz.ts'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const desktopRoot = join(__dirname, '..')
|
||||
@@ -88,15 +90,65 @@ if (existsSync(zjuEmblemSrc)) {
|
||||
const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json'))
|
||||
const mediaPipeOutDir = join(bundleEarthDir, 'vendor/mediapipe')
|
||||
mkdirSync(mediaPipeOutDir, { recursive: true })
|
||||
for (const candidate of ['vision_bundle.mjs', 'vision_bundle.cjs']) {
|
||||
const srcFile = join(mediaPipePkgDir, candidate)
|
||||
if (existsSync(srcFile)) {
|
||||
cpSync(srcFile, join(mediaPipeOutDir, candidate))
|
||||
}
|
||||
const mediaPipeBundleSrc = join(mediaPipePkgDir, 'vision_bundle.mjs')
|
||||
if (existsSync(mediaPipeBundleSrc)) {
|
||||
cpSync(mediaPipeBundleSrc, join(mediaPipeOutDir, 'vision_bundle.mjs'))
|
||||
}
|
||||
const mediaPipeWasmDir = join(mediaPipePkgDir, 'wasm')
|
||||
if (existsSync(mediaPipeWasmDir)) {
|
||||
cpSync(mediaPipeWasmDir, join(mediaPipeOutDir, 'wasm'), { recursive: true })
|
||||
}
|
||||
const poseModelSrc = join(earthSourceDir, 'vendor/mediapipe/pose_landmarker_lite.task')
|
||||
if (!existsSync(poseModelSrc)) {
|
||||
throw new Error(`Missing bundled MediaPipe pose model: ${poseModelSrc}`)
|
||||
}
|
||||
cpSync(poseModelSrc, join(mediaPipeOutDir, 'pose_landmarker_lite.task'))
|
||||
|
||||
console.log(`Built offline Earth bundle at ${bundleEarthDir}`)
|
||||
|
||||
const clientPkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
|
||||
const bundleVersion = String(clientPkg.version || '0.0.0').trim()
|
||||
const metaPayload = {
|
||||
version: bundleVersion,
|
||||
shellVersion: bundleVersion,
|
||||
builtAt: new Date().toISOString(),
|
||||
}
|
||||
writeFileSync(join(bundleEarthDir, 'bundle-meta.json'), `${JSON.stringify(metaPayload, null, 2)}\n`, 'utf8')
|
||||
|
||||
function collectHotfixEntries(rootDir) {
|
||||
const entries = []
|
||||
for (const topFile of ['index.html', 'bundle-meta.json']) {
|
||||
const filePath = join(rootDir, topFile)
|
||||
if (existsSync(filePath)) {
|
||||
entries.push({ path: topFile, data: readFileSync(filePath) })
|
||||
}
|
||||
}
|
||||
const walk = (relDir) => {
|
||||
const absDir = join(rootDir, relDir)
|
||||
if (!existsSync(absDir)) return
|
||||
for (const dirent of readdirSync(absDir, { withFileTypes: true })) {
|
||||
const relPath = `${relDir}/${dirent.name}`
|
||||
if (dirent.isDirectory()) {
|
||||
walk(relPath)
|
||||
} else if (dirent.isFile()) {
|
||||
entries.push({ path: relPath, data: readFileSync(join(rootDir, relPath)) })
|
||||
}
|
||||
}
|
||||
}
|
||||
walk('js')
|
||||
walk('css')
|
||||
return entries
|
||||
}
|
||||
|
||||
const hotfixEntries = collectHotfixEntries(bundleEarthDir)
|
||||
const hotfixArchive = createTarGz(hotfixEntries)
|
||||
const hotfixSha256 = createHash('sha256').update(hotfixArchive).digest('hex')
|
||||
const releaseOutDir = join(desktopRoot, 'release')
|
||||
mkdirSync(releaseOutDir, { recursive: true })
|
||||
const hotfixName = `planet-earth-bundle-${bundleVersion}.tar.gz`
|
||||
const hotfixPath = join(releaseOutDir, hotfixName)
|
||||
writeFileSync(hotfixPath, hotfixArchive)
|
||||
writeFileSync(join(releaseOutDir, `${hotfixName}.sha256`), `${hotfixSha256} ${hotfixName}\n`, 'utf8')
|
||||
console.log(
|
||||
`Built L1 hotfix bundle ${hotfixPath} (${(hotfixArchive.byteLength / 1024).toFixed(1)} KiB, sha256=${hotfixSha256})`,
|
||||
)
|
||||
@@ -16,6 +16,11 @@ const mainBuild = await Bun.build({
|
||||
external: ['electron'],
|
||||
minify: true,
|
||||
naming: 'index.cjs',
|
||||
define: {
|
||||
'process.env.PLANET_EARTH_DESKTOP_HANDSHAKE_SECRET': JSON.stringify(
|
||||
process.env.PLANET_EARTH_DESKTOP_HANDSHAKE_SECRET || '',
|
||||
),
|
||||
},
|
||||
})
|
||||
|
||||
if (!mainBuild.success) {
|
||||
@@ -36,4 +41,32 @@ if (!preloadBuild.success) {
|
||||
throw new AggregateError(preloadBuild.logs, 'Electron preload build failed')
|
||||
}
|
||||
|
||||
const indicatorPreloadBuild = await Bun.build({
|
||||
entrypoints: [join(desktopRoot, 'src/preload/recording-indicator.ts')],
|
||||
outdir: join(outDir, 'preload'),
|
||||
target: 'node',
|
||||
format: 'cjs',
|
||||
external: ['electron'],
|
||||
minify: true,
|
||||
naming: 'recording-indicator.cjs',
|
||||
})
|
||||
|
||||
if (!indicatorPreloadBuild.success) {
|
||||
throw new AggregateError(indicatorPreloadBuild.logs, 'Electron indicator preload build failed')
|
||||
}
|
||||
|
||||
const cursorPreloadBuild = await Bun.build({
|
||||
entrypoints: [join(desktopRoot, 'src/preload/recording-cursor.ts')],
|
||||
outdir: join(outDir, 'preload'),
|
||||
target: 'node',
|
||||
format: 'cjs',
|
||||
external: ['electron'],
|
||||
minify: true,
|
||||
naming: 'recording-cursor.cjs',
|
||||
})
|
||||
|
||||
if (!cursorPreloadBuild.success) {
|
||||
throw new AggregateError(cursorPreloadBuild.logs, 'Electron cursor preload build failed')
|
||||
}
|
||||
|
||||
console.log('Built Electron main and preload to dist-electron/')
|
||||
+175
-31
@@ -1,7 +1,10 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import {
|
||||
chmodSync,
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
@@ -129,43 +132,177 @@ function resolveLinuxTargets() {
|
||||
return targets
|
||||
}
|
||||
|
||||
function toWslPath(winPath) {
|
||||
if (!winPath) return ''
|
||||
const res = spawnSync('wslpath', ['-u', winPath], { encoding: 'utf8' })
|
||||
return res.status === 0 ? (res.stdout || '').trim() : ''
|
||||
}
|
||||
|
||||
function toWinPath(linuxPath) {
|
||||
const res = spawnSync('wslpath', ['-w', linuxPath], { encoding: 'utf8' })
|
||||
return res.status === 0 ? (res.stdout || '').trim() : ''
|
||||
}
|
||||
|
||||
function resolveElectronVersion() {
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
|
||||
const raw = String(pkg?.devDependencies?.electron || '').replace(/^[^0-9]*/, '')
|
||||
return raw || ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function runWinViaWindowsHost() {
|
||||
if (!isWsl()) return false
|
||||
const winProbeScript = [
|
||||
'$env:PLANET_WIN_BUN_EXE',
|
||||
'(Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source)',
|
||||
'(Join-Path $env:USERPROFILE ".bun\\bin\\bun.exe")',
|
||||
'(Join-Path $env:USERPROFILE "scoop\\shims\\bun.exe")',
|
||||
'(Join-Path $env:LOCALAPPDATA "bun\\bin\\bun.exe")',
|
||||
'@(Get-ChildItem (Join-Path $env:LOCALAPPDATA "PlanetReleaseBuild\\*\\tools\\bun.exe") -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -ExpandProperty FullName)',
|
||||
].join(', ')
|
||||
const probePs = [
|
||||
`$candidates = @(${winProbeScript}) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }`,
|
||||
'$bunPath = $candidates | Select-Object -First 1',
|
||||
'$cacheDirs = @((Get-ChildItem (Join-Path $env:LOCALAPPDATA "PlanetReleaseBuild\\*\\electron-cache") -Directory -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -ExpandProperty FullName), (Join-Path $env:LOCALAPPDATA "electron\\Cache")) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }',
|
||||
'$cacheHit = $cacheDirs | Where-Object { Get-ChildItem $_ -Filter "electron-v*-win32-x64.zip" -ErrorAction SilentlyContinue } | Select-Object -First 1',
|
||||
'Write-Output ("LOCALAPPDATA=" + $env:LOCALAPPDATA)',
|
||||
'Write-Output ("BUN=" + $bunPath)',
|
||||
'Write-Output ("ELECTRON_CACHE=" + $cacheHit)',
|
||||
].join('; ')
|
||||
const probe = spawnSync('powershell.exe', ['-NoProfile', '-Command', probePs], { encoding: 'utf8' })
|
||||
if (probe.status !== 0) return false
|
||||
|
||||
const info = {}
|
||||
for (const line of (probe.stdout || '').split(/\r?\n/)) {
|
||||
const idx = line.indexOf('=')
|
||||
if (idx > 0) info[line.slice(0, idx).trim()] = line.slice(idx + 1).trim()
|
||||
}
|
||||
const winBunPath = info.BUN || ''
|
||||
const winLocalAppData = info.LOCALAPPDATA || ''
|
||||
if (!winBunPath || !winLocalAppData) return false
|
||||
|
||||
const localAppDataWsl = toWslPath(winLocalAppData)
|
||||
if (!localAppDataWsl) return false
|
||||
|
||||
const releaseOutDir = join(desktopRoot, 'release')
|
||||
mkdirSync(releaseOutDir, { recursive: true })
|
||||
const stageRoot = join(localAppDataWsl, 'PlanetReleaseBuild', `wsl-stage-${process.pid}`)
|
||||
const stageClient = join(stageRoot, 'client')
|
||||
const stageRelease = join(stageClient, 'release')
|
||||
const stageCache = join(stageRoot, 'electron-cache')
|
||||
mkdirSync(stageClient, { recursive: true })
|
||||
|
||||
let winElectronDist = info.ELECTRON_CACHE || ''
|
||||
const electronVer = resolveElectronVersion()
|
||||
const wslElectronZip = electronVer ? join(homedir(), '.cache', 'electron', `electron-v${electronVer}-win32-x64.zip`) : ''
|
||||
if (!winElectronDist && wslElectronZip && existsSync(wslElectronZip)) {
|
||||
mkdirSync(stageCache, { recursive: true })
|
||||
copyFileSync(wslElectronZip, join(stageCache, `electron-v${electronVer}-win32-x64.zip`))
|
||||
winElectronDist = toWinPath(stageCache)
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`WSL2 detected; staging Windows NSIS + zip build on NTFS via ${winBunPath}...`)
|
||||
for (const rel of ['package.json', 'bun.lock', 'electron-builder.yml', 'dist-electron', '.earth-bundle', 'resources', 'scripts']) {
|
||||
const src = join(desktopRoot, rel)
|
||||
if (!existsSync(src)) {
|
||||
throw new Error(`Missing required client build asset for Windows staging: ${src}`)
|
||||
}
|
||||
cpSync(src, join(stageClient, rel), { recursive: true })
|
||||
}
|
||||
|
||||
const winStageClient = toWinPath(stageClient)
|
||||
if (!winStageClient) return false
|
||||
|
||||
const builderArgs = ['--win', 'nsis', 'zip', '--x64', '--publish', 'never']
|
||||
if (winElectronDist) {
|
||||
builderArgs.push(`--config.electronDist=${winElectronDist}`)
|
||||
}
|
||||
const psArgs = builderArgs.map((arg) => `'${arg.replace(/'/g, "''")}'`).join(' ')
|
||||
const psScript = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
`$env:ELECTRON_MIRROR = '${env.ELECTRON_MIRROR}'`,
|
||||
`$env:ELECTRON_BUILDER_BINARIES_MIRROR = '${env.ELECTRON_BUILDER_BINARIES_MIRROR}'`,
|
||||
`Set-Location -LiteralPath '${winStageClient.replace(/'/g, "''")}'`,
|
||||
`& '${winBunPath.replace(/'/g, "''")}' install --frozen-lockfile --ignore-scripts`,
|
||||
'if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
|
||||
`& '${winBunPath.replace(/'/g, "''")}' ./node_modules/electron-builder/cli.js ${psArgs}`,
|
||||
'if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
|
||||
].join('; ')
|
||||
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], { stdio: 'inherit' })
|
||||
if ((winRun.status ?? 1) !== 0 || !existsSync(stageRelease)) {
|
||||
return false
|
||||
}
|
||||
|
||||
let copied = 0
|
||||
for (const entry of readdirSync(stageRelease)) {
|
||||
if (entry.startsWith('__uninstaller-')) continue
|
||||
if (entry.toLowerCase().endsWith('.exe') || entry.toLowerCase().endsWith('-win.zip')) {
|
||||
copyFileSync(join(stageRelease, entry), join(releaseOutDir, entry))
|
||||
copied += 1
|
||||
}
|
||||
}
|
||||
return copied >= 2
|
||||
} finally {
|
||||
rmSync(stageRoot, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function runWinViaDockerWine() {
|
||||
if (!hasCommand('docker')) return false
|
||||
const image = process.env.PLANET_ELECTRON_BUILDER_IMAGE || 'electronuserland/builder:wine'
|
||||
const home = homedir()
|
||||
const electronCache = join(home, '.cache', 'electron')
|
||||
const builderCache = join(home, '.cache', 'electron-builder')
|
||||
mkdirSync(electronCache, { recursive: true })
|
||||
mkdirSync(builderCache, { recursive: true })
|
||||
const uid = typeof process.getuid === 'function' ? process.getuid() : 0
|
||||
const gid = typeof process.getgid === 'function' ? process.getgid() : 0
|
||||
|
||||
console.log(`Building Windows NSIS + zip installers via Docker Wine (${image})...`)
|
||||
const dockerCmd = [
|
||||
'run', '--rm',
|
||||
'-v', `${desktopRoot}:/project`,
|
||||
'-v', `${electronCache}:/root/.cache/electron`,
|
||||
'-v', `${builderCache}:/root/.cache/electron-builder`,
|
||||
'-e', `ELECTRON_MIRROR=${env.ELECTRON_MIRROR}`,
|
||||
'-e', `ELECTRON_BUILDER_BINARIES_MIRROR=${env.ELECTRON_BUILDER_BINARIES_MIRROR}`,
|
||||
'-w', '/project',
|
||||
image,
|
||||
'bash', '-lc',
|
||||
`./node_modules/.bin/electron-builder --win nsis zip --publish never; status=$?; chown -R ${uid}:${gid} /project/release 2>/dev/null || true; exit $status`,
|
||||
]
|
||||
const res = spawnSync('docker', dockerCmd, { stdio: 'inherit' })
|
||||
return (res.status ?? 1) === 0
|
||||
}
|
||||
|
||||
function runWinBuild() {
|
||||
if (process.platform === 'win32' || hasCommand('wine') || hasCommand('wine64')) {
|
||||
runBuilder(['--win', 'nsis', 'portable'])
|
||||
runBuilder(['--win', 'nsis', 'zip'])
|
||||
return
|
||||
}
|
||||
|
||||
if (isWsl()) {
|
||||
const winBunCheck = spawnSync(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-Command', 'Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source'],
|
||||
{ encoding: 'utf8' },
|
||||
)
|
||||
const winBunPath = (winBunCheck.stdout || '').trim()
|
||||
const winPathRes = spawnSync('wslpath', ['-w', desktopRoot], { encoding: 'utf8' })
|
||||
const winDesktopRoot = (winPathRes.stdout || '').trim()
|
||||
if (winBunCheck.status === 0 && winBunPath && winDesktopRoot) {
|
||||
console.log('WSL2 detected without Wine; building Windows installers via Windows host toolchain...')
|
||||
const psScript = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
`$env:ELECTRON_MIRROR = '${env.ELECTRON_MIRROR}'`,
|
||||
`$env:ELECTRON_BUILDER_BINARIES_MIRROR = '${env.ELECTRON_BUILDER_BINARIES_MIRROR}'`,
|
||||
`Set-Location -LiteralPath '${winDesktopRoot.replace(/'/g, "''")}'`,
|
||||
'bun x electron-builder --win nsis portable --publish never',
|
||||
].join('; ')
|
||||
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], {
|
||||
stdio: 'inherit',
|
||||
})
|
||||
if ((winRun.status ?? 1) === 0) {
|
||||
return
|
||||
}
|
||||
console.warn('Windows host build fell back to unpacked/zip cross-build without Wine.')
|
||||
}
|
||||
} else {
|
||||
console.warn('Wine not available on Linux host: building standalone Windows zip bundle (win-unpacked + zip).')
|
||||
if (runWinViaWindowsHost()) {
|
||||
return
|
||||
}
|
||||
|
||||
runBuilder(['--win', 'zip', '--config.win.signAndEditExecutable=false'])
|
||||
if (runWinViaDockerWine()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (process.env.PLANET_ALLOW_WIN_ZIP_FALLBACK === '1') {
|
||||
console.warn('PLANET_ALLOW_WIN_ZIP_FALLBACK=1 set without Wine/Docker/Windows Bun: building win zip without NSIS .exe.')
|
||||
runBuilder(['--win', 'zip', '--config.win.signAndEditExecutable=false'])
|
||||
return
|
||||
}
|
||||
|
||||
console.error(
|
||||
'Unable to build Windows NSIS (.exe) installer: install Wine (wine64), enable Docker (electronuserland/builder:wine), or install Windows bun.exe (or set PLANET_ALLOW_WIN_ZIP_FALLBACK=1 for zip-only).',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
function runMacBuild() {
|
||||
@@ -177,7 +314,14 @@ function runMacBuild() {
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === '--dir') {
|
||||
if (mode === '--hotfix') {
|
||||
const result = spawnSync(process.execPath, [join(__dirname, 'build-earth-bundle.mjs')], {
|
||||
cwd: desktopRoot,
|
||||
env,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
process.exit(result.status ?? 1)
|
||||
} else if (mode === '--dir') {
|
||||
runBuilder(['--dir'])
|
||||
} else if (mode === '--linux') {
|
||||
runBuilder(['--linux', ...resolveLinuxTargets()])
|
||||
|
||||
+185
-17
@@ -1,7 +1,8 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
|
||||
export type SplashTheme = 'singularity' | 'off'
|
||||
export type GpuRenderMode = 'auto' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export interface ServerEndpoints {
|
||||
backendUrl: string
|
||||
@@ -11,6 +12,25 @@ export interface ServerEndpoints {
|
||||
|
||||
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
|
||||
splashTheme?: SplashTheme
|
||||
gpuMode?: GpuRenderMode
|
||||
recordAudio?: boolean
|
||||
recordHideCursor?: boolean
|
||||
}
|
||||
|
||||
export type GpuHandoffTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export function normalizeGpuHandoffTarget(raw: unknown): GpuHandoffTarget | undefined {
|
||||
if (typeof raw !== 'string') return undefined
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (
|
||||
normalized === 'default' ||
|
||||
normalized === 'high-performance' ||
|
||||
normalized === 'low-power' ||
|
||||
normalized === 'software'
|
||||
) {
|
||||
return normalized
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export interface DesktopLaunchFlags {
|
||||
@@ -22,18 +42,35 @@ export interface DesktopLaunchFlags {
|
||||
smokeOutputPath: string | null
|
||||
deepLinkUrl: string | null
|
||||
splashThemeOverride?: SplashTheme
|
||||
gpuModeOverride?: GpuRenderMode
|
||||
gpuHandoff: boolean
|
||||
gpuHandoffTarget?: GpuHandoffTarget
|
||||
}
|
||||
|
||||
export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags {
|
||||
wsUrl: string
|
||||
splashTheme: SplashTheme
|
||||
gpuMode: GpuRenderMode
|
||||
recordAudio: boolean
|
||||
recordHideCursor: boolean
|
||||
}
|
||||
|
||||
const VALID_SPLASH_THEMES: ReadonlySet<SplashTheme> = new Set([
|
||||
export function normalizeBooleanFlag(raw: unknown, fallback = false): boolean {
|
||||
if (typeof raw === 'boolean') return raw
|
||||
if (typeof raw === 'string') {
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'true' || normalized === '1' || normalized === 'yes') return true
|
||||
if (normalized === 'false' || normalized === '0' || normalized === 'no') return false
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
|
||||
'singularity',
|
||||
'constellation',
|
||||
'horizon',
|
||||
'off',
|
||||
'on',
|
||||
'default',
|
||||
])
|
||||
|
||||
export function normalizeSplashTheme(
|
||||
@@ -41,8 +78,38 @@ export function normalizeSplashTheme(
|
||||
fallback: SplashTheme = 'singularity',
|
||||
): SplashTheme {
|
||||
if (typeof raw !== 'string') return fallback
|
||||
const normalized = raw.trim().toLowerCase() as SplashTheme
|
||||
return VALID_SPLASH_THEMES.has(normalized) ? normalized : fallback
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'off') return 'off'
|
||||
return LEGACY_ACTIVE_THEMES.has(normalized) ? 'singularity' : fallback
|
||||
}
|
||||
|
||||
export function normalizeGpuMode(
|
||||
raw: unknown,
|
||||
fallback: GpuRenderMode = 'auto',
|
||||
): GpuRenderMode {
|
||||
if (typeof raw !== 'string') return fallback
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'auto') return 'auto'
|
||||
if (
|
||||
normalized === 'high-performance' ||
|
||||
normalized === 'high' ||
|
||||
normalized === 'discrete' ||
|
||||
normalized === 'dgpu'
|
||||
) {
|
||||
return 'high-performance'
|
||||
}
|
||||
if (
|
||||
normalized === 'low-power' ||
|
||||
normalized === 'low' ||
|
||||
normalized === 'integrated' ||
|
||||
normalized === 'igpu'
|
||||
) {
|
||||
return 'low-power'
|
||||
}
|
||||
if (normalized === 'software' || normalized === 'cpu' || normalized === 'swiftshader') {
|
||||
return 'software'
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
|
||||
@@ -113,6 +180,7 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
headlessSmoke: false,
|
||||
smokeOutputPath: null,
|
||||
deepLinkUrl: null,
|
||||
gpuHandoff: false,
|
||||
}
|
||||
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
@@ -134,6 +202,22 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length))
|
||||
} else if (arg === '--splash-theme' && argv[i + 1]) {
|
||||
flags.splashThemeOverride = normalizeSplashTheme(argv[++i])
|
||||
} else if (arg.startsWith('--gpu-mode=')) {
|
||||
flags.gpuModeOverride = normalizeGpuMode(arg.slice('--gpu-mode='.length))
|
||||
} else if (arg === '--gpu-mode' && argv[i + 1]) {
|
||||
flags.gpuModeOverride = normalizeGpuMode(argv[++i])
|
||||
} else if (arg === '--software-gl') {
|
||||
flags.gpuModeOverride = 'software'
|
||||
} else if (arg === '--low-power-gpu') {
|
||||
flags.gpuModeOverride = 'low-power'
|
||||
} else if (arg === '--high-performance-gpu') {
|
||||
flags.gpuModeOverride = 'high-performance'
|
||||
} else if (arg === '--gpu-handoff') {
|
||||
flags.gpuHandoff = true
|
||||
} else if (arg.startsWith('--gpu-handoff-target=')) {
|
||||
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(arg.slice('--gpu-handoff-target='.length))
|
||||
} else if (arg === '--gpu-handoff-target' && argv[i + 1]) {
|
||||
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(argv[++i])
|
||||
} else if (arg === '--fullscreen') {
|
||||
flags.fullscreen = true
|
||||
} else if (arg === '--kiosk') {
|
||||
@@ -155,6 +239,55 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
return { endpoints, flags }
|
||||
}
|
||||
|
||||
function getPortableConfigPaths(exeDir: string, resourcesDir?: string): string[] {
|
||||
const candidates: string[] = []
|
||||
if (exeDir) {
|
||||
candidates.push(path.join(exeDir, 'planet-earth.json'))
|
||||
}
|
||||
if (resourcesDir) {
|
||||
candidates.push(path.join(resourcesDir, 'planet-earth.json'))
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
function readFirstPortableConfig(paths: string[]): PersistedUserConfig {
|
||||
for (const candidate of paths) {
|
||||
const data = readJsonFileSafe(candidate)
|
||||
if (Object.keys(data).length > 0) {
|
||||
return data
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
export function readPreReadyGpuMode(options: {
|
||||
userDataDir: string
|
||||
exeDir: string
|
||||
resourcesDir?: string
|
||||
argv: string[]
|
||||
env?: NodeJS.ProcessEnv
|
||||
}): GpuRenderMode {
|
||||
const env = options.env ?? process.env
|
||||
const { flags } = parseLaunchArgs(options.argv)
|
||||
const portable = readFirstPortableConfig(getPortableConfigPaths(options.exeDir, options.resourcesDir))
|
||||
const userSaved = options.userDataDir ? readJsonFileSafe(path.join(options.userDataDir, 'config.json')) : {}
|
||||
return normalizeGpuMode(
|
||||
flags.gpuModeOverride ?? env.PLANET_GPU_MODE ?? portable.gpuMode ?? userSaved.gpuMode,
|
||||
'auto',
|
||||
)
|
||||
}
|
||||
|
||||
export function readPreReadyGpuHandoff(argv: string[]): {
|
||||
gpuHandoff: boolean
|
||||
gpuHandoffTarget?: GpuHandoffTarget
|
||||
} {
|
||||
const { flags } = parseLaunchArgs(argv)
|
||||
return {
|
||||
gpuHandoff: flags.gpuHandoff,
|
||||
gpuHandoffTarget: flags.gpuHandoffTarget,
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConfigStore {
|
||||
private readonly userConfigPath: string
|
||||
private readonly portableConfigPaths: string[]
|
||||
@@ -170,10 +303,7 @@ export class DesktopConfigStore {
|
||||
env?: NodeJS.ProcessEnv
|
||||
}) {
|
||||
this.userConfigPath = path.join(options.userDataDir, 'config.json')
|
||||
this.portableConfigPaths = [
|
||||
path.join(options.exeDir, 'planet-earth.json'),
|
||||
...(options.resourcesDir ? [path.join(options.resourcesDir, 'planet-earth.json')] : []),
|
||||
]
|
||||
this.portableConfigPaths = getPortableConfigPaths(options.exeDir, options.resourcesDir)
|
||||
const parsed = parseLaunchArgs(options.argv)
|
||||
this.cliEndpoints = parsed.endpoints
|
||||
this.launchFlags = parsed.flags
|
||||
@@ -182,14 +312,7 @@ export class DesktopConfigStore {
|
||||
|
||||
private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig {
|
||||
const userSaved = readJsonFileSafe(this.userConfigPath)
|
||||
let portable: PersistedUserConfig = {}
|
||||
for (const candidate of this.portableConfigPaths) {
|
||||
const data = readJsonFileSafe(candidate)
|
||||
if (Object.keys(data).length > 0) {
|
||||
portable = data
|
||||
break
|
||||
}
|
||||
}
|
||||
const portable = readFirstPortableConfig(this.portableConfigPaths)
|
||||
|
||||
const backendUrl = normalizeHttpUrl(
|
||||
this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl,
|
||||
@@ -210,6 +333,18 @@ export class DesktopConfigStore {
|
||||
userSaved.splashTheme,
|
||||
'singularity',
|
||||
)
|
||||
const gpuMode = normalizeGpuMode(
|
||||
this.launchFlags.gpuModeOverride ??
|
||||
env.PLANET_GPU_MODE ??
|
||||
portable.gpuMode ??
|
||||
userSaved.gpuMode,
|
||||
'auto',
|
||||
)
|
||||
const recordAudio = normalizeBooleanFlag(portable.recordAudio ?? userSaved.recordAudio, false)
|
||||
const recordHideCursor = normalizeBooleanFlag(
|
||||
portable.recordHideCursor ?? userSaved.recordHideCursor,
|
||||
false,
|
||||
)
|
||||
|
||||
return {
|
||||
backendUrl,
|
||||
@@ -217,6 +352,9 @@ export class DesktopConfigStore {
|
||||
motionWsUrl,
|
||||
wsUrl: deriveBackendWsUrl(backendUrl),
|
||||
splashTheme,
|
||||
gpuMode,
|
||||
recordAudio,
|
||||
recordHideCursor,
|
||||
...this.launchFlags,
|
||||
}
|
||||
}
|
||||
@@ -258,4 +396,34 @@ export class DesktopConfigStore {
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
|
||||
updateGpuMode(rawMode: unknown): DesktopRuntimeConfig {
|
||||
const nextMode = normalizeGpuMode(rawMode, this.current.gpuMode)
|
||||
this.writeUserConfig({ gpuMode: nextMode })
|
||||
this.current = {
|
||||
...this.current,
|
||||
gpuMode: nextMode,
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
|
||||
updateRecordAudio(enabled: unknown): DesktopRuntimeConfig {
|
||||
const nextRecordAudio = normalizeBooleanFlag(enabled, this.current.recordAudio)
|
||||
this.writeUserConfig({ recordAudio: nextRecordAudio })
|
||||
this.current = {
|
||||
...this.current,
|
||||
recordAudio: nextRecordAudio,
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
|
||||
updateRecordHideCursor(enabled: unknown): DesktopRuntimeConfig {
|
||||
const nextRecordHideCursor = normalizeBooleanFlag(enabled, this.current.recordHideCursor)
|
||||
this.writeUserConfig({ recordHideCursor: nextRecordHideCursor })
|
||||
this.current = {
|
||||
...this.current,
|
||||
recordHideCursor: nextRecordHideCursor,
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
export interface EarthDesktopAuth {
|
||||
getToken(options?: { forceRefresh?: boolean }): Promise<string | null>
|
||||
clear(): void
|
||||
}
|
||||
|
||||
interface CachedEarthToken {
|
||||
backendUrl: string
|
||||
token: string
|
||||
expiresAtMs: number
|
||||
}
|
||||
|
||||
const REFRESH_MARGIN_MS = 120_000
|
||||
const DEFAULT_TTL_SECONDS = 1800
|
||||
const AUTH_TIMEOUT_MS = 8000
|
||||
|
||||
export function createEarthDesktopAuth(options: {
|
||||
getBackendUrl: () => string
|
||||
getAppVersion: () => string
|
||||
handshakeSecret?: string
|
||||
fetchImpl?: typeof fetch
|
||||
nowMs?: () => number
|
||||
}): EarthDesktopAuth {
|
||||
const fetchImpl = options.fetchImpl ?? fetch
|
||||
const nowMs = options.nowMs ?? (() => Date.now())
|
||||
let cached: CachedEarthToken | null = null
|
||||
let inFlight: Promise<string | null> | null = null
|
||||
let inFlightBackendUrl = ''
|
||||
|
||||
const fetchFreshToken = async (backendUrl: string): Promise<string | null> => {
|
||||
const version = (options.getAppVersion() || '0.0.0').trim() || '0.0.0'
|
||||
const clientHeader = `planet-earth-desktop/${version}`
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Planet-Client': clientHeader,
|
||||
}
|
||||
|
||||
const secret = String(options.handshakeSecret || '').trim()
|
||||
if (secret) {
|
||||
const timestamp = String(Math.floor(nowMs() / 1000))
|
||||
const nonce = crypto.randomBytes(16).toString('hex')
|
||||
const signature = crypto
|
||||
.createHmac('sha256', secret)
|
||||
.update(`${timestamp}.${nonce}.${clientHeader}`)
|
||||
.digest('hex')
|
||||
headers['X-Planet-Client-Timestamp'] = timestamp
|
||||
headers['X-Planet-Client-Nonce'] = nonce
|
||||
headers['X-Planet-Client-Signature'] = signature
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS)
|
||||
try {
|
||||
const targetUrl = new URL('/api/v1/auth/earth-session', backendUrl).toString()
|
||||
const response = await fetchImpl(targetUrl, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ client_type: 'desktop' }),
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (!response.ok) {
|
||||
return null
|
||||
}
|
||||
const data = (await response.json()) as { token?: unknown; expires_in?: unknown }
|
||||
if (typeof data?.token !== 'string' || !data.token.trim()) {
|
||||
return null
|
||||
}
|
||||
const ttlSeconds =
|
||||
typeof data.expires_in === 'number' && Number.isFinite(data.expires_in) && data.expires_in > 0
|
||||
? data.expires_in
|
||||
: DEFAULT_TTL_SECONDS
|
||||
cached = {
|
||||
backendUrl,
|
||||
token: data.token.trim(),
|
||||
expiresAtMs: nowMs() + ttlSeconds * 1000,
|
||||
}
|
||||
return cached.token
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async getToken(getOpts) {
|
||||
const backendUrl = String(options.getBackendUrl() || '').trim().replace(/\/+$/, '')
|
||||
if (!backendUrl) return null
|
||||
|
||||
if (cached && cached.backendUrl !== backendUrl) {
|
||||
cached = null
|
||||
}
|
||||
|
||||
if (
|
||||
!getOpts?.forceRefresh &&
|
||||
cached &&
|
||||
cached.expiresAtMs - nowMs() > REFRESH_MARGIN_MS
|
||||
) {
|
||||
return cached.token
|
||||
}
|
||||
|
||||
if (inFlight && inFlightBackendUrl === backendUrl && !getOpts?.forceRefresh) {
|
||||
return inFlight
|
||||
}
|
||||
|
||||
const promise = fetchFreshToken(backendUrl).finally(() => {
|
||||
if (inFlight === promise) {
|
||||
inFlight = null
|
||||
inFlightBackendUrl = ''
|
||||
}
|
||||
})
|
||||
inFlight = promise
|
||||
inFlightBackendUrl = backendUrl
|
||||
return promise
|
||||
},
|
||||
|
||||
clear() {
|
||||
cached = null
|
||||
inFlight = null
|
||||
inFlightBackendUrl = ''
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { execFile, execFileSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import type { BrowserWindow } from 'electron'
|
||||
|
||||
import type { GpuRenderMode } from './config'
|
||||
import {
|
||||
canAutoSwitchGpu,
|
||||
createVramHysteresisTracker,
|
||||
detectIntegratedGpuFromRegistryOutput,
|
||||
parseNvidiaSmiCsv,
|
||||
VRAM_LOW_THRESHOLD_MIB,
|
||||
VRAM_MONITOR_INTERVAL_MS,
|
||||
type DiscreteVramSample,
|
||||
type ResolvedGpuTarget,
|
||||
type StartupGpuDecision,
|
||||
type StartupGpuDecisionReason,
|
||||
} from './gpu-policy'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const HANDOFF_RECORD_MAX_AGE_MS = 30_000
|
||||
const HANDOFF_RECORD_FILE = 'gpu-handoff.json'
|
||||
|
||||
const NVIDIA_SMI_ARGS = [
|
||||
'--query-gpu=name,memory.used,memory.free,memory.total',
|
||||
'--format=csv,noheader,nounits',
|
||||
]
|
||||
|
||||
const DISPLAY_CLASS_REG_ARGS = [
|
||||
'query',
|
||||
'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}',
|
||||
'/s',
|
||||
'/v',
|
||||
'DriverDesc',
|
||||
]
|
||||
|
||||
export interface GpuHandoffRecord {
|
||||
lastSwitchAt: number
|
||||
target: ResolvedGpuTarget
|
||||
reason: 'low-fps-low-vram' | 'vram-recovered' | 'manual'
|
||||
freeMiB?: number
|
||||
avgFps?: number
|
||||
}
|
||||
|
||||
export interface GpuRuntimeSummary {
|
||||
requestedMode: GpuRenderMode
|
||||
activeTarget: ResolvedGpuTarget
|
||||
reason: StartupGpuDecisionReason
|
||||
hasIntegratedGpu: boolean
|
||||
latestVramSample: DiscreteVramSample | null
|
||||
}
|
||||
|
||||
export interface AdaptiveGpuMonitor {
|
||||
start(): void
|
||||
stop(): void
|
||||
handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void>
|
||||
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null
|
||||
getRuntimeSummary(): GpuRuntimeSummary
|
||||
}
|
||||
|
||||
export function readGpuHandoffRecord(userDataDir: string): GpuHandoffRecord | null {
|
||||
if (!userDataDir) return null
|
||||
try {
|
||||
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
|
||||
if (!fs.existsSync(filePath)) return null
|
||||
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<GpuHandoffRecord>
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed.lastSwitchAt !== 'number' ||
|
||||
!Number.isFinite(parsed.lastSwitchAt) ||
|
||||
typeof parsed.target !== 'string' ||
|
||||
typeof parsed.reason !== 'string'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return parsed as GpuHandoffRecord
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function writeGpuHandoffRecord(userDataDir: string, record: GpuHandoffRecord): void {
|
||||
if (!userDataDir) return
|
||||
try {
|
||||
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
fs.writeFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
|
||||
} catch {
|
||||
// Ignore non-critical handoff state write failures.
|
||||
}
|
||||
}
|
||||
|
||||
export function probeWindowsGpuEnvironmentSync(): {
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
} {
|
||||
if (process.platform !== 'win32') {
|
||||
return { vramSample: null, hasIntegratedGpu: false }
|
||||
}
|
||||
|
||||
let vramSample: DiscreteVramSample | null = null
|
||||
try {
|
||||
const out = execFileSync('nvidia-smi', NVIDIA_SMI_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 800,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
vramSample = parseNvidiaSmiCsv(out)
|
||||
} catch {
|
||||
vramSample = null
|
||||
}
|
||||
|
||||
let hasIntegratedGpu = false
|
||||
try {
|
||||
const out = execFileSync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 800,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
hasIntegratedGpu = detectIntegratedGpuFromRegistryOutput(out)
|
||||
} catch {
|
||||
hasIntegratedGpu = false
|
||||
}
|
||||
|
||||
return { vramSample, hasIntegratedGpu }
|
||||
}
|
||||
|
||||
export async function probeDiscreteVramAsync(): Promise<DiscreteVramSample | null> {
|
||||
if (process.platform !== 'win32') {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('nvidia-smi', NVIDIA_SMI_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 2000,
|
||||
windowsHide: true,
|
||||
})
|
||||
return parseNvidiaSmiCsv(stdout)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeIntegratedGpuAsync(): Promise<boolean> {
|
||||
if (process.platform !== 'win32') {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 2000,
|
||||
windowsHide: true,
|
||||
})
|
||||
return detectIntegratedGpuFromRegistryOutput(stdout)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function createAdaptiveGpuMonitor(options: {
|
||||
userDataDir: string
|
||||
startupDecision: StartupGpuDecision
|
||||
getConfiguredMode: () => GpuRenderMode
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
onAutoSwitch: (target: ResolvedGpuTarget, record: GpuHandoffRecord) => void
|
||||
onStatusUpdated?: () => void
|
||||
}): AdaptiveGpuMonitor {
|
||||
let latestVramSample: DiscreteVramSample | null = options.startupDecision.vramSample
|
||||
let switching = false
|
||||
let toastConsumed = false
|
||||
let intervalTimer: ReturnType<typeof setInterval> | null = null
|
||||
const lastSwitchAt = readGpuHandoffRecord(options.userDataDir)?.lastSwitchAt ?? null
|
||||
|
||||
const activeTarget = options.startupDecision.target
|
||||
const isDiscrete = activeTarget === 'default' || activeTarget === 'high-performance'
|
||||
const isOffloaded = activeTarget === 'low-power' || activeTarget === 'software'
|
||||
|
||||
const tracker = createVramHysteresisTracker({
|
||||
activeTarget,
|
||||
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
|
||||
})
|
||||
|
||||
const triggerAutoSwitch = (target: ResolvedGpuTarget, record: GpuHandoffRecord) => {
|
||||
if (switching) return
|
||||
switching = true
|
||||
if (intervalTimer) {
|
||||
clearInterval(intervalTimer)
|
||||
intervalTimer = null
|
||||
}
|
||||
writeGpuHandoffRecord(options.userDataDir, record)
|
||||
options.onAutoSwitch(target, record)
|
||||
}
|
||||
|
||||
const tickOffloadedRecovery = async () => {
|
||||
if (switching || !isOffloaded || options.getConfiguredMode() !== 'auto') return
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, Date.now())) return
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.isMinimized()) return
|
||||
|
||||
const sample = await probeDiscreteVramAsync()
|
||||
latestVramSample = sample
|
||||
options.onStatusUpdated?.()
|
||||
|
||||
if (switching || options.getConfiguredMode() !== 'auto') return
|
||||
const action = tracker.observe(sample)
|
||||
if (!action || action.kind !== 'switch-to-discrete') return
|
||||
|
||||
const now = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
|
||||
console.info(
|
||||
`[planet-client] Discrete GPU VRAM recovered (freeMiB=${action.sample.freeMiB}); auto-switching back to discrete GPU`,
|
||||
)
|
||||
triggerAutoSwitch('default', {
|
||||
lastSwitchAt: now,
|
||||
target: 'default',
|
||||
reason: 'vram-recovered',
|
||||
freeMiB: action.sample.freeMiB,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
start() {
|
||||
if (process.platform !== 'win32' || options.startupDecision.reason === 'headless-smoke') {
|
||||
return
|
||||
}
|
||||
if (!isOffloaded || intervalTimer) return
|
||||
intervalTimer = setInterval(() => {
|
||||
void tickOffloadedRecovery()
|
||||
}, VRAM_MONITOR_INTERVAL_MS)
|
||||
},
|
||||
|
||||
stop() {
|
||||
if (intervalTimer) {
|
||||
clearInterval(intervalTimer)
|
||||
intervalTimer = null
|
||||
}
|
||||
},
|
||||
|
||||
async handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void> {
|
||||
if (
|
||||
process.platform !== 'win32' ||
|
||||
options.startupDecision.reason === 'headless-smoke' ||
|
||||
switching ||
|
||||
!isDiscrete ||
|
||||
options.getConfiguredMode() !== 'auto'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
|
||||
|
||||
const sample = await probeDiscreteVramAsync()
|
||||
latestVramSample = sample
|
||||
options.onStatusUpdated?.()
|
||||
|
||||
if (
|
||||
switching ||
|
||||
options.getConfiguredMode() !== 'auto' ||
|
||||
!sample ||
|
||||
sample.freeMiB >= VRAM_LOW_THRESHOLD_MIB
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const hasIgpu = options.startupDecision.hasIntegratedGpu || (await probeIntegratedGpuAsync())
|
||||
const nextTarget: ResolvedGpuTarget = hasIgpu ? 'low-power' : 'software'
|
||||
const switchNow = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, switchNow)) return
|
||||
|
||||
console.info(
|
||||
`[planet-client] Sustained low FPS (${report.avgFps} fps for ${report.sustainedMs}ms) with low discrete VRAM (freeMiB=${sample.freeMiB}); auto-switching to ${nextTarget}`,
|
||||
)
|
||||
triggerAutoSwitch(nextTarget, {
|
||||
lastSwitchAt: switchNow,
|
||||
target: nextTarget,
|
||||
reason: 'low-fps-low-vram',
|
||||
freeMiB: sample.freeMiB,
|
||||
avgFps: report.avgFps,
|
||||
})
|
||||
},
|
||||
|
||||
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null {
|
||||
if (toastConsumed || options.startupDecision.reason !== 'gpu-handoff') {
|
||||
return null
|
||||
}
|
||||
toastConsumed = true
|
||||
const record = readGpuHandoffRecord(options.userDataDir)
|
||||
if (!record || Date.now() - record.lastSwitchAt >= HANDOFF_RECORD_MAX_AGE_MS) {
|
||||
return null
|
||||
}
|
||||
if (record.reason === 'low-fps-low-vram') {
|
||||
return record.target === 'software'
|
||||
? { message: '独显显存不足且帧率偏低,已自动切换至 CPU 软渲染', type: 'info' }
|
||||
: {
|
||||
message: '独显显存不足且帧率偏低,已自动切换至集成核显渲染(保留全部特效)',
|
||||
type: 'info',
|
||||
}
|
||||
}
|
||||
if (record.reason === 'vram-recovered') {
|
||||
return { message: '独显显存已充足,已自动切回独立显卡渲染', type: 'success' }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
getRuntimeSummary(): GpuRuntimeSummary {
|
||||
return {
|
||||
requestedMode: options.getConfiguredMode(),
|
||||
activeTarget: options.startupDecision.target,
|
||||
reason: options.startupDecision.reason,
|
||||
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
|
||||
latestVramSample,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import type { GpuRenderMode } from './config'
|
||||
|
||||
export const VRAM_LOW_THRESHOLD_MIB = 2048
|
||||
export const VRAM_RECOVER_THRESHOLD_MIB = 3584
|
||||
export const VRAM_MONITOR_INTERVAL_MS = 5_000
|
||||
export const VRAM_SWITCH_CONSECUTIVE_REQUIRED = 2
|
||||
export const LOW_FPS_THRESHOLD = 20
|
||||
export const LOW_FPS_SUSTAINED_MS = 5_000
|
||||
export const FPS_STARTUP_WARMUP_MS = 6_000
|
||||
export const FPS_REPORT_COOLDOWN_MS = 15_000
|
||||
export const AUTO_SWITCH_COOLDOWN_MS = 45_000
|
||||
|
||||
export interface ChromiumSwitch {
|
||||
name: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
export type ResolvedGpuTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export interface DiscreteVramSample {
|
||||
gpuName: string
|
||||
usedMiB: number
|
||||
freeMiB: number
|
||||
totalMiB: number
|
||||
}
|
||||
|
||||
export type StartupGpuDecisionReason =
|
||||
| 'headless-smoke'
|
||||
| 'gpu-handoff'
|
||||
| 'user-software'
|
||||
| 'user-low-power'
|
||||
| 'user-high-performance'
|
||||
| 'low-vram-igpu'
|
||||
| 'low-vram-software'
|
||||
| 'normal-gpu'
|
||||
|
||||
export interface StartupGpuDecision {
|
||||
target: ResolvedGpuTarget
|
||||
requestedMode: GpuRenderMode
|
||||
reason: StartupGpuDecisionReason
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
}
|
||||
|
||||
export interface VramMonitorAction {
|
||||
kind: 'switch-to-discrete' | 'switch-to-low-power' | 'switch-to-software'
|
||||
sample: DiscreteVramSample
|
||||
}
|
||||
|
||||
export interface GpuPolicyInput {
|
||||
platform: NodeJS.Platform
|
||||
headlessSmoke: boolean
|
||||
softwareGl?: boolean
|
||||
target?: ResolvedGpuTarget
|
||||
}
|
||||
|
||||
const VIRTUAL_DISPLAY_ADAPTER_RE = /microsoft basic|remote display|parsec|virtual|indirect|mirage/i
|
||||
const INTEL_ADAPTER_RE = /\bintel\b/i
|
||||
const INTEL_DISCRETE_ARC_RE = /\barc\b.*\b[ab]\d{3}\b/i
|
||||
const AMD_INTEGRATED_RE = /\bamd\s+radeon(?:\(tm\))?\s+(?:graphics|\d+m\b|vega\s+\d+\s+graphics)/i
|
||||
|
||||
function parseMiBField(raw: string | undefined): number | null {
|
||||
if (!raw) return null
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed || /n\/a/i.test(trimmed)) return null
|
||||
const cleaned = trimmed.replace(/\s*mib$/i, '')
|
||||
if (!/^\d+(?:\.\d+)?$/.test(cleaned)) return null
|
||||
const num = Number(cleaned)
|
||||
return Number.isFinite(num) ? num : null
|
||||
}
|
||||
|
||||
export function parseNvidiaSmiCsv(stdout: string): DiscreteVramSample | null {
|
||||
if (!stdout) return null
|
||||
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||
const line = rawLine.trim()
|
||||
if (!line) continue
|
||||
const parts = line.split(',')
|
||||
if (parts.length < 4) continue
|
||||
const gpuName = parts.slice(0, -3).join(',').trim()
|
||||
const usedMiB = parseMiBField(parts[parts.length - 3])
|
||||
const freeMiB = parseMiBField(parts[parts.length - 2])
|
||||
const totalMiB = parseMiBField(parts[parts.length - 1])
|
||||
if (
|
||||
!gpuName ||
|
||||
usedMiB === null ||
|
||||
freeMiB === null ||
|
||||
totalMiB === null ||
|
||||
usedMiB < 0 ||
|
||||
freeMiB < 0 ||
|
||||
totalMiB <= 0
|
||||
) {
|
||||
continue
|
||||
}
|
||||
return { gpuName, usedMiB, freeMiB, totalMiB }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function detectIntegratedGpuFromRegistryOutput(stdout: string): boolean {
|
||||
if (!stdout) return false
|
||||
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||
const match = /^\s*DriverDesc\s+REG_SZ\s+(.+?)\s*$/i.exec(rawLine)
|
||||
if (!match) continue
|
||||
const desc = match[1].trim()
|
||||
if (!desc || VIRTUAL_DISPLAY_ADAPTER_RE.test(desc)) continue
|
||||
if (INTEL_ADAPTER_RE.test(desc) && !INTEL_DISCRETE_ARC_RE.test(desc)) {
|
||||
return true
|
||||
}
|
||||
if (AMD_INTEGRATED_RE.test(desc)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function chooseStartupGpuTarget(input: {
|
||||
platform: NodeJS.Platform
|
||||
headlessSmoke: boolean
|
||||
requestedMode: GpuRenderMode
|
||||
handoffTarget?: ResolvedGpuTarget
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
}): StartupGpuDecision {
|
||||
const base = {
|
||||
requestedMode: input.requestedMode,
|
||||
vramSample: input.vramSample,
|
||||
hasIntegratedGpu: input.hasIntegratedGpu,
|
||||
}
|
||||
|
||||
if (input.headlessSmoke) {
|
||||
return { ...base, target: 'software', reason: 'headless-smoke' }
|
||||
}
|
||||
if (input.requestedMode === 'software') {
|
||||
return { ...base, target: 'software', reason: 'user-software' }
|
||||
}
|
||||
if (input.requestedMode === 'low-power') {
|
||||
return { ...base, target: 'low-power', reason: 'user-low-power' }
|
||||
}
|
||||
if (input.requestedMode === 'high-performance') {
|
||||
return { ...base, target: 'high-performance', reason: 'user-high-performance' }
|
||||
}
|
||||
if (input.handoffTarget) {
|
||||
return { ...base, target: input.handoffTarget, reason: 'gpu-handoff' }
|
||||
}
|
||||
|
||||
if (
|
||||
input.platform === 'win32' &&
|
||||
input.vramSample &&
|
||||
input.vramSample.freeMiB < VRAM_LOW_THRESHOLD_MIB
|
||||
) {
|
||||
return input.hasIntegratedGpu
|
||||
? { ...base, target: 'low-power', reason: 'low-vram-igpu' }
|
||||
: { ...base, target: 'software', reason: 'low-vram-software' }
|
||||
}
|
||||
|
||||
return { ...base, target: 'default', reason: 'normal-gpu' }
|
||||
}
|
||||
|
||||
export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitch[] {
|
||||
const effectiveTarget: ResolvedGpuTarget =
|
||||
input.headlessSmoke || input.softwareGl || input.target === 'software'
|
||||
? 'software'
|
||||
: (input.target ?? 'default')
|
||||
|
||||
if (effectiveTarget === 'software') {
|
||||
return [
|
||||
{ name: 'disable-gpu' },
|
||||
{ name: 'use-gl', value: 'angle' },
|
||||
{ name: 'use-angle', value: 'swiftshader' },
|
||||
{ name: 'enable-unsafe-swiftshader' },
|
||||
]
|
||||
}
|
||||
|
||||
// Avoid forcing enable-zero-copy / enable-gpu-rasterization:
|
||||
// on Windows dual-GPU setups with high baseline VRAM usage they can provoke driver TDRs.
|
||||
const switches: ChromiumSwitch[] = []
|
||||
if (effectiveTarget === 'low-power') {
|
||||
switches.push({ name: 'force_low_power_gpu' })
|
||||
} else if (effectiveTarget === 'high-performance') {
|
||||
switches.push({ name: 'force_high_performance_gpu' })
|
||||
}
|
||||
switches.push({ name: 'disable-renderer-backgrounding' })
|
||||
if (input.platform === 'linux') {
|
||||
switches.push({ name: 'ozone-platform-hint', value: 'auto' })
|
||||
}
|
||||
return switches
|
||||
}
|
||||
|
||||
export function createVramHysteresisTracker(options: {
|
||||
activeTarget: ResolvedGpuTarget
|
||||
hasIntegratedGpu: boolean
|
||||
lowThresholdMiB?: number
|
||||
recoverThresholdMiB?: number
|
||||
requiredConsecutive?: number
|
||||
}) {
|
||||
const lowThresholdMiB = options.lowThresholdMiB ?? VRAM_LOW_THRESHOLD_MIB
|
||||
const recoverThresholdMiB = options.recoverThresholdMiB ?? VRAM_RECOVER_THRESHOLD_MIB
|
||||
const requiredConsecutive = Math.max(1, options.requiredConsecutive ?? VRAM_SWITCH_CONSECUTIVE_REQUIRED)
|
||||
let streak = 0
|
||||
|
||||
return {
|
||||
observe(sample: DiscreteVramSample | null): VramMonitorAction | null {
|
||||
if (!sample) {
|
||||
streak = 0
|
||||
return null
|
||||
}
|
||||
|
||||
if (options.activeTarget === 'low-power' || options.activeTarget === 'software') {
|
||||
if (sample.freeMiB >= recoverThresholdMiB) {
|
||||
streak += 1
|
||||
if (streak >= requiredConsecutive) {
|
||||
return { kind: 'switch-to-discrete', sample }
|
||||
}
|
||||
} else {
|
||||
streak = 0
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (sample.freeMiB < lowThresholdMiB) {
|
||||
streak += 1
|
||||
if (streak >= requiredConsecutive) {
|
||||
return {
|
||||
kind: options.hasIntegratedGpu ? 'switch-to-low-power' : 'switch-to-software',
|
||||
sample,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
streak = 0
|
||||
}
|
||||
return null
|
||||
},
|
||||
reset(): void {
|
||||
streak = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function createSustainedLowFpsTracker(
|
||||
options: {
|
||||
thresholdFps?: number
|
||||
sustainedMs?: number
|
||||
sampleWindowMs?: number
|
||||
reportCooldownMs?: number
|
||||
} = {},
|
||||
) {
|
||||
const thresholdFps = options.thresholdFps ?? LOW_FPS_THRESHOLD
|
||||
const sustainedMs = options.sustainedMs ?? LOW_FPS_SUSTAINED_MS
|
||||
const sampleWindowMs = options.sampleWindowMs ?? 1000
|
||||
const reportCooldownMs = options.reportCooldownMs ?? FPS_REPORT_COOLDOWN_MS
|
||||
|
||||
let bucketStartMs: number | null = null
|
||||
let bucketFrames = 0
|
||||
let lowDurationMs = 0
|
||||
let lowFrames = 0
|
||||
let lastReportedAt = -Infinity
|
||||
|
||||
return {
|
||||
onFrame(nowMs: number): { avgFps: number; sustainedMs: number } | null {
|
||||
if (!Number.isFinite(nowMs)) return null
|
||||
if (bucketStartMs === null) {
|
||||
bucketStartMs = nowMs
|
||||
bucketFrames = 0
|
||||
return null
|
||||
}
|
||||
bucketFrames += 1
|
||||
const elapsedMs = nowMs - bucketStartMs
|
||||
if (elapsedMs < sampleWindowMs) {
|
||||
return null
|
||||
}
|
||||
|
||||
const fps = (bucketFrames * 1000) / elapsedMs
|
||||
bucketStartMs = nowMs
|
||||
|
||||
if (fps < thresholdFps) {
|
||||
lowDurationMs += elapsedMs
|
||||
lowFrames += bucketFrames
|
||||
bucketFrames = 0
|
||||
if (lowDurationMs >= sustainedMs && nowMs - lastReportedAt >= reportCooldownMs) {
|
||||
const avgFps = Math.round(((lowFrames * 1000) / lowDurationMs) * 10) / 10
|
||||
const reportedDuration = Math.round(lowDurationMs)
|
||||
lastReportedAt = nowMs
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
return { avgFps, sustainedMs: reportedDuration }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
bucketFrames = 0
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
return null
|
||||
},
|
||||
reset(): void {
|
||||
bucketStartMs = null
|
||||
bucketFrames = 0
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function canAutoSwitchGpu(
|
||||
lastSwitchAt: number | null | undefined,
|
||||
nowMs: number,
|
||||
cooldownMs = AUTO_SWITCH_COOLDOWN_MS,
|
||||
): boolean {
|
||||
return !lastSwitchAt || !Number.isFinite(lastSwitchAt) || nowMs - lastSwitchAt >= cooldownMs
|
||||
}
|
||||
|
||||
export function stripGpuOverrideArgs(argv: string[]): string[] {
|
||||
const stripped: string[] = []
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i]
|
||||
if (
|
||||
arg === '--software-gl' ||
|
||||
arg === '--low-power-gpu' ||
|
||||
arg === '--high-performance-gpu' ||
|
||||
arg === '--gpu-handoff' ||
|
||||
arg.startsWith('--gpu-mode=') ||
|
||||
arg.startsWith('--gpu-handoff-target=')
|
||||
) {
|
||||
continue
|
||||
}
|
||||
if (arg === '--gpu-mode' || arg === '--gpu-handoff-target') {
|
||||
i += 1
|
||||
continue
|
||||
}
|
||||
stripped.push(arg)
|
||||
}
|
||||
return stripped
|
||||
}
|
||||
|
||||
export function buildGpuHandoffArgs(argv: string[], target?: ResolvedGpuTarget): string[] {
|
||||
return [
|
||||
...stripGpuOverrideArgs(argv),
|
||||
'--gpu-handoff',
|
||||
...(target ? [`--gpu-handoff-target=${target}`] : []),
|
||||
]
|
||||
}
|
||||
|
||||
export function isGpuProcessCrash(
|
||||
details: { type?: string; reason?: string } | null | undefined,
|
||||
): boolean {
|
||||
return Boolean(details && details.type === 'GPU' && details.reason !== 'clean-exit')
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import { extractTarGzSafely } from './tar-gz'
|
||||
|
||||
export interface ClientShellUpdateInfo {
|
||||
version: string
|
||||
minRequired?: string | null
|
||||
downloadUrl: string
|
||||
releaseNotes?: string | null
|
||||
}
|
||||
|
||||
export interface ClientBundleUpdateInfo {
|
||||
version: string
|
||||
minShellVersion: string
|
||||
url: string
|
||||
sha256: string
|
||||
size?: number
|
||||
releaseNotes?: string | null
|
||||
}
|
||||
|
||||
export interface ClientUpdateManifest {
|
||||
shell?: ClientShellUpdateInfo | null
|
||||
bundle?: ClientBundleUpdateInfo | null
|
||||
}
|
||||
|
||||
export interface HotfixState {
|
||||
activeVersion: string | null
|
||||
previousVerifiedVersion: string | null
|
||||
status: 'verified' | 'pending'
|
||||
pendingAttempts: number
|
||||
blacklistedVersions: string[]
|
||||
installedAt?: string
|
||||
}
|
||||
|
||||
export interface ActiveOverlayResolution {
|
||||
overlayRoot: string | null
|
||||
activeBundleVersion: string
|
||||
pendingVerification: boolean
|
||||
rolledBackFrom: string | null
|
||||
}
|
||||
|
||||
export type UpdateDecision =
|
||||
| { kind: 'up-to-date' }
|
||||
| { kind: 'hotfix-update'; bundle: ClientBundleUpdateInfo }
|
||||
| { kind: 'shell-update'; shell: ClientShellUpdateInfo; mandatory: boolean }
|
||||
|
||||
const SEMVER_PATTERN = /^[vV]?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
|
||||
const STRICT_VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/
|
||||
const SHA256_PATTERN = /^[0-9a-f]{64}$/i
|
||||
const MAX_PENDING_ATTEMPTS = 2
|
||||
|
||||
interface ParsedSemver {
|
||||
major: number
|
||||
minor: number
|
||||
patch: number
|
||||
prerelease: string[]
|
||||
}
|
||||
|
||||
function parseSemver(raw: string): ParsedSemver | null {
|
||||
const match = SEMVER_PATTERN.exec(String(raw || '').trim())
|
||||
if (!match) return null
|
||||
return {
|
||||
major: Number(match[1] ?? 0),
|
||||
minor: Number(match[2] ?? 0),
|
||||
patch: Number(match[3] ?? 0),
|
||||
prerelease: match[4] ? match[4].split('.') : [],
|
||||
}
|
||||
}
|
||||
|
||||
export function compareSemver(a: string, b: string): number {
|
||||
const pa = parseSemver(a)
|
||||
const pb = parseSemver(b)
|
||||
if (!pa || !pb) {
|
||||
return String(a).localeCompare(String(b))
|
||||
}
|
||||
for (const [va, vb] of [
|
||||
[pa.major, pb.major],
|
||||
[pa.minor, pb.minor],
|
||||
[pa.patch, pb.patch],
|
||||
]) {
|
||||
if (va !== vb) return va > vb ? 1 : -1
|
||||
}
|
||||
if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0
|
||||
if (pa.prerelease.length === 0) return 1
|
||||
if (pb.prerelease.length === 0) return -1
|
||||
|
||||
const maxLen = Math.max(pa.prerelease.length, pb.prerelease.length)
|
||||
for (let i = 0; i < maxLen; i += 1) {
|
||||
const ia = pa.prerelease[i]
|
||||
const ib = pb.prerelease[i]
|
||||
if (ia === undefined) return -1
|
||||
if (ib === undefined) return 1
|
||||
const na = /^\d+$/.test(ia) ? Number(ia) : null
|
||||
const nb = /^\d+$/.test(ib) ? Number(ib) : null
|
||||
if (na !== null && nb !== null) {
|
||||
if (na !== nb) return na > nb ? 1 : -1
|
||||
} else if (na !== null) {
|
||||
return -1
|
||||
} else if (nb !== null) {
|
||||
return 1
|
||||
} else if (ia !== ib) {
|
||||
return ia > ib ? 1 : -1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
export function getHotfixRootDir(userDataDir: string): string {
|
||||
return path.join(userDataDir, 'earth-hotfix')
|
||||
}
|
||||
|
||||
export function getHotfixBundlesDir(userDataDir: string): string {
|
||||
return path.join(getHotfixRootDir(userDataDir), 'bundles')
|
||||
}
|
||||
|
||||
export function getHotfixBundleDir(userDataDir: string, version: string): string {
|
||||
return path.join(getHotfixBundlesDir(userDataDir), version)
|
||||
}
|
||||
|
||||
function getHotfixStatePath(userDataDir: string): string {
|
||||
return path.join(getHotfixRootDir(userDataDir), 'state.json')
|
||||
}
|
||||
|
||||
function defaultHotfixState(): HotfixState {
|
||||
return {
|
||||
activeVersion: null,
|
||||
previousVerifiedVersion: null,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: [],
|
||||
}
|
||||
}
|
||||
|
||||
export function readHotfixState(userDataDir: string): HotfixState {
|
||||
const statePath = getHotfixStatePath(userDataDir)
|
||||
try {
|
||||
if (!fs.existsSync(statePath)) return defaultHotfixState()
|
||||
const raw = JSON.parse(fs.readFileSync(statePath, 'utf8')) as Partial<HotfixState>
|
||||
return {
|
||||
activeVersion: typeof raw.activeVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.activeVersion)
|
||||
? raw.activeVersion
|
||||
: null,
|
||||
previousVerifiedVersion: typeof raw.previousVerifiedVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.previousVerifiedVersion)
|
||||
? raw.previousVerifiedVersion
|
||||
: null,
|
||||
status: raw.status === 'pending' ? 'pending' : 'verified',
|
||||
pendingAttempts: Number.isInteger(raw.pendingAttempts) && Number(raw.pendingAttempts) >= 0
|
||||
? Number(raw.pendingAttempts)
|
||||
: 0,
|
||||
blacklistedVersions: Array.isArray(raw.blacklistedVersions)
|
||||
? raw.blacklistedVersions.filter((item): item is string => typeof item === 'string' && STRICT_VERSION_PATTERN.test(item))
|
||||
: [],
|
||||
installedAt: typeof raw.installedAt === 'string' ? raw.installedAt : undefined,
|
||||
}
|
||||
} catch {
|
||||
return defaultHotfixState()
|
||||
}
|
||||
}
|
||||
|
||||
export function writeHotfixStateAtomic(userDataDir: string, state: HotfixState): void {
|
||||
const rootDir = getHotfixRootDir(userDataDir)
|
||||
const statePath = getHotfixStatePath(userDataDir)
|
||||
const tmpPath = `${statePath}.${process.pid}.tmp`
|
||||
fs.mkdirSync(rootDir, { recursive: true })
|
||||
fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, 'utf8')
|
||||
fs.renameSync(tmpPath, statePath)
|
||||
}
|
||||
|
||||
function hasValidBundleIndex(bundleDir: string): boolean {
|
||||
try {
|
||||
return fs.statSync(path.join(bundleDir, 'index.html')).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFallbackVersion(state: HotfixState, shellVersion: string, userDataDir: string): string | null {
|
||||
const candidate = state.previousVerifiedVersion
|
||||
if (!candidate) return null
|
||||
if (candidate === state.activeVersion) return null
|
||||
if (state.blacklistedVersions.includes(candidate)) return null
|
||||
if (compareSemver(candidate, shellVersion) <= 0) return null
|
||||
if (!hasValidBundleIndex(getHotfixBundleDir(userDataDir, candidate))) return null
|
||||
return candidate
|
||||
}
|
||||
|
||||
function pruneObsoleteBundles(userDataDir: string, keepVersions: Set<string>): void {
|
||||
const bundlesDir = getHotfixBundlesDir(userDataDir)
|
||||
try {
|
||||
if (!fs.existsSync(bundlesDir)) return
|
||||
for (const entry of fs.readdirSync(bundlesDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue
|
||||
if (keepVersions.has(entry.name)) continue
|
||||
fs.rmSync(path.join(bundlesDir, entry.name), { recursive: true, force: true })
|
||||
}
|
||||
} catch {
|
||||
// Non-fatal cleanup best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveActiveEarthOverlay(options: {
|
||||
userDataDir: string
|
||||
shellVersion: string
|
||||
}): ActiveOverlayResolution {
|
||||
const { userDataDir, shellVersion } = options
|
||||
const state = readHotfixState(userDataDir)
|
||||
|
||||
if (!state.activeVersion || compareSemver(state.activeVersion, shellVersion) <= 0) {
|
||||
return {
|
||||
overlayRoot: null,
|
||||
activeBundleVersion: shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
const activeDir = getHotfixBundleDir(userDataDir, state.activeVersion)
|
||||
const activeUsable =
|
||||
!state.blacklistedVersions.includes(state.activeVersion) && hasValidBundleIndex(activeDir)
|
||||
|
||||
if (!activeUsable) {
|
||||
const badVersion = state.activeVersion
|
||||
const fallbackVer = resolveFallbackVersion(state, shellVersion, userDataDir)
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
return {
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: badVersion,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === 'pending') {
|
||||
if (state.pendingAttempts >= MAX_PENDING_ATTEMPTS) {
|
||||
const rolledBackFrom = state.activeVersion
|
||||
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
||||
? state.blacklistedVersions
|
||||
: [...state.blacklistedVersions, rolledBackFrom]
|
||||
const fallbackVer = resolveFallbackVersion(
|
||||
{ ...state, blacklistedVersions: blacklist },
|
||||
shellVersion,
|
||||
userDataDir,
|
||||
)
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: blacklist,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
fs.rmSync(activeDir, { recursive: true, force: true })
|
||||
return {
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom,
|
||||
}
|
||||
}
|
||||
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
pendingAttempts: state.pendingAttempts + 1,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
return {
|
||||
overlayRoot: activeDir,
|
||||
activeBundleVersion: state.activeVersion,
|
||||
pendingVerification: true,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
overlayRoot: activeDir,
|
||||
activeBundleVersion: state.activeVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
export function markHotfixVerified(userDataDir: string): HotfixState {
|
||||
const state = readHotfixState(userDataDir)
|
||||
if (!state.activeVersion) {
|
||||
return state
|
||||
}
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
previousVerifiedVersion: state.activeVersion,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
const keep = new Set<string>([state.activeVersion])
|
||||
if (nextState.previousVerifiedVersion) {
|
||||
keep.add(nextState.previousVerifiedVersion)
|
||||
}
|
||||
pruneObsoleteBundles(userDataDir, keep)
|
||||
return nextState
|
||||
}
|
||||
|
||||
export function rollbackPendingHotfix(userDataDir: string, shellVersion: string): {
|
||||
rolledBackFrom: string | null
|
||||
overlayRoot: string | null
|
||||
activeBundleVersion: string
|
||||
} {
|
||||
const state = readHotfixState(userDataDir)
|
||||
if (!state.activeVersion || state.status !== 'pending') {
|
||||
const activeDir = state.activeVersion ? getHotfixBundleDir(userDataDir, state.activeVersion) : null
|
||||
const valid = Boolean(
|
||||
activeDir &&
|
||||
state.activeVersion &&
|
||||
compareSemver(state.activeVersion, shellVersion) > 0 &&
|
||||
hasValidBundleIndex(activeDir),
|
||||
)
|
||||
return {
|
||||
rolledBackFrom: null,
|
||||
overlayRoot: valid ? activeDir : null,
|
||||
activeBundleVersion: valid && state.activeVersion ? state.activeVersion : shellVersion,
|
||||
}
|
||||
}
|
||||
|
||||
const rolledBackFrom = state.activeVersion
|
||||
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
||||
? state.blacklistedVersions
|
||||
: [...state.blacklistedVersions, rolledBackFrom]
|
||||
const fallbackVer = resolveFallbackVersion(
|
||||
{ ...state, blacklistedVersions: blacklist },
|
||||
shellVersion,
|
||||
userDataDir,
|
||||
)
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: blacklist,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
fs.rmSync(getHotfixBundleDir(userDataDir, rolledBackFrom), { recursive: true, force: true })
|
||||
|
||||
return {
|
||||
rolledBackFrom,
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
}
|
||||
}
|
||||
|
||||
export function evaluateUpdateDecision(input: {
|
||||
shellVersion: string
|
||||
activeBundleVersion: string
|
||||
blacklistedVersions: string[]
|
||||
manifest: ClientUpdateManifest | null | undefined
|
||||
}): UpdateDecision {
|
||||
const manifest = input.manifest
|
||||
if (!manifest || typeof manifest !== 'object') {
|
||||
return { kind: 'up-to-date' }
|
||||
}
|
||||
|
||||
const shell = manifest.shell
|
||||
const hasShellDownload = Boolean(shell?.downloadUrl && typeof shell.downloadUrl === 'string')
|
||||
const shellMandatory = Boolean(
|
||||
hasShellDownload && shell?.minRequired && compareSemver(shell.minRequired, input.shellVersion) > 0,
|
||||
)
|
||||
const shellNewer = Boolean(
|
||||
hasShellDownload && shell?.version && compareSemver(shell.version, input.shellVersion) > 0,
|
||||
)
|
||||
if (shell && shellMandatory) {
|
||||
return { kind: 'shell-update', shell, mandatory: true }
|
||||
}
|
||||
|
||||
const bundle = manifest.bundle
|
||||
if (
|
||||
bundle &&
|
||||
typeof bundle.version === 'string' &&
|
||||
STRICT_VERSION_PATTERN.test(bundle.version) &&
|
||||
typeof bundle.url === 'string' &&
|
||||
bundle.url.trim().length > 0 &&
|
||||
typeof bundle.sha256 === 'string' &&
|
||||
SHA256_PATTERN.test(bundle.sha256.trim()) &&
|
||||
compareSemver(bundle.version, input.activeBundleVersion) > 0 &&
|
||||
compareSemver(input.shellVersion, bundle.minShellVersion || '0.0.0') >= 0 &&
|
||||
!input.blacklistedVersions.includes(bundle.version)
|
||||
) {
|
||||
return { kind: 'hotfix-update', bundle }
|
||||
}
|
||||
|
||||
if (shell && shellNewer) {
|
||||
return { kind: 'shell-update', shell, mandatory: false }
|
||||
}
|
||||
|
||||
return { kind: 'up-to-date' }
|
||||
}
|
||||
|
||||
export const PERIODIC_UPDATE_CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000
|
||||
|
||||
export function getUpdatePromptKey(decision: UpdateDecision): string | null {
|
||||
if (decision.kind === 'hotfix-update') {
|
||||
return `hotfix:${decision.bundle.version}`
|
||||
}
|
||||
if (decision.kind === 'shell-update') {
|
||||
return `shell:${decision.shell.version}`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function shouldSuppressUpdatePrompt(
|
||||
decision: UpdateDecision,
|
||||
options: { manual: boolean; dismissedKeys: ReadonlySet<string> },
|
||||
): boolean {
|
||||
if (options.manual || decision.kind === 'up-to-date') {
|
||||
return false
|
||||
}
|
||||
const key = getUpdatePromptKey(decision)
|
||||
return Boolean(key && options.dismissedKeys.has(key))
|
||||
}
|
||||
|
||||
export function resolveUpdateAssetUrl(rawUrl: string, backendUrl: string): string {
|
||||
const trimmed = String(rawUrl || '').trim()
|
||||
if (!trimmed) {
|
||||
throw new Error('Empty update asset URL')
|
||||
}
|
||||
if (trimmed.startsWith('/')) {
|
||||
const base = new URL(backendUrl)
|
||||
return new URL(trimmed, `${base.origin}`).toString()
|
||||
}
|
||||
const parsed = new URL(trimmed)
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error(`Unsupported update asset URL protocol: ${parsed.protocol}`)
|
||||
}
|
||||
return parsed.toString()
|
||||
}
|
||||
|
||||
export function installHotfixArchive(input: {
|
||||
userDataDir: string
|
||||
version: string
|
||||
archiveBuffer: Buffer
|
||||
expectedSha256: string
|
||||
}): { overlayRoot: string; filesCount: number } {
|
||||
const version = String(input.version || '').trim()
|
||||
if (!STRICT_VERSION_PATTERN.test(version)) {
|
||||
throw new Error(`Invalid hotfix bundle version: ${version}`)
|
||||
}
|
||||
const expected = String(input.expectedSha256 || '').trim().toLowerCase()
|
||||
if (!SHA256_PATTERN.test(expected)) {
|
||||
throw new Error('Invalid expected SHA-256 checksum')
|
||||
}
|
||||
|
||||
const actual = crypto.createHash('sha256').update(input.archiveBuffer).digest('hex').toLowerCase()
|
||||
if (actual !== expected) {
|
||||
throw new Error(`Hotfix SHA-256 mismatch (expected ${expected}, got ${actual})`)
|
||||
}
|
||||
|
||||
const rootDir = getHotfixRootDir(input.userDataDir)
|
||||
const bundlesDir = getHotfixBundlesDir(input.userDataDir)
|
||||
const targetDir = getHotfixBundleDir(input.userDataDir, version)
|
||||
const stagingDir = path.join(rootDir, `staging-${version}-${Date.now()}`)
|
||||
|
||||
try {
|
||||
const extracted = extractTarGzSafely(input.archiveBuffer, stagingDir)
|
||||
if (!hasValidBundleIndex(stagingDir)) {
|
||||
throw new Error('Hotfix archive is missing required index.html entry')
|
||||
}
|
||||
|
||||
fs.mkdirSync(bundlesDir, { recursive: true })
|
||||
fs.rmSync(targetDir, { recursive: true, force: true })
|
||||
fs.renameSync(stagingDir, targetDir)
|
||||
|
||||
const previousState = readHotfixState(input.userDataDir)
|
||||
const preservedVerified =
|
||||
previousState.status === 'verified' && previousState.activeVersion && previousState.activeVersion !== version
|
||||
? previousState.activeVersion
|
||||
: previousState.previousVerifiedVersion && previousState.previousVerifiedVersion !== version
|
||||
? previousState.previousVerifiedVersion
|
||||
: null
|
||||
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: version,
|
||||
previousVerifiedVersion: preservedVerified,
|
||||
status: 'pending',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: previousState.blacklistedVersions.filter((item) => item !== version),
|
||||
installedAt: new Date().toISOString(),
|
||||
}
|
||||
writeHotfixStateAtomic(input.userDataDir, nextState)
|
||||
|
||||
return {
|
||||
overlayRoot: targetDir,
|
||||
filesCount: extracted.files.length,
|
||||
}
|
||||
} catch (error) {
|
||||
fs.rmSync(stagingDir, { recursive: true, force: true })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import { dialog, net, shell, type BrowserWindow, type MessageBoxOptions } from 'electron'
|
||||
|
||||
import {
|
||||
evaluateUpdateDecision,
|
||||
getUpdatePromptKey,
|
||||
installHotfixArchive,
|
||||
markHotfixVerified,
|
||||
readHotfixState,
|
||||
resolveActiveEarthOverlay,
|
||||
resolveUpdateAssetUrl,
|
||||
rollbackPendingHotfix,
|
||||
shouldSuppressUpdatePrompt,
|
||||
type ClientUpdateManifest,
|
||||
} from './hot-update-core'
|
||||
|
||||
export interface HotUpdateVersionInfo {
|
||||
shellVersion: string
|
||||
activeBundleVersion: string
|
||||
usingHotfix: boolean
|
||||
pendingVerification: boolean
|
||||
}
|
||||
|
||||
export interface HotUpdateController {
|
||||
getOverlayRoot(): string | null
|
||||
getVersionInfo(): HotUpdateVersionInfo
|
||||
markStartupReady(): void
|
||||
handleRendererCrash(): void
|
||||
startStartupWatchdog(): void
|
||||
stopStartupWatchdog(): void
|
||||
checkForUpdates(options?: { manual?: boolean }): Promise<void>
|
||||
}
|
||||
|
||||
const MANIFEST_TIMEOUT_MS = 10_000
|
||||
const DOWNLOAD_TIMEOUT_MS = 60_000
|
||||
const STARTUP_VERIFY_TIMEOUT_MS = 15_000
|
||||
|
||||
async function fetchWithTimeout(
|
||||
fetchImpl: typeof fetch,
|
||||
url: string,
|
||||
timeoutMs: number,
|
||||
init: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
try {
|
||||
return await fetchImpl(url, { ...init, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
export function createHotUpdateController(options: {
|
||||
userDataDir: string
|
||||
shellVersion: string
|
||||
getBackendUrl: () => string
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
onOverlayChanged: (nextOverlayRoot: string | null, nextBundleVersion: string) => void
|
||||
fetchImpl?: typeof fetch
|
||||
}): HotUpdateController {
|
||||
const fetchImpl = options.fetchImpl ?? ((input, init) => net.fetch(input as string, init))
|
||||
|
||||
const initial = resolveActiveEarthOverlay({
|
||||
userDataDir: options.userDataDir,
|
||||
shellVersion: options.shellVersion,
|
||||
})
|
||||
if (initial.rolledBackFrom) {
|
||||
console.warn(
|
||||
`[planet-client] Rolled back unverified hotfix v${initial.rolledBackFrom} -> v${initial.activeBundleVersion}`,
|
||||
)
|
||||
}
|
||||
|
||||
let overlayRoot = initial.overlayRoot
|
||||
let activeBundleVersion = initial.activeBundleVersion
|
||||
let pendingVerification = initial.pendingVerification
|
||||
let watchdogTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let inFlightCheck: Promise<void> | null = null
|
||||
const dismissedPromptKeys = new Set<string>()
|
||||
|
||||
const notifyStatus = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.send('planet:update-status', { message, type })
|
||||
}
|
||||
}
|
||||
|
||||
const showBox = (boxOptions: MessageBoxOptions) => {
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed()) {
|
||||
return dialog.showMessageBox(win, boxOptions)
|
||||
}
|
||||
return dialog.showMessageBox(boxOptions)
|
||||
}
|
||||
|
||||
const stopStartupWatchdog = () => {
|
||||
if (watchdogTimer) {
|
||||
clearTimeout(watchdogTimer)
|
||||
watchdogTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const performRollbackAndReload = (reason: string) => {
|
||||
stopStartupWatchdog()
|
||||
const result = rollbackPendingHotfix(options.userDataDir, options.shellVersion)
|
||||
if (!result.rolledBackFrom) return
|
||||
console.warn(`[planet-client] ${reason}; rolled back v${result.rolledBackFrom} -> v${result.activeBundleVersion}`)
|
||||
overlayRoot = result.overlayRoot
|
||||
activeBundleVersion = result.activeBundleVersion
|
||||
pendingVerification = false
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.reloadIgnoringCache()
|
||||
}
|
||||
}
|
||||
|
||||
const startStartupWatchdog = () => {
|
||||
stopStartupWatchdog()
|
||||
if (!pendingVerification) return
|
||||
watchdogTimer = setTimeout(() => {
|
||||
watchdogTimer = null
|
||||
if (!pendingVerification) return
|
||||
performRollbackAndReload('Hotfix startup verification timed out')
|
||||
}, STARTUP_VERIFY_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
const markStartupReady = () => {
|
||||
stopStartupWatchdog()
|
||||
if (!pendingVerification) return
|
||||
pendingVerification = false
|
||||
markHotfixVerified(options.userDataDir)
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
notifyStatus(`热更新已生效 / Hotfix v${activeBundleVersion} active`, 'success')
|
||||
}
|
||||
|
||||
const handleRendererCrash = () => {
|
||||
if (!pendingVerification) return
|
||||
performRendererCrashRecovery()
|
||||
}
|
||||
|
||||
const performRendererCrashRecovery = () => {
|
||||
performRendererSafeRollback()
|
||||
}
|
||||
|
||||
const performRendererSafeRollback = () => {
|
||||
performRollbackAndReload('Renderer exited unexpectedly under pending hotfix')
|
||||
}
|
||||
|
||||
const applyHotfixBundle = async (bundleUrl: string, version: string, expectedSha256: string) => {
|
||||
notifyStatus(`正在下载热更新 v${version}… / Downloading hotfix v${version}…`, 'info')
|
||||
const response = await fetchWithTimeout(fetchImpl, bundleUrl, DOWNLOAD_TIMEOUT_MS, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
const arrayBuf = await response.arrayBuffer()
|
||||
const archiveBuffer = Buffer.from(arrayBuf)
|
||||
|
||||
const installed = installHotfixArchive({
|
||||
userDataDir: options.userDataDir,
|
||||
version,
|
||||
archiveBuffer,
|
||||
expectedSha256,
|
||||
})
|
||||
|
||||
overlayRoot = installed.overlayRoot
|
||||
activeBundleVersion = version
|
||||
pendingVerification = true
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
startStartupWatchdog()
|
||||
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.reloadIgnoringCache()
|
||||
}
|
||||
}
|
||||
|
||||
const runCheck = async (manual: boolean): Promise<void> => {
|
||||
const backendUrl = options.getBackendUrl().replace(/\/+$/, '')
|
||||
const manifestUrl = new URL(`${backendUrl}/api/v1/client/update-manifest`)
|
||||
manifestUrl.searchParams.set('platform', process.platform)
|
||||
manifestUrl.searchParams.set('arch', process.arch)
|
||||
manifestUrl.searchParams.set('shell', options.shellVersion)
|
||||
manifestUrl.searchParams.set('bundle', activeBundleVersion)
|
||||
|
||||
let manifest: ClientUpdateManifest
|
||||
try {
|
||||
const response = await fetchWithTimeout(fetchImpl, manifestUrl.toString(), MANIFEST_TIMEOUT_MS, {
|
||||
cache: 'no-store',
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
manifest = (await response.json()) as ClientUpdateManifest
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
if (manual) {
|
||||
await showBox({
|
||||
type: 'warning',
|
||||
title: '检查更新失败 / Update Check Failed',
|
||||
message: '无法获取版本清单,请确认服务端连接正常。',
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
} else {
|
||||
console.warn('[planet-client] Startup update check skipped:', detail)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const state = readHotfixState(options.userDataDir)
|
||||
const decision = evaluateUpdateDecision({
|
||||
shellVersion: options.shellVersion,
|
||||
activeBundleVersion,
|
||||
blacklistedVersions: state.blacklistedVersions,
|
||||
manifest,
|
||||
})
|
||||
|
||||
if (decision.kind === 'up-to-date') {
|
||||
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'],
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (shouldSuppressUpdatePrompt(decision, { manual, dismissedKeys: dismissedPromptKeys })) {
|
||||
return
|
||||
}
|
||||
|
||||
const promptKey = getUpdatePromptKey(decision)
|
||||
|
||||
if (decision.kind === 'hotfix-update') {
|
||||
const { bundle } = decision
|
||||
const notes = bundle.releaseNotes?.trim() ? `\n\n更新内容:\n${bundle.releaseNotes.trim()}` : ''
|
||||
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'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
if (response !== 0) {
|
||||
if (promptKey) dismissedPromptKeys.add(promptKey)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const assetUrl = resolveUpdateAssetUrl(bundle.url, backendUrl)
|
||||
await applyHotfixBundle(assetUrl, bundle.version, bundle.sha256)
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
console.error('[planet-client] Hotfix installation failed:', detail)
|
||||
await showBox({
|
||||
type: 'error',
|
||||
title: '热更新失败 / Hotfix Failed',
|
||||
message: `热更新包 v${bundle.version} 下载或校验失败,已保留当前版本运行。`,
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const { shell: shellInfo, mandatory } = decision
|
||||
const notes = shellInfo.releaseNotes?.trim() ? `\n\n更新说明:\n${shellInfo.releaseNotes.trim()}` : ''
|
||||
const { response } = await showBox({
|
||||
type: mandatory ? 'warning' : 'info',
|
||||
title: '发现客户端大版本更新 / Major Client Update',
|
||||
message: mandatory
|
||||
? `当前客户端版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}`
|
||||
: `发现客户端新版本 v${shellInfo.version}`,
|
||||
detail: `当前客户端外壳:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n该版本包含底层架构或原生壳变更,需下载安装包覆盖更新。${notes}`,
|
||||
buttons: ['前往下载 / Download', '稍后提醒 / Later'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
if (response === 0) {
|
||||
await shell.openExternal(shellInfo.downloadUrl)
|
||||
} else if (promptKey) {
|
||||
dismissedPromptKeys.add(promptKey)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getOverlayRoot: () => overlayRoot,
|
||||
getVersionInfo: () => ({
|
||||
shellVersion: options.shellVersion,
|
||||
activeBundleVersion,
|
||||
usingHotfix: Boolean(overlayRoot),
|
||||
pendingVerification,
|
||||
}),
|
||||
markStartupReady,
|
||||
handleRendererCrash,
|
||||
startStartupWatchdog,
|
||||
stopStartupWatchdog,
|
||||
checkForUpdates(checkOpts = {}) {
|
||||
if (inFlightCheck) return inFlightCheck
|
||||
inFlightCheck = runCheck(Boolean(checkOpts.manual)).finally(() => {
|
||||
inFlightCheck = null
|
||||
})
|
||||
return inFlightCheck
|
||||
},
|
||||
}
|
||||
}
|
||||
+313
-26
@@ -1,30 +1,75 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron'
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, net, session, shell } from 'electron'
|
||||
|
||||
import { DesktopConfigStore, normalizeSplashTheme, type ServerEndpoints } from './config'
|
||||
import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config'
|
||||
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
|
||||
import { createEarthDesktopAuth } from './earth-auth'
|
||||
import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
|
||||
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 { buildApplicationMenu } from './menu'
|
||||
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
|
||||
import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation } from './window'
|
||||
import { createScreenRecorderController } from './screen-recorder'
|
||||
import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
|
||||
|
||||
registerEarthScheme()
|
||||
|
||||
const isHeadlessSmoke = process.argv.includes('--headless-smoke')
|
||||
if (isHeadlessSmoke) {
|
||||
app.commandLine.appendSwitch('disable-gpu')
|
||||
app.commandLine.appendSwitch('use-gl', 'angle')
|
||||
app.commandLine.appendSwitch('use-angle', 'swiftshader')
|
||||
app.commandLine.appendSwitch('enable-unsafe-swiftshader')
|
||||
} else {
|
||||
// Prioritize discrete/high-performance GPU and avoid throttling visible secondary-screen renders.
|
||||
app.commandLine.appendSwitch('force_high_performance_gpu')
|
||||
app.commandLine.appendSwitch('enable-gpu-rasterization')
|
||||
app.commandLine.appendSwitch('enable-zero-copy')
|
||||
app.commandLine.appendSwitch('disable-renderer-backgrounding')
|
||||
if (process.platform === 'linux') {
|
||||
app.commandLine.appendSwitch('ozone-platform-hint', 'auto')
|
||||
let preReadyUserDataDir = ''
|
||||
let preReadyExeDir = process.cwd()
|
||||
try {
|
||||
preReadyUserDataDir = app.getPath('userData')
|
||||
} catch {
|
||||
preReadyUserDataDir = ''
|
||||
}
|
||||
try {
|
||||
preReadyExeDir = path.dirname(app.getPath('exe'))
|
||||
} catch {
|
||||
preReadyExeDir = process.cwd()
|
||||
}
|
||||
|
||||
const requestedGpuMode = readPreReadyGpuMode({
|
||||
userDataDir: preReadyUserDataDir,
|
||||
exeDir: preReadyExeDir,
|
||||
resourcesDir: process.resourcesPath,
|
||||
argv: process.argv,
|
||||
})
|
||||
const preReadyHandoff = readPreReadyGpuHandoff(process.argv)
|
||||
const preReadyGpuEnv =
|
||||
!isHeadlessSmoke &&
|
||||
!preReadyHandoff.gpuHandoffTarget &&
|
||||
requestedGpuMode === 'auto' &&
|
||||
process.platform === 'win32'
|
||||
? probeWindowsGpuEnvironmentSync()
|
||||
: { vramSample: null, hasIntegratedGpu: false }
|
||||
|
||||
const startupGpuDecision = chooseStartupGpuTarget({
|
||||
platform: process.platform,
|
||||
headlessSmoke: isHeadlessSmoke,
|
||||
requestedMode: requestedGpuMode,
|
||||
handoffTarget: preReadyHandoff.gpuHandoffTarget,
|
||||
vramSample: preReadyGpuEnv.vramSample,
|
||||
hasIntegratedGpu: preReadyGpuEnv.hasIntegratedGpu,
|
||||
})
|
||||
|
||||
if (startupGpuDecision.reason === 'low-vram-igpu' || startupGpuDecision.reason === 'low-vram-software') {
|
||||
console.info(
|
||||
`[planet-client] Adaptive GPU selected ${startupGpuDecision.target} (reason=${startupGpuDecision.reason}, freeMiB=${startupGpuDecision.vramSample?.freeMiB ?? 'unknown'})`,
|
||||
)
|
||||
}
|
||||
|
||||
for (const sw of resolveChromiumGpuSwitches({
|
||||
platform: process.platform,
|
||||
headlessSmoke: isHeadlessSmoke,
|
||||
target: startupGpuDecision.target,
|
||||
})) {
|
||||
if (sw.value !== undefined) {
|
||||
app.commandLine.appendSwitch(sw.name, sw.value)
|
||||
} else {
|
||||
app.commandLine.appendSwitch(sw.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +108,24 @@ function resolvePreloadPath(): string {
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
|
||||
}
|
||||
|
||||
function resolveIndicatorPreloadPath(): string {
|
||||
const candidates = [
|
||||
path.join(app.getAppPath(), 'dist-electron/preload/recording-indicator.cjs'),
|
||||
path.resolve(app.getAppPath(), '../preload/recording-indicator.cjs'),
|
||||
path.resolve(process.cwd(), 'dist-electron/preload/recording-indicator.cjs'),
|
||||
]
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
|
||||
}
|
||||
|
||||
function resolveCursorOverlayPreloadPath(): string {
|
||||
const candidates = [
|
||||
path.join(app.getAppPath(), 'dist-electron/preload/recording-cursor.cjs'),
|
||||
path.resolve(app.getAppPath(), '../preload/recording-cursor.cjs'),
|
||||
path.resolve(process.cwd(), 'dist-electron/preload/recording-cursor.cjs'),
|
||||
]
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
|
||||
}
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
let launchWindow: (() => void) | undefined
|
||||
|
||||
@@ -93,6 +156,20 @@ if (!singleInstanceLock) {
|
||||
}
|
||||
})
|
||||
|
||||
app.on('child-process-gone', (_event, details) => {
|
||||
if (!isGpuProcessCrash(details)) return
|
||||
console.warn('[planet-client] GPU process exited unexpectedly', {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
})
|
||||
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {
|
||||
mainWindow.webContents.send('planet:gpu-process-gone', {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
void app.whenReady().then(async () => {
|
||||
if (!isHeadlessSmoke) {
|
||||
void registerDesktopLink().catch(error => console.warn('Planet Earth protocol registration failed', error))
|
||||
@@ -105,11 +182,173 @@ if (!singleInstanceLock) {
|
||||
})
|
||||
|
||||
const earthBundleRoot = resolveEarthBundleRoot()
|
||||
const relaunchDesktopApp = (relaunchOptions?: {
|
||||
gpuHandoff?: boolean
|
||||
gpuHandoffTarget?: ResolvedGpuTarget
|
||||
}) => {
|
||||
flushWindowState(mainWindow)
|
||||
if (singleInstanceLock) {
|
||||
app.releaseSingleInstanceLock()
|
||||
}
|
||||
const rawArgs = process.argv.slice(1)
|
||||
const args = relaunchOptions?.gpuHandoff
|
||||
? buildGpuHandoffArgs(rawArgs, relaunchOptions.gpuHandoffTarget)
|
||||
: stripGpuOverrideArgs(rawArgs)
|
||||
app.relaunch({ args })
|
||||
app.exit(0)
|
||||
}
|
||||
|
||||
const hotUpdater = createHotUpdateController({
|
||||
userDataDir: app.getPath('userData'),
|
||||
shellVersion: app.getVersion(),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getMainWindow: () => mainWindow,
|
||||
onOverlayChanged: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
|
||||
const gpuMonitor = createAdaptiveGpuMonitor({
|
||||
userDataDir: app.getPath('userData'),
|
||||
startupDecision: startupGpuDecision,
|
||||
getConfiguredMode: () => configStore.get().gpuMode,
|
||||
getMainWindow: () => mainWindow,
|
||||
onAutoSwitch: (nextTarget) => {
|
||||
relaunchDesktopApp({ gpuHandoff: true, gpuHandoffTarget: nextTarget })
|
||||
},
|
||||
onStatusUpdated: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
|
||||
const sendPendingHandoffToast = () => {
|
||||
if (isHeadlessSmoke || !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
const toast = gpuMonitor.consumePendingHandoffToast()
|
||||
if (toast) {
|
||||
mainWindow.webContents.send('planet:update-status', toast)
|
||||
}
|
||||
}
|
||||
|
||||
let screenRecorder: ReturnType<typeof createScreenRecorderController> | null = null
|
||||
|
||||
const refreshApplicationMenu = () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
Menu.setApplicationMenu(
|
||||
buildApplicationMenu({
|
||||
mainWindow,
|
||||
configStore,
|
||||
getVersionInfo: () => hotUpdater.getVersionInfo(),
|
||||
onCheckForUpdates: () => {
|
||||
void hotUpdater.checkForUpdates({ manual: true })
|
||||
},
|
||||
getGpuStatus: () => gpuMonitor.getRuntimeSummary(),
|
||||
onSelectGpuMode: async (nextMode: GpuRenderMode) => {
|
||||
configStore.updateGpuMode(nextMode)
|
||||
refreshApplicationMenu()
|
||||
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'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
}
|
||||
const { response } = targetWin
|
||||
? await dialog.showMessageBox(targetWin, boxOptions)
|
||||
: await dialog.showMessageBox(boxOptions)
|
||||
if (response === 0) {
|
||||
relaunchDesktopApp({ gpuHandoff: true })
|
||||
}
|
||||
},
|
||||
getRecordingState: () => screenRecorder?.getState() ?? {
|
||||
state: 'idle',
|
||||
elapsedMs: 0,
|
||||
includeAudio: configStore.get().recordAudio,
|
||||
hideCursor: configStore.get().recordHideCursor,
|
||||
filePath: null,
|
||||
},
|
||||
onToggleRecording: (fromMenu = false) => {
|
||||
void screenRecorder?.toggleRecording({ fromMenu })
|
||||
},
|
||||
onToggleRecordAudio: (enabled: boolean) => {
|
||||
configStore.updateRecordAudio(enabled)
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
onToggleRecordHideCursor: (enabled: boolean) => {
|
||||
configStore.updateRecordHideCursor(enabled)
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
onOpenRecordingsFolder: () => {
|
||||
void screenRecorder?.openRecordingsFolder()
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
screenRecorder = createScreenRecorderController({
|
||||
getMainWindow: () => mainWindow,
|
||||
configStore,
|
||||
session: session.defaultSession,
|
||||
indicatorPreloadPath: resolveIndicatorPreloadPath(),
|
||||
cursorOverlayPreloadPath: resolveCursorOverlayPreloadPath(),
|
||||
dismissMenuBar: dismissMenuBarOnPointerDown,
|
||||
onStateChanged: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
app.on('will-quit', () => {
|
||||
screenRecorder?.destroy()
|
||||
})
|
||||
|
||||
const earthAuth = createEarthDesktopAuth({
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getAppVersion: () => app.getVersion(),
|
||||
handshakeSecret: process.env.PLANET_EARTH_DESKTOP_HANDSHAKE_SECRET || '',
|
||||
fetchImpl: (input, init) => net.fetch(input as string, init),
|
||||
})
|
||||
|
||||
installEarthSessionHandlers(session.defaultSession, {
|
||||
earthBundleRoot,
|
||||
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getEarthAuthToken: (opts) => earthAuth.getToken(opts),
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:get-earth-session-token', (_event, opts: unknown) => {
|
||||
const forceRefresh = Boolean(
|
||||
opts && typeof opts === 'object' && (opts as { forceRefresh?: unknown }).forceRefresh,
|
||||
)
|
||||
return earthAuth.getToken({ forceRefresh })
|
||||
})
|
||||
|
||||
ipcMain.on('planet:earth-startup-ready', () => {
|
||||
if (!isHeadlessSmoke) {
|
||||
hotUpdater.markStartupReady()
|
||||
sendPendingHandoffToast()
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on('planet:low-fps-report', (_event, payload: unknown) => {
|
||||
if (isHeadlessSmoke || !payload || typeof payload !== 'object') return
|
||||
const candidate = payload as { avgFps?: unknown; sustainedMs?: unknown }
|
||||
const avgFps = Number(candidate.avgFps)
|
||||
const sustainedMs = Number(candidate.sustainedMs)
|
||||
if (!Number.isFinite(avgFps) || avgFps <= 0 || !Number.isFinite(sustainedMs) || sustainedMs <= 0) {
|
||||
return
|
||||
}
|
||||
void gpuMonitor.handleLowFpsReport({ avgFps, sustainedMs })
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:check-for-updates', async () => {
|
||||
await hotUpdater.checkForUpdates({ manual: true })
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:get-version-info', () => hotUpdater.getVersionInfo())
|
||||
|
||||
ipcMain.on('planet:get-runtime-config', (event) => {
|
||||
const cfg = configStore.get()
|
||||
event.returnValue = {
|
||||
@@ -119,10 +358,14 @@ if (!singleInstanceLock) {
|
||||
wsUrl: cfg.wsUrl,
|
||||
forceShowFps: cfg.forceShowFps,
|
||||
splashTheme: cfg.splashTheme,
|
||||
gpuMode: cfg.gpuMode,
|
||||
gpuTarget: startupGpuDecision.target,
|
||||
gpuHandoff: cfg.gpuHandoff,
|
||||
headlessSmoke: cfg.headlessSmoke,
|
||||
isElectron: true,
|
||||
platform: process.platform,
|
||||
localMediaPipeBaseUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe`,
|
||||
localPoseModelUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe/pose_landmarker_lite.task`,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -168,6 +411,7 @@ if (!singleInstanceLock) {
|
||||
|
||||
ipcMain.handle('planet:set-server-config', (_event, partial: unknown) => {
|
||||
const next = configStore.updateEndpoints((partial || {}) as Partial<ServerEndpoints>)
|
||||
earthAuth.clear()
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.reload()
|
||||
}
|
||||
@@ -178,9 +422,7 @@ if (!singleInstanceLock) {
|
||||
|
||||
ipcMain.handle('planet:set-splash-theme', (_event, rawTheme: unknown) => {
|
||||
const next = configStore.updateSplashTheme(normalizeSplashTheme(rawTheme, configStore.get().splashTheme))
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
|
||||
}
|
||||
refreshApplicationMenu()
|
||||
return next.splashTheme
|
||||
})
|
||||
|
||||
@@ -195,13 +437,59 @@ if (!singleInstanceLock) {
|
||||
iconPath: resolveIconPath(),
|
||||
userDataDir: app.getPath('userData'),
|
||||
configStore,
|
||||
onToggleRecording: () => {
|
||||
void screenRecorder?.toggleRecording({ fromMenu: false })
|
||||
},
|
||||
})
|
||||
|
||||
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
|
||||
mainWindow.on('close', (event) => {
|
||||
if (mainWindow) {
|
||||
screenRecorder?.handleWindowClose(mainWindow, event)
|
||||
}
|
||||
})
|
||||
|
||||
refreshApplicationMenu()
|
||||
if (process.platform !== 'darwin') {
|
||||
mainWindow.setMenuBarVisibility(false)
|
||||
}
|
||||
|
||||
if (!isHeadlessSmoke) {
|
||||
let autoUpdateTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let periodicUpdateTimer: ReturnType<typeof setInterval> | null = null
|
||||
mainWindow.webContents.on('render-process-gone', () => {
|
||||
hotUpdater.handleRendererCrash()
|
||||
})
|
||||
hotUpdater.startStartupWatchdog()
|
||||
mainWindow.webContents.once('did-finish-load', () => {
|
||||
gpuMonitor.start()
|
||||
autoUpdateTimer = setTimeout(() => {
|
||||
autoUpdateTimer = null
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
void hotUpdater.checkForUpdates({ manual: false })
|
||||
}
|
||||
}, 4000)
|
||||
if (!periodicUpdateTimer) {
|
||||
periodicUpdateTimer = setInterval(() => {
|
||||
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.isMinimized()) {
|
||||
void hotUpdater.checkForUpdates({ manual: false })
|
||||
}
|
||||
}, PERIODIC_UPDATE_CHECK_INTERVAL_MS)
|
||||
}
|
||||
})
|
||||
mainWindow.once('closed', () => {
|
||||
gpuMonitor.stop()
|
||||
if (autoUpdateTimer) {
|
||||
clearTimeout(autoUpdateTimer)
|
||||
autoUpdateTimer = null
|
||||
}
|
||||
if (periodicUpdateTimer) {
|
||||
clearInterval(periodicUpdateTimer)
|
||||
periodicUpdateTimer = null
|
||||
}
|
||||
hotUpdater.stopStartupWatchdog()
|
||||
})
|
||||
}
|
||||
|
||||
if (isHeadlessSmoke) {
|
||||
const smokeTimeout = setTimeout(() => {
|
||||
app.exit(1)
|
||||
@@ -267,19 +555,18 @@ if (!singleInstanceLock) {
|
||||
const img = sr?.querySelector('.splash-zju-emblem');
|
||||
const copy = sr?.querySelector('.splash-presenter-copy')?.textContent || '';
|
||||
const finishCheck = () => {
|
||||
window.planetDesktop.replaySplash('constellation');
|
||||
const firstSwitch = host?.dataset.splashTheme || '';
|
||||
window.planetDesktop.replaySplash('horizon');
|
||||
const secondSwitch = host?.dataset.splashTheme || '';
|
||||
const activeTheme = host?.dataset.splashTheme || '';
|
||||
const hasNoThemeSwitcher = !sr?.querySelector('.splash-switcher');
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
resolve({
|
||||
mounted: Boolean(host && sr),
|
||||
hasPresentedBy: copy.includes('PRESENTED BY'),
|
||||
hasPresenterZh: copy.includes('临空智能媒体研究院'),
|
||||
hasPresenterEn: copy.includes('Institute of Intelligent Media'),
|
||||
hasPresenterEn: copy.includes('Intelligent Media Institute'),
|
||||
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
|
||||
emblemWidth: img ? img.naturalWidth : 0,
|
||||
switchedThemes: [firstSwitch, secondSwitch],
|
||||
activeTheme,
|
||||
hasNoThemeSwitcher,
|
||||
});
|
||||
};
|
||||
if (!img || img.complete) {
|
||||
|
||||
+146
-24
@@ -1,11 +1,39 @@
|
||||
import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } from 'electron'
|
||||
|
||||
import type { DesktopConfigStore, SplashTheme } from './config'
|
||||
import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config'
|
||||
import type { GpuRuntimeSummary } from './gpu-monitor'
|
||||
import type { HotUpdateVersionInfo } from './hot-updater'
|
||||
import type { RecordingStatusSnapshot } from './recording-core'
|
||||
import { openServerSettingsDialog, toggleWindowOrientation } from './window'
|
||||
|
||||
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
|
||||
const targetLabel =
|
||||
summary.activeTarget === 'low-power'
|
||||
? '集成核显'
|
||||
: summary.activeTarget === 'software'
|
||||
? 'CPU 软渲染'
|
||||
: summary.activeTarget === 'high-performance' || summary.latestVramSample
|
||||
? '独立显卡'
|
||||
: '硬件 GPU'
|
||||
const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动'
|
||||
const vramTag = summary.latestVramSample
|
||||
? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`
|
||||
: ''
|
||||
return `当前生效: ${targetLabel} (${modeTag}${vramTag})`
|
||||
}
|
||||
|
||||
export function buildApplicationMenu(options: {
|
||||
mainWindow: BrowserWindow
|
||||
configStore: DesktopConfigStore
|
||||
getVersionInfo?: () => HotUpdateVersionInfo
|
||||
onCheckForUpdates?: () => void
|
||||
getGpuStatus?: () => GpuRuntimeSummary
|
||||
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
|
||||
getRecordingState?: () => RecordingStatusSnapshot
|
||||
onToggleRecording?: (fromMenu?: boolean) => void
|
||||
onToggleRecordAudio?: (enabled: boolean) => void
|
||||
onToggleRecordHideCursor?: (enabled: boolean) => void
|
||||
onOpenRecordingsFolder?: () => void
|
||||
}): Menu {
|
||||
const sendAction = (action: string) => {
|
||||
if (!options.mainWindow.isDestroyed()) {
|
||||
@@ -19,6 +47,13 @@ export function buildApplicationMenu(options: {
|
||||
}
|
||||
|
||||
const currentSplashTheme = options.configStore.get().splashTheme
|
||||
const currentGpuMode = options.configStore.get().gpuMode
|
||||
const currentRecordAudio = options.configStore.get().recordAudio
|
||||
const currentRecordHideCursor = options.configStore.get().recordHideCursor
|
||||
const gpuSummary = options.getGpuStatus?.()
|
||||
const recordingSnapshot = options.getRecordingState?.()
|
||||
const recordingState = recordingSnapshot?.state ?? 'idle'
|
||||
const isRecordingOrStopping = recordingState === 'recording' || recordingState === 'stopping'
|
||||
|
||||
const selectSplashTheme = (theme: SplashTheme) => {
|
||||
options.configStore.updateSplashTheme(theme)
|
||||
@@ -72,31 +107,13 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '启动画面方案 / Splash Screen',
|
||||
label: '启动画面 / Splash Screen',
|
||||
submenu: [
|
||||
{
|
||||
label: '方案 1:星核奇点展开 / Singularity Burst',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'singularity',
|
||||
click: () => selectSplashTheme('singularity'),
|
||||
},
|
||||
{
|
||||
label: '方案 2:轨道星座校准 / Orbital Astrolabe',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'constellation',
|
||||
click: () => selectSplashTheme('constellation'),
|
||||
},
|
||||
{
|
||||
label: '方案 3:晨昏日冕破晓 / Eclipse Horizon',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'horizon',
|
||||
click: () => selectSplashTheme('horizon'),
|
||||
},
|
||||
{
|
||||
label: '关闭启动画面 / Off',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'off',
|
||||
click: () => selectSplashTheme('off'),
|
||||
label: '启用启动画面 / Enable Splash Screen',
|
||||
type: 'checkbox',
|
||||
checked: currentSplashTheme !== 'off',
|
||||
click: () => selectSplashTheme(currentSplashTheme === 'off' ? 'singularity' : 'off'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
@@ -106,6 +123,94 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '渲染设备 / GPU Mode',
|
||||
submenu: [
|
||||
...(gpuSummary
|
||||
? [
|
||||
{
|
||||
label: formatGpuSummaryLabel(gpuSummary),
|
||||
enabled: false,
|
||||
},
|
||||
{ type: 'separator' as const },
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'auto',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('auto')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '独立显卡(高性能) / Discrete GPU',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'high-performance',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('high-performance')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '集成核显(不占独显显存) / Integrated GPU',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'low-power',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('low-power')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '纯 CPU 软渲染 / Software GL',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'software',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('software')
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '录屏 / Screen Recording',
|
||||
submenu: [
|
||||
{
|
||||
label: isRecordingOrStopping
|
||||
? '停止录屏 / Stop Recording'
|
||||
: recordingState === 'starting'
|
||||
? '正在启动录屏… / Starting…'
|
||||
: '开始录屏 / Start Recording',
|
||||
accelerator: 'CmdOrCtrl+Shift+F9',
|
||||
enabled: recordingState === 'idle' || recordingState === 'recording',
|
||||
click: () => {
|
||||
options.onToggleRecording?.(true)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '录制声音 / Include Audio',
|
||||
type: 'checkbox',
|
||||
checked: currentRecordAudio,
|
||||
enabled: recordingState === 'idle',
|
||||
click: (item) => {
|
||||
options.onToggleRecordAudio?.(item.checked)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '隐藏光标 / Hide Cursor',
|
||||
type: 'checkbox',
|
||||
checked: currentRecordHideCursor,
|
||||
enabled: recordingState === 'idle',
|
||||
click: (item) => {
|
||||
options.onToggleRecordHideCursor?.(item.checked)
|
||||
},
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '打开录屏目录 / Open Recordings Folder',
|
||||
click: () => {
|
||||
options.onOpenRecordingsFolder?.()
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '打开运维控制台 / Open Admin Console',
|
||||
@@ -116,6 +221,23 @@ export function buildApplicationMenu(options: {
|
||||
click: () => openAdminPath('/docs/manual'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '检查更新 / Check for Updates...',
|
||||
click: () => options.onCheckForUpdates?.(),
|
||||
},
|
||||
...(options.getVersionInfo
|
||||
? [
|
||||
(() => {
|
||||
const info = options.getVersionInfo!()
|
||||
const suffix = info.usingHotfix ? ' (热更 / Hotfix)' : ''
|
||||
return {
|
||||
label: `当前版本: Shell v${info.shellVersion} · Earth v${info.activeBundleVersion}${suffix}`,
|
||||
enabled: false,
|
||||
}
|
||||
})(),
|
||||
]
|
||||
: []),
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit', label: '退出 / Quit' },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -101,3 +101,44 @@ export function computeLandscapeBounds(params: {
|
||||
const targetPos = pos ?? centerOnAnchor(anchorBounds, width, height)
|
||||
return clampBoundsToWorkArea({ x: targetPos.x, y: targetPos.y, width, height }, workArea)
|
||||
}
|
||||
|
||||
export function resolveInitialWindowBounds(params: {
|
||||
saved: {
|
||||
x?: number
|
||||
y?: number
|
||||
width: number
|
||||
height: number
|
||||
isMaximized?: boolean
|
||||
isFullScreen?: boolean
|
||||
}
|
||||
launchFullScreen: boolean
|
||||
headlessSmoke: boolean
|
||||
displayWorkArea: Rect
|
||||
displayBounds: Rect
|
||||
}): {
|
||||
initialBounds: { x?: number; y?: number; width: number; height: number }
|
||||
shouldRestoreNormalBoundsOnUnmaximize: boolean
|
||||
} {
|
||||
const { saved, launchFullScreen, headlessSmoke, displayWorkArea, displayBounds } = params
|
||||
if (!headlessSmoke && (launchFullScreen || saved.isFullScreen)) {
|
||||
return {
|
||||
initialBounds: { ...displayBounds },
|
||||
shouldRestoreNormalBoundsOnUnmaximize: Boolean(saved.isMaximized),
|
||||
}
|
||||
}
|
||||
if (!headlessSmoke && saved.isMaximized) {
|
||||
return {
|
||||
initialBounds: { ...displayWorkArea },
|
||||
shouldRestoreNormalBoundsOnUnmaximize: true,
|
||||
}
|
||||
}
|
||||
return {
|
||||
initialBounds: {
|
||||
x: saved.x,
|
||||
y: saved.y,
|
||||
width: saved.width,
|
||||
height: saved.height,
|
||||
},
|
||||
shouldRestoreNormalBoundsOnUnmaximize: false,
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,9 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade
|
||||
|
||||
export function createEarthProtocolHandler(options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
|
||||
fetchImpl?: typeof fetch
|
||||
}): (request: Request) => Promise<Response> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch
|
||||
@@ -169,31 +171,71 @@ export function createEarthProtocolHandler(options: {
|
||||
|
||||
if (isProxiedBackendPath(parsedUrl.pathname)) {
|
||||
const targetUrl = new URL(`${parsedUrl.pathname}${parsedUrl.search}`, options.getBackendUrl())
|
||||
const forwardHeaders = new Headers(request.headers)
|
||||
forwardHeaders.delete('host')
|
||||
forwardHeaders.delete('content-length')
|
||||
const buildForwardHeaders = async (forceRefresh = false): Promise<Headers> => {
|
||||
const headers = new Headers(request.headers)
|
||||
headers.delete('host')
|
||||
headers.delete('content-length')
|
||||
if (!headers.has('accept-encoding')) {
|
||||
headers.set('accept-encoding', 'gzip, deflate, br')
|
||||
}
|
||||
if (
|
||||
options.getEarthAuthToken &&
|
||||
parsedUrl.pathname !== '/api/v1/auth/earth-session' &&
|
||||
(forceRefresh || !headers.has('x-planet-earth-token'))
|
||||
) {
|
||||
const token = await options.getEarthAuthToken({ forceRefresh })
|
||||
if (token) {
|
||||
headers.set('x-planet-earth-token', token)
|
||||
}
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
const method = request.method.toUpperCase()
|
||||
const hasBody = method !== 'GET' && method !== 'HEAD'
|
||||
try {
|
||||
const init: RequestInit & { duplex?: 'half' } = {
|
||||
method,
|
||||
headers: forwardHeaders,
|
||||
const makeInit = (headers: Headers): RequestInit & { duplex?: 'half' } => {
|
||||
const init: RequestInit & { duplex?: 'half' } = {
|
||||
method,
|
||||
headers,
|
||||
}
|
||||
if (request.signal) {
|
||||
init.signal = request.signal
|
||||
}
|
||||
if (hasBody && request.body) {
|
||||
init.body = request.body
|
||||
init.duplex = 'half'
|
||||
}
|
||||
return init
|
||||
}
|
||||
if (hasBody && request.body) {
|
||||
init.body = request.body
|
||||
init.duplex = 'half'
|
||||
|
||||
let upstream = await fetchImpl(targetUrl.toString(), makeInit(await buildForwardHeaders(false)))
|
||||
if (
|
||||
upstream.status === 401 &&
|
||||
!hasBody &&
|
||||
options.getEarthAuthToken &&
|
||||
parsedUrl.pathname !== '/api/v1/auth/earth-session'
|
||||
) {
|
||||
try {
|
||||
await upstream.body?.cancel()
|
||||
} catch {
|
||||
// Ignore cancel errors on drained/aborted streams.
|
||||
}
|
||||
upstream = await fetchImpl(targetUrl.toString(), makeInit(await buildForwardHeaders(true)))
|
||||
}
|
||||
const upstream = await fetchImpl(targetUrl.toString(), init)
|
||||
const responseHeaders = new Headers(upstream.headers)
|
||||
responseHeaders.delete('content-encoding')
|
||||
responseHeaders.delete('content-length')
|
||||
return new Response(upstream.body, {
|
||||
const isNullBodyStatus = upstream.status === 204 || upstream.status === 205 || upstream.status === 304
|
||||
return new Response(isNullBodyStatus ? null : upstream.body, {
|
||||
status: upstream.status,
|
||||
statusText: upstream.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
if (request.signal?.aborted) {
|
||||
throw error
|
||||
}
|
||||
return Response.json(
|
||||
{
|
||||
detail: 'Backend service unavailable',
|
||||
@@ -209,6 +251,21 @@ export function createEarthProtocolHandler(options: {
|
||||
if (!staticPath) {
|
||||
return new Response('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
const overlayRoot = options.getEarthOverlayRoot?.()
|
||||
if (overlayRoot) {
|
||||
const overlayPath = resolveEarthStaticPath(overlayRoot, parsedUrl.pathname)
|
||||
if (overlayPath) {
|
||||
try {
|
||||
if (fs.statSync(overlayPath).isFile()) {
|
||||
return createStaticFileResponse(overlayPath, request.headers)
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the built-in shell bundle for non-overlaid static assets.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return createStaticFileResponse(staticPath, request.headers)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import { net, protocol, type Session } from 'electron'
|
||||
import { net, protocol, systemPreferences, type Session } from 'electron'
|
||||
|
||||
import { createEarthProtocolHandler } from './protocol-core'
|
||||
|
||||
export const EARTH_ORIGIN = 'planet://earth'
|
||||
export const EARTH_ENTRY_URL = `${EARTH_ORIGIN}/earth/index.html`
|
||||
|
||||
function isEarthUrl(url: string): boolean {
|
||||
return url === EARTH_ORIGIN || url.startsWith(`${EARTH_ORIGIN}/`)
|
||||
}
|
||||
|
||||
export function registerEarthScheme(): void {
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
@@ -25,12 +29,16 @@ export function installEarthSessionHandlers(
|
||||
targetSession: Session,
|
||||
options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
|
||||
},
|
||||
): void {
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: options.earthBundleRoot,
|
||||
getEarthOverlayRoot: options.getEarthOverlayRoot,
|
||||
getBackendUrl: options.getBackendUrl,
|
||||
getEarthAuthToken: options.getEarthAuthToken,
|
||||
fetchImpl: (input, init) => net.fetch(input as string, init),
|
||||
})
|
||||
|
||||
@@ -49,13 +57,35 @@ export function installEarthSessionHandlers(
|
||||
},
|
||||
)
|
||||
|
||||
targetSession.setPermissionRequestHandler((webContents, permission, callback) => {
|
||||
const pageUrl = webContents.getURL()
|
||||
const isEarthOrigin = pageUrl.startsWith(EARTH_ORIGIN)
|
||||
if (isEarthOrigin && (permission === 'media' || permission === 'fullscreen')) {
|
||||
targetSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
|
||||
if (permission === 'fullscreen') {
|
||||
callback(isEarthUrl(webContents.getURL()))
|
||||
return
|
||||
}
|
||||
if (permission === 'media' && details.isMainFrame && isEarthUrl(details.requestingUrl)) {
|
||||
if ('mediaTypes' in details && details.mediaTypes?.includes('audio')) {
|
||||
callback(false)
|
||||
return
|
||||
}
|
||||
if (process.platform === 'darwin') {
|
||||
void systemPreferences.askForMediaAccess('camera').then(
|
||||
(granted) => callback(granted),
|
||||
() => callback(false),
|
||||
)
|
||||
return
|
||||
}
|
||||
callback(true)
|
||||
return
|
||||
}
|
||||
callback(false)
|
||||
})
|
||||
|
||||
targetSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'fullscreen') return isEarthUrl(webContents?.getURL() || '')
|
||||
if (permission !== 'media' || details.mediaType === 'audio' || !details.isMainFrame) return false
|
||||
return (
|
||||
isEarthUrl(details.requestingUrl || requestingOrigin) &&
|
||||
(process.platform !== 'darwin' || systemPreferences.getMediaAccessStatus('camera') === 'granted')
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
export type RecordingState = 'idle' | 'starting' | 'recording' | 'stopping'
|
||||
|
||||
export interface RecordingStatusSnapshot {
|
||||
state: RecordingState
|
||||
elapsedMs: number
|
||||
includeAudio: boolean
|
||||
hideCursor: boolean
|
||||
filePath: string | null
|
||||
}
|
||||
|
||||
export type RecordingCursorShape = 'default' | 'pointer' | 'grab' | 'grabbing' | 'text'
|
||||
|
||||
export interface RecordingCursorPayload {
|
||||
visible: boolean
|
||||
x: number
|
||||
y: number
|
||||
shape: RecordingCursorShape
|
||||
}
|
||||
|
||||
export interface RectBounds {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
const INDICATOR_BASE_WIDTH = 120
|
||||
const INDICATOR_LONG_WIDTH = 136
|
||||
const INDICATOR_HEIGHT = 36
|
||||
|
||||
/**
|
||||
* Format elapsed recording duration as MM:SS (or HH:MM:SS once >= 1 hour).
|
||||
*/
|
||||
export function formatRecordingDuration(elapsedMs: number): string {
|
||||
const safeSeconds = Number.isFinite(elapsedMs) && elapsedMs > 0 ? Math.floor(elapsedMs / 1000) : 0
|
||||
const hours = Math.floor(safeSeconds / 3600)
|
||||
const minutes = Math.floor((safeSeconds % 3600) / 60)
|
||||
const seconds = safeSeconds % 60
|
||||
const pad = (value: number) => String(value).padStart(2, '0')
|
||||
return hours > 0 ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}` : `${pad(minutes)}:${pad(seconds)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a MediaRecorder MIME type to an output video container extension.
|
||||
*/
|
||||
export function resolveRecordingExtension(mimeType?: string): 'mp4' | 'webm' {
|
||||
return typeof mimeType === 'string' && mimeType.toLowerCase().includes('mp4') ? 'mp4' : 'webm'
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a collision-safe output filename for saved screen recordings.
|
||||
*/
|
||||
export function buildRecordingFilename(now: Date, ext: 'mp4' | 'webm', suffixIndex = 0): string {
|
||||
const pad = (value: number) => String(value).padStart(2, '0')
|
||||
const stamp = [
|
||||
now.getFullYear(),
|
||||
pad(now.getMonth() + 1),
|
||||
pad(now.getDate()),
|
||||
'-',
|
||||
pad(now.getHours()),
|
||||
pad(now.getMinutes()),
|
||||
pad(now.getSeconds()),
|
||||
].join('')
|
||||
const suffix = suffixIndex > 0 ? `-${suffixIndex + 1}` : ''
|
||||
return `Planet-Earth-${stamp}${suffix}.${ext}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Return ordered MediaRecorder MIME candidates, preferring H.264 MP4 before WebM fallbacks.
|
||||
*/
|
||||
export function pickSupportedRecordingMimeTypes(includeAudio: boolean): string[] {
|
||||
if (includeAudio) {
|
||||
return [
|
||||
'video/mp4;codecs=avc1.42E01E,mp4a.40.2',
|
||||
'video/mp4;codecs=avc1.4d401f,mp4a.40.2',
|
||||
'video/mp4;codecs=avc1.42E01E',
|
||||
'video/mp4',
|
||||
'video/webm;codecs=vp9,opus',
|
||||
'video/webm;codecs=vp8,opus',
|
||||
'video/webm;codecs=vp9',
|
||||
'video/webm;codecs=vp8',
|
||||
'video/webm',
|
||||
]
|
||||
}
|
||||
return [
|
||||
'video/mp4;codecs=avc1.42E01E',
|
||||
'video/mp4;codecs=avc1.4d401f',
|
||||
'video/mp4',
|
||||
'video/webm;codecs=vp9',
|
||||
'video/webm;codecs=vp8',
|
||||
'video/webm',
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute centered top-overlay indicator bounds anchored safely inside mainWindow content area.
|
||||
*/
|
||||
export function computeIndicatorBounds(options: {
|
||||
contentBounds: RectBounds
|
||||
elapsedMs: number
|
||||
}): RectBounds {
|
||||
const { contentBounds, elapsedMs } = options
|
||||
const desiredWidth = elapsedMs >= 3_600_000 ? INDICATOR_LONG_WIDTH : INDICATOR_BASE_WIDTH
|
||||
const width = Math.max(60, Math.min(desiredWidth, Math.max(60, contentBounds.width - 16)))
|
||||
const height = Math.min(INDICATOR_HEIGHT, Math.max(24, contentBounds.height - 8))
|
||||
const rawX = contentBounds.x + Math.round((contentBounds.width - width) / 2)
|
||||
const topOffset = Math.min(56, Math.max(10, Math.round(contentBounds.height * 0.08)))
|
||||
const rawY = contentBounds.y + topOffset
|
||||
const maxX = contentBounds.x + Math.max(0, contentBounds.width - width)
|
||||
const maxY = contentBounds.y + Math.max(0, contentBounds.height - height)
|
||||
return {
|
||||
x: Math.max(contentBounds.x, Math.min(rawX, maxX)),
|
||||
y: Math.max(contentBounds.y, Math.min(rawY, maxY)),
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render self-contained HTML for the transparent floating recording indicator pill.
|
||||
*/
|
||||
export function buildRecordingIndicatorHtml(): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
overflow: hidden;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
.rec-pill {
|
||||
appearance: none;
|
||||
height: 30px;
|
||||
padding: 0 12px 0 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(201, 225, 247, 0.22);
|
||||
background: rgba(8, 16, 28, 0.8);
|
||||
backdrop-filter: blur(14px) saturate(130%);
|
||||
-webkit-backdrop-filter: blur(14px) saturate(130%);
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.42), inset 0 1px 0 rgba(255, 255, 255, 0.14);
|
||||
color: #eef5ff;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
transition: border-color 0.16s ease, background 0.16s ease, box-shadow 0.16s ease, transform 0.14s ease;
|
||||
}
|
||||
.rec-pill:hover {
|
||||
border-color: rgba(248, 113, 113, 0.56);
|
||||
background: rgba(24, 18, 28, 0.88);
|
||||
box-shadow: 0 6px 20px rgba(239, 68, 68, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
.rec-pill:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
.rec-glyph-wrap {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.rec-glyph {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #ef4444;
|
||||
box-shadow: 0 0 8px rgba(239, 68, 68, 0.72);
|
||||
animation: recPulse 1.4s ease-in-out infinite;
|
||||
transition: width 0.15s ease, height 0.15s ease, border-radius 0.15s ease, background 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
.rec-pill:hover .rec-glyph {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 2px;
|
||||
background: #f87171;
|
||||
box-shadow: 0 0 10px rgba(248, 113, 113, 0.8);
|
||||
animation: none;
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
.rec-time {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
letter-spacing: 0.03em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@keyframes recPulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.32;
|
||||
transform: scale(0.8);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<button id="rec-stop-btn" class="rec-pill" type="button" title="点击停止录屏 (Ctrl+Shift+F9)" aria-label="停止录屏">
|
||||
<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>
|
||||
<script>
|
||||
const btn = document.getElementById('rec-stop-btn');
|
||||
const timerEl = document.getElementById('rec-timer');
|
||||
if (window.planetRecordingIndicator?.onTick) {
|
||||
window.planetRecordingIndicator.onTick((formatted) => {
|
||||
if (typeof formatted === 'string' && timerEl) {
|
||||
timerEl.textContent = formatted;
|
||||
}
|
||||
});
|
||||
}
|
||||
btn?.addEventListener('click', () => {
|
||||
window.planetRecordingIndicator?.requestStop?.();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Render self-contained HTML for the transparent click-through custom cursor overlay window.
|
||||
*/
|
||||
export function buildCursorOverlayHtml(): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
#cursor-root {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
opacity: 0;
|
||||
will-change: transform;
|
||||
pointer-events: none;
|
||||
}
|
||||
.cursor-svg {
|
||||
display: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.55));
|
||||
}
|
||||
#cursor-root[data-shape="default"] .cursor-svg--default,
|
||||
#cursor-root[data-shape="pointer"] .cursor-svg--pointer,
|
||||
#cursor-root[data-shape="grab"] .cursor-svg--grab,
|
||||
#cursor-root[data-shape="grabbing"] .cursor-svg--grabbing,
|
||||
#cursor-root[data-shape="text"] .cursor-svg--text {
|
||||
display: block;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="cursor-root" data-shape="default" aria-hidden="true">
|
||||
<svg class="cursor-svg cursor-svg--default" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M2 1.5L2 19.5L6.8 14.9L10.3 21.8L13.1 20.4L9.7 13.6L16.3 13.6L2 1.5Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--pointer" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M8.5 1.8C9.6 1.8 10.5 2.7 10.5 3.8V10.1C11 9.6 11.7 9.4 12.4 9.7C13.1 9.9 13.6 10.5 13.7 11.1C14.2 10.7 15 10.5 15.7 10.8C16.4 11.1 16.9 11.8 17 12.6C17.5 12.3 18.2 12.3 18.8 12.6C19.5 12.9 20 13.6 20 14.5V16.8C20 19.7 17.8 22 14.9 22H11.5C9.6 22 7.9 21 6.9 19.4L4.7 15.7C4.2 14.9 4.5 13.8 5.3 13.4C6 13 6.9 13.2 7.4 13.9L6.5 15.3V3.8C6.5 2.7 7.4 1.8 8.5 1.8Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.45" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--grab" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M7 11V5.5C7 4.7 7.7 4 8.5 4C9.3 4 10 4.7 10 5.5V10.5M10 10V4.5C10 3.7 10.7 3 11.5 3C12.3 3 13 3.7 13 4.5V10.5M13 10.5V5.5C13 4.7 13.7 4 14.5 4C15.3 4 16 4.7 16 5.5V11.5M16 11.5V7.5C16 6.7 16.7 6 17.5 6C18.3 6 19 6.7 19 7.5V15C19 18.6 16.3 21 12.8 21H10.5C8.5 21 6.7 20 5.7 18.3L4.2 15.7C3.7 14.9 4 13.9 4.8 13.4C5.5 13 6.4 13.2 6.9 13.9L7 14V11Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--grabbing" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6.5 11.5C6.5 9.8 7.8 8.8 9.2 9.2V8.2C9.2 7 10.2 6.2 11.3 6.5C11.9 6.7 12.4 7.1 12.6 7.7C13.2 7 14.3 6.8 15.2 7.3C15.8 7.6 16.2 8.2 16.3 8.9C17.2 8.7 18.2 9.4 18.2 10.4V15C18.2 18.4 15.7 21 12.4 21H10.4C8.4 21 6.7 19.8 5.9 18L4.9 15.6C4.6 14.9 4.9 14 5.7 13.7L6.5 13.4V11.5Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.45" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--text" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6 4H14M6 20H14M10 4V20" stroke="#0f172a" stroke-width="3.2" stroke-linecap="round"/>
|
||||
<path d="M6 4H14M6 20H14M10 4V20" stroke="#ffffff" stroke-width="1.6" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<script>
|
||||
const root = document.getElementById('cursor-root');
|
||||
const HOTSPOTS = {
|
||||
default: [0, 0],
|
||||
pointer: [-8, -2],
|
||||
grab: [-10, -10],
|
||||
grabbing: [-10, -10],
|
||||
text: [-10, -12],
|
||||
};
|
||||
if (window.planetRecordingCursor?.onUpdate) {
|
||||
window.planetRecordingCursor.onUpdate((payload) => {
|
||||
if (!root || !payload) return;
|
||||
if (!payload.visible) {
|
||||
root.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
const shape = HOTSPOTS[payload.shape] ? payload.shape : 'default';
|
||||
const [ox, oy] = HOTSPOTS[shape];
|
||||
root.dataset.shape = shape;
|
||||
root.style.transform = 'translate3d(' + (Math.round(payload.x) + ox) + 'px, ' + (Math.round(payload.y) + oy) + 'px, 0)';
|
||||
root.style.opacity = '1';
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
|
||||
import { buildCursorOverlayHtml, type RecordingCursorPayload } from './recording-core'
|
||||
|
||||
export interface RecordingCursorOverlayController {
|
||||
show: () => void
|
||||
updateCursor: (payload: RecordingCursorPayload) => void
|
||||
hide: () => void
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
const HIDDEN_CURSOR_PAYLOAD: RecordingCursorPayload = {
|
||||
visible: false,
|
||||
x: 0,
|
||||
y: 0,
|
||||
shape: 'default',
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage a stationary, transparent, click-through overlay window that renders a custom
|
||||
* pointer for the user while the OS cursor is hidden in mainFrame screen recordings.
|
||||
*/
|
||||
export function createRecordingCursorOverlayController(options: {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
preloadPath: string
|
||||
}): RecordingCursorOverlayController {
|
||||
let overlayWin: BrowserWindow | null = null
|
||||
let boundMainWin: BrowserWindow | null = null
|
||||
let blurHideTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let visible = false
|
||||
let destroyed = false
|
||||
let readyToShow = false
|
||||
|
||||
const clearBlurHideTimer = () => {
|
||||
if (blurHideTimer) {
|
||||
clearTimeout(blurHideTimer)
|
||||
blurHideTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const pushCursor = (payload: RecordingCursorPayload) => {
|
||||
if (!overlayWin || overlayWin.isDestroyed() || overlayWin.webContents.isDestroyed()) return
|
||||
overlayWin.webContents.send('planet:recording-cursor-update', payload)
|
||||
}
|
||||
|
||||
const syncBoundsAndLevel = () => {
|
||||
const mainWin = options.getMainWindow()
|
||||
if (
|
||||
destroyed ||
|
||||
!visible ||
|
||||
!overlayWin ||
|
||||
overlayWin.isDestroyed() ||
|
||||
!mainWin ||
|
||||
mainWin.isDestroyed()
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (mainWin.isMinimized() || !mainWin.isVisible() || !mainWin.isFocused()) {
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (overlayWin.isVisible()) {
|
||||
overlayWin.hide()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const contentBounds = mainWin.getContentBounds()
|
||||
if (contentBounds.width > 0 && contentBounds.height > 0) {
|
||||
overlayWin.setBounds(contentBounds)
|
||||
}
|
||||
|
||||
overlayWin.setAlwaysOnTop(true, mainWin.isFullScreen() ? 'screen-saver' : 'floating')
|
||||
if (readyToShow && !overlayWin.isVisible()) {
|
||||
overlayWin.showInactive()
|
||||
}
|
||||
}
|
||||
|
||||
const handleMainFocus = () => {
|
||||
clearBlurHideTimer()
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const handleMainBlur = () => {
|
||||
clearBlurHideTimer()
|
||||
blurHideTimer = setTimeout(() => {
|
||||
blurHideTimer = null
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed() || !mainWin.isFocused()) {
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (overlayWin && !overlayWin.isDestroyed() && overlayWin.isVisible()) {
|
||||
overlayWin.hide()
|
||||
}
|
||||
}
|
||||
}, 60)
|
||||
}
|
||||
|
||||
const unbindMainWindowListeners = () => {
|
||||
clearBlurHideTimer()
|
||||
if (!boundMainWin || boundMainWin.isDestroyed()) {
|
||||
boundMainWin = null
|
||||
return
|
||||
}
|
||||
boundMainWin.removeListener('move', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('resize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('maximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('unmaximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('minimize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('restore', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('enter-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('leave-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('show', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('hide', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('focus', handleMainFocus)
|
||||
boundMainWin.removeListener('blur', handleMainBlur)
|
||||
boundMainWin.removeListener('closed', hide)
|
||||
boundMainWin = null
|
||||
}
|
||||
|
||||
const bindMainWindowListeners = (mainWin: BrowserWindow) => {
|
||||
if (boundMainWin === mainWin) return
|
||||
unbindMainWindowListeners()
|
||||
boundMainWin = mainWin
|
||||
mainWin.on('move', syncBoundsAndLevel)
|
||||
mainWin.on('resize', syncBoundsAndLevel)
|
||||
mainWin.on('maximize', syncBoundsAndLevel)
|
||||
mainWin.on('unmaximize', syncBoundsAndLevel)
|
||||
mainWin.on('minimize', syncBoundsAndLevel)
|
||||
mainWin.on('restore', syncBoundsAndLevel)
|
||||
mainWin.on('enter-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('leave-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('show', syncBoundsAndLevel)
|
||||
mainWin.on('hide', syncBoundsAndLevel)
|
||||
mainWin.on('focus', handleMainFocus)
|
||||
mainWin.on('blur', handleMainBlur)
|
||||
mainWin.on('closed', hide)
|
||||
}
|
||||
|
||||
const ensureOverlayWindow = (mainWin: BrowserWindow): BrowserWindow => {
|
||||
if (overlayWin && !overlayWin.isDestroyed()) {
|
||||
return overlayWin
|
||||
}
|
||||
readyToShow = false
|
||||
const contentBounds = mainWin.getContentBounds()
|
||||
overlayWin = new BrowserWindow({
|
||||
x: contentBounds.x,
|
||||
y: contentBounds.y,
|
||||
width: Math.max(1, contentBounds.width),
|
||||
height: Math.max(1, contentBounds.height),
|
||||
transparent: true,
|
||||
backgroundColor: '#00000000',
|
||||
frame: false,
|
||||
thickFrame: false,
|
||||
roundedCorners: false,
|
||||
resizable: false,
|
||||
movable: false,
|
||||
minimizable: false,
|
||||
maximizable: false,
|
||||
closable: false,
|
||||
focusable: false,
|
||||
skipTaskbar: true,
|
||||
hasShadow: false,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: options.preloadPath,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
})
|
||||
overlayWin.setMenuBarVisibility(false)
|
||||
overlayWin.setIgnoreMouseEvents(true)
|
||||
overlayWin.webContents.once('did-finish-load', () => {
|
||||
if (!overlayWin || overlayWin.isDestroyed()) return
|
||||
void overlayWin.webContents.setVisualZoomLevelLimits(1, 1)
|
||||
readyToShow = true
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (visible) {
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
})
|
||||
void overlayWin.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(buildCursorOverlayHtml())}`)
|
||||
return overlayWin
|
||||
}
|
||||
|
||||
const show = () => {
|
||||
if (destroyed) return
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed()) return
|
||||
clearBlurHideTimer()
|
||||
visible = true
|
||||
bindMainWindowListeners(mainWin)
|
||||
ensureOverlayWindow(mainWin)
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const updateCursor = (payload: RecordingCursorPayload) => {
|
||||
if (destroyed || !visible || !readyToShow) return
|
||||
pushCursor(payload)
|
||||
}
|
||||
|
||||
function hide() {
|
||||
clearBlurHideTimer()
|
||||
visible = false
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (overlayWin && !overlayWin.isDestroyed() && overlayWin.isVisible()) {
|
||||
overlayWin.hide()
|
||||
}
|
||||
}
|
||||
|
||||
const destroy = () => {
|
||||
destroyed = true
|
||||
visible = false
|
||||
unbindMainWindowListeners()
|
||||
if (overlayWin && !overlayWin.isDestroyed()) {
|
||||
overlayWin.destroy()
|
||||
}
|
||||
overlayWin = null
|
||||
}
|
||||
|
||||
return {
|
||||
show,
|
||||
updateCursor,
|
||||
hide,
|
||||
destroy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
|
||||
import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core'
|
||||
|
||||
export interface RecordingIndicatorController {
|
||||
show: (elapsedMs?: number) => void
|
||||
updateElapsed: (elapsedMs: number) => void
|
||||
hide: () => void
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
export function createRecordingIndicatorController(options: {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
preloadPath: string
|
||||
}): RecordingIndicatorController {
|
||||
let indicatorWin: BrowserWindow | null = null
|
||||
let boundMainWin: BrowserWindow | null = null
|
||||
let blurHideTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let visible = false
|
||||
let lastElapsedMs = 0
|
||||
let destroyed = false
|
||||
let readyToShow = false
|
||||
|
||||
const clearBlurHideTimer = () => {
|
||||
if (blurHideTimer) {
|
||||
clearTimeout(blurHideTimer)
|
||||
blurHideTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const syncBoundsAndLevel = () => {
|
||||
const mainWin = options.getMainWindow()
|
||||
if (
|
||||
destroyed ||
|
||||
!visible ||
|
||||
!indicatorWin ||
|
||||
indicatorWin.isDestroyed() ||
|
||||
!mainWin ||
|
||||
mainWin.isDestroyed()
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (mainWin.isMinimized() || !mainWin.isVisible() || !mainWin.isFocused()) {
|
||||
if (indicatorWin.isVisible()) {
|
||||
indicatorWin.hide()
|
||||
}
|
||||
return
|
||||
}
|
||||
const contentBounds = mainWin.getContentBounds()
|
||||
const nextBounds = computeIndicatorBounds({ contentBounds, elapsedMs: lastElapsedMs })
|
||||
indicatorWin.setBounds(nextBounds)
|
||||
|
||||
indicatorWin.setAlwaysOnTop(true, mainWin.isFullScreen() ? 'screen-saver' : 'pop-up-menu')
|
||||
if (readyToShow && !indicatorWin.isVisible()) {
|
||||
indicatorWin.showInactive()
|
||||
}
|
||||
}
|
||||
|
||||
const handleMainFocus = () => {
|
||||
clearBlurHideTimer()
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const handleMainBlur = () => {
|
||||
clearBlurHideTimer()
|
||||
blurHideTimer = setTimeout(() => {
|
||||
blurHideTimer = null
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed() || !mainWin.isFocused()) {
|
||||
if (indicatorWin && !indicatorWin.isDestroyed() && indicatorWin.isVisible()) {
|
||||
indicatorWin.hide()
|
||||
}
|
||||
}
|
||||
}, 60)
|
||||
}
|
||||
|
||||
const pushTick = (elapsedMs: number) => {
|
||||
if (!indicatorWin || indicatorWin.isDestroyed() || indicatorWin.webContents.isDestroyed()) return
|
||||
indicatorWin.webContents.send('planet:recording-indicator-tick', formatRecordingDuration(elapsedMs))
|
||||
}
|
||||
|
||||
const unbindMainWindowListeners = () => {
|
||||
clearBlurHideTimer()
|
||||
if (!boundMainWin || boundMainWin.isDestroyed()) {
|
||||
boundMainWin = null
|
||||
return
|
||||
}
|
||||
boundMainWin.removeListener('move', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('resize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('maximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('unmaximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('minimize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('restore', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('enter-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('leave-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('show', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('hide', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('focus', handleMainFocus)
|
||||
boundMainWin.removeListener('blur', handleMainBlur)
|
||||
boundMainWin.removeListener('closed', hide)
|
||||
boundMainWin = null
|
||||
}
|
||||
|
||||
const bindMainWindowListeners = (mainWin: BrowserWindow) => {
|
||||
if (boundMainWin === mainWin) return
|
||||
unbindMainWindowListeners()
|
||||
boundMainWin = mainWin
|
||||
mainWin.on('move', syncBoundsAndLevel)
|
||||
mainWin.on('resize', syncBoundsAndLevel)
|
||||
mainWin.on('maximize', syncBoundsAndLevel)
|
||||
mainWin.on('unmaximize', syncBoundsAndLevel)
|
||||
mainWin.on('minimize', syncBoundsAndLevel)
|
||||
mainWin.on('restore', syncBoundsAndLevel)
|
||||
mainWin.on('enter-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('leave-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('show', syncBoundsAndLevel)
|
||||
mainWin.on('hide', syncBoundsAndLevel)
|
||||
mainWin.on('focus', handleMainFocus)
|
||||
mainWin.on('blur', handleMainBlur)
|
||||
mainWin.on('closed', hide)
|
||||
}
|
||||
|
||||
const ensureIndicatorWindow = (mainWin: BrowserWindow): BrowserWindow => {
|
||||
if (indicatorWin && !indicatorWin.isDestroyed()) {
|
||||
return indicatorWin
|
||||
}
|
||||
readyToShow = false
|
||||
const initialBounds = computeIndicatorBounds({
|
||||
contentBounds: mainWin.getContentBounds(),
|
||||
elapsedMs: lastElapsedMs,
|
||||
})
|
||||
indicatorWin = new BrowserWindow({
|
||||
...initialBounds,
|
||||
transparent: true,
|
||||
backgroundColor: '#00000000',
|
||||
frame: false,
|
||||
thickFrame: false,
|
||||
roundedCorners: false,
|
||||
resizable: false,
|
||||
movable: false,
|
||||
minimizable: false,
|
||||
maximizable: false,
|
||||
closable: false,
|
||||
focusable: false,
|
||||
skipTaskbar: true,
|
||||
hasShadow: false,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: options.preloadPath,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
})
|
||||
indicatorWin.setMenuBarVisibility(false)
|
||||
indicatorWin.webContents.once('did-finish-load', () => {
|
||||
if (!indicatorWin || indicatorWin.isDestroyed()) return
|
||||
void indicatorWin.webContents.setVisualZoomLevelLimits(1, 1)
|
||||
readyToShow = true
|
||||
pushTick(lastElapsedMs)
|
||||
if (visible) {
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
})
|
||||
void indicatorWin.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(buildRecordingIndicatorHtml())}`)
|
||||
return indicatorWin
|
||||
}
|
||||
|
||||
const show = (elapsedMs = 0) => {
|
||||
if (destroyed) return
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed()) return
|
||||
clearBlurHideTimer()
|
||||
visible = true
|
||||
lastElapsedMs = Math.max(0, elapsedMs)
|
||||
bindMainWindowListeners(mainWin)
|
||||
ensureIndicatorWindow(mainWin)
|
||||
pushTick(lastElapsedMs)
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const updateElapsed = (elapsedMs: number) => {
|
||||
lastElapsedMs = Math.max(0, elapsedMs)
|
||||
if (!visible) return
|
||||
pushTick(lastElapsedMs)
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
function hide() {
|
||||
clearBlurHideTimer()
|
||||
visible = false
|
||||
if (indicatorWin && !indicatorWin.isDestroyed() && indicatorWin.isVisible()) {
|
||||
indicatorWin.hide()
|
||||
}
|
||||
}
|
||||
|
||||
const destroy = () => {
|
||||
destroyed = true
|
||||
visible = false
|
||||
unbindMainWindowListeners()
|
||||
if (indicatorWin && !indicatorWin.isDestroyed()) {
|
||||
indicatorWin.destroy()
|
||||
}
|
||||
indicatorWin = null
|
||||
}
|
||||
|
||||
return {
|
||||
show,
|
||||
updateElapsed,
|
||||
hide,
|
||||
destroy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import {
|
||||
app,
|
||||
ipcMain,
|
||||
shell,
|
||||
type BrowserWindow,
|
||||
type Event as ElectronEvent,
|
||||
type Session,
|
||||
} from 'electron'
|
||||
|
||||
import type { DesktopConfigStore } from './config'
|
||||
import {
|
||||
buildRecordingFilename,
|
||||
resolveRecordingExtension,
|
||||
type RecordingCursorShape,
|
||||
type RecordingState,
|
||||
type RecordingStatusSnapshot,
|
||||
} from './recording-core'
|
||||
import { createRecordingCursorOverlayController } from './recording-cursor-overlay'
|
||||
import { createRecordingIndicatorController } from './recording-indicator'
|
||||
|
||||
export interface RecordingStatusToastOptions {
|
||||
message: string
|
||||
type?: 'info' | 'success' | 'error'
|
||||
fullText?: boolean
|
||||
durationMs?: number
|
||||
actionLabel?: string
|
||||
action?: 'open-recordings-folder'
|
||||
}
|
||||
|
||||
const VALID_CURSOR_SHAPES = new Set<RecordingCursorShape>(['default', 'pointer', 'grab', 'grabbing', 'text'])
|
||||
|
||||
export interface ScreenRecorderController {
|
||||
getState: () => RecordingStatusSnapshot
|
||||
isActive: () => boolean
|
||||
startRecording: (options?: { fromMenu?: boolean }) => Promise<void>
|
||||
stopRecording: (options?: { timeoutMs?: number }) => Promise<void>
|
||||
toggleRecording: (options?: { fromMenu?: boolean }) => Promise<RecordingStatusSnapshot>
|
||||
openRecordingsFolder: () => Promise<void>
|
||||
handleWindowClose: (win: BrowserWindow, event: ElectronEvent) => void
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
export function createScreenRecorderController(options: {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
configStore: DesktopConfigStore
|
||||
session: Session
|
||||
indicatorPreloadPath: string
|
||||
cursorOverlayPreloadPath: string
|
||||
dismissMenuBar: (win: BrowserWindow | null) => void
|
||||
onStateChanged: () => void
|
||||
}): ScreenRecorderController {
|
||||
let state: RecordingState = 'idle'
|
||||
let includeAudio = options.configStore.get().recordAudio
|
||||
let hideCursor = options.configStore.get().recordHideCursor
|
||||
let activeFilePath: string | null = null
|
||||
let activeFileName: string | null = null
|
||||
let lastSavedFilePath: string | null = null
|
||||
let writeStream: fs.WriteStream | null = null
|
||||
let writeChain: Promise<void> = Promise.resolve()
|
||||
let bytesWritten = 0
|
||||
let startedAtMs = 0
|
||||
let elapsedTimer: ReturnType<typeof setInterval> | null = null
|
||||
let pendingCaptureExpiresAt = 0
|
||||
let pendingCaptureIncludeAudio = false
|
||||
let finishPromise: Promise<void> | null = null
|
||||
let resolveFinish: (() => void) | null = null
|
||||
let lastToggleAt = 0
|
||||
let forceAllowWindowClose = false
|
||||
let destroyed = false
|
||||
|
||||
const cursorOverlay = createRecordingCursorOverlayController({
|
||||
getMainWindow: options.getMainWindow,
|
||||
preloadPath: options.cursorOverlayPreloadPath,
|
||||
})
|
||||
|
||||
const indicator = createRecordingIndicatorController({
|
||||
getMainWindow: options.getMainWindow,
|
||||
preloadPath: options.indicatorPreloadPath,
|
||||
})
|
||||
|
||||
const notifyStatus = (
|
||||
messageOrOptions: string | RecordingStatusToastOptions,
|
||||
type: 'info' | 'success' | 'error' = 'info',
|
||||
) => {
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return
|
||||
const payload: RecordingStatusToastOptions =
|
||||
typeof messageOrOptions === 'string'
|
||||
? { message: messageOrOptions, type }
|
||||
: { type: 'info', ...messageOrOptions }
|
||||
win.webContents.send('planet:update-status', payload)
|
||||
}
|
||||
|
||||
const resolveRecordingsDir = (): string => {
|
||||
try {
|
||||
return path.join(app.getPath('videos'), 'Planet Earth')
|
||||
} catch {
|
||||
return path.join(app.getPath('userData'), 'recordings')
|
||||
}
|
||||
}
|
||||
|
||||
const allocateOutputFile = (mimeType?: string): { filePath: string; fileName: string } => {
|
||||
const dir = resolveRecordingsDir()
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
const ext = resolveRecordingExtension(mimeType)
|
||||
const now = new Date()
|
||||
for (let suffix = 0; suffix < 100; suffix += 1) {
|
||||
const fileName = buildRecordingFilename(now, ext, suffix)
|
||||
const filePath = path.join(dir, fileName)
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return { filePath, fileName }
|
||||
}
|
||||
}
|
||||
const fallbackName = buildRecordingFilename(now, ext, Math.floor(Math.random() * 10000))
|
||||
return { filePath: path.join(dir, fallbackName), fileName: fallbackName }
|
||||
}
|
||||
|
||||
const clearElapsedTimer = () => {
|
||||
if (elapsedTimer) {
|
||||
clearInterval(elapsedTimer)
|
||||
elapsedTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const resolvePendingFinish = () => {
|
||||
const resolver = resolveFinish
|
||||
resolveFinish = null
|
||||
finishPromise = null
|
||||
resolver?.()
|
||||
}
|
||||
|
||||
const closeWriteStream = async (): Promise<{ savedPath: string | null; savedName: string | null; hadData: boolean }> => {
|
||||
const targetStream = writeStream
|
||||
const targetPath = activeFilePath
|
||||
const targetName = activeFileName
|
||||
const wroteBytes = bytesWritten
|
||||
writeStream = null
|
||||
activeFilePath = null
|
||||
activeFileName = null
|
||||
bytesWritten = 0
|
||||
|
||||
await writeChain.catch(() => {})
|
||||
if (targetStream) {
|
||||
await new Promise<void>((resolve) => {
|
||||
if (targetStream.closed || targetStream.writableEnded) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
targetStream.once('finish', resolve)
|
||||
targetStream.once('error', () => resolve())
|
||||
targetStream.end()
|
||||
})
|
||||
}
|
||||
|
||||
if (targetPath && wroteBytes === 0) {
|
||||
try {
|
||||
if (fs.existsSync(targetPath)) {
|
||||
fs.unlinkSync(targetPath)
|
||||
}
|
||||
} catch {
|
||||
// Ignore empty file cleanup error.
|
||||
}
|
||||
return { savedPath: null, savedName: null, hadData: false }
|
||||
}
|
||||
|
||||
return { savedPath: targetPath, savedName: targetName, hadData: wroteBytes > 0 }
|
||||
}
|
||||
|
||||
const resetToIdle = () => {
|
||||
clearElapsedTimer()
|
||||
pendingCaptureExpiresAt = 0
|
||||
startedAtMs = 0
|
||||
cursorOverlay.hide()
|
||||
indicator.hide()
|
||||
state = 'idle'
|
||||
options.onStateChanged()
|
||||
resolvePendingFinish()
|
||||
}
|
||||
|
||||
const getState = (): RecordingStatusSnapshot => ({
|
||||
state,
|
||||
elapsedMs: startedAtMs > 0 && (state === 'recording' || state === 'stopping') ? Date.now() - startedAtMs : 0,
|
||||
includeAudio,
|
||||
hideCursor,
|
||||
filePath: activeFilePath ?? lastSavedFilePath,
|
||||
})
|
||||
|
||||
const isActive = () => state !== 'idle'
|
||||
|
||||
// Capture Planet Earth's mainFrame directly so external floating overlays never appear in recordings.
|
||||
options.session.setDisplayMediaRequestHandler((_request, callback) => {
|
||||
if (destroyed || Date.now() > pendingCaptureExpiresAt) {
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) {
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
const mainFrame = win.webContents.mainFrame
|
||||
if (!mainFrame) {
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
callback(
|
||||
pendingCaptureIncludeAudio
|
||||
? { video: mainFrame, audio: mainFrame, enableLocalEcho: true }
|
||||
: { video: mainFrame },
|
||||
)
|
||||
})
|
||||
|
||||
const onOpenFile = (
|
||||
_event: Electron.IpcMainInvokeEvent,
|
||||
payload: { mimeType?: string; includeAudio?: boolean; hideCursor?: boolean } = {},
|
||||
) => {
|
||||
if (destroyed || state === 'idle' || state === 'stopping') {
|
||||
throw new Error('Recording is not active')
|
||||
}
|
||||
pendingCaptureExpiresAt = 0
|
||||
includeAudio = Boolean(payload?.includeAudio)
|
||||
hideCursor = Boolean(payload?.hideCursor)
|
||||
const { filePath, fileName } = allocateOutputFile(payload?.mimeType)
|
||||
activeFilePath = filePath
|
||||
activeFileName = fileName
|
||||
bytesWritten = 0
|
||||
writeChain = Promise.resolve()
|
||||
writeStream = fs.createWriteStream(filePath)
|
||||
writeStream.on('error', (err) => {
|
||||
notifyStatus(`录屏写入失败:${err.message}`, 'error')
|
||||
})
|
||||
|
||||
startedAtMs = Date.now()
|
||||
state = 'recording'
|
||||
if (hideCursor) {
|
||||
cursorOverlay.show()
|
||||
} else {
|
||||
cursorOverlay.hide()
|
||||
}
|
||||
// Show stop indicator after cursor overlay so the clickable pill stays above the cursor layer.
|
||||
indicator.show(0)
|
||||
clearElapsedTimer()
|
||||
elapsedTimer = setInterval(() => {
|
||||
if (state === 'recording' || state === 'stopping') {
|
||||
indicator.updateElapsed(Date.now() - startedAtMs)
|
||||
}
|
||||
}, 250)
|
||||
options.onStateChanged()
|
||||
return { filePath, fileName }
|
||||
}
|
||||
|
||||
const onChunk = (_event: Electron.IpcMainEvent, rawChunk: unknown) => {
|
||||
if (!writeStream || !(rawChunk instanceof Uint8Array || Buffer.isBuffer(rawChunk))) return
|
||||
const buffer = Buffer.from(rawChunk)
|
||||
if (buffer.byteLength === 0) return
|
||||
bytesWritten += buffer.byteLength
|
||||
const targetStream = writeStream
|
||||
writeChain = writeChain.then(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (!targetStream || targetStream.destroyed) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
const ok = targetStream.write(buffer, () => resolve())
|
||||
if (!ok) {
|
||||
targetStream.once('drain', resolve)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const onCursorMove = (_event: Electron.IpcMainEvent, rawPayload: unknown) => {
|
||||
if (destroyed || !hideCursor || (state !== 'recording' && state !== 'stopping')) return
|
||||
if (!rawPayload || typeof rawPayload !== 'object') return
|
||||
const candidate = rawPayload as { visible?: unknown; x?: unknown; y?: unknown; shape?: unknown }
|
||||
const x = Number(candidate.x)
|
||||
const y = Number(candidate.y)
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) return
|
||||
const shape: RecordingCursorShape =
|
||||
typeof candidate.shape === 'string' && VALID_CURSOR_SHAPES.has(candidate.shape as RecordingCursorShape)
|
||||
? (candidate.shape as RecordingCursorShape)
|
||||
: 'default'
|
||||
cursorOverlay.updateCursor({
|
||||
visible: Boolean(candidate.visible),
|
||||
x,
|
||||
y,
|
||||
shape,
|
||||
})
|
||||
}
|
||||
|
||||
const onFinish = async () => {
|
||||
clearElapsedTimer()
|
||||
const result = await closeWriteStream()
|
||||
if (result.savedPath && result.savedName && result.hadData) {
|
||||
lastSavedFilePath = result.savedPath
|
||||
notifyStatus({
|
||||
message: `已保存录屏:${result.savedPath}`,
|
||||
type: 'success',
|
||||
fullText: true,
|
||||
durationMs: 6000,
|
||||
actionLabel: '打开目录',
|
||||
action: 'open-recordings-folder',
|
||||
})
|
||||
} else if (state !== 'idle') {
|
||||
notifyStatus('录屏已停止(未采集到有效画面帧)', 'info')
|
||||
}
|
||||
resetToIdle()
|
||||
return result
|
||||
}
|
||||
|
||||
const onAbort = async (_event: Electron.IpcMainInvokeEvent, payload?: { error?: string }) => {
|
||||
await closeWriteStream()
|
||||
if (payload?.error) {
|
||||
notifyStatus(`启动录屏失败:${payload.error}`, 'error')
|
||||
}
|
||||
resetToIdle()
|
||||
}
|
||||
|
||||
const onAudioFallback = () => {
|
||||
includeAudio = false
|
||||
notifyStatus('当前设备不支持内录音频,已切换为静音录屏', 'info')
|
||||
}
|
||||
|
||||
const onIndicatorStop = () => {
|
||||
void stopRecording()
|
||||
}
|
||||
|
||||
const onIpcToggle = async () => {
|
||||
return toggleRecording({ fromMenu: false })
|
||||
}
|
||||
|
||||
const onIpcOpenFolder = async () => {
|
||||
await openRecordingsFolder()
|
||||
}
|
||||
|
||||
ipcMain.handle('planet:recording-open-file', onOpenFile)
|
||||
ipcMain.on('planet:recording-chunk', onChunk)
|
||||
ipcMain.on('planet:recording-cursor-move', onCursorMove)
|
||||
ipcMain.handle('planet:recording-finish', onFinish)
|
||||
ipcMain.handle('planet:recording-abort', onAbort)
|
||||
ipcMain.on('planet:recording-audio-fallback', onAudioFallback)
|
||||
ipcMain.on('planet:recording-indicator-stop', onIndicatorStop)
|
||||
ipcMain.handle('planet:recording-toggle', onIpcToggle)
|
||||
ipcMain.handle('planet:recording-open-folder', onIpcOpenFolder)
|
||||
|
||||
const startRecording = async (startOpts?: { fromMenu?: boolean }): Promise<void> => {
|
||||
if (destroyed || state !== 'idle') return
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return
|
||||
|
||||
state = 'starting'
|
||||
includeAudio = options.configStore.get().recordAudio
|
||||
hideCursor = options.configStore.get().recordHideCursor
|
||||
options.onStateChanged()
|
||||
|
||||
if (startOpts?.fromMenu) {
|
||||
options.dismissMenuBar(win)
|
||||
await new Promise((resolve) => setTimeout(resolve, 140))
|
||||
}
|
||||
if (destroyed || win.isDestroyed() || win.webContents.isDestroyed() || state !== 'starting') {
|
||||
resetToIdle()
|
||||
return
|
||||
}
|
||||
|
||||
pendingCaptureIncludeAudio = includeAudio
|
||||
pendingCaptureExpiresAt = Date.now() + 8000
|
||||
win.webContents.send('planet:recording-start', { includeAudio, hideCursor })
|
||||
}
|
||||
|
||||
const stopRecording = async (stopOpts?: { timeoutMs?: number }): Promise<void> => {
|
||||
if (destroyed || state === 'idle') return
|
||||
if (finishPromise) return finishPromise
|
||||
|
||||
const win = options.getMainWindow()
|
||||
state = 'stopping'
|
||||
options.onStateChanged()
|
||||
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) {
|
||||
await onFinish()
|
||||
return
|
||||
}
|
||||
|
||||
finishPromise = new Promise<void>((resolve) => {
|
||||
resolveFinish = resolve
|
||||
})
|
||||
const timeoutMs = stopOpts?.timeoutMs ?? 4000
|
||||
const timeoutHandle = setTimeout(() => {
|
||||
void onFinish()
|
||||
}, timeoutMs)
|
||||
|
||||
win.webContents.send('planet:recording-stop')
|
||||
await finishPromise
|
||||
clearTimeout(timeoutHandle)
|
||||
}
|
||||
|
||||
const toggleRecording = async (toggleOpts?: { fromMenu?: boolean }): Promise<RecordingStatusSnapshot> => {
|
||||
const now = Date.now()
|
||||
if (now - lastToggleAt < 250) {
|
||||
return getState()
|
||||
}
|
||||
lastToggleAt = now
|
||||
if (state === 'idle') {
|
||||
await startRecording(toggleOpts)
|
||||
} else if (state === 'recording') {
|
||||
await stopRecording()
|
||||
}
|
||||
return getState()
|
||||
}
|
||||
|
||||
const openRecordingsFolder = async (): Promise<void> => {
|
||||
const dir = resolveRecordingsDir()
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
if (lastSavedFilePath && fs.existsSync(lastSavedFilePath)) {
|
||||
shell.showItemInFolder(lastSavedFilePath)
|
||||
return
|
||||
}
|
||||
await shell.openPath(dir)
|
||||
}
|
||||
|
||||
const handleWindowClose = (win: BrowserWindow, event: ElectronEvent): void => {
|
||||
if (forceAllowWindowClose || state === 'idle') return
|
||||
event.preventDefault()
|
||||
void stopRecording({ timeoutMs: 3000 }).finally(() => {
|
||||
forceAllowWindowClose = true
|
||||
if (!win.isDestroyed()) {
|
||||
win.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const destroy = () => {
|
||||
if (destroyed) return
|
||||
destroyed = true
|
||||
clearElapsedTimer()
|
||||
pendingCaptureExpiresAt = 0
|
||||
void closeWriteStream()
|
||||
cursorOverlay.destroy()
|
||||
indicator.destroy()
|
||||
ipcMain.removeHandler('planet:recording-open-file')
|
||||
ipcMain.removeListener('planet:recording-chunk', onChunk)
|
||||
ipcMain.removeListener('planet:recording-cursor-move', onCursorMove)
|
||||
ipcMain.removeHandler('planet:recording-finish')
|
||||
ipcMain.removeHandler('planet:recording-abort')
|
||||
ipcMain.removeListener('planet:recording-audio-fallback', onAudioFallback)
|
||||
ipcMain.removeListener('planet:recording-indicator-stop', onIndicatorStop)
|
||||
ipcMain.removeHandler('planet:recording-toggle')
|
||||
ipcMain.removeHandler('planet:recording-open-folder')
|
||||
resolvePendingFinish()
|
||||
}
|
||||
|
||||
return {
|
||||
getState,
|
||||
isActive,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
toggleRecording,
|
||||
openRecordingsFolder,
|
||||
handleWindowClose,
|
||||
destroy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
export interface TarEntryInput {
|
||||
path: string
|
||||
data: Uint8Array
|
||||
}
|
||||
|
||||
export interface ExtractTarGzOptions {
|
||||
maxFiles?: number
|
||||
maxTotalBytes?: number
|
||||
}
|
||||
|
||||
export interface ExtractTarGzResult {
|
||||
files: string[]
|
||||
totalBytes: number
|
||||
}
|
||||
|
||||
const TAR_BLOCK_SIZE = 512
|
||||
const DEFAULT_MAX_FILES = 2000
|
||||
const DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024
|
||||
|
||||
export function normalizeArchiveEntryPath(rawPath: string): string {
|
||||
if (!rawPath || rawPath.includes('\0') || rawPath.includes('\\')) {
|
||||
throw new Error(`Invalid archive entry path: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
let stripped = rawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
|
||||
if (!stripped || stripped.startsWith('/')) {
|
||||
throw new Error(`Unsafe archive entry path: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
const segments = stripped.split('/')
|
||||
if (segments.some((seg) => !seg || seg === '.' || seg === '..')) {
|
||||
throw new Error(`Path traversal not allowed in archive entry: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
stripped = segments.join('/')
|
||||
if (/^[A-Za-z]:/.test(stripped)) {
|
||||
throw new Error(`Drive-prefixed archive entry path not allowed: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
return stripped
|
||||
}
|
||||
|
||||
function splitUstarPath(entryPath: string): { name: string; prefix: string } {
|
||||
const bytesLen = Buffer.byteLength(entryPath, 'utf8')
|
||||
if (bytesLen <= 100) {
|
||||
return { name: entryPath, prefix: '' }
|
||||
}
|
||||
if (bytesLen > 256) {
|
||||
throw new Error(`Archive entry path exceeds POSIX USTAR 256-byte limit: ${entryPath}`)
|
||||
}
|
||||
for (let idx = entryPath.indexOf('/', Math.max(0, entryPath.length - 101)); idx !== -1; idx = entryPath.indexOf('/', idx + 1)) {
|
||||
const prefix = entryPath.slice(0, idx)
|
||||
const name = entryPath.slice(idx + 1)
|
||||
if (name && Buffer.byteLength(name, 'utf8') <= 100 && Buffer.byteLength(prefix, 'utf8') <= 155) {
|
||||
return { name, prefix }
|
||||
}
|
||||
}
|
||||
throw new Error(`Cannot split archive entry path into USTAR prefix/name: ${entryPath}`)
|
||||
}
|
||||
|
||||
function writeOctalField(buf: Buffer, offset: number, length: number, value: number): void {
|
||||
const digits = length - 1
|
||||
const octal = Math.max(0, Math.floor(value)).toString(8)
|
||||
if (octal.length > digits) {
|
||||
throw new Error(`Tar numeric value overflows ${digits}-digit octal field: ${value}`)
|
||||
}
|
||||
buf.write(`${octal.padStart(digits, '0')}\0`, offset, length, 'ascii')
|
||||
}
|
||||
|
||||
export function createTarGz(entries: TarEntryInput[]): Buffer {
|
||||
const normalizedEntries = [...entries]
|
||||
.map((entry) => ({
|
||||
path: normalizeArchiveEntryPath(entry.path),
|
||||
data: entry.data instanceof Buffer ? entry.data : Buffer.from(entry.data),
|
||||
}))
|
||||
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
|
||||
|
||||
const chunks: Buffer[] = []
|
||||
for (const entry of normalizedEntries) {
|
||||
const { name, prefix } = splitUstarPath(entry.path)
|
||||
const header = Buffer.alloc(TAR_BLOCK_SIZE, 0)
|
||||
header.write(name, 0, 100, 'utf8')
|
||||
writeOctalField(header, 100, 8, 0o644)
|
||||
writeOctalField(header, 108, 8, 0)
|
||||
writeOctalField(header, 116, 8, 0)
|
||||
writeOctalField(header, 124, 12, entry.data.byteLength)
|
||||
writeOctalField(header, 136, 12, 0)
|
||||
header.fill(0x20, 148, 156)
|
||||
header.write('0', 156, 1, 'ascii')
|
||||
header.write('ustar\0', 257, 6, 'ascii')
|
||||
header.write('00', 263, 2, 'ascii')
|
||||
if (prefix) {
|
||||
header.write(prefix, 345, 155, 'utf8')
|
||||
}
|
||||
|
||||
let checksum = 0
|
||||
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
|
||||
checksum += header[i]
|
||||
}
|
||||
const chksumStr = `${checksum.toString(8).padStart(6, '0')}\0 `
|
||||
header.write(chksumStr, 148, 8, 'ascii')
|
||||
|
||||
chunks.push(header)
|
||||
if (entry.data.byteLength > 0) {
|
||||
chunks.push(entry.data)
|
||||
const remainder = entry.data.byteLength % TAR_BLOCK_SIZE
|
||||
if (remainder !== 0) {
|
||||
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE - remainder, 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE * 2, 0))
|
||||
const tarBuffer = Buffer.concat(chunks)
|
||||
return zlib.gzipSync(tarBuffer, { level: 9 })
|
||||
}
|
||||
|
||||
function readCString(buf: Buffer, start: number, length: number): string {
|
||||
const slice = buf.subarray(start, start + length)
|
||||
const nulIdx = slice.indexOf(0)
|
||||
return slice.subarray(0, nulIdx === -1 ? length : nulIdx).toString('utf8')
|
||||
}
|
||||
|
||||
function parseOctalField(buf: Buffer, start: number, length: number): number {
|
||||
const raw = readCString(buf, start, length).trim()
|
||||
if (!raw) return 0
|
||||
if (!/^[0-7]+$/.test(raw)) {
|
||||
throw new Error(`Invalid tar octal field: ${JSON.stringify(raw)}`)
|
||||
}
|
||||
return Number.parseInt(raw, 8)
|
||||
}
|
||||
|
||||
function isZeroBlock(block: Buffer): boolean {
|
||||
for (let i = 0; i < block.length; i += 1) {
|
||||
if (block[i] !== 0) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function verifyHeaderChecksum(header: Buffer): void {
|
||||
const stored = parseOctalField(header, 148, 8)
|
||||
let unsignedSum = 0
|
||||
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
|
||||
unsignedSum += i >= 148 && i < 156 ? 0x20 : header[i]
|
||||
}
|
||||
if (stored !== unsignedSum) {
|
||||
throw new Error(`Invalid tar header checksum (expected ${unsignedSum}, got ${stored})`)
|
||||
}
|
||||
}
|
||||
|
||||
export function extractTarGzSafely(
|
||||
archiveBuffer: Buffer,
|
||||
destDir: string,
|
||||
options: ExtractTarGzOptions = {},
|
||||
): ExtractTarGzResult {
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES
|
||||
const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES
|
||||
const tarBuffer = zlib.gunzipSync(archiveBuffer, {
|
||||
maxOutputLength: maxTotalBytes + 2 * 1024 * 1024,
|
||||
})
|
||||
if (tarBuffer.byteLength % TAR_BLOCK_SIZE !== 0) {
|
||||
throw new Error('Corrupt tar archive: unaligned block length')
|
||||
}
|
||||
|
||||
const resolvedDest = path.resolve(destDir)
|
||||
fs.mkdirSync(resolvedDest, { recursive: true })
|
||||
|
||||
const extractedFiles: string[] = []
|
||||
let totalBytes = 0
|
||||
let offset = 0
|
||||
|
||||
while (offset + TAR_BLOCK_SIZE <= tarBuffer.byteLength) {
|
||||
const header = tarBuffer.subarray(offset, offset + TAR_BLOCK_SIZE)
|
||||
offset += TAR_BLOCK_SIZE
|
||||
if (isZeroBlock(header)) {
|
||||
break
|
||||
}
|
||||
|
||||
verifyHeaderChecksum(header)
|
||||
const rawName = readCString(header, 0, 100)
|
||||
const rawPrefix = readCString(header, 345, 155)
|
||||
const fullRawPath = rawPrefix ? `${rawPrefix}/${rawName}` : rawName
|
||||
const size = parseOctalField(header, 124, 12)
|
||||
const typeFlagByte = header[156]
|
||||
const typeFlag = typeFlagByte === 0 ? '0' : String.fromCharCode(typeFlagByte)
|
||||
|
||||
if (offset + size > tarBuffer.byteLength) {
|
||||
throw new Error(`Truncated tar entry data for ${fullRawPath}`)
|
||||
}
|
||||
const data = tarBuffer.subarray(offset, offset + size)
|
||||
const paddedSize = Math.ceil(size / TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE
|
||||
offset += paddedSize
|
||||
|
||||
if (typeFlag === '5') {
|
||||
const normalizedDir = fullRawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
|
||||
if (normalizedDir && normalizedDir !== '.') {
|
||||
const safeDir = normalizeArchiveEntryPath(normalizedDir)
|
||||
const targetDir = path.resolve(resolvedDest, safeDir)
|
||||
if (targetDir !== resolvedDest && !targetDir.startsWith(`${resolvedDest}${path.sep}`)) {
|
||||
throw new Error(`Directory escapes extraction root: ${safeDir}`)
|
||||
}
|
||||
fs.mkdirSync(targetDir, { recursive: true })
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeFlag !== '0') {
|
||||
throw new Error(`Unsupported or unsafe tar entry type ${JSON.stringify(typeFlag)} for ${fullRawPath}`)
|
||||
}
|
||||
|
||||
const safeRelPath = normalizeArchiveEntryPath(fullRawPath)
|
||||
if (extractedFiles.length + 1 > maxFiles) {
|
||||
throw new Error(`Archive exceeds maximum file count limit (${maxFiles})`)
|
||||
}
|
||||
totalBytes += size
|
||||
if (totalBytes > maxTotalBytes) {
|
||||
throw new Error(`Archive exceeds maximum uncompressed byte limit (${maxTotalBytes})`)
|
||||
}
|
||||
|
||||
const targetPath = path.resolve(resolvedDest, safeRelPath)
|
||||
if (!targetPath.startsWith(`${resolvedDest}${path.sep}`)) {
|
||||
throw new Error(`File escapes extraction root: ${safeRelPath}`)
|
||||
}
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true })
|
||||
fs.writeFileSync(targetPath, data)
|
||||
extractedFiles.push(safeRelPath)
|
||||
}
|
||||
|
||||
return {
|
||||
files: extractedFiles,
|
||||
totalBytes,
|
||||
}
|
||||
}
|
||||
+90
-19
@@ -8,6 +8,7 @@ import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig }
|
||||
import { resolveExternalTargetUrl } from './external-links'
|
||||
import { createWindowShowGate } from './show-gate'
|
||||
import {
|
||||
clampBoundsToWorkArea,
|
||||
computeLandscapeBounds,
|
||||
computePortraitBounds,
|
||||
DEFAULT_LANDSCAPE_HEIGHT,
|
||||
@@ -15,12 +16,20 @@ import {
|
||||
detectWindowOrientation,
|
||||
MIN_WINDOW_HEIGHT,
|
||||
MIN_WINDOW_WIDTH,
|
||||
resolveInitialWindowBounds,
|
||||
type Rect,
|
||||
type WindowOrientation,
|
||||
} from './orientation'
|
||||
import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol'
|
||||
|
||||
const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>()
|
||||
const windowStateFlushers = new WeakMap<BrowserWindow, () => void>()
|
||||
const cancelInitialUnmaximizeRestore = new WeakMap<BrowserWindow, () => void>()
|
||||
|
||||
export function flushWindowState(win: BrowserWindow | null): void {
|
||||
if (!win || win.isDestroyed()) return
|
||||
windowStateFlushers.get(win)?.()
|
||||
}
|
||||
|
||||
interface OrientationWindowState {
|
||||
lastLandscapeBounds: Rect | null
|
||||
@@ -68,6 +77,7 @@ export function toggleWindowOrientation(win: BrowserWindow): WindowOrientation {
|
||||
win.setFullScreen(false)
|
||||
}
|
||||
if (wasMaximized) {
|
||||
cancelInitialUnmaximizeRestore.get(win)?.()
|
||||
win.unmaximize()
|
||||
}
|
||||
const portraitBounds = computePortraitBounds({
|
||||
@@ -170,18 +180,30 @@ export function createMainWindow(options: {
|
||||
iconPath: string
|
||||
userDataDir: string
|
||||
configStore: DesktopConfigStore
|
||||
onToggleRecording?: () => void
|
||||
}): BrowserWindow {
|
||||
nativeTheme.themeSource = 'dark'
|
||||
|
||||
const statePath = path.join(options.userDataDir, 'window-state.json')
|
||||
const runtimeConfig: DesktopRuntimeConfig = options.configStore.get()
|
||||
const saved = loadWindowState(statePath, runtimeConfig.headlessSmoke)
|
||||
const targetDisplay =
|
||||
saved.x !== undefined && saved.y !== undefined
|
||||
? screen.getDisplayMatching({ x: saved.x, y: saved.y, width: saved.width, height: saved.height })
|
||||
: screen.getPrimaryDisplay()
|
||||
const { initialBounds, shouldRestoreNormalBoundsOnUnmaximize } = resolveInitialWindowBounds({
|
||||
saved,
|
||||
launchFullScreen: Boolean(runtimeConfig.fullscreen || runtimeConfig.kiosk),
|
||||
headlessSmoke: runtimeConfig.headlessSmoke,
|
||||
displayWorkArea: targetDisplay.workArea,
|
||||
displayBounds: targetDisplay.bounds,
|
||||
})
|
||||
|
||||
const win = new BrowserWindow({
|
||||
x: saved.x,
|
||||
y: saved.y,
|
||||
width: saved.width,
|
||||
height: saved.height,
|
||||
x: initialBounds.x,
|
||||
y: initialBounds.y,
|
||||
width: initialBounds.width,
|
||||
height: initialBounds.height,
|
||||
minWidth: MIN_WINDOW_WIDTH,
|
||||
minHeight: MIN_WINDOW_HEIGHT,
|
||||
show: false,
|
||||
@@ -245,6 +267,21 @@ export function createMainWindow(options: {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
input.type === 'keyDown' &&
|
||||
!input.isAutoRepeat &&
|
||||
input.control &&
|
||||
input.shift &&
|
||||
!input.alt &&
|
||||
!input.meta &&
|
||||
input.key.toLowerCase() === 'f9'
|
||||
) {
|
||||
altTracker.reset()
|
||||
event.preventDefault()
|
||||
options.onToggleRecording?.()
|
||||
return
|
||||
}
|
||||
|
||||
const action = altTracker.handleInput(input)
|
||||
if (action === 'toggle') {
|
||||
event.preventDefault()
|
||||
@@ -282,7 +319,17 @@ export function createMainWindow(options: {
|
||||
restoreFullScreenOnLandscape: Boolean(saved.isFullScreen),
|
||||
})
|
||||
|
||||
let pendingInitialReveal =
|
||||
!runtimeConfig.headlessSmoke &&
|
||||
Boolean(saved.isMaximized || saved.isFullScreen || runtimeConfig.fullscreen || runtimeConfig.kiosk)
|
||||
let restoreNormalBoundsOnUnmaximize = shouldRestoreNormalBoundsOnUnmaximize
|
||||
|
||||
cancelInitialUnmaximizeRestore.set(win, () => {
|
||||
restoreNormalBoundsOnUnmaximize = false
|
||||
})
|
||||
|
||||
const captureNormalBounds = () => {
|
||||
if (pendingInitialReveal) return
|
||||
if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized() && !win.isFullScreen()) {
|
||||
lastNormalBounds = win.getBounds()
|
||||
const orientState = windowOrientationStates.get(win)
|
||||
@@ -296,13 +343,28 @@ export function createMainWindow(options: {
|
||||
}
|
||||
}
|
||||
|
||||
win.on('resize', captureNormalBounds)
|
||||
win.on('move', captureNormalBounds)
|
||||
win.on('close', () => {
|
||||
const flushCurrentWindowState = () => {
|
||||
captureNormalBounds()
|
||||
if (!runtimeConfig.headlessSmoke) {
|
||||
saveWindowState(statePath, win, lastNormalBounds)
|
||||
}
|
||||
}
|
||||
windowStateFlushers.set(win, flushCurrentWindowState)
|
||||
|
||||
win.on('resize', captureNormalBounds)
|
||||
win.on('move', captureNormalBounds)
|
||||
win.on('close', flushCurrentWindowState)
|
||||
win.on('unmaximize', () => {
|
||||
if (!restoreNormalBoundsOnUnmaximize) return
|
||||
restoreNormalBoundsOnUnmaximize = false
|
||||
if (win.isDestroyed() || win.isFullScreen()) return
|
||||
if (
|
||||
lastNormalBounds.width < targetDisplay.workArea.width ||
|
||||
lastNormalBounds.height < targetDisplay.workArea.height
|
||||
) {
|
||||
const workArea = screen.getDisplayMatching(win.getBounds()).workArea
|
||||
win.setBounds(clampBoundsToWorkArea(lastNormalBounds, workArea))
|
||||
}
|
||||
})
|
||||
|
||||
win.on('minimize', () => {
|
||||
@@ -331,22 +393,29 @@ export function createMainWindow(options: {
|
||||
|
||||
const revealMainWindow = () => {
|
||||
if (win.isDestroyed() || runtimeConfig.headlessSmoke) return
|
||||
if (saved.isMaximized) {
|
||||
win.maximize()
|
||||
}
|
||||
win.show()
|
||||
if (runtimeConfig.kiosk) {
|
||||
win.setKiosk(true)
|
||||
} else if (runtimeConfig.fullscreen || saved.isFullScreen) {
|
||||
win.setFullScreen(true)
|
||||
}
|
||||
if (runtimeConfig.devtools) {
|
||||
win.webContents.openDevTools({ mode: 'detach' })
|
||||
try {
|
||||
if (saved.isMaximized) {
|
||||
win.maximize()
|
||||
}
|
||||
win.show()
|
||||
if (runtimeConfig.kiosk) {
|
||||
win.setKiosk(true)
|
||||
} else if (runtimeConfig.fullscreen || saved.isFullScreen) {
|
||||
win.setFullScreen(true)
|
||||
}
|
||||
if (runtimeConfig.devtools) {
|
||||
win.webContents.openDevTools({ mode: 'detach' })
|
||||
}
|
||||
} finally {
|
||||
pendingInitialReveal = false
|
||||
}
|
||||
}
|
||||
|
||||
const showGate = createWindowShowGate({
|
||||
requireSplashFirstPaint: !runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off',
|
||||
requireSplashFirstPaint:
|
||||
!runtimeConfig.headlessSmoke &&
|
||||
!runtimeConfig.gpuHandoff &&
|
||||
runtimeConfig.splashTheme !== 'off',
|
||||
fallbackDelayMs: 1500,
|
||||
onReveal: revealMainWindow,
|
||||
})
|
||||
@@ -359,6 +428,8 @@ export function createMainWindow(options: {
|
||||
ipcMain.on('planet:splash-first-paint', onSplashFirstPaint)
|
||||
|
||||
win.once('closed', () => {
|
||||
windowStateFlushers.delete(win)
|
||||
cancelInitialUnmaximizeRestore.delete(win)
|
||||
showGate.dispose()
|
||||
ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
createSustainedLowFpsTracker,
|
||||
FPS_STARTUP_WARMUP_MS,
|
||||
} from '../main/gpu-policy'
|
||||
|
||||
export function startDesktopLowFpsWatcher(options: {
|
||||
onLowFps: (report: { avgFps: number; sustainedMs: number }) => void
|
||||
}): () => void {
|
||||
const tracker = createSustainedLowFpsTracker()
|
||||
let disposed = false
|
||||
let rafId = 0
|
||||
let warmupTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let startupReady = document.documentElement?.dataset?.earthStartupReady === '1'
|
||||
let warmupDone = false
|
||||
let desktopMinimized = false
|
||||
|
||||
const isActive = () =>
|
||||
!disposed && startupReady && warmupDone && !desktopMinimized && !document.hidden
|
||||
|
||||
const stopLoop = () => {
|
||||
if (rafId) {
|
||||
cancelAnimationFrame(rafId)
|
||||
rafId = 0
|
||||
}
|
||||
tracker.reset()
|
||||
}
|
||||
|
||||
const tick = (now: number) => {
|
||||
if (!isActive()) {
|
||||
rafId = 0
|
||||
tracker.reset()
|
||||
return
|
||||
}
|
||||
const report = tracker.onFrame(now)
|
||||
if (report) {
|
||||
options.onLowFps(report)
|
||||
}
|
||||
rafId = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
const syncLoop = () => {
|
||||
if (!isActive()) {
|
||||
stopLoop()
|
||||
return
|
||||
}
|
||||
if (!rafId) {
|
||||
rafId = requestAnimationFrame(tick)
|
||||
}
|
||||
}
|
||||
|
||||
const beginWarmup = () => {
|
||||
if (disposed || warmupDone || warmupTimer) return
|
||||
warmupTimer = setTimeout(() => {
|
||||
warmupTimer = null
|
||||
warmupDone = true
|
||||
syncLoop()
|
||||
}, FPS_STARTUP_WARMUP_MS)
|
||||
}
|
||||
|
||||
const onStartupReady = () => {
|
||||
startupReady = true
|
||||
beginWarmup()
|
||||
}
|
||||
|
||||
const onVisibilityChange = () => {
|
||||
syncLoop()
|
||||
}
|
||||
|
||||
const onDesktopVisibility = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ minimized?: boolean }>).detail
|
||||
desktopMinimized = Boolean(detail?.minimized)
|
||||
syncLoop()
|
||||
}
|
||||
|
||||
if (startupReady) {
|
||||
beginWarmup()
|
||||
} else {
|
||||
window.addEventListener('earth:startup-ready', onStartupReady, { once: true })
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
window.addEventListener('planet-desktop:visibility', onDesktopVisibility)
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
stopLoop()
|
||||
if (warmupTimer) {
|
||||
clearTimeout(warmupTimer)
|
||||
warmupTimer = null
|
||||
}
|
||||
window.removeEventListener('earth:startup-ready', onStartupReady)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
window.removeEventListener('planet-desktop:visibility', onDesktopVisibility)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
import { startDesktopLowFpsWatcher } from './fps-watcher'
|
||||
import { initDesktopScreenRecorder, openDesktopRecordingsFolder, toggleDesktopRecording } from './screen-recorder'
|
||||
import { createDesktopSplashController, type SplashTheme } from './splash'
|
||||
|
||||
interface PreloadRuntimeConfig {
|
||||
@@ -9,10 +11,14 @@ interface PreloadRuntimeConfig {
|
||||
wsUrl: string
|
||||
forceShowFps: boolean
|
||||
splashTheme: SplashTheme
|
||||
gpuMode?: string
|
||||
gpuTarget?: string
|
||||
gpuHandoff?: boolean
|
||||
headlessSmoke: boolean
|
||||
isElectron: true
|
||||
platform: string
|
||||
localMediaPipeBaseUrl: string
|
||||
localPoseModelUrl: string
|
||||
}
|
||||
|
||||
const runtimeConfig = ipcRenderer.sendSync('planet:get-runtime-config') as PreloadRuntimeConfig
|
||||
@@ -27,7 +33,7 @@ const splashController = createDesktopSplashController({
|
||||
},
|
||||
})
|
||||
|
||||
if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
|
||||
if (!runtimeConfig.headlessSmoke && !runtimeConfig.gpuHandoff && runtimeConfig.splashTheme !== 'off') {
|
||||
let bootStarted = false
|
||||
const tryStartBoot = () => {
|
||||
if (bootStarted || !document.documentElement) return false
|
||||
@@ -54,6 +60,23 @@ if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!runtimeConfig.headlessSmoke &&
|
||||
runtimeConfig.platform === 'win32' &&
|
||||
runtimeConfig.gpuMode === 'auto' &&
|
||||
(runtimeConfig.gpuTarget === 'default' || runtimeConfig.gpuTarget === 'high-performance')
|
||||
) {
|
||||
startDesktopLowFpsWatcher({
|
||||
onLowFps: (report) => {
|
||||
ipcRenderer.send('planet:low-fps-report', report)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (!runtimeConfig.headlessSmoke) {
|
||||
initDesktopScreenRecorder()
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('__PLANET_RUNTIME_CONFIG__', runtimeConfig)
|
||||
|
||||
contextBridge.exposeInMainWorld('planetDesktop', {
|
||||
@@ -75,6 +98,12 @@ contextBridge.exposeInMainWorld('planetDesktop', {
|
||||
replaySplash: (theme?: SplashTheme) => {
|
||||
splashController.replay(theme)
|
||||
},
|
||||
toggleRecording: () => toggleDesktopRecording(),
|
||||
openRecordingsFolder: () => openDesktopRecordingsFolder(),
|
||||
checkForUpdates: () => ipcRenderer.invoke('planet:check-for-updates') as Promise<void>,
|
||||
getVersionInfo: () => ipcRenderer.invoke('planet:get-version-info'),
|
||||
getEarthSessionToken: (opts?: { forceRefresh?: boolean }) =>
|
||||
ipcRenderer.invoke('planet:get-earth-session-token', opts) as Promise<string | null>,
|
||||
})
|
||||
|
||||
ipcRenderer.on('planet:visibility', (_event, detail) => {
|
||||
@@ -93,6 +122,25 @@ ipcRenderer.on('planet:replay-splash', (_event, detail?: { theme?: SplashTheme }
|
||||
splashController.replay(detail?.theme)
|
||||
})
|
||||
|
||||
ipcRenderer.on('planet:gpu-process-gone', (_event, detail) => {
|
||||
window.dispatchEvent(new CustomEvent('planet-desktop:gpu-process-gone', { detail }))
|
||||
})
|
||||
|
||||
ipcRenderer.on('planet:update-status', (_event, detail) => {
|
||||
window.dispatchEvent(new CustomEvent('earth:status', { detail }))
|
||||
})
|
||||
|
||||
if (document.documentElement?.dataset?.earthStartupReady === '1') {
|
||||
ipcRenderer.send('planet:earth-startup-ready')
|
||||
}
|
||||
window.addEventListener(
|
||||
'earth:startup-ready',
|
||||
() => {
|
||||
ipcRenderer.send('planet:earth-startup-ready')
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
|
||||
window.addEventListener(
|
||||
'pointerdown',
|
||||
() => {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
import type { RecordingCursorPayload } from '../main/recording-core'
|
||||
|
||||
contextBridge.exposeInMainWorld('planetRecordingCursor', {
|
||||
onUpdate: (callback: (payload: RecordingCursorPayload) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, payload: unknown) => {
|
||||
if (payload && typeof payload === 'object') {
|
||||
callback(payload as RecordingCursorPayload)
|
||||
}
|
||||
}
|
||||
ipcRenderer.on('planet:recording-cursor-update', listener)
|
||||
return () => {
|
||||
ipcRenderer.removeListener('planet:recording-cursor-update', listener)
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
contextBridge.exposeInMainWorld('planetRecordingIndicator', {
|
||||
onTick: (callback: (formattedElapsed: string) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, formatted: unknown) => {
|
||||
if (typeof formatted === 'string') {
|
||||
callback(formatted)
|
||||
}
|
||||
}
|
||||
ipcRenderer.on('planet:recording-indicator-tick', listener)
|
||||
return () => {
|
||||
ipcRenderer.removeListener('planet:recording-indicator-tick', listener)
|
||||
}
|
||||
},
|
||||
requestStop: () => {
|
||||
ipcRenderer.send('planet:recording-indicator-stop')
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,324 @@
|
||||
import { ipcRenderer } from 'electron'
|
||||
|
||||
import {
|
||||
pickSupportedRecordingMimeTypes,
|
||||
type RecordingCursorPayload,
|
||||
type RecordingCursorShape,
|
||||
type RecordingStatusSnapshot,
|
||||
} from '../main/recording-core'
|
||||
|
||||
interface ActiveCaptureSession {
|
||||
stream: MediaStream
|
||||
recorder: MediaRecorder
|
||||
mimeType: string
|
||||
includeAudio: boolean
|
||||
hideCursor: boolean
|
||||
pendingChunkWrites: Set<Promise<void>>
|
||||
stoppedByRenderer: boolean
|
||||
}
|
||||
|
||||
const HIDE_CURSOR_STYLE_ID = 'planet-recording-hide-cursor-style'
|
||||
const HIDE_CURSOR_CLASS = 'planet-recording-hide-cursor'
|
||||
|
||||
function chooseSupportedMimeType(includeAudio: boolean): string {
|
||||
if (typeof MediaRecorder === 'undefined' || typeof MediaRecorder.isTypeSupported !== 'function') {
|
||||
return ''
|
||||
}
|
||||
for (const candidate of pickSupportedRecordingMimeTypes(includeAudio)) {
|
||||
if (MediaRecorder.isTypeSupported(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function resolveCursorShape(target: EventTarget | null, buttons: number): RecordingCursorShape {
|
||||
if (!(target instanceof Element)) return 'default'
|
||||
if ((buttons & 1) !== 0 && target.tagName === 'CANVAS') {
|
||||
return 'grabbing'
|
||||
}
|
||||
if (
|
||||
target.closest(
|
||||
'input:not([type="checkbox"]):not([type="radio"]):not([type="range"]), textarea, [contenteditable="true"]',
|
||||
)
|
||||
) {
|
||||
return 'text'
|
||||
}
|
||||
if (
|
||||
target.closest(
|
||||
'a, button, summary, select, label, [role="button"], [tabindex], .hud-panel__action, .news-region-card__header',
|
||||
)
|
||||
) {
|
||||
return 'pointer'
|
||||
}
|
||||
return 'default'
|
||||
}
|
||||
|
||||
export function initDesktopScreenRecorder(): void {
|
||||
let activeSession: ActiveCaptureSession | null = null
|
||||
let stoppingPromise: Promise<void> | null = null
|
||||
let cursorMaskActive = false
|
||||
let pendingCursorPayload: RecordingCursorPayload | null = null
|
||||
let cursorRafId: number | null = null
|
||||
|
||||
const sendCursorPayload = (payload: RecordingCursorPayload) => {
|
||||
ipcRenderer.send('planet:recording-cursor-move', payload)
|
||||
}
|
||||
|
||||
const flushCursorPayload = () => {
|
||||
cursorRafId = null
|
||||
if (!cursorMaskActive || !pendingCursorPayload) return
|
||||
const next = pendingCursorPayload
|
||||
pendingCursorPayload = null
|
||||
sendCursorPayload(next)
|
||||
}
|
||||
|
||||
const scheduleCursorPayload = (payload: RecordingCursorPayload) => {
|
||||
if (!cursorMaskActive) return
|
||||
pendingCursorPayload = payload
|
||||
if (cursorRafId === null) {
|
||||
cursorRafId = window.requestAnimationFrame(flushCursorPayload)
|
||||
}
|
||||
}
|
||||
|
||||
const onPointerMove = (event: PointerEvent) => {
|
||||
scheduleCursorPayload({
|
||||
visible: true,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
shape: resolveCursorShape(event.target, event.buttons),
|
||||
})
|
||||
}
|
||||
|
||||
const onPointerButton = (event: PointerEvent) => {
|
||||
if (!cursorMaskActive) return
|
||||
sendCursorPayload({
|
||||
visible: true,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
shape: resolveCursorShape(event.target, event.buttons),
|
||||
})
|
||||
}
|
||||
|
||||
const onPointerHide = () => {
|
||||
if (cursorRafId !== null) {
|
||||
window.cancelAnimationFrame(cursorRafId)
|
||||
cursorRafId = null
|
||||
}
|
||||
pendingCursorPayload = null
|
||||
sendCursorPayload({ visible: false, x: 0, y: 0, shape: 'default' })
|
||||
}
|
||||
|
||||
const setCursorMaskEnabled = (enabled: boolean) => {
|
||||
const root = document.documentElement
|
||||
if (!root) return
|
||||
if (enabled === cursorMaskActive) return
|
||||
cursorMaskActive = enabled
|
||||
if (enabled) {
|
||||
if (!document.getElementById(HIDE_CURSOR_STYLE_ID)) {
|
||||
const styleEl = document.createElement('style')
|
||||
styleEl.id = HIDE_CURSOR_STYLE_ID
|
||||
styleEl.textContent = `html.${HIDE_CURSOR_CLASS}, html.${HIDE_CURSOR_CLASS} * { cursor: none !important; }`
|
||||
;(document.head || root).appendChild(styleEl)
|
||||
}
|
||||
root.classList.add(HIDE_CURSOR_CLASS)
|
||||
root.addEventListener('pointermove', onPointerMove, { capture: true, passive: true })
|
||||
root.addEventListener('pointerdown', onPointerButton, { capture: true, passive: true })
|
||||
root.addEventListener('pointerup', onPointerButton, { capture: true, passive: true })
|
||||
root.addEventListener('pointerleave', onPointerHide, { capture: true, passive: true })
|
||||
window.addEventListener('blur', onPointerHide)
|
||||
} else {
|
||||
root.classList.remove(HIDE_CURSOR_CLASS)
|
||||
root.removeEventListener('pointermove', onPointerMove, { capture: true })
|
||||
root.removeEventListener('pointerdown', onPointerButton, { capture: true })
|
||||
root.removeEventListener('pointerup', onPointerButton, { capture: true })
|
||||
root.removeEventListener('pointerleave', onPointerHide, { capture: true })
|
||||
window.removeEventListener('blur', onPointerHide)
|
||||
onPointerHide()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('beforeunload', () => {
|
||||
setCursorMaskEnabled(false)
|
||||
})
|
||||
|
||||
const cleanupStreamTracks = (stream: MediaStream | null) => {
|
||||
if (!stream) return
|
||||
for (const track of stream.getTracks()) {
|
||||
try {
|
||||
track.stop()
|
||||
} catch {
|
||||
// Ignore already-ended track stop errors.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const finalizeActiveSession = async (reason: string): Promise<void> => {
|
||||
if (stoppingPromise) return stoppingPromise
|
||||
const session = activeSession
|
||||
if (!session) return
|
||||
|
||||
stoppingPromise = (async () => {
|
||||
try {
|
||||
if (session.recorder.state !== 'inactive') {
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(resolve, 2500)
|
||||
session.recorder.addEventListener(
|
||||
'stop',
|
||||
() => {
|
||||
clearTimeout(timeout)
|
||||
resolve()
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
try {
|
||||
session.recorder.stop()
|
||||
} catch {
|
||||
clearTimeout(timeout)
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
if (session.pendingChunkWrites.size > 0) {
|
||||
await Promise.allSettled([...session.pendingChunkWrites])
|
||||
}
|
||||
await ipcRenderer.invoke('planet:recording-finish', { reason })
|
||||
} finally {
|
||||
setCursorMaskEnabled(false)
|
||||
cleanupStreamTracks(session.stream)
|
||||
if (activeSession === session) {
|
||||
activeSession = null
|
||||
}
|
||||
stoppingPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return stoppingPromise
|
||||
}
|
||||
|
||||
ipcRenderer.on(
|
||||
'planet:recording-start',
|
||||
(_event, payload?: { includeAudio?: boolean; hideCursor?: boolean }) => {
|
||||
void (async () => {
|
||||
if (activeSession || stoppingPromise) return
|
||||
const wantAudio = Boolean(payload?.includeAudio)
|
||||
const hideCursor = Boolean(payload?.hideCursor)
|
||||
|
||||
let stream: MediaStream | null = null
|
||||
let includeAudio = wantAudio
|
||||
|
||||
try {
|
||||
const videoConstraints = { frameRate: { ideal: 60, max: 60 } } as unknown as MediaTrackConstraints
|
||||
if (wantAudio) {
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getDisplayMedia({
|
||||
video: videoConstraints,
|
||||
audio: true,
|
||||
})
|
||||
if (stream.getAudioTracks().length === 0) {
|
||||
includeAudio = false
|
||||
ipcRenderer.send('planet:recording-audio-fallback')
|
||||
}
|
||||
} catch {
|
||||
includeAudio = false
|
||||
ipcRenderer.send('planet:recording-audio-fallback')
|
||||
stream = await navigator.mediaDevices.getDisplayMedia({
|
||||
video: videoConstraints,
|
||||
audio: false,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
stream = await navigator.mediaDevices.getDisplayMedia({
|
||||
video: videoConstraints,
|
||||
audio: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (!stream) {
|
||||
throw new Error('Display capture returned no stream')
|
||||
}
|
||||
|
||||
const mimeType = chooseSupportedMimeType(includeAudio && stream.getAudioTracks().length > 0)
|
||||
const recorderOptions: MediaRecorderOptions = {
|
||||
videoBitsPerSecond: 8_000_000,
|
||||
...(includeAudio ? { audioBitsPerSecond: 128_000 } : {}),
|
||||
...(mimeType ? { mimeType } : {}),
|
||||
}
|
||||
|
||||
await ipcRenderer.invoke('planet:recording-open-file', {
|
||||
mimeType,
|
||||
includeAudio,
|
||||
hideCursor,
|
||||
})
|
||||
|
||||
setCursorMaskEnabled(hideCursor)
|
||||
|
||||
const recorder = new MediaRecorder(stream, recorderOptions)
|
||||
const pendingChunkWrites = new Set<Promise<void>>()
|
||||
const session: ActiveCaptureSession = {
|
||||
stream,
|
||||
recorder,
|
||||
mimeType: recorder.mimeType || mimeType,
|
||||
includeAudio,
|
||||
hideCursor,
|
||||
pendingChunkWrites,
|
||||
stoppedByRenderer: false,
|
||||
}
|
||||
activeSession = session
|
||||
|
||||
recorder.addEventListener('dataavailable', (event: BlobEvent) => {
|
||||
if (!event.data || event.data.size === 0) return
|
||||
const task = event.data
|
||||
.arrayBuffer()
|
||||
.then((buffer) => {
|
||||
ipcRenderer.send('planet:recording-chunk', new Uint8Array(buffer))
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
pendingChunkWrites.delete(task)
|
||||
})
|
||||
pendingChunkWrites.add(task)
|
||||
})
|
||||
|
||||
const [videoTrack] = stream.getVideoTracks()
|
||||
if (videoTrack) {
|
||||
videoTrack.addEventListener(
|
||||
'ended',
|
||||
() => {
|
||||
if (activeSession === session && !session.stoppedByRenderer) {
|
||||
session.stoppedByRenderer = true
|
||||
void finalizeActiveSession('track-ended')
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
}
|
||||
|
||||
recorder.start(1000)
|
||||
} catch (error) {
|
||||
setCursorMaskEnabled(false)
|
||||
cleanupStreamTracks(stream)
|
||||
activeSession = null
|
||||
await ipcRenderer.invoke('planet:recording-abort', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
})()
|
||||
},
|
||||
)
|
||||
|
||||
ipcRenderer.on('planet:recording-stop', () => {
|
||||
if (activeSession) {
|
||||
activeSession.stoppedByRenderer = true
|
||||
}
|
||||
void finalizeActiveSession('requested-stop')
|
||||
})
|
||||
}
|
||||
|
||||
export async function toggleDesktopRecording(): Promise<RecordingStatusSnapshot> {
|
||||
return (await ipcRenderer.invoke('planet:recording-toggle')) as RecordingStatusSnapshot
|
||||
}
|
||||
|
||||
export async function openDesktopRecordingsFolder(): Promise<void> {
|
||||
await ipcRenderer.invoke('planet:recording-open-folder')
|
||||
}
|
||||
+220
-365
@@ -1,7 +1,7 @@
|
||||
import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from './earth-landmask'
|
||||
|
||||
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
|
||||
export type ActiveSplashTheme = Exclude<SplashTheme, 'off'>
|
||||
export type SplashTheme = 'singularity' | 'off'
|
||||
export type ActiveSplashTheme = 'singularity'
|
||||
|
||||
interface GlobePoint {
|
||||
lat: number
|
||||
@@ -32,10 +32,70 @@ interface ArcDef {
|
||||
|
||||
const SPLASH_HOST_ID = 'planet-desktop-splash-host'
|
||||
const DEFAULT_HOST_THEME: ActiveSplashTheme = 'singularity'
|
||||
const REPLAY_DURATION_MS = 2600
|
||||
const MIN_BOOT_SHOWCASE_MS = 1800
|
||||
const REPLAY_DURATION_MS = 3200
|
||||
const MIN_BOOT_SHOWCASE_MS = 2200
|
||||
const MAX_BOOT_CAP_MS = 20000
|
||||
|
||||
export interface SplashCanvasSize {
|
||||
dpr: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export function computeSplashCanvasSize(
|
||||
width: number,
|
||||
height: number,
|
||||
devicePixelRatio: number,
|
||||
maxPixels = 1920 * 1080,
|
||||
maxDpr = 1.5,
|
||||
): SplashCanvasSize {
|
||||
const safeW = Math.max(1, Number(width) || 1)
|
||||
const safeH = Math.max(1, Number(height) || 1)
|
||||
const rawDpr = Math.min(Math.max(Number(devicePixelRatio) || 1, 0.5), maxDpr)
|
||||
const totalPixels = safeW * safeH * rawDpr * rawDpr
|
||||
const dpr =
|
||||
totalPixels > maxPixels
|
||||
? Math.min(rawDpr, Math.max(0.75, Math.floor(Math.sqrt(maxPixels / (safeW * safeH)) * 100) / 100))
|
||||
: rawDpr
|
||||
return {
|
||||
dpr,
|
||||
width: Math.max(1, Math.round(safeW * dpr)),
|
||||
height: Math.max(1, Math.round(safeH * dpr)),
|
||||
}
|
||||
}
|
||||
|
||||
export interface SplashMorphPhases {
|
||||
dawnIntensity: number
|
||||
coreReveal: number
|
||||
orbitReveal: number
|
||||
arcReveal: number
|
||||
burst: number
|
||||
fade: number
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
return Math.max(0, Math.min(1, value))
|
||||
}
|
||||
|
||||
function smoothstep(edge0: number, edge1: number, x: number): number {
|
||||
if (edge1 <= edge0) return x >= edge1 ? 1 : 0
|
||||
const t = clamp01((x - edge0) / (edge1 - edge0))
|
||||
return t * t * (3 - 2 * t)
|
||||
}
|
||||
|
||||
export function computeSplashMorphPhases(progress: number, exitRatio: number): SplashMorphPhases {
|
||||
const p = clamp01(Number.isFinite(progress) ? progress : 0)
|
||||
const e = clamp01(Number.isFinite(exitRatio) ? exitRatio : 0)
|
||||
return {
|
||||
dawnIntensity: (1 - smoothstep(0.36, 0.78, p)) * (1 - smoothstep(0, 0.35, e)),
|
||||
coreReveal: smoothstep(0.18, 0.68, p),
|
||||
orbitReveal: smoothstep(0.38, 0.82, p),
|
||||
arcReveal: smoothstep(0.56, 0.9, p),
|
||||
burst: e > 0 ? Math.pow(e, 1.38) : 0,
|
||||
fade: 1 - Math.pow(e, 2.2),
|
||||
}
|
||||
}
|
||||
|
||||
export interface BootSplashStateInput {
|
||||
elapsedMs: number
|
||||
minDurationMs: number
|
||||
@@ -84,7 +144,7 @@ const ARC_DEFINITIONS: readonly ArcDef[] = [
|
||||
]
|
||||
|
||||
function isActiveTheme(value: string | undefined | null): value is ActiveSplashTheme {
|
||||
return value === 'singularity' || value === 'constellation' || value === 'horizon'
|
||||
return value === 'singularity'
|
||||
}
|
||||
|
||||
function getLocaleIsEn(): boolean {
|
||||
@@ -205,6 +265,8 @@ const SPLASH_CSS = `
|
||||
all: initial;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 2147483000;
|
||||
display: block;
|
||||
pointer-events: auto;
|
||||
@@ -225,14 +287,6 @@ const SPLASH_CSS = `
|
||||
transition: opacity 380ms cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="horizon"] {
|
||||
background: radial-gradient(circle at 50% 41%, #091322 0%, #030710 56%, #010308 100%);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="constellation"] {
|
||||
background: radial-gradient(circle at 50% 41%, #06182c 0%, #030916 55%, #02040a 100%);
|
||||
}
|
||||
|
||||
.splash-root.is-exiting {
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -309,48 +363,24 @@ const SPLASH_CSS = `
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.splash-switcher {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 3px;
|
||||
border: 1px solid rgba(173, 210, 255, 0.16);
|
||||
background: rgba(8, 19, 36, 0.62);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.splash-pill,
|
||||
.splash-skip {
|
||||
appearance: none;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: rgba(190, 216, 245, 0.72);
|
||||
border: 1px solid rgba(173, 210, 255, 0.16);
|
||||
background: rgba(8, 19, 36, 0.55);
|
||||
backdrop-filter: blur(10px);
|
||||
color: rgba(190, 216, 245, 0.78);
|
||||
font-family: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 4px 9px;
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
transition: color 160ms ease, background-color 160ms ease, border-color 160ms ease;
|
||||
}
|
||||
|
||||
.splash-pill:hover,
|
||||
.splash-skip:hover {
|
||||
color: #f3f9ff;
|
||||
background: rgba(132, 192, 255, 0.12);
|
||||
}
|
||||
|
||||
.splash-pill.is-active {
|
||||
color: #f5faff;
|
||||
background: rgba(82, 168, 255, 0.24);
|
||||
border-color: rgba(136, 206, 255, 0.42);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
|
||||
.splash-skip {
|
||||
border-color: rgba(173, 210, 255, 0.16);
|
||||
background: rgba(8, 19, 36, 0.55);
|
||||
padding: 5px 10px;
|
||||
background: rgba(132, 192, 255, 0.14);
|
||||
}
|
||||
|
||||
.splash-footer {
|
||||
@@ -438,21 +468,6 @@ const SPLASH_CSS = `
|
||||
border: 1px solid rgba(173, 214, 255, 0.12);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="horizon"] .splash-progress-track {
|
||||
height: 2px;
|
||||
border: none;
|
||||
background: rgba(210, 232, 255, 0.14);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="constellation"] .splash-progress-track {
|
||||
height: 6px;
|
||||
background: repeating-linear-gradient(
|
||||
90deg,
|
||||
rgba(135, 188, 242, 0.18) 0 12px,
|
||||
rgba(6, 15, 30, 0.7) 12px 16px
|
||||
);
|
||||
}
|
||||
|
||||
.splash-progress-fill {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
@@ -461,20 +476,6 @@ const SPLASH_CSS = `
|
||||
box-shadow: 0 0 14px rgba(105, 198, 255, 0.55);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="constellation"] .splash-progress-fill {
|
||||
background: repeating-linear-gradient(
|
||||
90deg,
|
||||
#77cfff 0 12px,
|
||||
transparent 12px 16px
|
||||
);
|
||||
box-shadow: 0 0 12px rgba(105, 206, 255, 0.45);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="horizon"] .splash-progress-fill {
|
||||
background: linear-gradient(90deg, rgba(84, 165, 255, 0.55) 0%, #c4e4ff 70%, #ffffff 100%);
|
||||
box-shadow: 0 0 16px rgba(196, 228, 255, 0.72);
|
||||
}
|
||||
|
||||
.splash-progress-fill::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
@@ -594,11 +595,11 @@ export function createDesktopSplashController(options: {
|
||||
let progressFillEl: HTMLDivElement | null = null
|
||||
let stageEl: HTMLSpanElement | null = null
|
||||
let percentEl: HTMLSpanElement | null = null
|
||||
let switcherButtons: HTMLButtonElement[] = []
|
||||
|
||||
let rafId = 0
|
||||
let statusObserver: MutationObserver | null = null
|
||||
let keydownHandler: ((event: KeyboardEvent) => void) | null = null
|
||||
let resizeHandler: (() => void) | null = null
|
||||
let startupProgressHandler: ((event: Event) => void) | null = null
|
||||
let startupReadyHandler: (() => void) | null = null
|
||||
let sessionMode: 'boot' | 'replay' = 'boot'
|
||||
@@ -657,6 +658,10 @@ export function createDesktopSplashController(options: {
|
||||
window.removeEventListener('keydown', keydownHandler, true)
|
||||
keydownHandler = null
|
||||
}
|
||||
if (resizeHandler) {
|
||||
window.removeEventListener('resize', resizeHandler)
|
||||
resizeHandler = null
|
||||
}
|
||||
if (hostEl && hostEl.parentNode) {
|
||||
hostEl.parentNode.removeChild(hostEl)
|
||||
}
|
||||
@@ -667,7 +672,6 @@ export function createDesktopSplashController(options: {
|
||||
progressFillEl = null
|
||||
stageEl = null
|
||||
percentEl = null
|
||||
switcherButtons = []
|
||||
exitStartTime = 0
|
||||
}
|
||||
|
||||
@@ -685,11 +689,6 @@ export function createDesktopSplashController(options: {
|
||||
if (hostEl) {
|
||||
hostEl.dataset.splashTheme = nextTheme
|
||||
}
|
||||
for (const btn of switcherButtons) {
|
||||
const match = btn.dataset.splashSwitch === nextTheme
|
||||
btn.classList.toggle('is-active', match)
|
||||
btn.setAttribute('aria-pressed', String(match))
|
||||
}
|
||||
}
|
||||
|
||||
const notifyFirstPaintOnce = () => {
|
||||
@@ -746,7 +745,7 @@ export function createDesktopSplashController(options: {
|
||||
|
||||
hostEl = document.createElement('div')
|
||||
hostEl.id = SPLASH_HOST_ID
|
||||
hostEl.style.cssText = 'position:fixed;inset:0;z-index:2147483647;pointer-events:auto;'
|
||||
hostEl.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;z-index:2147483647;pointer-events:auto;'
|
||||
hostEl.dataset.splashTheme = activeTheme
|
||||
shadow = hostEl.attachShadow({ mode: 'open' })
|
||||
|
||||
@@ -764,11 +763,6 @@ export function createDesktopSplashController(options: {
|
||||
<span>PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL</span>
|
||||
</div>
|
||||
<div class="splash-controls">
|
||||
<div class="splash-switcher" role="group" aria-label="启动画面方案">
|
||||
<button type="button" class="splash-pill" data-splash-switch="singularity">01 星核</button>
|
||||
<button type="button" class="splash-pill" data-splash-switch="constellation">02 星轨</button>
|
||||
<button type="button" class="splash-pill" data-splash-switch="horizon">03 破晓</button>
|
||||
</div>
|
||||
<button type="button" class="splash-skip" data-splash-skip title="跳过启动动画 (Esc)">ESC 跳过</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -792,7 +786,7 @@ export function createDesktopSplashController(options: {
|
||||
<div class="splash-presenter-copy">
|
||||
<span class="splash-presenter-kicker">PRESENTED BY</span>
|
||||
<span class="splash-presenter-zh">临空智能媒体研究院</span>
|
||||
<span class="splash-presenter-en">Institute of Intelligent Media</span>
|
||||
<span class="splash-presenter-en">Intelligent Media Institute</span>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
@@ -807,23 +801,6 @@ export function createDesktopSplashController(options: {
|
||||
progressFillEl = root.querySelector('[data-splash-fill]')
|
||||
stageEl = root.querySelector('[data-splash-stage]')
|
||||
percentEl = root.querySelector('[data-splash-percent]')
|
||||
switcherButtons = Array.from(root.querySelectorAll('[data-splash-switch]'))
|
||||
|
||||
for (const btn of switcherButtons) {
|
||||
btn.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
const picked = btn.dataset.splashSwitch
|
||||
if (isActiveTheme(picked)) {
|
||||
preferredTheme = picked
|
||||
options.onSelectTheme(picked)
|
||||
if (sessionMode === 'boot' && !startupReady) {
|
||||
setActiveThemeVisual(picked)
|
||||
} else {
|
||||
startSplashSession(picked, 'replay')
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const skipBtn = root.querySelector('[data-splash-skip]')
|
||||
skipBtn?.addEventListener('click', (event) => {
|
||||
@@ -840,6 +817,18 @@ export function createDesktopSplashController(options: {
|
||||
window.addEventListener('keydown', keydownHandler, true)
|
||||
}
|
||||
|
||||
if (!resizeHandler) {
|
||||
resizeHandler = () => {
|
||||
if (!canvasEl || !rootEl) return
|
||||
const now = performance.now()
|
||||
const exitDuration = prefersReducedMotion() ? 300 : 940
|
||||
const clampedProgress = Math.max(0, Math.min(1, displayProgress))
|
||||
const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0
|
||||
renderSceneFrame(now, clampedProgress, exitRatio)
|
||||
}
|
||||
window.addEventListener('resize', resizeHandler)
|
||||
}
|
||||
|
||||
setActiveThemeVisual(activeTheme)
|
||||
}
|
||||
|
||||
@@ -932,7 +921,7 @@ export function createDesktopSplashController(options: {
|
||||
cx: number,
|
||||
cy: number,
|
||||
) => {
|
||||
const warp = exitRatio > 0 && activeTheme === 'singularity' ? exitRatio * exitRatio : 0
|
||||
const warp = exitRatio > 0 ? exitRatio * exitRatio : 0
|
||||
for (const star of stars) {
|
||||
const sx = star.x * w
|
||||
const sy = star.y * h
|
||||
@@ -960,7 +949,7 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
}
|
||||
|
||||
const drawSingularityScene = (
|
||||
const drawDawnToSingularityScene = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
w: number,
|
||||
h: number,
|
||||
@@ -971,57 +960,115 @@ export function createDesktopSplashController(options: {
|
||||
progress: number,
|
||||
exitRatio: number,
|
||||
) => {
|
||||
const burst = exitRatio > 0 ? Math.pow(exitRatio, 1.4) : 0
|
||||
const fade = 1 - Math.pow(exitRatio, 2.2)
|
||||
const { dawnIntensity, coreReveal, orbitReveal, arcReveal, burst, fade } =
|
||||
computeSplashMorphPhases(progress, exitRatio)
|
||||
|
||||
// Deep holographic ambient halo
|
||||
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
|
||||
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * fade).toFixed(3)})`)
|
||||
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * fade).toFixed(3)})`)
|
||||
glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
|
||||
ctx.fillStyle = glow
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
const perspD = 3.6
|
||||
const perspK = 3.25
|
||||
const tiltX = -0.25
|
||||
const rollZ = -0.11
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 2.1)
|
||||
const eclipseR = radius * 0.955
|
||||
const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45
|
||||
|
||||
// Tilted orbital rings accelerating cleanly toward phase lock
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * (0.42 + progress * 0.48 + burst * 2.2)
|
||||
const ringConfigs = [
|
||||
{ rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
|
||||
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
|
||||
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
|
||||
]
|
||||
for (let i = 0; i < ringConfigs.length; i += 1) {
|
||||
const ring = ringConfigs[i]
|
||||
ctx.save()
|
||||
ctx.translate(cx, cy)
|
||||
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
|
||||
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.15
|
||||
// Act 1 -> Act 2: Eclipse atmospheric corona cross-dissolves into deep holographic halo
|
||||
if (dawnIntensity > 0.01) {
|
||||
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const coronaAlpha = dawnIntensity * fade
|
||||
const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 1.4))
|
||||
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.9 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.5 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.15 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
|
||||
ctx.fillStyle = corona
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
|
||||
// Moving orbital shard beacon along ellipse
|
||||
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
|
||||
const sx = Math.cos(a) * ring.rx
|
||||
const sy = Math.sin(a) * ring.ry
|
||||
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * fade).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
|
||||
ctx.arc(cx, cy, eclipseR * (1.95 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
// 3D Holographic Earth point cloud + burst explosion streaks
|
||||
const tiltX = -0.26
|
||||
const rollZ = -0.14
|
||||
const perspD = 3.1
|
||||
if (coreReveal > 0.01) {
|
||||
const haloAlpha = coreReveal * fade
|
||||
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
|
||||
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`)
|
||||
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * haloAlpha).toFixed(3)})`)
|
||||
glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
|
||||
ctx.fillStyle = glow
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
|
||||
// Act 1 silhouette & luminous dawn limb hugging the sphere edge cleanly without shadowBlur
|
||||
if (dawnIntensity > 0.01) {
|
||||
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const discAlpha = dawnIntensity * fade
|
||||
const discGrad = ctx.createRadialGradient(lx, ly, eclipseR * 0.55, cx, cy, eclipseR)
|
||||
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * discAlpha).toFixed(3)})`)
|
||||
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * discAlpha).toFixed(3)})`)
|
||||
ctx.fillStyle = discGrad
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, eclipseR * 0.99, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
|
||||
const arcStart = coronaOffsetAngle - 0.88
|
||||
const arcEnd = coronaOffsetAngle + 0.88
|
||||
ctx.strokeStyle = `rgba(148, 214, 255, ${(0.24 * discAlpha).toFixed(3)})`
|
||||
ctx.lineWidth = 7
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
|
||||
ctx.stroke()
|
||||
|
||||
ctx.strokeStyle = `rgba(226, 246, 255, ${(0.92 * discAlpha).toFixed(3)})`
|
||||
ctx.lineWidth = 2.3
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Act 2: Three tilted orbital rings drawing into full orbits, expanding on Act 3 burst
|
||||
if (orbitReveal > 0.01) {
|
||||
const ringConfigs = [
|
||||
{ rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
|
||||
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
|
||||
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
|
||||
]
|
||||
for (let i = 0; i < ringConfigs.length; i += 1) {
|
||||
const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8)
|
||||
if (ringReveal <= 0.005) continue
|
||||
const ring = ringConfigs[i]
|
||||
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(cx, cy)
|
||||
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
|
||||
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.15
|
||||
ctx.beginPath()
|
||||
if (ringReveal >= 0.995) {
|
||||
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
|
||||
} else {
|
||||
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, a - ringReveal * Math.PI * 2, a)
|
||||
}
|
||||
ctx.stroke()
|
||||
|
||||
const sx = Math.cos(a) * ring.rx
|
||||
const sy = Math.sin(a) * ring.ry
|
||||
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * fade).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
}
|
||||
|
||||
// Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> radial scatter
|
||||
const oceanReveal = clamp01((coreReveal - 0.25) / 0.75)
|
||||
for (const pt of globePoints) {
|
||||
const p = projectSpherePoint(pt.lat, pt.lon, yaw, tiltX, rollZ)
|
||||
if (burst === 0 && p.nz < -0.22) continue
|
||||
|
||||
// On explosion, scatter outward radially & toward camera
|
||||
const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8)
|
||||
const jitterX = Math.cos(pt.shardAngle) * burst * 0.28
|
||||
const jitterY = Math.sin(pt.shardAngle) * burst * 0.28
|
||||
@@ -1030,7 +1077,7 @@ export function createDesktopSplashController(options: {
|
||||
const pz = p.nz + burst * pt.shardSpeed * 1.1
|
||||
|
||||
const depth = Math.max(0.25, perspD - pz)
|
||||
const screenScale = (radius * (perspD - 0.6)) / depth
|
||||
const screenScale = (radius * perspK) / depth
|
||||
const sx = cx + px * screenScale
|
||||
const sy = cy + py * screenScale
|
||||
if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) continue
|
||||
@@ -1038,23 +1085,29 @@ export function createDesktopSplashController(options: {
|
||||
const depthFade = p.nz >= 0 ? 1 : Math.max(0.14, 1 + p.nz * 2.2)
|
||||
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.36 : 1
|
||||
let color = '84, 146, 232'
|
||||
let baseAlpha = 0.28
|
||||
let pointGain = 0
|
||||
let dotR = 1.1
|
||||
if (pt.kind === 2) {
|
||||
color = '196, 240, 255'
|
||||
baseAlpha = 0.94
|
||||
dotR = 1.75
|
||||
const dawnShimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
|
||||
const dawnWeight = p.nz > 0.06 ? dawnIntensity * 0.58 * p.nz * dawnShimmer : 0
|
||||
const coreWeight = coreReveal * 0.94 * depthFade
|
||||
pointGain = Math.max(dawnWeight, coreWeight)
|
||||
dotR = 1.45 + coreReveal * 0.3
|
||||
} else if (pt.kind === 1) {
|
||||
color = '106, 188, 255'
|
||||
baseAlpha = 0.56
|
||||
pointGain = coreReveal * 0.56 * depthFade
|
||||
dotR = 1.3
|
||||
} else {
|
||||
pointGain = oceanReveal * 0.28 * depthFade
|
||||
}
|
||||
const alpha = baseAlpha * depthFade * polarFade * fade
|
||||
|
||||
const alpha = pointGain * polarFade * fade
|
||||
if (alpha <= 0.015) continue
|
||||
|
||||
if (burst > 0.03) {
|
||||
const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst)
|
||||
const prevScale = (radius * (perspD - 0.6)) / Math.max(0.3, perspD - p.nz)
|
||||
const prevScale = (radius * perspK) / Math.max(0.3, perspD - p.nz)
|
||||
const ox = cx + p.nx * prevBoost * prevScale
|
||||
const oy = cy + p.ny * prevBoost * prevScale
|
||||
ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})`
|
||||
@@ -1071,8 +1124,9 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
}
|
||||
|
||||
// Great-circle telemetry arcs across front hemisphere
|
||||
if (burst < 0.55) {
|
||||
// Intercontinental telemetry arcs across front hemisphere
|
||||
if (arcReveal > 0.01 && burst < 0.55) {
|
||||
const arcAlpha = arcReveal * fade * Math.max(0, 1 - burst * 1.6)
|
||||
for (const arc of ARC_DEFINITIONS) {
|
||||
const p1 = projectSpherePoint((arc.lat1 * Math.PI) / 180, (arc.lon1 * Math.PI) / 180, yaw, tiltX, rollZ)
|
||||
const p2 = projectSpherePoint((arc.lat2 * Math.PI) / 180, (arc.lon2 * Math.PI) / 180, yaw, tiltX, rollZ)
|
||||
@@ -1088,7 +1142,7 @@ export function createDesktopSplashController(options: {
|
||||
const cpx = cx + mx * radius * lift
|
||||
const cpy = cy + my * radius * lift
|
||||
|
||||
ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * fade).toFixed(3)})`
|
||||
ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * arcAlpha).toFixed(3)})`
|
||||
ctx.lineWidth = 1.25
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x1, y1)
|
||||
@@ -1099,14 +1153,14 @@ export function createDesktopSplashController(options: {
|
||||
const inv = 1 - u
|
||||
const px = inv * inv * x1 + 2 * inv * u * cpx + u * u * x2
|
||||
const py = inv * inv * y1 + 2 * inv * u * cpy + u * u * y2
|
||||
ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * fade).toFixed(3)})`
|
||||
ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * arcAlpha).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(px, py, 2.2, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
|
||||
// Shockwave ring on climax burst
|
||||
// Act 3: Climax shockwave ring on scatter burst
|
||||
if (burst > 0.005) {
|
||||
const shockR = radius * (0.88 + exitRatio * 5.2)
|
||||
ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})`
|
||||
@@ -1117,203 +1171,16 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
}
|
||||
|
||||
const drawConstellationScene = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
_w: number,
|
||||
_h: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
radius: number,
|
||||
elapsed: number,
|
||||
progress: number,
|
||||
exitRatio: number,
|
||||
) => {
|
||||
const irisScale = 1 + Math.pow(exitRatio, 1.55) * 2.1
|
||||
const fade = 1 - Math.pow(exitRatio, 1.8)
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * 0.34
|
||||
|
||||
// Outer calibrated compass reticle rings
|
||||
ctx.save()
|
||||
ctx.translate(cx, cy)
|
||||
ctx.scale(irisScale, irisScale)
|
||||
|
||||
const outerR = radius * 1.42
|
||||
const midR = radius * 1.2
|
||||
ctx.strokeStyle = `rgba(130, 198, 255, ${(0.22 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, outerR, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
|
||||
ctx.strokeStyle = `rgba(154, 214, 255, ${(0.36 * fade).toFixed(3)})`
|
||||
ctx.setLineDash([4, 6])
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, midR, -elapsed * 0.25, -elapsed * 0.25 + Math.PI * 1.65)
|
||||
ctx.stroke()
|
||||
ctx.setLineDash([])
|
||||
|
||||
// Progress calibration arc
|
||||
const sweepAngle = Math.max(0.08, progress * Math.PI * 2)
|
||||
ctx.strokeStyle = `rgba(126, 222, 255, ${(0.88 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 2.1
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, radius * 1.29, -Math.PI / 2, -Math.PI / 2 + sweepAngle)
|
||||
ctx.stroke()
|
||||
|
||||
// 72 degree graduation ticks
|
||||
for (let deg = 0; deg < 360; deg += 5) {
|
||||
const rad = (deg * Math.PI) / 180 + elapsed * 0.05
|
||||
const major = deg % 30 === 0
|
||||
const len = major ? 9 : 4
|
||||
ctx.strokeStyle = `rgba(170, 216, 255, ${((major ? 0.55 : 0.22) * fade).toFixed(3)})`
|
||||
ctx.lineWidth = major ? 1.3 : 0.85
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(Math.cos(rad) * (outerR - len), Math.sin(rad) * (outerR - len))
|
||||
ctx.lineTo(Math.cos(rad) * outerR, Math.sin(rad) * outerR)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Precision meridian & equator CAD wireframe + continental points
|
||||
ctx.strokeStyle = `rgba(104, 178, 245, ${(0.22 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 0.9
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, radius, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
for (const tilt of [-0.55, 0, 0.55]) {
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(0, 0, radius * Math.abs(Math.cos(tilt)), radius, 0, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
for (const pt of globePoints) {
|
||||
if (pt.kind === 0) continue
|
||||
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, 0)
|
||||
if (p.nz < 0) continue
|
||||
const sx = p.nx * radius
|
||||
const sy = p.ny * radius
|
||||
const isCoast = pt.kind === 2
|
||||
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
|
||||
ctx.fillStyle = isCoast
|
||||
? `rgba(216, 246, 255, ${(0.92 * polarFade * fade).toFixed(3)})`
|
||||
: `rgba(106, 186, 255, ${(0.42 * polarFade * fade).toFixed(3)})`
|
||||
ctx.fillRect(sx - (isCoast ? 1 : 0.7), sy - (isCoast ? 1 : 0.7), isCoast ? 2 : 1.4, isCoast ? 2 : 1.4)
|
||||
}
|
||||
|
||||
// Hangzhou target crosshair lock when front-facing
|
||||
const hz = projectSpherePoint((30.27 * Math.PI) / 180, (120.15 * Math.PI) / 180, yaw, -0.24, 0)
|
||||
if (hz.nz > 0.1) {
|
||||
const hx = hz.nx * radius
|
||||
const hy = hz.ny * radius
|
||||
ctx.strokeStyle = `rgba(255, 255, 255, ${(0.88 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.2
|
||||
ctx.strokeRect(hx - 6, hy - 6, 12, 12)
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(hx - 12, hy)
|
||||
ctx.lineTo(hx + 12, hy)
|
||||
ctx.moveTo(hx, hy - 12)
|
||||
ctx.lineTo(hx, hy + 12)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Keplerian satellites
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
ctx.save()
|
||||
ctx.rotate(-0.5 + i * 0.55)
|
||||
const rx = radius * 1.48
|
||||
const ry = radius * 0.42
|
||||
ctx.strokeStyle = `rgba(136, 206, 255, ${(0.24 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 0.9
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
|
||||
const theta = elapsed * (0.9 + i * 0.35) + i * 1.9
|
||||
const sx = Math.cos(theta) * rx
|
||||
const sy = Math.sin(theta) * ry
|
||||
ctx.fillStyle = `rgba(232, 249, 255, ${(0.95 * fade).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, 3, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
const drawHorizonScene = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
_w: number,
|
||||
_h: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
radius: number,
|
||||
elapsed: number,
|
||||
progress: number,
|
||||
exitRatio: number,
|
||||
) => {
|
||||
const fade = 1 - Math.pow(exitRatio, 2.0)
|
||||
const bloom = 1 + exitRatio * 0.55
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * 0.24
|
||||
const r = radius * 1.06 * bloom
|
||||
|
||||
// Volumetric atmospheric crescent corona behind dark planet
|
||||
const coronaOffsetAngle = -Math.PI * 0.65 + progress * Math.PI * 0.38
|
||||
const lx = cx + Math.cos(coronaOffsetAngle) * r * 0.72
|
||||
const ly = cy + Math.sin(coronaOffsetAngle) * r * 0.72
|
||||
const corona = ctx.createRadialGradient(lx, ly, r * 0.15, cx, cy, r * (1.85 + exitRatio * 1.4))
|
||||
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.92 * fade).toFixed(3)})`)
|
||||
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.52 * fade).toFixed(3)})`)
|
||||
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.16 * fade).toFixed(3)})`)
|
||||
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
|
||||
ctx.fillStyle = corona
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, r * (1.9 + exitRatio * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
|
||||
// Planetary shadow disc eclipsing the sun
|
||||
const discGrad = ctx.createRadialGradient(lx, ly, r * 0.55, cx, cy, r)
|
||||
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * fade).toFixed(3)})`)
|
||||
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * fade).toFixed(3)})`)
|
||||
ctx.fillStyle = discGrad
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, r * 0.99, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
|
||||
// Crisp luminous terminator limb sweep following progress
|
||||
ctx.save()
|
||||
ctx.strokeStyle = `rgba(222, 245, 255, ${(0.92 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 2.4
|
||||
ctx.shadowColor = 'rgba(148, 214, 255, 0.95)'
|
||||
ctx.shadowBlur = 18
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, r, coronaOffsetAngle - 0.85, coronaOffsetAngle + 0.85)
|
||||
ctx.stroke()
|
||||
ctx.restore()
|
||||
|
||||
// Subtle night-side coastline lights glimmering across the shadowed face
|
||||
for (const pt of globePoints) {
|
||||
if (pt.kind !== 2) continue
|
||||
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, -0.08)
|
||||
if (p.nz < 0.08) continue
|
||||
const shimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
|
||||
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
|
||||
const alpha = 0.56 * p.nz * shimmer * polarFade * fade
|
||||
if (alpha <= 0.02) continue
|
||||
ctx.fillStyle = `rgba(176, 224, 255, ${alpha.toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx + p.nx * r * 0.96, cy + p.ny * r * 0.96, 1.4, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
|
||||
const renderSceneFrame = (now: number, clampedProgress: number, exitRatio: number) => {
|
||||
if (!canvasEl || !rootEl) return
|
||||
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2)
|
||||
const width = window.innerWidth || 1280
|
||||
const height = window.innerHeight || 800
|
||||
const targetCanvasW = Math.max(1, Math.round(width * dpr))
|
||||
const targetCanvasH = Math.max(1, Math.round(height * dpr))
|
||||
const { dpr, width: targetCanvasW, height: targetCanvasH } = computeSplashCanvasSize(
|
||||
width,
|
||||
height,
|
||||
window.devicePixelRatio || 1,
|
||||
)
|
||||
if (canvasEl.width !== targetCanvasW || canvasEl.height !== targetCanvasH) {
|
||||
canvasEl.width = targetCanvasW
|
||||
canvasEl.height = targetCanvasH
|
||||
@@ -1347,7 +1214,7 @@ export function createDesktopSplashController(options: {
|
||||
const radius = Math.max(82, Math.min(width * 0.24, height * 0.21, 196))
|
||||
|
||||
if (exitRatio > 0) {
|
||||
if (reducedMotion || activeTheme === 'horizon') {
|
||||
if (reducedMotion) {
|
||||
rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(exitRatio, 1.35)).toFixed(3)}`
|
||||
} else {
|
||||
// Portal cutout expands from center while particle bursts continue radiating over edges
|
||||
@@ -1365,13 +1232,7 @@ export function createDesktopSplashController(options: {
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
|
||||
ctx.clearRect(0, 0, width, height)
|
||||
drawStars(ctx, width, height, elapsedSec, exitRatio, cx, cy)
|
||||
if (activeTheme === 'singularity') {
|
||||
drawSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
} else if (activeTheme === 'constellation') {
|
||||
drawConstellationScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
} else {
|
||||
drawHorizonScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
}
|
||||
drawDawnToSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1463,13 +1324,7 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
|
||||
const clampedProgress = Math.max(0, Math.min(1, displayProgress))
|
||||
const exitDuration = reducedMotion
|
||||
? 300
|
||||
: activeTheme === 'singularity'
|
||||
? 920
|
||||
: activeTheme === 'constellation'
|
||||
? 860
|
||||
: 900
|
||||
const exitDuration = reducedMotion ? 300 : 940
|
||||
const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0
|
||||
|
||||
renderSceneFrame(now, clampedProgress, exitRatio)
|
||||
|
||||
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user