Compare commits

...
1 Commits
Author SHA1 Message Date
linkong 3b1b9ef68c release: bump version to 0.83.0
ci / frontend (push) Waiting to run
ci / backend (push) Waiting to run
2026-12-02 18:53:58 +08:00
96 changed files with 8492 additions and 1021 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
0.82.0 0.83.0
+22
View File
@@ -29,11 +29,13 @@ from app.services.ai.tool_registry import (
safe_web_fetch, safe_web_fetch,
) )
from app.services.ai.workflow_evolver import ( from app.services.ai.workflow_evolver import (
FIXTURE_EXPECT_KEY,
compute_workflow_health, compute_workflow_health,
dismiss_ledger_entry, dismiss_ledger_entry,
get_evolution_ledger, get_evolution_ledger,
get_evolution_policy, get_evolution_policy,
incubate_workflow_from_runs, incubate_workflow_from_runs,
normalize_fixture_expect,
propose_meta_evolution, propose_meta_evolution,
propose_workflow_evolution, propose_workflow_evolution,
record_run_feedback, record_run_feedback,
@@ -176,6 +178,9 @@ class WorkflowFixtureCreateRequest(BaseModel):
earth_context: dict[str, Any] = Field(default_factory=dict) earth_context: dict[str, Any] = Field(default_factory=dict)
context_json: dict[str, Any] | None = None context_json: dict[str, Any] | None = None
sample_question: str = "" sample_question: str = ""
# Gradable assertions: numbers / must_include / must_not_include /
# require_uncertainty_without_evidence / min_evidence (stored in context_json["expect"]).
expect: dict[str, Any] | None = None
class AdvisorChatMessageInput(BaseModel): class AdvisorChatMessageInput(BaseModel):
@@ -421,6 +426,12 @@ async def create_ai_workflow_fixture(
ctx_payload = dict(payload.context_json if payload.context_json is not None else payload.earth_context or {}) 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: if payload.description.strip() and "_description" not in ctx_payload:
ctx_payload["_description"] = payload.description.strip() ctx_payload["_description"] = payload.description.strip()
expect = normalize_fixture_expect(
payload.expect if payload.expect is not None else ctx_payload.get(FIXTURE_EXPECT_KEY)
)
ctx_payload.pop(FIXTURE_EXPECT_KEY, None)
if expect:
ctx_payload[FIXTURE_EXPECT_KEY] = expect
row = AIWorkflowFixture( row = AIWorkflowFixture(
workflow_id=workflow_id, workflow_id=workflow_id,
name=payload.name.strip(), name=payload.name.strip(),
@@ -863,6 +874,7 @@ async def stream_advisor_playground_chat(
error_text = "" error_text = ""
resolved_model = str(payload.model_override or "").strip() resolved_model = str(payload.model_override or "").strip()
resolved_provider = "" resolved_provider = ""
verification: dict[str, Any] = {}
workflow_revision = 1 workflow_revision = 1
is_slash_cmd = effective_message.strip().startswith( is_slash_cmd = effective_message.strip().startswith(
("/bgp-brief", "/alerts-brief", "/situational-brief", "/locate") ("/bgp-brief", "/alerts-brief", "/situational-brief", "/locate")
@@ -996,6 +1008,8 @@ async def stream_advisor_playground_chat(
resolved_model = str(ev_data["model"]) resolved_model = str(ev_data["model"])
if ev_data.get("provider"): if ev_data.get("provider"):
resolved_provider = str(ev_data["provider"]) resolved_provider = str(ev_data["provider"])
if isinstance(ev_data.get("verification"), dict):
verification = ev_data["verification"]
elif ev_name == "error": elif ev_name == "error":
status_value = "failed" status_value = "failed"
error_text = str(ev_data.get("message") or "Workflow execution failed") error_text = str(ev_data.get("message") or "Workflow execution failed")
@@ -1035,6 +1049,14 @@ async def stream_advisor_playground_chat(
"provider": resolved_provider, "provider": resolved_provider,
"latency_ms": latency_ms, "latency_ms": latency_ms,
"workflow_revision": workflow_revision, "workflow_revision": workflow_revision,
**(
{
"verification_passed": bool(verification.get("passed", True)),
"verification_warnings": list(verification.get("warnings") or [])[:6],
}
if verification
else {}
),
}, },
error_message=error_text[:500], error_message=error_text[:500],
started_at=started_at, started_at=started_at,
@@ -1,7 +1,6 @@
"""Compute observations, administrator configuration and independent facility samples.""" """Compute observations, administrator configuration and independent facility samples."""
from datetime import UTC, datetime from datetime import UTC, datetime
from typing import Literal
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression from app.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.api.v1.visualization import convert_compute_centers_to_geojson
+35 -33
View File
@@ -44,7 +44,7 @@ from app.services.custom_datasource_runtime import (
) )
from app.services.datasource_connectivity import ( from app.services.datasource_connectivity import (
_resolve_aisstream_api_key, _resolve_aisstream_api_key,
_resolve_spacetrack_credentials_with_override, resolve_spacetrack_credentials,
get_builtin_connection_status, get_builtin_connection_status,
save_connectivity_success, save_connectivity_success,
strip_connectivity_validation, strip_connectivity_validation,
@@ -123,7 +123,10 @@ class DataSourceConfigCreate(BaseModel):
description: Optional[str] = None description: Optional[str] = None
source_type: str = Field(..., description="rest, websocket, http, api, database") source_type: str = Field(..., description="rest, websocket, http, api, database")
endpoint: str = Field(..., max_length=500) endpoint: str = Field(..., max_length=500)
auth_type: AuthType = Field(default=AuthType.NONE, description="none, bearer, api_key, basic") auth_type: AuthType = Field(
default=AuthType.NONE,
description="none, bearer, api_key, basic, oauth_client",
)
auth_config: dict = Field(default={}) auth_config: dict = Field(default={})
headers: dict = Field(default={}) headers: dict = Field(default={})
config: dict = Field(default={"timeout": 30, "retry": 3}) config: dict = Field(default={"timeout": 30, "retry": 3})
@@ -162,28 +165,6 @@ def _is_builtin_config_name(name: str | None) -> bool:
return bool(name and name in DEFAULT_DATASOURCES) return bool(name and name in DEFAULT_DATASOURCES)
async def _ensure_builtin_connection_verified(
db: AsyncSession,
config_data: DataSourceConfigCreate,
) -> None:
if not _is_builtin_config_name(config_data.name):
return
status_result = await get_builtin_connection_status(
db,
config_data.name,
config_data.endpoint,
config_data.auth_type,
config_data.headers,
config_data.config,
)
if not status_result.get("connected"):
raise HTTPException(
status_code=400,
detail=status_result.get("message") or "请先完成连接验证,再保存内置采集器配置。",
)
class CustomSampleRequest(BaseModel): class CustomSampleRequest(BaseModel):
datasource_config_id: Optional[int] = None datasource_config_id: Optional[int] = None
config: Optional[DataSourceConfigCreate] = None config: Optional[DataSourceConfigCreate] = None
@@ -543,12 +524,7 @@ async def reveal_builtin_config_secrets(
payload.update({"api_key": api_key, "api_key_source": api_key_source}) payload.update({"api_key": api_key, "api_key_source": api_key_source})
details.update({"api_key_configured": bool(api_key), "api_key_source": api_key_source}) details.update({"api_key_configured": bool(api_key), "api_key_source": api_key_source})
elif provider == "spacetrack": elif provider == "spacetrack":
if auth_config.get("username") or auth_config.get("password"): username, password, credential_source = await resolve_spacetrack_credentials(db)
username = str(auth_config.get("username") or "")
password = str(auth_config.get("password") or "")
credential_source = "datasource_config"
else:
username, password, credential_source = _resolve_spacetrack_credentials_with_override()
payload.update( payload.update(
{ {
"username": username, "username": username,
@@ -606,6 +582,32 @@ async def get_config(
} }
_SECRET_AUTH_KEYS = frozenset(
{"api_key", "client_secret", "password", "token", "access_token", "bearer_token"}
)
def _is_masked_secret(value: Any) -> bool:
if not isinstance(value, str):
return False
stripped = value.strip()
return bool(stripped) and set(stripped) <= {"•", "*"}
def _merge_auth_config(existing: dict[str, Any] | None, incoming: dict[str, Any] | None) -> dict[str, Any]:
"""Merge partial `auth_config` updates while preserving omitted or masked secrets."""
merged = dict(existing or {})
if not isinstance(incoming, dict):
return merged
for key, raw in incoming.items():
if key in _SECRET_AUTH_KEYS:
cleaned = str(raw or "").strip() if isinstance(raw, str) else raw
if not cleaned or _is_masked_secret(cleaned):
continue
merged[key] = raw
return merged
@router.post("/configs") @router.post("/configs")
async def create_config( async def create_config(
config_data: DataSourceConfigCreate, config_data: DataSourceConfigCreate,
@@ -619,7 +621,7 @@ async def create_config(
source_type=config_data.source_type, source_type=config_data.source_type,
endpoint=config_data.endpoint, endpoint=config_data.endpoint,
auth_type=config_data.auth_type, auth_type=config_data.auth_type,
auth_config=config_data.auth_config, auth_config=_merge_auth_config({}, config_data.auth_config),
headers=config_data.headers, headers=config_data.headers,
config=strip_connectivity_validation(config_data.config), config=strip_connectivity_validation(config_data.config),
) )
@@ -655,8 +657,8 @@ async def update_config(
for field, value in update_data.items(): for field, value in update_data.items():
if field == "config": if field == "config":
value = strip_connectivity_validation(value) value = strip_connectivity_validation(value)
if field == "auth_config" and value == {} and (config.auth_config or {}): if field == "auth_config":
continue value = _merge_auth_config(config.auth_config or {}, value)
setattr(config, field, value) setattr(config, field, value)
await db.commit() await db.commit()
+1 -20
View File
@@ -2,7 +2,7 @@ from copy import deepcopy
from datetime import UTC, datetime from datetime import UTC, datetime
import os import os
from pathlib import Path from pathlib import Path
from typing import Literal, Optional from typing import Optional
from urllib.parse import urlsplit from urllib.parse import urlsplit
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
@@ -70,7 +70,6 @@ from app.services.llm_model_catalog import (
LLMProviderCatalogConfigError, LLMProviderCatalogConfigError,
can_refresh_catalog_without_api_key, can_refresh_catalog_without_api_key,
catalog_error_message, catalog_error_message,
catalog_requires_api_key,
fetch_model_catalog, fetch_model_catalog,
) )
from app.services.scheduler import sync_datasource_job from app.services.scheduler import sync_datasource_job
@@ -759,24 +758,6 @@ def _runtime_config_from_ai_payload(ai_payload: dict) -> dict:
} }
def _ai_provider_runtime_fingerprint(ai_payload: dict) -> dict:
runtime_config = _runtime_config_from_ai_payload(ai_payload)
llm_config = runtime_config.get("llm_config") or {}
return {
"service_url": runtime_config.get("service_url") or "",
"service_token": runtime_config.get("service_token") or "",
"timeout_seconds": int(runtime_config.get("timeout_seconds") or 0),
"retry_attempts": int(runtime_config.get("retry_attempts") or 0),
"provider": llm_config.get("provider") or "",
"provider_api": llm_config.get("provider_api") or "",
"base_url": llm_config.get("base_url") or "",
"model": llm_config.get("model") or "",
"api_key": llm_config.get("api_key") or "",
"max_tokens": int(llm_config.get("max_tokens") or 0),
"anthropic_version": llm_config.get("anthropic_version") or "",
}
async def _validate_ai_provider_full_connection(ai_payload: dict) -> dict: async def _validate_ai_provider_full_connection(ai_payload: dict) -> dict:
runtime_config = _runtime_config_from_ai_payload(ai_payload) runtime_config = _runtime_config_from_ai_payload(ai_payload)
client = AIProviderClient( client = AIProviderClient(
+4 -4
View File
@@ -14,10 +14,10 @@ fao:
landing_point_url: "https://data.apps.fao.org/catalog/dataset/1b75ff21-92f2-4b96-9b7b-98e8aa65ad5d/resource/b6071077-d1d4-4e97-aa00-42e902847c87/download/landing-point-geo.csv" landing_point_url: "https://data.apps.fao.org/catalog/dataset/1b75ff21-92f2-4b96-9b7b-98e8aa65ad5d/resource/b6071077-d1d4-4e97-aa00-42e902847c87/download/landing-point-geo.csv"
telegeography: telegeography:
# TeleGeography 海缆/系统主数据源,当前使用 GitHub 镜像 JSON # TeleGeography 官方海缆/系统 JSON 接口
cable_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/cable.json" cable_url: "https://www.submarinecablemap.com/api/v3/cable/all.json"
# TeleGeography 登陆点主数据源,当前使用 GitHub 镜像 JSON # TeleGeography 官方登陆点 GeoJSON 接口
landing_point_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/landing_point.json" landing_point_url: "https://www.submarinecablemap.com/api/v3/landing-point/landing-point-geo.json"
# TeleGeography 历史 API 存档,用于 cable collector 的 fallback # TeleGeography 历史 API 存档,用于 cable collector 的 fallback
archived_cable_url: "https://web.archive.org/web/2024/https://www.submarinecablemap.com/api/v3/cable" archived_cable_url: "https://web.archive.org/web/2024/https://www.submarinecablemap.com/api/v3/cable"
# TeleGeography 官网页面,用于 cable collector 的最终 HTML 抓取 fallback # TeleGeography 官网页面,用于 cable collector 的最终 HTML 抓取 fallback
+1 -1
View File
@@ -161,7 +161,7 @@ DEFAULT_DATASOURCES = {
"is_free": True, "is_free": True,
"requires_credentials": True, "requires_credentials": True,
"credential_provider": "spacetrack", "credential_provider": "spacetrack",
"credential_status": "planned", "credential_status": "supported",
}, },
"celestrak_tle": { "celestrak_tle": {
"id": 20, "id": 20,
+1
View File
@@ -217,6 +217,7 @@ class AuthType(StrEnum):
BEARER = "bearer" BEARER = "bearer"
API_KEY = "api_key" API_KEY = "api_key"
BASIC = "basic" BASIC = "basic"
OAUTH_CLIENT = "oauth_client"
class TVSourceType(StrEnum): class TVSourceType(StrEnum):
+3
View File
@@ -52,6 +52,9 @@ class AIWorkflow(Base):
"published_graph": self.published_graph or {}, "published_graph": self.published_graph or {},
"draft_graph": self.draft_graph, "draft_graph": self.draft_graph,
"bindings": self.bindings or {}, "bindings": self.bindings or {},
"draft_bindings": (
self.draft_graph.get("bindings") if isinstance(self.draft_graph, dict) else None
),
"updated_by": self.updated_by, "updated_by": self.updated_by,
"created_at": to_iso8601_utc(self.created_at), "created_at": to_iso8601_utc(self.created_at),
"updated_at": to_iso8601_utc(self.updated_at), "updated_at": to_iso8601_utc(self.updated_at),
+337 -37
View File
@@ -10,6 +10,12 @@ from typing import Any, AsyncIterator
from app.core.logging import get_logger from app.core.logging import get_logger
from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest
from app.services.ai.scene_directives import (
INFLUENCE_ZONE_GUIDANCE,
consume_text_holding_scene_tag,
extract_planet_scene_from_text,
merge_scene_specs,
)
from app.services.ai.thinking_sanitizer import strip_thinking_text from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.ai.tool_registry import ( from app.services.ai.tool_registry import (
TimeBasis, TimeBasis,
@@ -23,7 +29,7 @@ from app.services.ai.tool_registry import (
query_vessel_posture_tool, query_vessel_posture_tool,
safe_web_fetch, safe_web_fetch,
) )
from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES, _extract_first_json_object
from app.services.compute_center_locations import build_compute_center_location_query from app.services.compute_center_locations import build_compute_center_location_query
from app.services.location.agent_resolver import run_l1_structured_facility_resolvers from app.services.location.agent_resolver import run_l1_structured_facility_resolvers
@@ -101,24 +107,44 @@ def render_workflow_template(
return _TEMPLATE_VAR_RE.sub(lambda m: _lookup(m.group(1)), raw) return _TEMPLATE_VAR_RE.sub(lambda m: _lookup(m.group(1)), raw)
def _extract_target_ids_and_codes( def _target_entity_type(target: dict[str, Any]) -> str:
return str(target.get("entity_type") or target.get("type") or "").strip().lower()
def _target_id_for_types(
targets: list[dict[str, Any]], targets: list[dict[str, Any]],
earth_context: dict[str, Any], entity_types: frozenset[str],
) -> tuple[str | None, list[str], str]: ) -> str | None:
first = targets[0] if targets else {} """Return the ID of the first selected target whose type matches `entity_types`.
primary_id = str(
first.get("entity_id") Each data source must query its own object: a multi-select of cable + vessel + BGP
or first.get("id") must never leak the cable ID into the vessel or BGP lookup, regardless of click order.
or earth_context.get("entity_id") """
or "" for target in targets:
).strip() or None if _target_entity_type(target) in entity_types:
raw = str(target.get("entity_id") or target.get("id") or "").strip()
if raw:
return raw
return None
def _extract_codes_and_mode(earth_context: dict[str, Any]) -> tuple[list[str], str]:
codes = earth_context.get("selected_codes") codes = earth_context.get("selected_codes")
if not isinstance(codes, list) or not codes: if not isinstance(codes, list) or not codes:
codes = ["CN", "US"] codes = ["CN", "US"]
else: else:
codes = [str(c).strip().upper() for c in codes if str(c).strip()][:12] or ["CN", "US"] codes = [str(c).strip().upper() for c in codes if str(c).strip()][:12] or ["CN", "US"]
mode = str(earth_context.get("mode") or "global_share") mode = str(earth_context.get("mode") or "global_share")
return primary_id, codes, mode return codes, mode
_BGP_ENTITY_TYPES = frozenset({"bgp"})
_CABLE_ENTITY_TYPES = frozenset({"cable", "landing_point"})
_SATELLITE_ENTITY_TYPES = frozenset({"satellite"})
_VESSEL_ENTITY_TYPES = frozenset({"vessel"})
_COMPUTE_FACILITY_TYPES = frozenset(
{"supercomputer", "gpu_cluster", "data_center", "cloud_center", "edge_node", "compute_center_unresolved"}
)
async def _execute_tool( async def _execute_tool(
@@ -131,7 +157,7 @@ async def _execute_tool(
allow_external_tools: bool, allow_external_tools: bool,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Execute one whitelisted read-only or controlled external tool cleanly.""" """Execute one whitelisted read-only or controlled external tool cleanly."""
primary_id, codes, mode = _extract_target_ids_and_codes(targets, earth_context) codes, mode = _extract_codes_and_mode(earth_context)
time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment] time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment]
if time_basis not in {"live", "as_known_then", "retrospective"}: if time_basis not in {"live", "as_known_then", "retrospective"}:
time_basis = "retrospective" time_basis = "retrospective"
@@ -158,7 +184,7 @@ async def _execute_tool(
if tool_id == "query_bgp_incidents": if tool_id == "query_bgp_incidents":
incidents = await query_bgp_incidents_tool( incidents = await query_bgp_incidents_tool(
db, db,
incident_key=primary_id if any(t.get("entity_type") == "bgp" for t in targets) else None, incident_key=_target_id_for_types(targets, _BGP_ENTITY_TYPES),
limit=8, limit=8,
time_basis=time_basis, time_basis=time_basis,
cutoff_at=cutoff_at, cutoff_at=cutoff_at,
@@ -169,32 +195,32 @@ async def _execute_tool(
db, db,
time_basis=time_basis, time_basis=time_basis,
cutoff_at=cutoff_at, cutoff_at=cutoff_at,
entity_id=primary_id if any(t.get("entity_type") in {"cable", "landing_point"} for t in targets) else None, entity_id=_target_id_for_types(targets, _CABLE_ENTITY_TYPES),
) )
if tool_id == "query_satellite_posture": if tool_id == "query_satellite_posture":
return await query_satellite_posture_tool( return await query_satellite_posture_tool(
db, db,
time_basis=time_basis, time_basis=time_basis,
cutoff_at=cutoff_at, cutoff_at=cutoff_at,
entity_id=primary_id if any(t.get("entity_type") == "satellite" for t in targets) else None, entity_id=_target_id_for_types(targets, _SATELLITE_ENTITY_TYPES),
) )
if tool_id == "query_vessel_posture": if tool_id == "query_vessel_posture":
return await query_vessel_posture_tool( return await query_vessel_posture_tool(
db, db,
time_basis=time_basis, time_basis=time_basis,
cutoff_at=cutoff_at, cutoff_at=cutoff_at,
entity_id=primary_id if any(t.get("entity_type") == "vessel" for t in targets) else None, entity_id=_target_id_for_types(targets, _VESSEL_ENTITY_TYPES),
) )
if tool_id == "query_recent_earth_news": if tool_id == "query_recent_earth_news":
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {} news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
region = str(news_ctx.get("region_key") or "").strip() or None region = str(news_ctx.get("region_key") or "").strip() or None
return await query_recent_earth_news_tool(db, region=region, limit=10) return await query_recent_earth_news_tool(db, region=region, limit=10)
if tool_id in _L1_KNOWLEDGE_TOOL_IDS: if tool_id in _L1_KNOWLEDGE_TOOL_IDS:
target_name = str( facility = next(
(targets[0].get("label") if targets else "") (t for t in targets if _target_entity_type(t) in _COMPUTE_FACILITY_TYPES),
or question targets[0] if targets else {},
or "Unknown Facility" )
).strip() target_name = str(facility.get("label") or question or "Unknown Facility").strip()
query = build_compute_center_location_query(name=target_name) query = build_compute_center_location_query(name=target_name)
candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db) candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db)
return { return {
@@ -320,13 +346,21 @@ def _has_downstream_llm(
return False return False
TRIGGER_SOURCES = frozenset({"interactive", "ingest"})
def _eval_edge_condition( def _eval_edge_condition(
edge: dict[str, Any], edge: dict[str, Any],
pred_state: dict[str, Any], pred_state: dict[str, Any],
targets: list[dict[str, Any]], targets: list[dict[str, Any]],
trigger_source: str = "interactive",
) -> bool: ) -> bool:
cond = str(edge.get("condition") or "always").strip() cond = str(edge.get("condition") or "always").strip()
if cond in {"always", "", "interactive", "ingest", "not_terminal", "high_confidence_hit", "fallback_to_agent"}: if cond in TRIGGER_SOURCES:
# Background RSS ingest and user-clicked analysis share one graph; only the branch
# matching the actual trigger may run (avoids a second model call and leaked JSON).
return cond == trigger_source
if cond in {"always", "", "not_terminal", "high_confidence_hit", "fallback_to_agent"}:
return True return True
if cond == "on_empty_or_low_confidence": if cond == "on_empty_or_low_confidence":
return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6 return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6
@@ -364,6 +398,145 @@ def _build_deterministic_fallback_markdown(
return "\n".join(lines).strip() return "\n".join(lines).strip()
# Prompt keys whose LLM contract is a strict JSON object (rendered as cards, never streamed raw).
COMPUTE_BRIEF_PROMPT_KEY = "compute.posture.brief"
_STRUCTURED_JSON_PROMPT_KEYS = frozenset({COMPUTE_BRIEF_PROMPT_KEY})
_COMPUTE_BRIEF_SCHEMA_HINT = (
"严格输出单个紧凑 JSON 对象(不加围栏外文字),字段结构:\n"
'{"headline": str, "headline_en": str, "executive_assertion": str, "executive_assertion_en": str, '
'"causes": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], '
'"breakthrough_levers": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], '
'"blind_spots": [str], "evidence_ids": [str]};所有 evidence_ids 必须来自 context.evidence。'
)
_EVIDENCE_GAP_SUGGESTIONS = (
"补充一手信源(运营商公告、BGP 采集器原始记录、官方通报)后复核成因",
"核对事件时间窗与受影响前缀 / 资产是否与所选对象一致",
)
def _node_wants_structured_json(node: dict[str, Any]) -> bool:
params = node.get("params") if isinstance(node.get("params"), dict) else {}
return (
str(node.get("prompt_key") or "") in _STRUCTURED_JSON_PROMPT_KEYS
or str(params.get("output_format") or "").strip().lower() == "json"
)
def _compute_series_from_tools(tool_results: dict[str, Any]) -> dict[str, Any] | None:
series = tool_results.get("query_compute_posture")
if not isinstance(series, dict) or series.get("error"):
return None
if not series.get("compute") and not series.get("years"):
return None
return series
def _resolve_compute_brief(
parsed: dict[str, Any] | None,
series: dict[str, Any],
) -> tuple[Any, bool]:
"""Validate an LLM compute brief against verified evidence; fall back to the deterministic baseline."""
from app.services.ai.posture_agent import (
StrategicPostureBrief,
build_deterministic_posture_brief,
verify_brief_citations,
)
if isinstance(parsed, dict):
try:
brief = StrategicPostureBrief.model_validate(parsed)
return verify_brief_citations(brief, series.get("evidence") or {}), True
except Exception as exc:
logger.warning_event(
"Compute brief failed schema or citation verification; using deterministic baseline",
event="ai_dag.compute_brief.fallback",
context={"error": str(exc)[:300]},
)
return build_deterministic_posture_brief(series), False
def _render_structured_markdown(parsed: dict[str, Any]) -> str:
"""Render a structured JSON analysis (e.g. StrategicPostureBrief) as readable Markdown."""
lines: list[str] = []
headline = str(parsed.get("headline") or parsed.get("title") or "").strip()
if headline:
lines.append(f"### {headline}")
assertion = str(
parsed.get("executive_assertion") or parsed.get("summary") or parsed.get("answer_markdown") or ""
).strip()
if assertion:
lines.extend(["", assertion])
for key, label in (
("key_judgments", "核心判断"),
("causes", "成因归因"),
("breakthrough_levers", "突破杠杆"),
):
items = parsed.get(key)
if not isinstance(items, list) or not items:
continue
lines.extend(["", f"**{label}**"])
for item in items[:6]:
if isinstance(item, dict):
item_label = str(item.get("label") or item.get("title") or "").strip()
detail = str(item.get("detail") or item.get("text") or "").strip()
if item_label and detail:
lines.append(f"- **{item_label}**:{detail}")
elif item_label or detail:
lines.append(f"- {item_label or detail}")
elif str(item).strip():
lines.append(f"- {str(item).strip()}")
blind_spots = [str(b).strip() for b in (parsed.get("blind_spots") or []) if str(b).strip()]
if blind_spots:
lines.extend(["", "**待核实盲区**", *[f"- {b}" for b in blind_spots[:4]]])
return "\n".join(lines).strip()
def _compile_compute_workbench(
series: dict[str, Any],
brief: Any,
earth_context: dict[str, Any],
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
"""Compile the existing compute `ViewSpec` workbench (trend + matrix) from verified series."""
from app.services.ai.workflow_runtime import compile_compute_view_spec
codes, mode = _extract_codes_and_mode(earth_context)
try:
view, scene = compile_compute_view_spec(
codes=codes,
mode=mode,
series=series,
posture={"payload": brief.model_dump(mode="json")},
)
except Exception as exc:
logger.warning_event(
"Compute workbench compilation failed",
event="ai_dag.compute_view_spec.failed",
context={"error": str(exc)[:300]},
)
return None, None
return view.model_dump(mode="json"), scene.model_dump(mode="json")
def _build_evidence_gap_markdown(tool_results: dict[str, Any], warnings: list[str]) -> str:
"""User-facing block delivered when an evidence guardrail fails: cause pending + follow-ups."""
pending: list[str] = []
for tid, res in tool_results.items():
if not isinstance(res, dict):
continue
if res.get("error") or res.get("skipped") or not _has_meaningful_tool_data({tid: res}):
pending.append(f"`{tid}` 未返回可溯源数据,需人工补查")
pending.extend(_EVIDENCE_GAP_SUGGESTIONS)
reason = ";".join(warnings) or "缺少结构化证据"
lines = [
"",
"",
f"> **证据校验未通过({reason})**:以上成因判断一律视为「原因待核实」,不作为定论。",
"> **待查项**:",
*[f"> - {item}" for item in pending[:6]],
]
return "\n".join(lines)
async def run_workflow_dag_stream( async def run_workflow_dag_stream(
*, *,
db: Any, db: Any,
@@ -381,12 +554,19 @@ async def run_workflow_dag_stream(
model_override: str | None = None, model_override: str | None = None,
allow_external_tools: bool = False, allow_external_tools: bool = False,
extra_meta: dict[str, Any] | None = None, extra_meta: dict[str, Any] | None = None,
trigger_source: str = "interactive",
cancel_event: asyncio.Event | None = None,
) -> AsyncIterator[dict[str, Any]]: ) -> AsyncIterator[dict[str, Any]]:
"""Execute a workflow DAG topologically and emit structured SSE-ready events.""" """Execute a workflow DAG topologically and emit structured SSE-ready events."""
if trigger_source not in TRIGGER_SOURCES:
trigger_source = "interactive"
wf_id = str(workflow.get("workflow_id") or "default.general") wf_id = str(workflow.get("workflow_id") or "default.general")
wf_name = str(workflow.get("name") or wf_id) wf_name = str(workflow.get("name") or wf_id)
active_rev = int(workflow.get("active_revision") or 1) active_rev = int(workflow.get("active_revision") or 1)
bindings = workflow.get("bindings") if isinstance(workflow.get("bindings"), dict) else {} bindings = workflow.get("bindings") if isinstance(workflow.get("bindings"), dict) else {}
draft_graph = workflow.get("draft_graph")
if use_draft and isinstance(draft_graph, dict) and isinstance(draft_graph.get("bindings"), dict):
bindings = draft_graph["bindings"]
graph = ( graph = (
workflow.get("draft_graph") workflow.get("draft_graph")
if use_draft and isinstance(workflow.get("draft_graph"), dict) if use_draft and isinstance(workflow.get("draft_graph"), dict)
@@ -438,9 +618,17 @@ async def run_workflow_dag_stream(
resolved_provider: str | None = None resolved_provider: str | None = None
resolved_model: str | None = None resolved_model: str | None = None
scene_spec: dict[str, Any] | None = None scene_spec: dict[str, Any] | None = None
parsed_dag_scene: dict[str, Any] | None = None
view_spec: dict[str, Any] | None = None
compute_brief: Any = None
compute_brief_llm_verified = False
guardrail_ran = False
guardrail_warnings: list[str] = []
last_llm_output: str = "" last_llm_output: str = ""
for node in ordered_nodes: for node in ordered_nodes:
if cancel_event is not None and cancel_event.is_set():
return
nid = str(node["id"]) nid = str(node["id"])
ntype = str(node.get("node_type") or "llm_agent") ntype = str(node.get("node_type") or "llm_agent")
ntitle = str(node.get("title") or nid) ntitle = str(node.get("title") or nid)
@@ -453,7 +641,7 @@ async def run_workflow_dag_stream(
pred_state = node_states.get(pred_id) pred_state = node_states.get(pred_id)
if not pred_state or pred_state.get("skipped"): if not pred_state or pred_state.get("skipped"):
continue continue
if _eval_edge_condition(edge, pred_state, clean_targets): if _eval_edge_condition(edge, pred_state, clean_targets, trigger_source):
passed = True passed = True
break break
if not passed: if not passed:
@@ -560,7 +748,23 @@ async def run_workflow_dag_stream(
f"{node_prompt}\n\n用户请求:{effective_question or question}" f"{node_prompt}\n\n用户请求:{effective_question or question}"
if node_prompt if node_prompt
else (effective_question or question) else (effective_question or question)
).strip() )
structured = _node_wants_structured_json(node)
is_compute_brief = str(node.get("prompt_key") or "") == COMPUTE_BRIEF_PROMPT_KEY
if is_compute_brief:
objective = f"{objective}\n\n{_COMPUTE_BRIEF_SCHEMA_HINT}"
wants_scene_zones = (
not has_next_llm
and not structured
and (wf_id.startswith("earth.") or bool(clean_earth_ctx) or bool(clean_targets))
)
if wants_scene_zones:
sys_prompt = f"{sys_prompt}\n\n{INFLUENCE_ZONE_GUIDANCE}".strip()
objective = (
f"{objective}\n\n"
"【空间联动提醒】若本回答涉及任何明确国家、地区、海域走廊或地理影响范围,请务必按系统指令在正文最末尾另起一行附带 <planet_scene>...</planet_scene>。"
)
objective = objective.strip()
# Execute any extra read-only tools configured directly on the LLM node before inference. # Execute any extra read-only tools configured directly on the LLM node before inference.
node_tool_results: dict[str, Any] = {} node_tool_results: dict[str, Any] = {}
@@ -592,6 +796,8 @@ async def run_workflow_dag_stream(
} }
if clean_earth_ctx: if clean_earth_ctx:
ctx_payload["earth_context"] = clean_earth_ctx ctx_payload["earth_context"] = clean_earth_ctx
if wants_scene_zones:
ctx_payload["scene_overlay_guidance"] = INFLUENCE_ZONE_GUIDANCE
if attachments: if attachments:
ctx_payload["attachments"] = attachments[:8] ctx_payload["attachments"] = attachments[:8]
@@ -626,14 +832,23 @@ async def run_workflow_dag_stream(
images=parsed_images, images=parsed_images,
) )
compute_series = _compute_series_from_tools(tool_results) if is_compute_brief else None
if not ai_ready or ai_client is None: if not ai_ready or ai_client is None:
fallback_md = _build_deterministic_fallback_markdown( if compute_series is not None and not has_next_llm:
workflow_name=wf_name, compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, compute_series)
question=effective_question or question, fallback_md = (
targets=clean_targets, _render_structured_markdown(compute_brief.model_dump(mode="json"))
tool_results=tool_results, + "\n\n> 当前未配置可用 AI Provider,以上为基于已核验算力台账的确定性研判。"
ai_configured=False, )
) else:
fallback_md = _build_deterministic_fallback_markdown(
workflow_name=wf_name,
question=effective_question or question,
targets=clean_targets,
tool_results=tool_results,
ai_configured=False,
)
node_outputs[nid] = fallback_md node_outputs[nid] = fallback_md
node_states[nid] = {"skipped": False, "confidence": 0.65, "is_empty": False} node_states[nid] = {"skipped": False, "confidence": 0.65, "is_empty": False}
executed_trace.append(nid) executed_trace.append(nid)
@@ -647,8 +862,13 @@ async def run_workflow_dag_stream(
continue continue
timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300)) timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300))
if has_next_llm: if cancel_event is not None and cancel_event.is_set():
return
if has_next_llm or structured:
# Intermediate nodes and strict-JSON nodes run non-streaming so raw JSON never reaches the user.
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec) resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec)
if cancel_event is not None and cancel_event.is_set():
return
clean_text, inline_thoughts = strip_thinking_text(str(getattr(resp, "content", "") or "")) clean_text, inline_thoughts = strip_thinking_text(str(getattr(resp, "content", "") or ""))
node_outputs[nid] = clean_text or str(getattr(resp, "content", "") or "") node_outputs[nid] = clean_text or str(getattr(resp, "content", "") or "")
if node_outputs[nid]: if node_outputs[nid]:
@@ -660,6 +880,22 @@ async def run_workflow_dag_stream(
final_reasoning_md = final_reasoning_md.strip() final_reasoning_md = final_reasoning_md.strip()
generation_mode = "llm_verified" generation_mode = "llm_verified"
zero_token = False zero_token = False
if structured and not has_next_llm:
parsed = _extract_first_json_object(node_outputs[nid])
narrative = ""
if compute_series is not None:
compute_brief, compute_brief_llm_verified = _resolve_compute_brief(parsed, compute_series)
narrative = _render_structured_markdown(compute_brief.model_dump(mode="json"))
if not compute_brief_llm_verified:
narrative += "\n\n> 模型结论未通过结构或证据 ID 核验,已改用已核验台账的确定性研判。"
elif parsed:
narrative = _render_structured_markdown(parsed)
narrative = narrative.strip() or node_outputs[nid].strip()
node_outputs[nid] = narrative
last_llm_output = narrative
final_answer_md = narrative
if narrative:
yield {"event": "text", "data": {"delta": narrative}}
node_states[nid] = { node_states[nid] = {
"skipped": False, "skipped": False,
"confidence": 0.85 if node_outputs[nid] else 0.4, "confidence": 0.85 if node_outputs[nid] else 0.4,
@@ -673,10 +909,13 @@ async def run_workflow_dag_stream(
else: else:
text_parts: list[str] = [] text_parts: list[str] = []
reasoning_parts: list[str] = [] reasoning_parts: list[str] = []
pending_scene_tail = ""
resolved_provider = provider_name or None resolved_provider = provider_name or None
resolved_model = preferred_model or default_model or None resolved_model = preferred_model or default_model or None
async for ev in ai_client.stream_analyze(req, request_id=run_id): async for ev in ai_client.stream_analyze(req, request_id=run_id):
if request is not None and await request.is_disconnected(): if (cancel_event is not None and cancel_event.is_set()) or (
request is not None and await request.is_disconnected()
):
return return
ev_type = str(ev.get("event") or "") ev_type = str(ev.get("event") or "")
if ev_type == "start": if ev_type == "start":
@@ -691,7 +930,10 @@ async def run_workflow_dag_stream(
elif ev_type == "text" and ev.get("delta"): elif ev_type == "text" and ev.get("delta"):
delta = str(ev["delta"]) delta = str(ev["delta"])
text_parts.append(delta) text_parts.append(delta)
yield {"event": "text", "data": {"delta": delta}} combined_buf = pending_scene_tail + delta
emit_chunk, pending_scene_tail = consume_text_holding_scene_tag(combined_buf)
if emit_chunk:
yield {"event": "text", "data": {"delta": emit_chunk}}
elif ev_type == "done": elif ev_type == "done":
if isinstance(ev.get("provider"), str) and ev["provider"]: if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"] resolved_provider = ev["provider"]
@@ -701,9 +943,29 @@ async def run_workflow_dag_stream(
err_msg = str(ev.get("message") or ev.get("detail") or "AI stream error") err_msg = str(ev.get("message") or ev.get("detail") or "AI stream error")
raise RuntimeError(err_msg) raise RuntimeError(err_msg)
if pending_scene_tail:
cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail)
if cleaned_tail:
yield {"event": "text", "data": {"delta": cleaned_tail}}
if cancel_event is not None and cancel_event.is_set():
return
raw_text = "".join(text_parts) raw_text = "".join(text_parts)
clean_text, inline_thoughts = strip_thinking_text(raw_text) clean_text, inline_thoughts = strip_thinking_text(raw_text)
final_answer_md = (clean_text or raw_text).strip() stripped_answer, node_parsed_scene = extract_planet_scene_from_text(clean_text or raw_text)
if node_parsed_scene:
parsed_dag_scene = node_parsed_scene
logger.info_event(
"DAG LLM node emitted scene directives",
event="ai_dag.scene.extracted",
context={
"workflow_id": wf_id,
"run_id": run_id,
"node_id": nid,
"zones_count": len(node_parsed_scene.get("influence_zones") or []),
},
)
final_answer_md = stripped_answer.strip()
if inline_thoughts: if inline_thoughts:
reasoning_parts.extend(inline_thoughts) reasoning_parts.extend(inline_thoughts)
if reasoning_parts: if reasoning_parts:
@@ -746,6 +1008,14 @@ async def run_workflow_dag_stream(
extra_block = f"\n\n> {disclaimer}" extra_block = f"\n\n> {disclaimer}"
final_answer_md += extra_block final_answer_md += extra_block
yield {"event": "text", "data": {"delta": extra_block}} yield {"event": "text", "data": {"delta": extra_block}}
guardrail_ran = True
if not passed:
guardrail_warnings.extend(w for w in warnings if w not in guardrail_warnings)
if gr.get("require_evidence") and not evidence:
# Evidence-required analyses must not present unverified causes as conclusions.
gap_block = _build_evidence_gap_markdown(tool_results, warnings)
final_answer_md += gap_block
yield {"event": "text", "data": {"delta": gap_block}}
node_states[nid] = { node_states[nid] = {
"skipped": False, "skipped": False,
"confidence": 0.95 if passed else 0.45, "confidence": 0.95 if passed else 0.45,
@@ -785,6 +1055,14 @@ async def run_workflow_dag_stream(
if t.get("entity_id") or t.get("id") if t.get("entity_id") or t.get("id")
], ],
} }
wants_compute_view = compute_brief is not None or str(params.get("view_spec") or "") == "compute"
series_for_view = _compute_series_from_tools(tool_results) if wants_compute_view else None
if series_for_view is not None:
if compute_brief is None:
compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, series_for_view)
view_spec, compute_scene = _compile_compute_workbench(series_for_view, compute_brief, clean_earth_ctx)
if scene_spec is None and compute_scene is not None:
scene_spec = compute_scene
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False} node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
executed_trace.append(nid) executed_trace.append(nid)
yield { yield {
@@ -802,13 +1080,33 @@ async def run_workflow_dag_stream(
) )
yield {"event": "text", "data": {"delta": final_answer_md}} yield {"event": "text", "data": {"delta": final_answer_md}}
if parsed_dag_scene:
dag_domain = str((clean_earth_ctx or {}).get("domain") or "global")
scene_spec = merge_scene_specs(scene_spec, parsed_dag_scene, domain=dag_domain)
if view_spec is not None:
# Late `meta` patch: the Earth copilot already applies `view_spec` from meta events to render
# trend/matrix workbench cards; the DAG only knows the spec after the series + brief nodes ran.
yield {
"event": "meta",
"data": {"run_id": run_id, "domain": "compute", "view_spec": view_spec, "scene_spec": scene_spec},
}
if isinstance(scene_spec, dict) and (scene_spec.get("influence_zones") or parsed_dag_scene):
yield {"event": "scene", "data": {"scene_spec": scene_spec}}
verification = {
"guardrail_ran": guardrail_ran,
"passed": not guardrail_warnings,
"warnings": guardrail_warnings,
}
yield { yield {
"event": "done", "event": "done",
"data": { "data": {
"run_id": run_id, "run_id": run_id,
"workflow_id": wf_id, "workflow_id": wf_id,
"workflow_name": wf_name, "workflow_name": wf_name,
"status": "completed", "status": "completed" if not guardrail_warnings else "unverified",
"generation_mode": generation_mode, "generation_mode": generation_mode,
"zero_token": zero_token, "zero_token": zero_token,
"provider": resolved_provider, "provider": resolved_provider,
@@ -816,6 +1114,8 @@ async def run_workflow_dag_stream(
"nodes": executed_trace, "nodes": executed_trace,
"evidence": evidence, "evidence": evidence,
"scene_spec": scene_spec, "scene_spec": scene_spec,
"view_spec": view_spec,
"verification": verification,
"answer_markdown": final_answer_md, "answer_markdown": final_answer_md,
"reasoning_markdown": final_reasoning_md, "reasoning_markdown": final_reasoning_md,
"text_length": len(final_answer_md), "text_length": len(final_answer_md),
+150
View File
@@ -0,0 +1,150 @@
"""Shared `<planet_scene>` prompt guidance and streaming extraction for Earth Influence Zones."""
from __future__ import annotations
import json
import re
from typing import Any
from app.core.logging import get_logger
from app.services.ai.workflow_runtime import validate_influence_zones
logger = get_logger(__name__, service="ai_scene")
PLANET_SCENE_TAG_OPEN = "<planet_scene>"
PLANET_SCENE_RE = re.compile(r"<planet_scene>\s*(.*?)\s*</planet_scene>", re.DOTALL | re.IGNORECASE)
PLANET_SCENE_OPEN_RE = re.compile(r"<\s*planet_scene\b", re.IGNORECASE)
_CODE_FENCE_OPEN_RE = re.compile(r"^\s*```[a-zA-Z0-9_-]*\s*\n?")
_CODE_FENCE_CLOSE_RE = re.compile(r"\n?\s*```\s*$")
_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")
INFLUENCE_ZONE_GUIDANCE = (
"【地球影响范围联动指令】正文仍用自然 Markdown 输出(绝不在正文解释本标签);"
"只要分析涉及明确地理国家、地区、消费/市场辐射域、基础设施影响区、海域/海峡走廊、峰会/组织或用户询问“影响范围/影响地区/覆盖区域”,"
"就必须在回答**最末尾另起一行**附带一个纯 JSON(禁用 markdown 代码围栏)的系统隐藏标签:\n"
"<planet_scene>{...}</planet_scene>\n"
"分层输出规范(严格遵循):\n"
"- 第一层(必需,直接当事国/核心对象):shape.mode=\"countries\",color=\"#ef4444\",opacity=0.54,edge.style=\"sharp\";必须填全所有直接核心国家且严格使用标准 ISO-3 代码(如朝鲜必须写 \"PRK\",禁用 \"DPRK\";中国 \"CHN\"、韩国 \"KOR\"、日本 \"JPN\"、俄罗斯 \"RUS\"、英国 \"GBR\")。\n"
"- 第二层(若事件存在跨国/区域外溢则必填;纯单一国内消费/内部新闻则不填第二、三层):次级邻近/区域辐射,shape.mode=\"countries\" 或已支持的 \"region_preset\",color=\"#f59e0b\",opacity=0.32,edge.style=\"soft\"。\n"
"- 第三层(仅当明确涉及海峡、海域航道或边境辐射带时可选):shape.mode=\"circle\"(center:[lat,lon], radius_km),color=\"#38bdf8\",opacity=0.28,edge.style=\"soft\"。\n"
"完整单国示例:\n"
"<planet_scene>{\"influence_zones\":[{\"id\":\"chn-core\",\"label\":\"直接影响:中国\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\"]}}],\"camera_hint\":{\"lat\":35.0,\"lon\":104.0}}</planet_scene>\n"
"双国核心+区域外溢+海域辐射示例:\n"
"<planet_scene>{\"influence_zones\":[{\"id\":\"core\",\"label\":\"核心国家\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\",\"PRK\"]}},{\"id\":\"spill\",\"label\":\"东北亚周边外溢\",\"color\":\"#f59e0b\",\"opacity\":0.32,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"fade\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"KOR\",\"JPN\",\"RUS\"]}},{\"id\":\"sea\",\"label\":\"黄海—朝鲜海峡航道辐射\",\"color\":\"#38bdf8\",\"opacity\":0.28,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"radial\"},\"shape\":{\"mode\":\"circle\",\"center\":[36.5,124.5],\"radius_km\":850}}],\"camera_hint\":{\"lat\":38.0,\"lon\":122.0}}</planet_scene>\n"
"可选 region_preset 枚举(仅限此列表,勿自造名称):"
"APEC, ASIA_PACIFIC, NORTHEAST_ASIA, EAST_ASIA, KOREAN_PENINSULA, SOUTHEAST_ASIA, SOUTH_ASIA, CENTRAL_ASIA, ASEAN, INDO_PACIFIC, "
"EU, EUROPE, EASTERN_EUROPE, NORTHERN_EUROPE, WESTERN_EUROPE, G7, BRICS, NATO, MIDDLE_EAST, MENA, AMERICAS, NORTH_AMERICA, SOUTH_AMERICA, AFRICA;"
"animation.type 选 \"sweep\"、\"radial\" 或 \"fade\"。"
)
def sanitize_camera_hint(raw: Any) -> dict[str, float] | None:
if not isinstance(raw, dict):
return None
cleaned: dict[str, float] = {}
for key in ("lat", "lon", "altitude", "zoom"):
val = raw.get(key)
if isinstance(val, (int, float)) and not isinstance(val, bool):
cleaned[key] = float(val)
return cleaned if ("lat" in cleaned and "lon" in cleaned) else None
def _parse_scene_json_candidate(raw_json: str) -> dict[str, Any] | None:
"""Parse JSON inside `<planet_scene>` even if wrapped in code fences or containing trailing commas."""
text = str(raw_json or "").strip()
if not text:
return None
text = _CODE_FENCE_OPEN_RE.sub("", text)
text = _CODE_FENCE_CLOSE_RE.sub("", text).strip()
candidates = [text]
first_brace = text.find("{")
last_brace = text.rfind("}")
if first_brace != -1 and last_brace > first_brace:
sliced = text[first_brace : last_brace + 1]
if sliced != text:
candidates.append(sliced)
for cand in candidates:
for attempt in (cand, _TRAILING_COMMA_RE.sub(r"\1", cand)):
try:
parsed = json.loads(attempt)
except Exception:
continue
if isinstance(parsed, dict):
return parsed
return None
def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | None]:
"""Strip `<planet_scene>...</planet_scene>` blocks and return validated scene spec fields."""
if not text:
return "", None
parsed_scene: dict[str, Any] | None = None
matches = PLANET_SCENE_RE.findall(text)
for raw_json in matches:
payload = _parse_scene_json_candidate(raw_json)
if payload is None:
continue
zones = [z.model_dump(mode="json") for z in validate_influence_zones(payload.get("influence_zones"))]
camera_hint = sanitize_camera_hint(payload.get("camera_hint"))
if zones or camera_hint:
parsed_scene = {}
if zones:
parsed_scene["influence_zones"] = zones
if camera_hint:
parsed_scene["camera_hint"] = camera_hint
if matches and parsed_scene is not None:
extracted_zones = parsed_scene.get("influence_zones") or []
logger.info_event(
"Extracted planet scene directives",
event="ai_scene.directive.extracted",
context={
"zones_count": len(extracted_zones),
"zone_ids": [z.get("id") for z in extracted_zones if isinstance(z, dict)],
"has_camera_hint": "camera_hint" in parsed_scene,
},
)
elif matches:
logger.warning_event(
"Planet scene directive ignored after parse/validation failure",
event="ai_scene.directive.dropped",
context={"snippet": str(matches[-1])[:300]},
)
cleaned = PLANET_SCENE_RE.sub("", text)
open_match = PLANET_SCENE_OPEN_RE.search(cleaned)
if open_match:
cleaned = cleaned[: open_match.start()]
return cleaned.rstrip(), parsed_scene
def consume_text_holding_scene_tag(buffer: str, *, flush_all: bool = False) -> tuple[str, str]:
"""Yield visible text before `<planet_scene` while holding back partial tag prefixes."""
stripped_blocks = PLANET_SCENE_RE.sub("", buffer)
open_match = PLANET_SCENE_OPEN_RE.search(stripped_blocks)
if open_match:
return stripped_blocks[: open_match.start()], stripped_blocks[open_match.start() :]
if flush_all:
return stripped_blocks, ""
last_lt = stripped_blocks.rfind("<")
if last_lt != -1:
tail = stripped_blocks[last_lt:]
if len(tail) < len(PLANET_SCENE_TAG_OPEN) and PLANET_SCENE_TAG_OPEN.startswith(tail.lower()):
return stripped_blocks[:last_lt], tail
return stripped_blocks, ""
def merge_scene_specs(
base_scene: dict[str, Any] | None,
parsed_scene: dict[str, Any] | None,
*,
domain: str | None = None,
) -> dict[str, Any] | None:
if not parsed_scene and not isinstance(base_scene, dict):
return None
merged: dict[str, Any] = dict(base_scene) if isinstance(base_scene, dict) else {}
if parsed_scene:
merged.update(parsed_scene)
if domain and not merged.get("domain"):
merged["domain"] = domain
return merged
+113 -27
View File
@@ -32,9 +32,20 @@ from app.services.ai.tool_registry import (
query_global_situational_tool, query_global_situational_tool,
query_recent_earth_news_tool, query_recent_earth_news_tool,
) )
from app.services.ai.scene_directives import (
INFLUENCE_ZONE_GUIDANCE as _INFLUENCE_ZONE_GUIDANCE,
consume_text_holding_scene_tag as _consume_text_holding_scene_tag,
extract_planet_scene_from_text,
)
from app.services.ai.workflow_evolver import schedule_post_run_evolution from app.services.ai.workflow_evolver import schedule_post_run_evolution
from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows
from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn from app.services.ai.workflow_runtime import (
ActiveRunHandle,
classify_turn_intent,
execute_session_turn,
register_active_run_handle,
unregister_active_run_handle,
)
from app.services.ai_client import AIProviderClient from app.services.ai_client import AIProviderClient
logger = get_logger(__name__, service="ai_stream") logger = get_logger(__name__, service="ai_stream")
@@ -186,6 +197,7 @@ def _build_news_analysis_request(
context["user_memory_notes"] = memory_notes context["user_memory_notes"] = memory_notes
if pinned_summaries: if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries context["pinned_comparisons"] = pinned_summaries
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
return SituationalAnalysisRequest( return SituationalAnalysisRequest(
title="Planet 全球新闻与国际局势研判", title="Planet 全球新闻与国际局势研判",
objective=( objective=(
@@ -194,16 +206,17 @@ def _build_news_analysis_request(
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n" "1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n" "2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
"3. **后续重点观察信号与不确定边界**。\n" "3. **后续重点观察信号与不确定边界**。\n"
"请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。" "正文直接输出面向用户的 Markdown,不要把正文包在 JSON 里;若存在任何明确的地理国家、地区或海域影响范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
), ),
system_prompt=( system_prompt=(
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。" "你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
"如有前序对话与用户备忘录,请保持指代与口径延续。" "如有前序对话与用户备忘录,请保持指代与口径延续。"
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。" "请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。\n\n"
f"{_INFLUENCE_ZONE_GUIDANCE}"
), ),
context=context, context=context,
constraints=[ constraints=[
"Output clean user-facing Markdown directly (not JSON).", "Output clean user-facing Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
"Distinguish reported facts from analytical outlook.", "Distinguish reported facts from analytical outlook.",
], ],
thinking=thinking_cfg, thinking=thinking_cfg,
@@ -239,20 +252,23 @@ def _build_telemetry_stream_request(
context["user_memory_notes"] = memory_notes context["user_memory_notes"] = memory_notes
if pinned_summaries: if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries context["pinned_comparisons"] = pinned_summaries
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
return SituationalAnalysisRequest( return SituationalAnalysisRequest(
title=f"Planet 态势参谋分析({domain})", title=f"Planet 态势参谋分析({domain})",
objective=( objective=(
f"用户问题:{question}\n\n" f"用户问题:{question}\n\n"
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条," "请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。" "使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要把正文包在 JSON 对象里;"
"若涉及明确国家、地区或海域范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
), ),
system_prompt=( system_prompt=(
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;" "你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。" "所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。\n\n"
f"{_INFLUENCE_ZONE_GUIDANCE}"
), ),
context=context, context=context,
constraints=[ constraints=[
"Output clean Markdown directly (not JSON).", "Output clean Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
"Do not invent telemetry counts or unverified outages outside context.", "Do not invent telemetry counts or unverified outages outside context.",
], ],
thinking=thinking_cfg, thinking=thinking_cfg,
@@ -365,6 +381,18 @@ async def stream_session_turn(
wf_model = str(model_name or "") wf_model = str(model_name or "")
wf_provider = str(provider_name or "") wf_provider = str(provider_name or "")
wf_revision = int(wf_dict.get("active_revision") or 1) wf_revision = int(wf_dict.get("active_revision") or 1)
wf_scene_zones_count = 0
run_handle = register_active_run_handle(
ActiveRunHandle(
run_id=run_id,
session_id=session_id_val if session is not None else None,
actor_key=getattr(access, "actor_key", "anonymous"),
workflow_id=workflow_id,
access_tier=getattr(access, "access_tier", "public_zero_cost"),
question=question[:500],
started_at=wf_started_at,
)
)
try: try:
wf_earth_ctx: dict[str, Any] = { wf_earth_ctx: dict[str, Any] = {
**merged_ctx, **merged_ctx,
@@ -398,6 +426,7 @@ async def stream_session_turn(
request=request, request=request,
run_id=run_id, run_id=run_id,
allow_external_tools=allow_external, allow_external_tools=allow_external,
cancel_event=run_handle.cancel_event,
extra_meta={ extra_meta={
"session_id": session_id_val, "session_id": session_id_val,
"domain": domain, "domain": domain,
@@ -411,26 +440,42 @@ async def stream_session_turn(
**({"session_token": issued_session_token} if issued_session_token else {}), **({"session_token": issued_session_token} if issued_session_token else {}),
}, },
): ):
if run_handle.cancel_event.is_set() or (
request is not None and await request.is_disconnected()
):
wf_status = "cancelled"
break
ev_name = str(item.get("event") or "") ev_name = str(item.get("event") or "")
ev_data = dict(item.get("data") or {}) ev_data = dict(item.get("data") or {})
if ev_name == "node" and ev_data.get("status") == "completed": if ev_name == "node" and ev_data.get("status") == "completed":
nid = str(ev_data.get("node_id") or "") nid = str(ev_data.get("node_id") or "")
if nid and nid not in wf_trace: if nid and nid not in wf_trace:
wf_trace.append(nid) wf_trace.append(nid)
elif ev_name == "scene":
s_spec = ev_data.get("scene_spec")
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
wf_scene_zones_count = len(s_spec["influence_zones"])
elif ev_name == "done": elif ev_name == "done":
if run_handle.cancel_event.is_set():
wf_status = "cancelled"
break
if isinstance(ev_data.get("nodes"), list): if isinstance(ev_data.get("nodes"), list):
wf_trace = [str(n) for n in ev_data["nodes"] if n] wf_trace = [str(n) for n in ev_data["nodes"] if n]
if ev_data.get("model"): if ev_data.get("model"):
wf_model = str(ev_data["model"]) wf_model = str(ev_data["model"])
if ev_data.get("provider"): if ev_data.get("provider"):
wf_provider = str(ev_data["provider"]) wf_provider = str(ev_data["provider"])
s_spec = ev_data.get("scene_spec")
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
wf_scene_zones_count = len(s_spec["influence_zones"])
wf_answer = str(ev_data.get("answer_markdown") or "") wf_answer = str(ev_data.get("answer_markdown") or "")
ev_data.setdefault("usage", {}) ev_data.setdefault("usage", {})
ev_data["compacted"] = compacted_flag ev_data["compacted"] = compacted_flag
ev_data["conversation_summary"] = compacted_summary ev_data["conversation_summary"] = compacted_summary
ev_data["memory_used"] = memory_used_flag ev_data["memory_used"] = memory_used_flag
if session is not None and isinstance(session.context_state, dict): if session is not None and isinstance(session.context_state, dict):
updated_recent = [*recent_history, {"role": "user", "content": question}] base_recent = list(session.context_state.get("recent_messages") or recent_history)
updated_recent = [*base_recent, {"role": "user", "content": question}]
if wf_answer: if wf_answer:
updated_recent.append({"role": "assistant", "content": wf_answer[:1800]}) updated_recent.append({"role": "assistant", "content": wf_answer[:1800]})
session.context_state = { session.context_state = {
@@ -442,6 +487,8 @@ async def stream_session_turn(
wf_status = "failed" wf_status = "failed"
wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error") wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error")
yield _format_sse(ev_name, ev_data) yield _format_sse(ev_name, ev_data)
if run_handle.cancel_event.is_set():
wf_status = "cancelled"
except asyncio.CancelledError: except asyncio.CancelledError:
wf_status = "cancelled" wf_status = "cancelled"
raise raise
@@ -455,6 +502,7 @@ async def stream_session_turn(
) )
yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)}) yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)})
finally: finally:
unregister_active_run_handle(run_id)
try: try:
wf_completed_at = datetime.now(UTC) wf_completed_at = datetime.now(UTC)
wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000)) wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000))
@@ -479,6 +527,7 @@ async def stream_session_turn(
"provider": wf_provider, "provider": wf_provider,
"latency_ms": wf_latency_ms, "latency_ms": wf_latency_ms,
"workflow_revision": wf_revision, "workflow_revision": wf_revision,
"scene_zones_count": wf_scene_zones_count,
}, },
error_message=wf_error[:500], error_message=wf_error[:500],
started_at=wf_started_at, started_at=wf_started_at,
@@ -590,7 +639,8 @@ async def stream_session_turn(
def _persist_session_memory(answer_text: str) -> None: def _persist_session_memory(answer_text: str) -> None:
if session is None or not isinstance(session.context_state, dict): if session is None or not isinstance(session.context_state, dict):
return return
updated_recent = [*recent_history, {"role": "user", "content": question}] base_recent = list(session.context_state.get("recent_messages") or recent_history)
updated_recent = [*base_recent, {"role": "user", "content": question}]
if answer_text: if answer_text:
updated_recent.append({"role": "assistant", "content": answer_text[:1800]}) updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
session.context_state = { session.context_state = {
@@ -665,13 +715,27 @@ async def stream_session_turn(
text_chunks: list[str] = [] text_chunks: list[str] = []
reasoning_chunks: list[str] = [] reasoning_chunks: list[str] = []
pending_scene_tail = ""
resolved_provider = provider_name resolved_provider = provider_name
resolved_model = model_name resolved_model = model_name
final_usage: dict[str, Any] = {} final_usage: dict[str, Any] = {}
direct_run_handle = register_active_run_handle(
ActiveRunHandle(
run_id=run_id,
session_id=session_id_val if session is not None else None,
actor_key=getattr(access, "actor_key", "anonymous"),
workflow_id=f"stream.{domain}",
access_tier=getattr(access, "access_tier", "public_zero_cost"),
question=question[:500],
started_at=datetime.now(UTC),
)
)
try: try:
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id): async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
if request is not None and await request.is_disconnected(): if direct_run_handle.cancel_event.is_set() or (
request is not None and await request.is_disconnected()
):
return return
ev_type = str(ev.get("event") or "") ev_type = str(ev.get("event") or "")
if ev_type == "start": if ev_type == "start":
@@ -688,7 +752,10 @@ async def stream_session_turn(
delta = ev.get("delta") delta = ev.get("delta")
if isinstance(delta, str) and delta: if isinstance(delta, str) and delta:
text_chunks.append(delta) text_chunks.append(delta)
yield _format_sse("text", {"delta": delta}) combined_buf = pending_scene_tail + delta
emit_chunk, pending_scene_tail = _consume_text_holding_scene_tag(combined_buf)
if emit_chunk:
yield _format_sse("text", {"delta": emit_chunk})
elif ev_type == "done": elif ev_type == "done":
if isinstance(ev.get("provider"), str) and ev["provider"]: if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"] resolved_provider = ev["provider"]
@@ -699,17 +766,30 @@ async def stream_session_turn(
elif ev_type == "error": elif ev_type == "error":
raise RuntimeError(str(ev.get("detail") or "AI stream error")) raise RuntimeError(str(ev.get("detail") or "AI stream error"))
if direct_run_handle.cancel_event.is_set():
return
if pending_scene_tail:
cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail)
if cleaned_tail:
yield _format_sse("text", {"delta": cleaned_tail})
combined_text = "".join(text_chunks).strip() combined_text = "".join(text_chunks).strip()
if not combined_text: if not combined_text:
raise RuntimeError("AI provider stream returned empty response") raise RuntimeError("AI provider stream returned empty response")
clean_text, inline_thoughts = strip_thinking_text(combined_text) clean_text, inline_thoughts = strip_thinking_text(combined_text)
clean_text, parsed_scene = extract_planet_scene_from_text(clean_text or combined_text)
combined_reasoning = "".join(reasoning_chunks).strip() combined_reasoning = "".join(reasoning_chunks).strip()
if inline_thoughts: if inline_thoughts:
extra_thought = "\n\n".join(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 combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
final_answer_md = clean_text or combined_text final_answer_md = clean_text or combined_text
merged_scene_spec: dict[str, Any] | None = dict(scene_spec) if isinstance(scene_spec, dict) else None
if parsed_scene:
merged_scene_spec = {**(merged_scene_spec or {}), "domain": (merged_scene_spec or {}).get("domain") or domain, **parsed_scene}
_persist_session_memory(final_answer_md) _persist_session_memory(final_answer_md)
if hasattr(db, "commit"): if hasattr(db, "commit"):
try: try:
@@ -717,22 +797,26 @@ async def stream_session_turn(
except Exception: except Exception:
pass pass
yield _format_sse( if merged_scene_spec is not None and (merged_scene_spec.get("influence_zones") or parsed_scene):
"done", yield _format_sse("scene", {"scene_spec": merged_scene_spec})
{
"status": "completed", done_payload: dict[str, Any] = {
"generation_mode": "llm_verified", "status": "completed",
"zero_token": False, "generation_mode": "llm_verified",
"provider": resolved_provider, "zero_token": False,
"model": resolved_model, "provider": resolved_provider,
"usage": final_usage, "model": resolved_model,
"compacted": compacted_flag, "usage": final_usage,
"conversation_summary": compacted_summary, "compacted": compacted_flag,
"memory_used": memory_used_flag, "conversation_summary": compacted_summary,
"answer_markdown": final_answer_md, "memory_used": memory_used_flag,
"reasoning_markdown": combined_reasoning, "answer_markdown": final_answer_md,
}, "reasoning_markdown": combined_reasoning,
) }
if merged_scene_spec is not None:
done_payload["scene_spec"] = merged_scene_spec
yield _format_sse("done", done_payload)
except asyncio.CancelledError: except asyncio.CancelledError:
raise raise
except Exception as exc: except Exception as exc:
@@ -772,3 +856,5 @@ async def stream_session_turn(
"fallback_reason": str(exc), "fallback_reason": str(exc),
}, },
) )
finally:
unregister_active_run_handle(run_id)
+405 -57
View File
@@ -21,6 +21,7 @@ import copy
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
import os import os
import re
from typing import Any, Protocol from typing import Any, Protocol
from uuid import uuid4 from uuid import uuid4
@@ -38,6 +39,7 @@ from app.services.ai.dag_executor import run_workflow_dag_stream
from app.services.ai.thinking_sanitizer import strip_thinking_text from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.ai.workflow_registry import ( from app.services.ai.workflow_registry import (
ALLOWED_NODE_PATCH_FIELDS, ALLOWED_NODE_PATCH_FIELDS,
DRAFT_BINDINGS_KEY,
TOOL_CATALOG, TOOL_CATALOG,
VALID_TOOL_IDS, VALID_TOOL_IDS,
_apply_validated_node_patches, _apply_validated_node_patches,
@@ -216,6 +218,80 @@ class UnusedToolSignalDetector:
return [] return []
FIXTURE_EXPECT_KEY = "expect"
_UNCERTAINTY_MARKERS = (
"待核实", "待查", "不确定", "证据不足", "无法确认", "尚无法", "有待", "unverified", "uncertain", "insufficient evidence",
)
def normalize_fixture_expect(raw: Any) -> dict[str, Any]:
"""Normalize gradable fixture assertions stored under `context_json["expect"]`."""
if not isinstance(raw, dict):
return {}
def _str_list(key: str) -> list[str]:
vals = raw.get(key)
if not isinstance(vals, list):
return []
return [str(v).strip()[:120] for v in vals if str(v).strip()][:10]
numbers: list[str] = []
for val in raw.get("numbers") or []:
if isinstance(val, bool):
continue
if isinstance(val, (int, float)):
numbers.append(str(int(val)) if float(val).is_integer() else str(val))
elif isinstance(val, str) and re.fullmatch(r"-?\d+(?:\.\d+)?", val.strip()):
numbers.append(val.strip())
expect: dict[str, Any] = {}
if numbers:
expect["numbers"] = numbers[:10]
for key in ("must_include", "must_not_include"):
items = _str_list(key)
if items:
expect[key] = items
if raw.get("require_uncertainty_without_evidence"):
expect["require_uncertainty_without_evidence"] = True
min_evidence = raw.get("min_evidence")
if isinstance(min_evidence, int) and not isinstance(min_evidence, bool) and min_evidence > 0:
expect["min_evidence"] = min(min_evidence, 50)
return expect
def _answer_contains_number(answer: str, number: str) -> bool:
return re.search(rf"(?<![\d.]){re.escape(number)}(?!\d|\.\d)", answer) is not None
def grade_fixture_result(result: dict[str, Any], expect: dict[str, Any]) -> list[str]:
"""Return the failed checks for one sample run (empty list == pass)."""
failures: list[str] = []
answer = str(result.get("answer") or "")
if result.get("error"):
failures.append(f"执行出错:{str(result['error'])[:120]}")
if not answer.strip():
failures.append("没有输出正文")
if result.get("verification_passed") is False:
warns = ";".join(result.get("verification_warnings") or []) or "护栏校验失败"
failures.append(f"护栏校验未通过:{warns}")
for number in expect.get("numbers") or []:
if not _answer_contains_number(answer, number):
failures.append(f"未给出期望数值 {number}")
for phrase in expect.get("must_include") or []:
if phrase not in answer:
failures.append(f"缺少必备表述「{phrase}」")
for phrase in expect.get("must_not_include") or []:
if phrase in answer:
failures.append(f"出现禁用表述「{phrase}」")
evidence_count = int(result.get("evidence_count") or 0)
if expect.get("min_evidence") and evidence_count < int(expect["min_evidence"]):
failures.append(f"证据条目 {evidence_count} 少于要求的 {expect['min_evidence']}")
if expect.get("require_uncertainty_without_evidence") and evidence_count == 0:
lowered = answer.lower()
if not any(marker in lowered for marker in _UNCERTAINTY_MARKERS):
failures.append("证据不足时未保留不确定性(缺少「待核实/证据不足」等表述)")
return failures
class FixtureABEvaluator: class FixtureABEvaluator:
evaluator_id = "fixture_ab" evaluator_id = "fixture_ab"
@@ -255,9 +331,14 @@ class FixtureABEvaluator:
comparisons: list[dict[str, Any]] = [] comparisons: list[dict[str, Any]] = []
base_ok = 0 base_ok = 0
prop_ok = 0 prop_ok = 0
graded = 0
regressions: list[str] = []
for row in rows: for row in rows:
question = str(row.sample_question or "").strip() or f"请分析 {row.name}" question = str(row.sample_question or "").strip() or f"请分析 {row.name}"
ctx = dict(row.context_json or {}) ctx = dict(row.context_json or {})
expect = normalize_fixture_expect(ctx.pop(FIXTURE_EXPECT_KEY, None))
if expect:
graded += 1
base_res = await _run_graph_single_sample( base_res = await _run_graph_single_sample(
db=db, db=db,
workflow=workflow, workflow=workflow,
@@ -274,24 +355,32 @@ class FixtureABEvaluator:
earth_context=ctx, earth_context=ctx,
ai_client=ai_client, ai_client=ai_client,
) )
for res in (base_res, prop_res):
res["failures"] = grade_fixture_result(res, expect)
res["ok"] = not res["failures"]
res["answer_preview"] = str(res.pop("answer", ""))[:280]
if base_res["ok"]: if base_res["ok"]:
base_ok += 1 base_ok += 1
if prop_res["ok"]: if prop_res["ok"]:
prop_ok += 1 prop_ok += 1
if base_res["ok"] and not prop_res["ok"]:
regressions.append(str(row.name))
comparisons.append( comparisons.append(
{ {
"fixture_id": row.id, "fixture_id": row.id,
"fixture_name": row.name, "fixture_name": row.name,
"question": question[:160], "question": question[:160],
"graded": bool(expect),
"expect": expect,
"base": base_res, "base": base_res,
"proposed": prop_res, "proposed": prop_res,
} }
) )
if prop_ok > base_ok: if regressions or prop_ok < base_ok:
verdict = "improved"
elif prop_ok < base_ok:
verdict = "regressed" verdict = "regressed"
elif prop_ok > base_ok:
verdict = "improved"
else: else:
avg_base_ms = sum(c["base"]["latency_ms"] for c in comparisons) / len(comparisons) avg_base_ms = sum(c["base"]["latency_ms"] for c in comparisons) / len(comparisons)
avg_prop_ms = sum(c["proposed"]["latency_ms"] for c in comparisons) / len(comparisons) avg_prop_ms = sum(c["proposed"]["latency_ms"] for c in comparisons) / len(comparisons)
@@ -300,13 +389,19 @@ class FixtureABEvaluator:
else: else:
verdict = "neutral" verdict = "neutral"
graded_note = "" if graded else "(样本未设置可判对错的断言,仅校验执行成功与护栏)"
return { return {
"evaluator_id": self.evaluator_id, "evaluator_id": self.evaluator_id,
"fixture_count": len(comparisons), "fixture_count": len(comparisons),
"graded_fixture_count": graded,
"base_passed": base_ok, "base_passed": base_ok,
"proposed_passed": prop_ok, "proposed_passed": prop_ok,
"regressions": regressions,
"verdict": verdict, "verdict": verdict,
"summary": f"已对照 {len(comparisons)} 组样本:原版通过 {base_ok}/{len(comparisons)},新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict})。", "summary": (
f"已对照 {len(comparisons)} 组样本(含断言 {graded} 组):原版通过 {base_ok}/{len(comparisons)},"
f"新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict}){graded_note}。"
),
"comparisons": comparisons, "comparisons": comparisons,
} }
@@ -947,6 +1042,20 @@ async def _evaluate_meta_canary(db: AsyncSession) -> None:
) )
if meta_canary is None: if meta_canary is None:
return return
meta_target = meta_canary.get("target_revision")
meta_live = (
await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == META_WORKFLOW_ID))
).scalar_one_or_none()
if isinstance(meta_target, int) and meta_live is not None and int(meta_live) != meta_target:
await update_ledger_entry(
db,
str(meta_canary["id"]),
{
"status": "superseded",
"superseded_reason": f"元引擎当前生效版本已变为 v{int(meta_live)}(灰度目标 v{meta_target}),终止灰度且不回滚。",
},
)
return
meta_started = _parse_iso(meta_canary.get("created_at")) meta_started = _parse_iso(meta_canary.get("created_at"))
downstream = [ downstream = [
e e
@@ -1002,6 +1111,28 @@ async def evaluate_canary_and_maybe_rollback(
if canary is None: if canary is None:
return None return None
# A manual publish / rollback after this canary started supersedes it: rolling back now would
# overwrite the newer live revision (e.g. revert a hand-published v3 to v1).
target_rev = canary.get("target_revision")
live_rev = (
await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if isinstance(target_rev, int) and live_rev is not None and int(live_rev) != target_rev:
updated = await update_ledger_entry(
db,
str(canary["id"]),
{
"status": "superseded",
"superseded_reason": f"当前生效版本已变为 v{int(live_rev)}(灰度目标 v{target_rev}),终止本轮灰度且不回滚。",
},
)
logger.info_event(
"Workflow canary superseded by a newer live revision",
event="ai_evolver.canary.superseded",
context={"workflow_id": workflow_id, "target_revision": target_rev, "live_revision": int(live_rev)},
)
return {"action": "superseded", "entry": updated}
runs = ( runs = (
await db.execute( await db.execute(
select(WorkflowRun) select(WorkflowRun)
@@ -1204,20 +1335,12 @@ def _deterministic_business_patches(
"reason": f"供应商 {profile.get('provider')} 支持原生联网检索,开启后可协同补充最新一手信源。", "reason": f"供应商 {profile.get('provider')} 支持原生联网检索,开启后可协同补充最新一手信源。",
} }
) )
if not patches: # No capability mismatch found -> no change (never pad with generic prompt clauses).
base_sys = str(llm_node.get("system_prompt") or "").strip() summary = (
model_name = str(profile.get("model") or "当前模型").strip() f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。"
tag = f"[模型适配 {model_name}] 请优先依据工具返回的实测数值作答,禁止臆测缺失字段。" if patches
if tag not in base_sys and base_sys: else f"当前模型 {profile.get('model') or profile.get('provider')} 与工作流配置匹配,无需调整。"
patches.append( )
{
"node_id": llm_node["id"],
"field": "system_prompt",
"after": f"{base_sys}\n{tag}",
"reason": f"针对当前模型({model_name})补强事实边界约束。",
}
)
summary = f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。"
return summary, patches return summary, patches
inst_lower = instruction.lower() inst_lower = instruction.lower()
@@ -1255,20 +1378,21 @@ def _deterministic_business_patches(
"reason": f"精简近期零调用的闲置工具({', '.join(unused[:3])}),减少无效上下文干扰。", "reason": f"精简近期零调用的闲置工具({', '.join(unused[:3])}),减少无效上下文干扰。",
} }
) )
if not patches: if not patches and instruction.strip():
# Only an explicit admin instruction justifies a prompt edit without a detected signal.
base_sys = str(llm_node.get("system_prompt") or "").strip() base_sys = str(llm_node.get("system_prompt") or "").strip()
target_note = instruction.strip() or ( target_note = instruction.strip()
"先明确区分已核验事实与待查证缺口,不确定的数值或来源须直接说明。"
)
if target_note not in base_sys and base_sys: if target_note not in base_sys and base_sys:
patches.append( patches.append(
{ {
"node_id": llm_node["id"], "node_id": llm_node["id"],
"field": "system_prompt", "field": "system_prompt",
"after": f"{base_sys}\n[调优约束] {target_note}", "after": f"{base_sys}\n[调优约束] {target_note}",
"reason": "基于近期负反馈或调优目标加固提示词护栏。", "reason": "按管理员调优目标加固提示词护栏。",
} }
) )
if not patches:
return "未检测到需要调整的信号,本轮无需修改。", []
summary = ( summary = (
f"已针对「{instruction.strip()}」生成节点调优建议。" f"已针对「{instruction.strip()}」生成节点调优建议。"
if instruction.strip() if instruction.strip()
@@ -1277,6 +1401,159 @@ def _deterministic_business_patches(
return summary, patches return summary, patches
# Every (node, field) the meta-evolver may change must measurably alter the business proposal
# request built below; anything else would create versions that change nothing downstream.
META_EVOLVABLE_FIELDS: frozenset[tuple[str, str]] = frozenset(
{
("diag_node", "system_prompt"),
("diag_node", "prompt"),
("patch_node", "system_prompt"),
("patch_node", "prompt"),
("patch_node", "thinking_enabled"),
}
)
_DEFAULT_EVOLVER_SYSTEM_PROMPT = "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。"
_NO_CHANGE_CLAUSE = "若现有工作流已满足目标、无需调整,请返回空的 node_patches 数组,并在 summary 中说明理由。"
def build_business_evolution_request(
*,
workflow_id: str,
mode: str,
instruction: str,
diag_node: dict[str, Any],
patch_node: dict[str, Any],
schema: dict[str, Any],
context: dict[str, Any],
) -> SituationalAnalysisRequest:
"""Build the business-evolution LLM request from the live meta-evolver nodes."""
diag_sys = str(diag_node.get("system_prompt") or "").strip()
diag_prompt = str(diag_node.get("prompt") or "").strip()
patch_sys = str(patch_node.get("system_prompt") or "").strip()
patch_prompt = str(patch_node.get("prompt") or "").strip()
combined_sys = f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip() if (patch_sys or diag_sys) else ""
objective_parts = [
f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)",
f"工作流 ID:{workflow_id}",
f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}",
]
if diag_prompt:
objective_parts.append(f"[诊断任务]\n{diag_prompt}")
if patch_prompt:
objective_parts.append(f"[补丁任务]\n{patch_prompt}")
objective_parts.append(_NO_CHANGE_CLAUSE)
return SituationalAnalysisRequest(
title=f"Evolve workflow {workflow_id}",
objective="\n".join(objective_parts)[:16000],
system_prompt=(combined_sys or _DEFAULT_EVOLVER_SYSTEM_PROMPT)[:8000],
context=context,
thinking={"mode": "auto"} if bool(patch_node.get("thinking_enabled", True)) else {"mode": "off"},
response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}},
)
def _full_graph_diff(base_graph: dict[str, Any], proposed_graph: dict[str, Any]) -> list[dict[str, Any]]:
"""All node/edge differences between two graphs (layout positions ignored)."""
try:
base = _validate_graph_payload(base_graph)
proposed = _validate_graph_payload(proposed_graph)
except HTTPException:
return []
base_nodes = {str(n["id"]): n for n in base.get("nodes") or []}
prop_nodes = {str(n["id"]): n for n in proposed.get("nodes") or []}
changes: list[dict[str, Any]] = []
for nid in sorted(set(base_nodes) | set(prop_nodes)):
bnode, pnode = base_nodes.get(nid), prop_nodes.get(nid)
if bnode is None or pnode is None:
changes.append(
{
"node_id": nid,
"node_title": (pnode or bnode or {}).get("title") or nid,
"field": "__node__",
"before": None if bnode is None else "present",
"after": None if pnode is None else "present",
}
)
continue
for key in sorted(set(bnode) | set(pnode)):
if key == "position" or bnode.get(key) == pnode.get(key):
continue
changes.append(
{
"node_id": nid,
"node_title": pnode.get("title") or nid,
"field": key,
"before": copy.deepcopy(bnode.get(key)),
"after": copy.deepcopy(pnode.get(key)),
}
)
def _edge_keys(graph: dict[str, Any]) -> set[tuple[str, str, str]]:
return {
(str(e.get("source")), str(e.get("target")), str(e.get("condition") or "always"))
for e in graph.get("edges") or []
if isinstance(e, dict)
}
base_edges, prop_edges = _edge_keys(base), _edge_keys(proposed)
if base_edges != prop_edges:
changes.append(
{
"node_id": "__edges__",
"node_title": "edges",
"field": "edges",
"before": sorted(list(e) for e in base_edges - prop_edges),
"after": sorted(list(e) for e in prop_edges - base_edges),
}
)
return changes
def _no_change_result(
*,
workflow_id: str,
mode: str,
base_revision: int,
summary: str,
proposed_graph: dict[str, Any],
health: dict[str, Any] | None = None,
meta_revision: int | None = None,
) -> dict[str, Any]:
return {
"workflow_id": workflow_id,
"mode": mode,
"base_revision": base_revision,
"meta_revision": meta_revision,
"summary": summary,
"changes": [],
"changes_vs_live": [],
"proposed_graph": proposed_graph,
"constitution_ok": True,
"violations": [],
"applied_status": "no_change",
"new_revision": None,
"blocked_reason": "",
"ledger_entry": None,
"ab_eval": None,
"health": health,
}
def _ab_gate_allows_auto_publish(ab_eval: dict[str, Any]) -> tuple[bool, str]:
"""Auto-publish only when graded fixtures show the candidate is not worse than live."""
if int(ab_eval.get("fixture_count") or 0) == 0:
return False, "自动发布需先通过 A/B 门禁:当前工作流没有固定样本(Fixtures)。"
if int(ab_eval.get("graded_fixture_count") or 0) == 0:
return False, "自动发布需先通过 A/B 门禁:固定样本均未设置可判对错的断言(expect),无法证明候选版本不退化。"
regressions = list(ab_eval.get("regressions") or [])
if regressions:
return False, f"A/B 门禁未通过:{len(regressions)} 条样本在候选版本上退化({', '.join(regressions[:3])})。"
verdict = str(ab_eval.get("verdict") or "")
if verdict in {"regressed", "slower"}:
return False, f"A/B 门禁未通过(判定:{verdict})。"
return True, ""
async def propose_workflow_evolution( async def propose_workflow_evolution(
db: AsyncSession, db: AsyncSession,
workflow_id: str, workflow_id: str,
@@ -1309,7 +1586,13 @@ async def propose_workflow_evolution(
health = await compute_workflow_health(db, workflow_id, ai_client=ai_client) health = await compute_workflow_health(db, workflow_id, ai_client=ai_client)
parent_revision = int(wf.active_revision or 1) parent_revision = int(wf.active_revision or 1)
base_graph = copy.deepcopy(wf.draft_graph or wf.published_graph or {}) live_graph = copy.deepcopy(wf.published_graph or {})
# Only an admin explicitly tuning into a draft may build on their own unpublished draft.
# Background / auto-publish evolution always starts from the live revision so it can never
# smuggle unpublished human edits into production or clear them.
builds_on_human_draft = trigger == "manual" and apply_mode != "auto" and wf.draft_graph is not None
base_graph = copy.deepcopy(wf.draft_graph if builds_on_human_draft else live_graph)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
# Optional DGM archive parent selection # Optional DGM archive parent selection
if branch_from_best and health.get("recommended_parent_revision"): if branch_from_best and health.get("recommended_parent_revision"):
@@ -1323,6 +1606,7 @@ async def propose_workflow_evolution(
).scalar_one_or_none() ).scalar_one_or_none()
if rev_row is not None and isinstance(rev_row.graph_json, dict): if rev_row is not None and isinstance(rev_row.graph_json, dict):
base_graph = copy.deepcopy(rev_row.graph_json) base_graph = copy.deepcopy(rev_row.graph_json)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
parent_revision = best_rev parent_revision = best_rev
# Collect bad/selected run context for GEPA diagnosis # Collect bad/selected run context for GEPA diagnosis
@@ -1381,6 +1665,7 @@ async def propose_workflow_evolution(
summary = "" summary = ""
raw_patches: list[dict[str, Any]] = [] raw_patches: list[dict[str, Any]] = []
ai_decided = False
if ai_ready and client is not None: if ai_ready and client is not None:
schema = { schema = {
"type": "object", "type": "object",
@@ -1402,22 +1687,13 @@ async def propose_workflow_evolution(
}, },
"required": ["summary", "node_patches"], "required": ["summary", "node_patches"],
} }
diag_sys = str(diag_node.get("system_prompt") or "").strip() req = build_business_evolution_request(
patch_sys = str(patch_node.get("system_prompt") or "").strip() workflow_id=workflow_id,
combined_sys = ( mode=mode,
f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip() instruction=instruction,
or "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。" diag_node=diag_node,
) patch_node=patch_node,
objective = ( schema=schema,
f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)\n"
f"工作流 ID:{workflow_id}\n"
f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}\n"
f"{str(patch_node.get('prompt') or '')}"
).strip()
req = SituationalAnalysisRequest(
title=f"Evolve workflow {workflow_id}",
objective=objective[:16000],
system_prompt=combined_sys[:8000],
context={ context={
"workflow_id": workflow_id, "workflow_id": workflow_id,
"parent_revision": parent_revision, "parent_revision": parent_revision,
@@ -1431,7 +1707,6 @@ async def propose_workflow_evolution(
"selected_run": selected_run.to_dict() if selected_run else None, "selected_run": selected_run.to_dict() if selected_run else None,
"aflow_lessons": lessons, "aflow_lessons": lessons,
}, },
response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}},
) )
try: try:
resp = await client.analyze(req) resp = await client.analyze(req)
@@ -1441,6 +1716,8 @@ async def propose_workflow_evolution(
summary = str(parsed.get("summary") or "").strip() summary = str(parsed.get("summary") or "").strip()
if isinstance(parsed.get("node_patches"), list): if isinstance(parsed.get("node_patches"), list):
raw_patches = parsed["node_patches"] raw_patches = parsed["node_patches"]
# A valid, explicitly empty patch list means "no change needed" — honour it.
ai_decided = True
except Exception as exc: except Exception as exc:
logger.warning_event( logger.warning_event(
"AI evolution proposal failed; using deterministic fallback", "AI evolution proposal failed; using deterministic fallback",
@@ -1448,7 +1725,7 @@ async def propose_workflow_evolution(
context={"workflow_id": workflow_id, "mode": mode, "error": str(exc)}, context={"workflow_id": workflow_id, "mode": mode, "error": str(exc)},
) )
if not raw_patches: if not ai_decided:
summary, raw_patches = _deterministic_business_patches( summary, raw_patches = _deterministic_business_patches(
base_graph, base_graph,
mode=mode, mode=mode,
@@ -1458,11 +1735,23 @@ async def propose_workflow_evolution(
) )
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches) proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
if not diffs:
return _no_change_result(
workflow_id=workflow_id,
mode=mode,
base_revision=parent_revision,
summary=summary or "引擎判断当前工作流无需修改。",
proposed_graph=proposed_graph,
health=health,
)
is_auto_apply = apply_mode == "auto" is_auto_apply = apply_mode == "auto"
# Everything that would actually ship, measured against the live revision (not just engine patches).
changes_vs_live = _full_graph_diff(live_graph, proposed_graph)
constitution_ok, violations = validate_evolution_patch( constitution_ok, violations = validate_evolution_patch(
base_graph, live_graph if is_auto_apply else base_graph,
proposed_graph, proposed_graph,
diffs, changes_vs_live if is_auto_apply else diffs,
is_meta=False, is_meta=False,
is_auto=is_auto_apply, is_auto=is_auto_apply,
) )
@@ -1471,11 +1760,16 @@ async def propose_workflow_evolution(
new_revision = None new_revision = None
blocked_reason = "" blocked_reason = ""
ledger_entry: dict[str, Any] | None = None ledger_entry: dict[str, Any] | None = None
ab_eval: dict[str, Any] | None = None
if apply_mode == "draft": if apply_mode == "draft":
if not constitution_ok or not diffs: if trigger != "manual" and wf.draft_graph is not None:
# Never overwrite an admin's unpublished draft from a background run.
applied_status = "skipped"
blocked_reason = "存在未发布的人工草稿,自动进化不覆盖草稿,本轮跳过。"
elif not constitution_ok:
applied_status = "blocked" applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动" blocked_reason = ";".join(violations)
else: else:
await save_workflow_draft( await save_workflow_draft(
db, db,
@@ -1496,6 +1790,8 @@ async def propose_workflow_evolution(
"meta_revision": meta_revision, "meta_revision": meta_revision,
"summary": summary, "summary": summary,
"changes": diffs, "changes": diffs,
"changes_vs_live": changes_vs_live,
"built_on_human_draft": builds_on_human_draft,
}, },
) )
elif apply_mode == "auto": elif apply_mode == "auto":
@@ -1510,10 +1806,17 @@ async def propose_workflow_evolution(
if not budget_ok: if not budget_ok:
applied_status = "blocked" applied_status = "blocked"
blocked_reason = budget_msg blocked_reason = budget_msg
elif not constitution_ok or not diffs: elif not constitution_ok:
applied_status = "blocked" applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动" blocked_reason = ";".join(violations)
else: else:
# Auto-publish must prove on graded fixtures that the candidate is not worse than live.
ab_eval = await run_fixture_ab_eval(db, workflow_id, proposed_graph, max_fixtures=5)
gate_ok, gate_msg = _ab_gate_allows_auto_publish(ab_eval)
if not gate_ok:
applied_status = "blocked"
blocked_reason = gate_msg
if applied_status != "blocked":
prev_active_rev = int(wf.active_revision or 1) prev_active_rev = int(wf.active_revision or 1)
published = await publish_workflow( published = await publish_workflow(
db, db,
@@ -1521,6 +1824,7 @@ async def propose_workflow_evolution(
graph=proposed_graph, graph=proposed_graph,
change_summary=f"[Auto-Evolve/{mode}] {summary[:120]}", change_summary=f"[Auto-Evolve/{mode}] {summary[:120]}",
actor="system:auto_evolver", actor="system:auto_evolver",
keep_draft=True,
) )
applied_status = "auto_published" applied_status = "auto_published"
new_revision = int(published.get("active_revision") or (prev_active_rev + 1)) new_revision = int(published.get("active_revision") or (prev_active_rev + 1))
@@ -1539,6 +1843,8 @@ async def propose_workflow_evolution(
"baseline_failure_rate": health["failure_rate"], "baseline_failure_rate": health["failure_rate"],
"summary": summary, "summary": summary,
"changes": diffs, "changes": diffs,
"changes_vs_live": changes_vs_live,
"ab_eval_summary": (ab_eval or {}).get("summary"),
}, },
) )
if applied_status == "blocked": if applied_status == "blocked":
@@ -1554,6 +1860,7 @@ async def propose_workflow_evolution(
"summary": summary or f"{mode} blocked", "summary": summary or f"{mode} blocked",
"rollback_reason": blocked_reason, "rollback_reason": blocked_reason,
"changes": diffs, "changes": diffs,
"changes_vs_live": changes_vs_live,
}, },
) )
@@ -1564,6 +1871,7 @@ async def propose_workflow_evolution(
"meta_revision": meta_revision, "meta_revision": meta_revision,
"summary": summary or "暂无需要变更的字段。", "summary": summary or "暂无需要变更的字段。",
"changes": diffs, "changes": diffs,
"changes_vs_live": changes_vs_live,
"proposed_graph": proposed_graph, "proposed_graph": proposed_graph,
"constitution_ok": constitution_ok, "constitution_ok": constitution_ok,
"violations": violations, "violations": violations,
@@ -1571,6 +1879,7 @@ async def propose_workflow_evolution(
"new_revision": new_revision, "new_revision": new_revision,
"blocked_reason": blocked_reason, "blocked_reason": blocked_reason,
"ledger_entry": ledger_entry, "ledger_entry": ledger_entry,
"ab_eval": ab_eval,
"health": health, "health": health,
} }
@@ -1598,6 +1907,8 @@ async def _run_graph_single_sample(
answer = "" answer = ""
err = "" err = ""
nodes_done: list[str] = [] nodes_done: list[str] = []
verification: dict[str, Any] = {}
evidence_count = 0
try: try:
async for ev in run_workflow_dag_stream( async for ev in run_workflow_dag_stream(
db=db, db=db,
@@ -1613,6 +1924,10 @@ async def _run_graph_single_sample(
if ev_name == "done": if ev_name == "done":
answer = str(ev_data.get("answer_markdown") or "") answer = str(ev_data.get("answer_markdown") or "")
nodes_done = [str(x) for x in (ev_data.get("nodes") or [])] nodes_done = [str(x) for x in (ev_data.get("nodes") or [])]
if isinstance(ev_data.get("verification"), dict):
verification = ev_data["verification"]
if isinstance(ev_data.get("evidence"), dict):
evidence_count = len(ev_data["evidence"])
elif ev_name == "error": elif ev_name == "error":
err = str(ev_data.get("message") or "DAG error") err = str(ev_data.get("message") or "DAG error")
except Exception as exc: except Exception as exc:
@@ -1620,11 +1935,14 @@ async def _run_graph_single_sample(
latency_ms = max(0, int((_utc_now() - started).total_seconds() * 1000)) latency_ms = max(0, int((_utc_now() - started).total_seconds() * 1000))
return { return {
"ok": bool(answer.strip()) and not err, "answer": answer,
"latency_ms": latency_ms, "latency_ms": latency_ms,
"answer_length": len(answer.strip()), "answer_length": len(answer.strip()),
"nodes": nodes_done, "nodes": nodes_done,
"error": err, "error": err,
"verification_passed": bool(verification.get("passed", True)),
"verification_warnings": list(verification.get("warnings") or []),
"evidence_count": evidence_count,
} }
@@ -1874,7 +2192,11 @@ async def propose_meta_evolution(
if meta_wf is None: if meta_wf is None:
raise HTTPException(status_code=404, detail=f"Workflow '{META_WORKFLOW_ID}' not found") raise HTTPException(status_code=404, detail=f"Workflow '{META_WORKFLOW_ID}' not found")
base_graph = copy.deepcopy(meta_wf.draft_graph or meta_wf.published_graph or {}) builds_on_human_draft = trigger == "meta_manual" and apply_mode != "auto" and meta_wf.draft_graph is not None
base_graph = copy.deepcopy(
meta_wf.draft_graph if builds_on_human_draft else (meta_wf.published_graph or {})
)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
ledger = await _load_ledger_entries(db) ledger = await _load_ledger_entries(db)
outcomes = [ outcomes = [
e e
@@ -1901,6 +2223,7 @@ async def propose_meta_evolution(
summary = "" summary = ""
raw_patches: list[dict[str, Any]] = [] raw_patches: list[dict[str, Any]] = []
meta_ai_decided = False
if ai_ready and client is not None: if ai_ready and client is not None:
schema = { schema = {
"type": "object", "type": "object",
@@ -1926,8 +2249,9 @@ async def propose_meta_evolution(
title="Meta-evolve workflow evolver", title="Meta-evolve workflow evolver",
objective=( objective=(
f"管理员指示:{instruction.strip() or '基于进化台账中已验证与被回滚/忽略的案例,优化元引擎诊断与补丁合成精度。'}\n" f"管理员指示:{instruction.strip() or '基于进化台账中已验证与被回滚/忽略的案例,优化元引擎诊断与补丁合成精度。'}\n"
"仅允许修改 `diag_node` 或 `patch_node` 的提示词或 thinking_enabled;" "仅允许修改 `diag_node` 的 system_prompt/prompt,或 `patch_node` 的 system_prompt/prompt/thinking_enabled;"
"严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。" "严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。\n"
f"{_NO_CHANGE_CLAUSE}"
), ),
system_prompt="你是智能星球 AI 元进化策略师。仅输出严格 JSON:{summary, node_patches}。", system_prompt="你是智能星球 AI 元进化策略师。仅输出严格 JSON:{summary, node_patches}。",
context={ context={
@@ -1949,6 +2273,7 @@ async def propose_meta_evolution(
summary = str(parsed.get("summary") or "").strip() summary = str(parsed.get("summary") or "").strip()
if isinstance(parsed.get("node_patches"), list): if isinstance(parsed.get("node_patches"), list):
raw_patches = parsed["node_patches"] raw_patches = parsed["node_patches"]
meta_ai_decided = True
except Exception as exc: except Exception as exc:
logger.warning_event( logger.warning_event(
"AI meta-evolution request failed; using deterministic prompt refinement", "AI meta-evolution request failed; using deterministic prompt refinement",
@@ -1956,7 +2281,8 @@ async def propose_meta_evolution(
context={"error": str(exc)}, context={"error": str(exc)},
) )
if not raw_patches: if not meta_ai_decided and (instruction.strip() or outcomes):
# Deterministic refinement needs a real basis: an admin instruction or ledger outcomes.
target_node = next( target_node = next(
(n for n in (base_graph.get("nodes") or []) if n.get("id") == "patch_node"), (n for n in (base_graph.get("nodes") or []) if n.get("id") == "patch_node"),
None, None,
@@ -1987,7 +2313,25 @@ async def propose_meta_evolution(
f"基于 {len(outcomes)} 条进化台账记录(验证有效 {verified_count},回滚 {rollback_count},忽略 {dismissed_count})生成元引擎自举方案。" f"基于 {len(outcomes)} 条进化台账记录(验证有效 {verified_count},回滚 {rollback_count},忽略 {dismissed_count})生成元引擎自举方案。"
) )
# Drop patches to fields that have no downstream effect on the business proposal request.
raw_patches = [
p
for p in raw_patches
if isinstance(p, dict)
and (str(p.get("node_id") or ""), str(p.get("field") or "")) in META_EVOLVABLE_FIELDS
]
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches) proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
if not diffs:
return {
**_no_change_result(
workflow_id=META_WORKFLOW_ID,
mode="meta",
base_revision=int(meta_wf.active_revision or 1),
summary=summary or "元引擎判断当前策略无需修改(暂无进化台账结果或明确指示)。",
proposed_graph=proposed_graph,
),
"outcomes_analyzed": len(outcomes),
}
is_auto_apply = apply_mode == "auto" is_auto_apply = apply_mode == "auto"
constitution_ok, violations = validate_evolution_patch( constitution_ok, violations = validate_evolution_patch(
base_graph, base_graph,
@@ -2004,9 +2348,12 @@ async def propose_meta_evolution(
policy = await get_evolution_policy(db) policy = await get_evolution_policy(db)
if apply_mode == "draft": if apply_mode == "draft":
if not constitution_ok or not diffs: if trigger != "meta_manual" and meta_wf.draft_graph is not None:
applied_status = "skipped"
blocked_reason = "存在未发布的人工元引擎草稿,自动元进化不覆盖草稿,本轮跳过。"
elif not constitution_ok:
applied_status = "blocked" applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动" blocked_reason = ";".join(violations)
else: else:
await save_workflow_draft( await save_workflow_draft(
db, db,
@@ -2045,9 +2392,9 @@ async def propose_meta_evolution(
if not budget_ok: if not budget_ok:
applied_status = "blocked" applied_status = "blocked"
blocked_reason = budget_msg blocked_reason = budget_msg
elif not constitution_ok or not diffs: elif not constitution_ok:
applied_status = "blocked" applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动" blocked_reason = ";".join(violations)
else: else:
prev_rev = int(meta_wf.active_revision or 1) prev_rev = int(meta_wf.active_revision or 1)
published = await publish_workflow( published = await publish_workflow(
@@ -2056,6 +2403,7 @@ async def propose_meta_evolution(
graph=proposed_graph, graph=proposed_graph,
change_summary=f"[Meta-Evolve] {summary[:120]}", change_summary=f"[Meta-Evolve] {summary[:120]}",
actor="system:meta_evolver" if trigger != "meta_manual" else actor, actor="system:meta_evolver" if trigger != "meta_manual" else actor,
keep_draft=True,
) )
applied_status = "auto_published" applied_status = "auto_published"
new_revision = int(published.get("active_revision") or (prev_rev + 1)) new_revision = int(published.get("active_revision") or (prev_rev + 1))
+26 -7
View File
@@ -4,14 +4,13 @@ from __future__ import annotations
from collections import deque from collections import deque
import copy import copy
from datetime import UTC, datetime
import inspect import inspect
import json import json
import re import re
from typing import Any from typing import Any
from uuid import uuid4 from uuid import uuid4
from fastapi import HTTPException, status from fastapi import HTTPException
from sqlalchemy import delete, desc, select from sqlalchemy import delete, desc, select
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
@@ -140,6 +139,8 @@ TOOL_CATALOG: list[dict[str, Any]] = [
VALID_TOOL_IDS: frozenset[str] = frozenset(item["id"] for item in TOOL_CATALOG) VALID_TOOL_IDS: frozenset[str] = frozenset(item["id"] for item in TOOL_CATALOG)
MAX_WORKFLOW_NODES = 12 MAX_WORKFLOW_NODES = 12
# Graph-level key carrying Earth bindings inside drafts and revision snapshots (no extra column).
DRAFT_BINDINGS_KEY = "bindings"
VALID_NODE_TYPES: frozenset[str] = frozenset( VALID_NODE_TYPES: frozenset[str] = frozenset(
{"trigger", "deterministic", "llm_agent", "guardrail", "output"} {"trigger", "deterministic", "llm_agent", "guardrail", "output"}
) )
@@ -1355,7 +1356,7 @@ async def create_workflow(
workflow_id=wf_id, workflow_id=wf_id,
revision=1, revision=1,
status="published", status="published",
graph_json=validated_graph, graph_json={**validated_graph, DRAFT_BINDINGS_KEY: dict(normalized_bindings)},
change_summary="Created custom workflow", change_summary="Created custom workflow",
created_by=actor, created_by=actor,
) )
@@ -1437,7 +1438,11 @@ async def update_workflow_metadata(
if description_en is not None: if description_en is not None:
row.description_en = description_en.strip() row.description_en = description_en.strip()
if bindings is not None: if bindings is not None:
# Explicit "save bindings now" is a deliberate live change; keep any pending draft in sync
# so a later draft publish does not silently revert it.
row.bindings = normalize_bindings(bindings) row.bindings = normalize_bindings(bindings)
if isinstance(row.draft_graph, dict):
row.draft_graph = {**row.draft_graph, DRAFT_BINDINGS_KEY: dict(row.bindings)}
row.updated_by = actor row.updated_by = actor
await db.commit() await db.commit()
await db.refresh(row) await db.refresh(row)
@@ -1480,9 +1485,17 @@ async def save_workflow_draft(
).scalar_one_or_none() ).scalar_one_or_none()
if row is None: if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
row.draft_graph = _validate_graph_payload(graph) previous_draft_bindings = (
row.draft_graph.get(DRAFT_BINDINGS_KEY) if isinstance(row.draft_graph, dict) else None
)
staged = _validate_graph_payload(graph)
# Draft bindings stay inside the draft so the public Earth entry only changes on publish
# and is restored by discarding the draft.
if bindings is not None: if bindings is not None:
row.bindings = normalize_bindings(bindings) staged[DRAFT_BINDINGS_KEY] = normalize_bindings(bindings)
elif isinstance(previous_draft_bindings, dict):
staged[DRAFT_BINDINGS_KEY] = previous_draft_bindings
row.draft_graph = staged
if name is not None and name.strip(): if name is not None and name.strip():
row.name = name.strip()[:160] row.name = name.strip()[:160]
if description is not None: if description is not None:
@@ -1523,6 +1536,7 @@ async def publish_workflow(
description: str | None = None, description: str | None = None,
change_summary: str = "", change_summary: str = "",
actor: str = "admin", actor: str = "admin",
keep_draft: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
await ensure_builtin_workflows(db) await ensure_builtin_workflows(db)
row = ( row = (
@@ -1531,13 +1545,17 @@ async def publish_workflow(
if row is None: if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
target_graph = graph if graph is not None else (row.draft_graph or row.published_graph) target_graph = graph if graph is not None else (row.draft_graph or row.published_graph)
staged_bindings = target_graph.get(DRAFT_BINDINGS_KEY) if isinstance(target_graph, dict) else None
validated = _validate_graph_payload(target_graph) validated = _validate_graph_payload(target_graph)
next_rev = int(row.active_revision or 1) + 1 next_rev = int(row.active_revision or 1) + 1
row.published_graph = validated row.published_graph = validated
row.draft_graph = None if not keep_draft:
row.draft_graph = None
row.active_revision = next_rev row.active_revision = next_rev
if bindings is not None: if bindings is not None:
row.bindings = normalize_bindings(bindings) row.bindings = normalize_bindings(bindings)
elif isinstance(staged_bindings, dict):
row.bindings = normalize_bindings(staged_bindings)
if name is not None and name.strip(): if name is not None and name.strip():
row.name = name.strip()[:160] row.name = name.strip()[:160]
if description is not None: if description is not None:
@@ -1548,7 +1566,8 @@ async def publish_workflow(
workflow_id=workflow_id, workflow_id=workflow_id,
revision=next_rev, revision=next_rev,
status="published", status="published",
graph_json=validated, # Snapshot bindings with the graph so rollback restores the matching Earth entry.
graph_json={**validated, DRAFT_BINDINGS_KEY: dict(row.bindings or {})},
change_summary=change_summary.strip() or f"Published revision v{next_rev}", change_summary=change_summary.strip() or f"Published revision v{next_rev}",
created_by=actor, created_by=actor,
) )
+487
View File
@@ -94,6 +94,17 @@ def get_active_run_handle(run_id: str) -> ActiveRunHandle | None:
return _ACTIVE_RUNS.get(run_id) return _ACTIVE_RUNS.get(run_id)
def register_active_run_handle(handle: ActiveRunHandle) -> ActiveRunHandle:
"""Register an active streaming/execution run handle for explicit cooperative cancellation."""
_ACTIVE_RUNS[handle.run_id] = handle
return handle
def unregister_active_run_handle(run_id: str) -> None:
"""Remove an active run handle once execution finishes or aborts."""
_ACTIVE_RUNS.pop(run_id, None)
def cancel_active_run_handle(run_id: str) -> bool: def cancel_active_run_handle(run_id: str) -> bool:
"""Signal cancellation event and abort in-flight asyncio task if active.""" """Signal cancellation event and abort in-flight asyncio task if active."""
handle = _ACTIVE_RUNS.get(run_id) handle = _ACTIVE_RUNS.get(run_id)
@@ -136,6 +147,481 @@ class WorkbenchBlockSpec(BaseModel):
data: dict[str, Any] = Field(default_factory=dict) data: dict[str, Any] = Field(default_factory=dict)
class InfluenceZoneEdgeSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
style: Literal["soft", "sharp"] = "soft"
feather_px: float = Field(default=22.0, ge=0.0, le=48.0)
border_width: float = Field(default=1.5, ge=0.0, le=6.0)
class InfluenceZoneAnimationSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
type: Literal["sweep", "radial", "fade"] = "sweep"
direction: str = Field(default="west_to_east", max_length=32)
duration_ms: int = Field(default=1800, ge=150, le=8000)
delay_ms: int = Field(default=0, ge=0, le=5000)
class InfluenceZoneShapeSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
mode: Literal["countries", "region_preset", "circle", "polygon"]
countries: list[str] = Field(default_factory=list, max_length=64)
region_preset: str | None = Field(default=None, max_length=32)
center: list[float] | None = Field(default=None, min_length=2, max_length=2)
radius_km: float | None = Field(default=None, ge=20.0, le=15000.0)
coordinates: list[list[list[float]]] = Field(default_factory=list, max_length=16)
class InfluenceZoneSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str = Field(..., min_length=1, max_length=64)
label: str = Field(default="", max_length=80)
color: str = Field(default="#38bdf8", pattern=r"^#[0-9a-fA-F]{6}$")
opacity: float = Field(default=0.42, ge=0.05, le=0.9)
z_index: int = Field(default=0, ge=-50, le=50)
edge: InfluenceZoneEdgeSpec = Field(default_factory=InfluenceZoneEdgeSpec)
animation: InfluenceZoneAnimationSpec = Field(default_factory=InfluenceZoneAnimationSpec)
shape: InfluenceZoneShapeSpec
_SCENE_COLOR_NAMES: dict[str, str] = {
"red": "#ef4444",
"crimson": "#dc2626",
"orange": "#f97316",
"amber": "#f59e0b",
"yellow": "#eab308",
"green": "#22c55e",
"emerald": "#10b981",
"teal": "#14b8a6",
"cyan": "#06b6d4",
"blue": "#38bdf8",
"indigo": "#6366f1",
"purple": "#a855f7",
"violet": "#8b5cf6",
"pink": "#ec4899",
"white": "#f8fafc",
}
SUPPORTED_REGION_PRESETS: frozenset[str] = frozenset(
{
"APEC",
"ASIA_PACIFIC",
"NORTHEAST_ASIA",
"EAST_ASIA",
"KOREAN_PENINSULA",
"SOUTHEAST_ASIA",
"SOUTH_ASIA",
"CENTRAL_ASIA",
"INDO_PACIFIC",
"ASEAN",
"EU",
"EUROPE",
"EASTERN_EUROPE",
"NORTHERN_EUROPE",
"WESTERN_EUROPE",
"G7",
"BRICS",
"NATO",
"MIDDLE_EAST",
"MENA",
"AMERICAS",
"NORTH_AMERICA",
"SOUTH_AMERICA",
"AFRICA",
}
)
_REGION_PRESET_ALIASES: dict[str, str] = {
"东北亚": "NORTHEAST_ASIA",
"NE_ASIA": "NORTHEAST_ASIA",
"东亚": "EAST_ASIA",
"朝鲜半岛": "KOREAN_PENINSULA",
"PENINSULA": "KOREAN_PENINSULA",
"东南": "SOUTHEAST_ASIA",
"东南亚": "SOUTHEAST_ASIA",
"SE_ASIA": "SOUTHEAST_ASIA",
"南亚": "SOUTH_ASIA",
"中亚": "CENTRAL_ASIA",
"亚太": "ASIA_PACIFIC",
"印太": "INDO_PACIFIC",
"欧洲": "EUROPE",
"东欧": "EASTERN_EUROPE",
"北欧": "NORTHERN_EUROPE",
"NORDIC": "NORTHERN_EUROPE",
"BALTIC": "NORTHERN_EUROPE",
"波罗的海": "NORTHERN_EUROPE",
"西欧": "WESTERN_EUROPE",
"欧盟": "EU",
"北约": "NATO",
"东盟": "ASEAN",
"中东": "MIDDLE_EAST",
"中东北非": "MENA",
"MIDDLE_EAST_NORTH_AFRICA": "MENA",
"美洲": "AMERICAS",
"北美": "NORTH_AMERICA",
"南美": "SOUTH_AMERICA",
"拉美": "SOUTH_AMERICA",
"LATIN_AMERICA": "SOUTH_AMERICA",
"非洲": "AFRICA",
}
_COUNTRY_ALIAS_MAP: dict[str, str] = {
"CN": "CHN",
"CHN": "CHN",
"CHINA": "CHN",
"PRC": "CHN",
"中国": "CHN",
"HK": "CHN",
"HKG": "CHN",
"香港": "CHN",
"MO": "CHN",
"MAC": "CHN",
"澳门": "CHN",
"TW": "CHN",
"TWN": "CHN",
"台湾": "CHN",
"KP": "PRK",
"PRK": "PRK",
"DPRK": "PRK",
"NK": "PRK",
"NKR": "PRK",
"NORTH KOREA": "PRK",
"NORTH_KOREA": "PRK",
"朝鲜": "PRK",
"北朝鲜": "PRK",
"朝鲜民主主义人民共和国": "PRK",
"KR": "KOR",
"KOR": "KOR",
"ROK": "KOR",
"KOREA": "KOR",
"SOUTH KOREA": "KOR",
"SOUTH_KOREA": "KOR",
"韩国": "KOR",
"南韩": "KOR",
"大韩民国": "KOR",
"US": "USA",
"USA": "USA",
"AMERICA": "USA",
"美国": "USA",
"RU": "RUS",
"RUS": "RUS",
"RUSSIA": "RUS",
"俄罗斯": "RUS",
"俄国": "RUS",
"JP": "JPN",
"JPN": "JPN",
"JAPAN": "JPN",
"日本": "JPN",
"UK": "GBR",
"GB": "GBR",
"GBR": "GBR",
"BRITAIN": "GBR",
"英国": "GBR",
"FR": "FRA",
"FRA": "FRA",
"FRANCE": "FRA",
"法国": "FRA",
"DE": "DEU",
"DEU": "DEU",
"GERMANY": "DEU",
"德国": "DEU",
"IN": "IND",
"IND": "IND",
"INDIA": "IND",
"印度": "IND",
"AU": "AUS",
"AUS": "AUS",
"AUSTRALIA": "AUS",
"澳大利亚": "AUS",
"CA": "CAN",
"CAN": "CAN",
"CANADA": "CAN",
"加拿大": "CAN",
"BR": "BRA",
"BRA": "BRA",
"BRAZIL": "BRA",
"巴西": "BRA",
"SG": "SGP",
"SGP": "SGP",
"SINGAPORE": "SGP",
"新加坡": "SGP",
"ID": "IDN",
"IDN": "IDN",
"INDONESIA": "IDN",
"印尼": "IDN",
"VN": "VNM",
"VNM": "VNM",
"VIETNAM": "VNM",
"越南": "VNM",
"TH": "THA",
"THA": "THA",
"THAILAND": "THA",
"泰国": "THA",
"MY": "MYS",
"MYS": "MYS",
"MALAYSIA": "MYS",
"马来西亚": "MYS",
"PH": "PHL",
"PHL": "PHL",
"PHILIPPINES": "PHL",
"菲律宾": "PHL",
"UA": "UKR",
"UKR": "UKR",
"UKRAINE": "UKR",
"乌克兰": "UKR",
"IR": "IRN",
"IRN": "IRN",
"IRAN": "IRN",
"伊朗": "IRN",
"SA": "SAU",
"SAU": "SAU",
"沙特": "SAU",
"TR": "TUR",
"TUR": "TUR",
"TURKEY": "TUR",
"土耳其": "TUR",
"IL": "ISR",
"ISR": "ISR",
"ISRAEL": "ISR",
"以色列": "ISR",
"EG": "EGY",
"EGY": "EGY",
"EGYPT": "EGY",
"埃及": "EGY",
"SO": "SOM",
"SOM": "SOM",
"SOMALIA": "SOM",
"索马里": "SOM",
"YE": "YEM",
"YEM": "YEM",
"YEMEN": "YEM",
"也门": "YEM",
"AE": "ARE",
"ARE": "ARE",
"UAE": "ARE",
"阿联酋": "ARE",
"MN": "MNG",
"MNG": "MNG",
"MONGOLIA": "MNG",
"蒙古": "MNG",
"PL": "POL",
"POL": "POL",
"POLAND": "POL",
"波兰": "POL",
}
def _normalize_country_code(raw: Any) -> str:
text = str(raw or "").strip()
if not text:
return ""
upper = text.upper()
return _COUNTRY_ALIAS_MAP.get(text) or _COUNTRY_ALIAS_MAP.get(upper) or upper
def _normalize_region_preset(raw: Any) -> str | None:
text = str(raw or "").strip()
if not text:
return None
normalized = re.sub(r"[\s-]+", "_", text.upper())
canonical = _REGION_PRESET_ALIASES.get(text) or _REGION_PRESET_ALIASES.get(normalized) or normalized
return canonical[:32] if canonical in SUPPORTED_REGION_PRESETS else None
def _coerce_bounded_float(value: Any, low: float, high: float, default: float) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
return default
try:
num = float(value)
except Exception:
return default
return max(low, min(high, num))
def _coerce_bounded_int(value: Any, low: int, high: int, default: int) -> int:
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
return default
try:
num = int(float(value))
except Exception:
return default
return max(low, min(high, num))
def _normalize_zone_color(raw: Any) -> str:
text = str(raw or "").strip().lower()
if re.fullmatch(r"#[0-9a-f]{6}", text):
return text
if re.fullmatch(r"#[0-9a-f]{3}", text):
return "#" + "".join(ch * 2 for ch in text[1:])
return _SCENE_COLOR_NAMES.get(text, "#38bdf8")
def _normalize_influence_zone_candidate(item: dict[str, Any], idx: int) -> dict[str, Any]:
"""Sanitize tolerant LLM-authored influence zone fields before strict Pydantic validation."""
raw_edge = item.get("edge")
edge_dict: dict[str, Any] = {}
hoisted_opacity = None
if isinstance(raw_edge, str):
style = raw_edge.strip().lower()
edge_dict["style"] = style if style in {"soft", "sharp"} else "soft"
elif isinstance(raw_edge, dict):
if "opacity" in raw_edge:
hoisted_opacity = raw_edge.get("opacity")
style = str(raw_edge.get("style") or "soft").strip().lower()
edge_dict["style"] = style if style in {"soft", "sharp"} else "soft"
if "feather_px" in raw_edge:
edge_dict["feather_px"] = _coerce_bounded_float(raw_edge.get("feather_px"), 0.0, 48.0, 22.0)
if "border_width" in raw_edge:
edge_dict["border_width"] = _coerce_bounded_float(raw_edge.get("border_width"), 0.0, 6.0, 1.5)
raw_anim = item.get("animation")
anim_dict: dict[str, Any] = {}
if isinstance(raw_anim, str):
atype = raw_anim.strip().lower()
anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep"
elif isinstance(raw_anim, dict):
atype = str(raw_anim.get("type") or "sweep").strip().lower()
anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep"
if raw_anim.get("direction"):
anim_dict["direction"] = str(raw_anim["direction"])[:32]
if "duration_ms" in raw_anim:
anim_dict["duration_ms"] = _coerce_bounded_int(raw_anim.get("duration_ms"), 150, 8000, 1800)
if "delay_ms" in raw_anim:
anim_dict["delay_ms"] = _coerce_bounded_int(raw_anim.get("delay_ms"), 0, 5000, 0)
raw_shape = item.get("shape")
shape_src = dict(raw_shape) if isinstance(raw_shape, dict) else {
k: item[k]
for k in ("mode", "countries", "country", "iso_codes", "region_preset", "region", "center", "radius_km", "coordinates")
if k in item
}
raw_countries = shape_src.get("countries") if "countries" in shape_src else (shape_src.get("country") or shape_src.get("iso_codes"))
if isinstance(raw_countries, str):
raw_country_items = [raw_countries]
elif isinstance(raw_countries, list):
raw_country_items = raw_countries[:64]
else:
raw_country_items = []
countries_list: list[str] = []
seen_countries: set[str] = set()
for raw_c in raw_country_items:
norm_c = _normalize_country_code(raw_c)
if norm_c and norm_c not in seen_countries:
seen_countries.add(norm_c)
countries_list.append(norm_c)
region_preset = shape_src.get("region_preset") or shape_src.get("region")
region_preset_val = _normalize_region_preset(region_preset)
raw_center = shape_src.get("center")
center_val: list[float] | None = None
if isinstance(raw_center, dict) and "lat" in raw_center and "lon" in raw_center:
center_val = [
_coerce_bounded_float(raw_center.get("lat"), -90.0, 90.0, 0.0),
_coerce_bounded_float(raw_center.get("lon"), -180.0, 180.0, 0.0),
]
elif isinstance(raw_center, (list, tuple)) and len(raw_center) >= 2:
center_val = [
_coerce_bounded_float(raw_center[0], -90.0, 90.0, 0.0),
_coerce_bounded_float(raw_center[1], -180.0, 180.0, 0.0),
]
raw_coords = shape_src.get("coordinates")
coords_val: list[list[list[float]]] = []
if isinstance(raw_coords, list) and raw_coords:
first_coord = raw_coords[0]
# Auto-wrap 2D polygon rings ([[lon, lat], ...]) to MultiPolygon ring list ([[[lon, lat], ...]]).
if (
isinstance(first_coord, (list, tuple))
and first_coord
and isinstance(first_coord[0], (int, float))
):
coords_val = [raw_coords] # type: ignore[list-item]
else:
coords_val = raw_coords[:16]
mode = str(shape_src.get("mode") or "").strip().lower()
if mode not in {"countries", "region_preset", "circle", "polygon"}:
if countries_list:
mode = "countries"
elif region_preset_val:
mode = "region_preset"
elif center_val is not None:
mode = "circle"
elif coords_val:
mode = "polygon"
elif mode == "region_preset" and region_preset_val is None and countries_list:
mode = "countries"
shape_clean: dict[str, Any] = {"mode": mode}
if countries_list:
shape_clean["countries"] = countries_list
if region_preset_val:
shape_clean["region_preset"] = region_preset_val
if center_val is not None:
shape_clean["center"] = center_val
if shape_src.get("radius_km") is not None:
shape_clean["radius_km"] = _coerce_bounded_float(shape_src.get("radius_km"), 20.0, 15000.0, 600.0)
if coords_val:
shape_clean["coordinates"] = coords_val
opacity_raw = item.get("opacity", hoisted_opacity)
candidate: dict[str, Any] = {
"id": str(item.get("id") or f"zone-{idx + 1}").strip()[:64] or f"zone-{idx + 1}",
"label": str(item.get("label") or item.get("name") or item.get("title") or "")[:80],
"color": _normalize_zone_color(item.get("color")),
"opacity": _coerce_bounded_float(opacity_raw, 0.05, 0.9, 0.42),
"z_index": _coerce_bounded_int(item.get("z_index"), -50, 50, 0),
"shape": shape_clean,
}
if edge_dict:
candidate["edge"] = edge_dict
if anim_dict:
candidate["animation"] = anim_dict
return candidate
def validate_influence_zones(raw: Any) -> list[InfluenceZoneSpec]:
"""Validate and bound LLM-proposed influence zones without failing the response."""
if not isinstance(raw, list):
return []
validated: list[InfluenceZoneSpec] = []
for idx, item in enumerate(raw[:12]):
if not isinstance(item, dict):
continue
candidate = _normalize_influence_zone_candidate(item, idx)
shape = candidate.get("shape") or {}
mode = shape.get("mode")
has_renderable_shape = (
(mode == "countries" and bool(shape.get("countries")))
or (mode == "region_preset" and bool(shape.get("region_preset")))
or (mode == "circle" and shape.get("center") is not None)
or (mode == "polygon" and bool(shape.get("coordinates")))
)
if not has_renderable_shape:
logger.warning_event(
"Influence zone candidate rejected due to empty/unrenderable shape",
event="ai_scene.zone.rejected",
context={"index": idx, "mode": mode, "id": candidate.get("id")},
)
continue
try:
validated.append(InfluenceZoneSpec.model_validate(candidate))
except Exception as exc:
logger.warning_event(
"Influence zone candidate rejected",
event="ai_scene.zone.rejected",
context={"index": idx, "error": str(exc)},
)
continue
return validated
class SceneSpec(BaseModel): class SceneSpec(BaseModel):
model_config = ConfigDict(extra="forbid") model_config = ConfigDict(extra="forbid")
@@ -147,6 +633,7 @@ class SceneSpec(BaseModel):
camera_hint: dict[str, float] | None = None camera_hint: dict[str, float] | None = None
presentation_key: str | None = None presentation_key: str | None = None
auto_play_presentation: bool = False auto_play_presentation: bool = False
influence_zones: list[InfluenceZoneSpec] = Field(default_factory=list, max_length=12)
class ViewSpec(BaseModel): class ViewSpec(BaseModel):
+32 -18
View File
@@ -7,7 +7,7 @@ from datetime import UTC, datetime
from time import perf_counter from time import perf_counter
from urllib.parse import urlparse from urllib.parse import urlparse
import httpx import httpx
from sqlalchemy import delete, insert, select, text, update from sqlalchemy import delete, insert, select, update
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from app.core.collected_data_fields import build_dynamic_metadata, get_record_field from app.core.collected_data_fields import build_dynamic_metadata, get_record_field
@@ -66,6 +66,15 @@ class BaseCollector(ABC):
self._fetch_is_complete: bool = False self._fetch_is_complete: bool = False
self._fetch_is_sample_fallback: bool = False self._fetch_is_sample_fallback: bool = False
self._sample_fallback_reason: Optional[str] = None self._sample_fallback_reason: Optional[str] = None
self._db_commit_lock: Optional[asyncio.Lock] = asyncio.Lock()
def _get_db_commit_lock(self) -> asyncio.Lock:
"""Return the per-collector lock used to serialize DB session commits."""
lock = getattr(self, "_db_commit_lock", None)
if lock is None:
lock = asyncio.Lock()
self._db_commit_lock = lock
return lock
def _mark_fetch_complete(self, complete: bool = True) -> None: def _mark_fetch_complete(self, complete: bool = True) -> None:
"""Mark the current fetch payload as a verified full-universe snapshot.""" """Mark the current fetch payload as a verified full-universe snapshot."""
@@ -157,7 +166,9 @@ class BaseCollector(ABC):
async def update_progress(self, records_processed: int, *, commit: bool = False, force: bool = False): async def update_progress(self, records_processed: int, *, commit: bool = False, force: bool = False):
"""Update task progress - call this during data processing""" """Update task progress - call this during data processing"""
if self._current_task and self._db_session: if not self._current_task or not self._db_session:
return
async with self._get_db_commit_lock():
self._current_task.records_processed = records_processed self._current_task.records_processed = records_processed
if self._current_task.total_records and self._current_task.total_records > 0: if self._current_task.total_records and self._current_task.total_records > 0:
self._current_task.progress = ( self._current_task.progress = (
@@ -172,7 +183,9 @@ class BaseCollector(ABC):
await self._publish_task_update(force=force) await self._publish_task_update(force=force)
async def set_phase(self, phase: str, *, message: str | None = None, reset_progress: bool = True): async def set_phase(self, phase: str, *, message: str | None = None, reset_progress: bool = True):
if self._current_task and self._db_session: if not self._current_task or not self._db_session:
return
async with self._get_db_commit_lock():
self._current_task.phase = phase self._current_task.phase = phase
self._current_task.phase_message = message self._current_task.phase_message = message
if reset_progress: if reset_progress:
@@ -198,24 +211,25 @@ class BaseCollector(ABC):
if not self._current_task or not self._db_session: if not self._current_task or not self._db_session:
return return
if progress is None and current is not None and total and total > 0: async with self._get_db_commit_lock():
progress = (current / total) * 100 if progress is None and current is not None and total and total > 0:
progress = (current / total) * 100
if progress is not None: if progress is not None:
self._current_task.phase_progress = max(0.0, min(float(progress), 100.0)) self._current_task.phase_progress = max(0.0, min(float(progress), 100.0))
if current is not None: if current is not None:
self._current_task.phase_current = max(0, int(current)) self._current_task.phase_current = max(0, int(current))
if total is not None: if total is not None:
self._current_task.phase_total = max(0, int(total)) self._current_task.phase_total = max(0, int(total))
if unit is not None: if unit is not None:
self._current_task.phase_unit = unit self._current_task.phase_unit = unit
if message is not None: if message is not None:
self._current_task.phase_message = message self._current_task.phase_message = message
if commit: if commit:
await self._db_session.commit() await self._db_session.commit()
await self._publish_task_update(force=force) await self._publish_task_update(force=force)
@abstractmethod @abstractmethod
async def fetch(self) -> List[Dict[str, Any]]: async def fetch(self) -> List[Dict[str, Any]]:
+26 -25
View File
@@ -116,16 +116,17 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
] ]
total_expected = sum(expected_sizes) if expected_sizes else 0 total_expected = sum(expected_sizes) if expected_sizes else 0
if total_expected > 0 and self._current_task and self._db_session: if total_expected > 0 and self._current_task and self._db_session:
self._current_task.total_records = total_expected async with self._get_db_commit_lock():
self._current_task.records_processed = 0 self._current_task.total_records = total_expected
self._current_task.progress = 0.0 self._current_task.records_processed = 0
self._current_task.phase_progress = 0.0 self._current_task.progress = 0.0
self._current_task.phase_message = "正在下载 IPtoASN 数据" self._current_task.phase_progress = 0.0
self._current_task.phase_current = 0 self._current_task.phase_message = "正在下载 IPtoASN 数据"
self._current_task.phase_total = total_expected self._current_task.phase_current = 0
self._current_task.phase_unit = "bytes" self._current_task.phase_total = total_expected
await self._db_session.commit() self._current_task.phase_unit = "bytes"
await self._publish_task_update(force=True) await self._db_session.commit()
await self._publish_task_update(force=True)
url_progress: dict[str, int] = {url: 0 for url in dataset_urls} url_progress: dict[str, int] = {url: 0 for url in dataset_urls}
progress_lock = asyncio.Lock() progress_lock = asyncio.Lock()
@@ -136,29 +137,29 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
if total_expected <= 0: if total_expected <= 0:
return return
async with progress_lock: async with progress_lock:
current = max(0, downloaded_bytes) url_downloaded = max(0, downloaded_bytes)
if current < url_progress[url]: if url_downloaded < url_progress[url]:
return return
url_progress[url] = current url_progress[url] = url_downloaded
aggregated = sum(url_progress.values()) aggregated = sum(url_progress.values())
now = time.monotonic() now = time.monotonic()
current = min(aggregated, total_expected)
should_emit = ( should_emit = (
aggregated >= total_expected (current >= total_expected and last_emit["value"] < total_expected)
or aggregated - last_emit["value"] >= min_emit_bytes or current - last_emit["value"] >= min_emit_bytes
or now - last_emit["t"] >= 2.0 or (current > last_emit["value"] and now - last_emit["t"] >= 2.0)
) )
if not should_emit: if not should_emit:
return return
last_emit["value"] = aggregated last_emit["value"] = current
last_emit["t"] = now last_emit["t"] = now
current = min(aggregated, total_expected) await self.update_phase_progress(
await self.update_phase_progress( current=current,
current=current, total=total_expected,
total=total_expected, unit="bytes",
unit="bytes", message="正在下载 IPtoASN 数据",
message="正在下载 IPtoASN 数据", )
) await self.update_progress(current, commit=True)
await self.update_progress(current, commit=True)
dataset_paths = await asyncio.gather( dataset_paths = await asyncio.gather(
*( *(
@@ -52,9 +52,11 @@ class SpaceTrackTLECollector(BaseCollector):
async def fetch(self) -> List[Dict[str, Any]]: async def fetch(self) -> List[Dict[str, Any]]:
from app.core.config import settings from app.core.config import settings
from app.services.datasource_connectivity import resolve_spacetrack_credentials
username = settings.SPACETRACK_USERNAME username, password, _ = await resolve_spacetrack_credentials(self._db_session)
password = settings.SPACETRACK_PASSWORD username = username or settings.SPACETRACK_USERNAME
password = password or settings.SPACETRACK_PASSWORD
if not username or not password: if not username or not password:
logger.warning_event( logger.warning_event(
+27
View File
@@ -131,9 +131,36 @@ AISSTREAM_DEFAULT_GUIDE = CredentialGuideDefault(
) )
SPACETRACK_DEFAULT_GUIDE = CredentialGuideDefault(
provider="spacetrack",
title="Space-Track TLE 凭证获取教程",
prompt=(
"请生成一份中文教程,指导开发者注册并获取 Space-Track.org 的账号凭证并配置到 Planet。"
"包含注册登录、遵循查询频率限制(如 GP 查询间隔)、在 Planet 采集器配置页填写用户名与密码、"
"测试连通性与常见失败排查。请以 Space-Track 当前官网文档为准。"
),
markdown="""## Space-Track TLE 凭证获取
官方入口:https://www.space-track.org/
1. 前往 Space-Track.org 注册或登录账号。
2. 确认账号已完成邮箱激活且可正常通过网站登录。
3. 回到 Planet 的「采集管理 -> 采集器配置 -> `spacetrack_tle`」。
4. 填写 `用户名` 与 `密码`(或通过环境变量 `SPACETRACK_USERNAME` / `SPACETRACK_PASSWORD` 注入)。
5. 点击「连接测试」验证登录态与 TLE 查询接口后点击「保存」。
### 注意事项
- Space-Track 对 GP 数据接口有严格的限频策略,请避免高频手动重复抓取。
- 本源使用表单会话登录(`/ajaxauth/login`),不要将账号密码当作普通 HTTP Basic Header 暴露。
""",
)
DEFAULT_CREDENTIAL_GUIDES = { DEFAULT_CREDENTIAL_GUIDES = {
BARENTSWATCH_DEFAULT_GUIDE.provider: BARENTSWATCH_DEFAULT_GUIDE, BARENTSWATCH_DEFAULT_GUIDE.provider: BARENTSWATCH_DEFAULT_GUIDE,
AISSTREAM_DEFAULT_GUIDE.provider: AISSTREAM_DEFAULT_GUIDE, AISSTREAM_DEFAULT_GUIDE.provider: AISSTREAM_DEFAULT_GUIDE,
SPACETRACK_DEFAULT_GUIDE.provider: SPACETRACK_DEFAULT_GUIDE,
} }
+239 -36
View File
@@ -3,10 +3,13 @@
from __future__ import annotations from __future__ import annotations
from datetime import UTC, datetime from datetime import UTC, datetime
import csv
import hashlib import hashlib
import io
import json import json
import os import os
from typing import Any from typing import Any
from urllib.parse import urlparse
import httpx import httpx
from sqlalchemy import func, select from sqlalchemy import func, select
@@ -17,6 +20,7 @@ from app.core.enums import JobStatus
from app.models.collected_data import CollectedData from app.models.collected_data import CollectedData
from app.models.datasource import DataSource from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig from app.models.datasource_config import DataSourceConfig
from app.models.earth_news import EarthNewsItem
from app.models.system_setting import SystemSetting from app.models.system_setting import SystemSetting
from app.services.barentswatch import ( from app.services.barentswatch import (
BarentsWatchConfig, BarentsWatchConfig,
@@ -29,6 +33,26 @@ from app.services.barentswatch import (
CONNECTIVITY_VALIDATION_KEY = "connectivity_validation" CONNECTIVITY_VALIDATION_KEY = "connectivity_validation"
CONNECTIVITY_STORE_CATEGORY = "datasource_connectivity_validations" CONNECTIVITY_STORE_CATEGORY = "datasource_connectivity_validations"
SUPPORTED_CREDENTIAL_PROVIDERS = {"barentswatch", "spacetrack", "aisstream"} SUPPORTED_CREDENTIAL_PROVIDERS = {"barentswatch", "spacetrack", "aisstream"}
_ARCGIS_SOURCES = frozenset(
{"arcgis_cables", "arcgis_landing_points", "arcgis_cable_landing_relation"}
)
_EPOCH_CSV_URL = "https://epoch.ai/data/gpu_clusters.csv"
def _is_masked_secret(value: Any) -> bool:
if not isinstance(value, str):
return False
stripped = value.strip()
return bool(stripped) and set(stripped) <= {"•", "*"}
def _clean_override_value(override: dict[str, str] | None, key: str, *, secret: bool = False) -> str:
if not isinstance(override, dict):
return ""
raw = str(override.get(key) or "").strip()
if not raw or (secret and _is_masked_secret(raw)):
return ""
return raw
def _sha256_json(payload: Any) -> str: def _sha256_json(payload: Any) -> str:
@@ -46,26 +70,68 @@ def _resolve_spacetrack_credentials() -> tuple[str, str, str]:
return username, password, source or "missing" return username, password, source or "missing"
def _resolve_spacetrack_credentials_with_override( async def resolve_spacetrack_credentials(
db=None,
credential_override: dict[str, str] | None = None, credential_override: dict[str, str] | None = None,
) -> tuple[str, str, str]: ) -> tuple[str, str, str]:
if credential_override and ( """Resolve Space-Track credentials (`draft override -> DataSourceConfig -> env -> ~/.zshrc`)."""
credential_override.get("username") or credential_override.get("password") db_user = ""
): db_pass = ""
return ( if db is not None and hasattr(db, "execute"):
str(credential_override.get("username") or ""), try:
str(credential_override.get("password") or ""), result = await db.execute(
"draft", select(DataSourceConfig)
) .where(DataSourceConfig.name == "spacetrack_tle")
return _resolve_spacetrack_credentials() .where(DataSourceConfig.is_active.is_(True))
)
record = result.scalar_one_or_none()
if record is not None:
auth_cfg = record.auth_config or {}
runtime_cfg = record.config or {}
db_user = str(auth_cfg.get("username") or runtime_cfg.get("username") or "").strip()
db_pass = str(auth_cfg.get("password") or runtime_cfg.get("password") or "").strip()
except Exception:
db_user = ""
db_pass = ""
env_user, env_pass, env_source = _resolve_spacetrack_credentials()
username = db_user or env_user
password = db_pass or env_pass
source = "datasource_config" if (db_user or db_pass) else env_source
ov_user = _clean_override_value(credential_override, "username")
ov_pass = _clean_override_value(credential_override, "password", secret=True)
if ov_user or ov_pass:
return ov_user or username, ov_pass or password, "draft"
return username, password, source or "missing"
async def _resolve_barentswatch_with_override(
db,
endpoint: str,
credential_override: dict[str, str] | None = None,
) -> BarentsWatchConfig:
"""Resolve BarentsWatch credentials merging partial draft overrides with saved config."""
saved = await resolve_barentswatch_config(db)
ov_id = _clean_override_value(credential_override, "client_id")
ov_secret = _clean_override_value(credential_override, "client_secret", secret=True)
has_override = bool(ov_id or ov_secret)
return BarentsWatchConfig(
endpoint=str(endpoint or "").strip() or saved.endpoint,
client_id=ov_id or saved.client_id,
client_secret=ov_secret or saved.client_secret,
credential_source="draft" if has_override else saved.credential_source,
endpoint_source="draft" if str(endpoint or "").strip() else saved.endpoint_source,
)
async def _resolve_aisstream_api_key( async def _resolve_aisstream_api_key(
db=None, db=None,
credential_override: dict[str, str] | None = None, credential_override: dict[str, str] | None = None,
) -> tuple[str, str]: ) -> tuple[str, str]:
if credential_override and credential_override.get("api_key"): ov_key = _clean_override_value(credential_override, "api_key", secret=True)
return str(credential_override["api_key"]), "draft" if ov_key:
return ov_key, "draft"
env_key = os.getenv("AISSTREAM_API_KEY") env_key = os.getenv("AISSTREAM_API_KEY")
zshrc_key = _read_zshrc_env().get("AISSTREAM_API_KEY") zshrc_key = _read_zshrc_env().get("AISSTREAM_API_KEY")
@@ -125,15 +191,12 @@ async def build_builtin_connectivity_checksum(
has_credentials = not defaults.get("requires_credentials", False) has_credentials = not defaults.get("requires_credentials", False)
if credential_provider == "barentswatch": if credential_provider == "barentswatch":
if credential_override: barentswatch_config = await _resolve_barentswatch_with_override(
client_id = credential_override.get("client_id", "") db, endpoint, credential_override
client_secret = credential_override.get("client_secret", "") )
credential_source = "draft" client_id = barentswatch_config.client_id
else: client_secret = barentswatch_config.client_secret
barentswatch_config = await resolve_barentswatch_config(db) credential_source = barentswatch_config.credential_source
client_id = barentswatch_config.client_id
client_secret = barentswatch_config.client_secret
credential_source = barentswatch_config.credential_source
has_credentials = bool(client_id and client_secret) has_credentials = bool(client_id and client_secret)
credential_fingerprint = _sha256_json( credential_fingerprint = _sha256_json(
{ {
@@ -142,8 +205,8 @@ async def build_builtin_connectivity_checksum(
} }
) )
elif credential_provider == "spacetrack": elif credential_provider == "spacetrack":
username, password, credential_source = _resolve_spacetrack_credentials_with_override( username, password, credential_source = await resolve_spacetrack_credentials(
credential_override db, credential_override
) )
has_credentials = bool(username and password) has_credentials = bool(username and password)
credential_fingerprint = _sha256_json( credential_fingerprint = _sha256_json(
@@ -176,6 +239,113 @@ async def build_builtin_connectivity_checksum(
} }
def _prepare_builtin_http_probe(
source: str,
endpoint: str,
headers: dict[str, str],
) -> tuple[str, Any, dict[str, str]]:
"""Build lightweight protocol-accurate probe URL, params, and headers for a built-in source."""
probe_url = str(endpoint or "").strip()
probe_params: Any = None
probe_headers = dict(headers)
if source == "bgpstream_bgp":
base = probe_url.rstrip("/")
probe_url = base if base.endswith("/data") else f"{base}/data"
end = int(datetime.now(UTC).timestamp()) - 3600
start = end - 3600
probe_params = [
("projects[]", "routeviews"),
("collectors[]", "route-views2"),
("types[]", "updates"),
("intervals[]", f"{start},{end}"),
]
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
elif source == "celestrak_tle":
if "?" not in probe_url:
probe_params = {"CATNR": "25544", "FORMAT": "json"}
elif source in _ARCGIS_SOURCES:
if probe_url.rstrip("/").endswith("/query") and "f=" not in probe_url:
probe_params = {"where": "1=1", "returnCountOnly": "true", "f": "json"}
elif source == "epoch_ai_gpu":
parsed = urlparse(probe_url)
if parsed.hostname == "epoch.ai" and not parsed.path.endswith(".csv"):
probe_url = _EPOCH_CSV_URL
elif source == "ris_live_bgp":
probe_headers.setdefault(
"X-RIS-Subscribe",
json.dumps({"host": "rrc00", "type": "UPDATE", "require": "announcements"}),
)
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
return probe_url, probe_params, probe_headers
async def _read_bounded_probe_bytes(response: httpx.Response, limit: int = 65536) -> bytes:
chunks: list[bytes] = []
size = 0
async for chunk in response.aiter_bytes():
chunks.append(chunk)
size += len(chunk)
if size >= limit:
break
return b"".join(chunks)[:limit]
async def _validate_builtin_probe_response(source: str, response: httpx.Response) -> str | None:
"""Validate response content for sources that return HTTP 200 even on invalid queries."""
if source == "ris_live_bgp":
first_line = ""
async for line in response.aiter_lines():
stripped = line.strip()
if stripped:
first_line = stripped
break
if not first_line:
return "RIS Live 流未返回任何有效消息。"
try:
payload = json.loads(first_line)
except json.JSONDecodeError:
return "RIS Live 返回非 JSON 响应。"
return None if isinstance(payload, dict) else "RIS Live 响应结构异常。"
if source not in _ARCGIS_SOURCES | {"bgpstream_bgp", "celestrak_tle", "epoch_ai_gpu"}:
return None
limit = 4096 if source == "epoch_ai_gpu" else 65536
raw = await _read_bounded_probe_bytes(response, limit=limit)
text = raw.decode(response.encoding or "utf-8", errors="replace").lstrip("\ufeff").strip()
if source == "epoch_ai_gpu":
if text.lower().startswith(("<!doctype", "<html")):
return "Epoch AI 返回了 HTML 页面而非 CSV 数据集。"
first_line = next((line for line in text.splitlines() if line.strip()), "")
headers_row = next(csv.reader(io.StringIO(first_line)), [])
if not {"Name", "Country"}.issubset(set(headers_row)):
return "Epoch AI CSV 表头校验失败(缺少 Name / Country)。"
return None
if source == "celestrak_tle":
if text.lower().startswith("invalid query"):
return f"CelesTrak 参数校验失败:{text[:120]}"
try:
parsed = json.loads(text)
except json.JSONDecodeError:
return "CelesTrak 未返回有效 JSON。"
return None if isinstance(parsed, list) else "CelesTrak 返回格式不是 JSON 数组。"
try:
parsed_obj = json.loads(text)
except json.JSONDecodeError:
return "接口返回了非 JSON 内容(可能是 HTML 错误页)。"
if not isinstance(parsed_obj, dict):
return "接口返回的 JSON 结构无效。"
if parsed_obj.get("error"):
return f"上游接口报错:{str(parsed_obj['error'])[:120]}"
if source == "bgpstream_bgp" and "data" not in parsed_obj:
return "BGPStream Broker 响应缺少 data 字段。"
return None
async def test_builtin_connectivity( async def test_builtin_connectivity(
source: str, source: str,
endpoint: str, endpoint: str,
@@ -223,6 +393,27 @@ async def test_builtin_connectivity(
**credential_context, **credential_context,
} }
if source == "media_news_archive":
if db is not None and hasattr(db, "execute"):
try:
await db.execute(select(func.count(EarthNewsItem.id)))
except Exception as exc:
return {
"success": False,
"checksum": checksum,
"stage": "internal",
"message": f"本地新闻归档表检查失败:{exc.__class__.__name__}",
"error": str(exc),
**credential_context,
}
return {
"success": True,
"checksum": checksum,
"stage": "internal",
"message": "内部新闻归档采集器无需外部连接,本地数据源正常。",
**credential_context,
}
request_headers = {str(key): str(value) for key, value in (headers or {}).items()} request_headers = {str(key): str(value) for key, value in (headers or {}).items()}
request_config = strip_connectivity_validation(config) request_config = strip_connectivity_validation(config)
timeout = float(request_config.get("timeout") or 30) timeout = float(request_config.get("timeout") or 30)
@@ -245,19 +436,15 @@ async def test_builtin_connectivity(
**credential_context, **credential_context,
} }
probe_url, probe_params, request_headers = _prepare_builtin_http_probe(
source, request_endpoint, request_headers
)
try: try:
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client: async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
if credential_context["credential_provider"] == "barentswatch": if credential_context["credential_provider"] == "barentswatch":
if credential_override: barentswatch_config = await _resolve_barentswatch_with_override(
barentswatch_config = BarentsWatchConfig( db, request_endpoint, credential_override
endpoint=str(request_endpoint or ""), )
client_id=str(credential_override.get("client_id") or ""),
client_secret=str(credential_override.get("client_secret") or ""),
credential_source="draft",
endpoint_source="draft",
)
else:
barentswatch_config = await resolve_barentswatch_config(db)
token = await fetch_barentswatch_access_token(client, barentswatch_config) token = await fetch_barentswatch_access_token(client, barentswatch_config)
if not token: if not token:
return { return {
@@ -270,8 +457,8 @@ async def test_builtin_connectivity(
} }
request_headers["Authorization"] = f"Bearer {token}" request_headers["Authorization"] = f"Bearer {token}"
elif credential_context["credential_provider"] == "spacetrack": elif credential_context["credential_provider"] == "spacetrack":
username, password, _source = _resolve_spacetrack_credentials_with_override( username, password, _source = await resolve_spacetrack_credentials(
credential_override db, credential_override
) )
login_url = "https://www.space-track.org/ajaxauth/login" login_url = "https://www.space-track.org/ajaxauth/login"
login_response = await client.post( login_response = await client.post(
@@ -284,10 +471,26 @@ async def test_builtin_connectivity(
login_response.raise_for_status() login_response.raise_for_status()
started = datetime.now(UTC) started = datetime.now(UTC)
async with client.stream("GET", request_endpoint, headers=request_headers) as response: async with client.stream(
"GET",
probe_url,
params=probe_params,
headers=request_headers,
) as response:
response.raise_for_status() response.raise_for_status()
status_code = response.status_code status_code = response.status_code
body_error = await _validate_builtin_probe_response(source, response)
elapsed_ms = (datetime.now(UTC) - started).total_seconds() * 1000 elapsed_ms = (datetime.now(UTC) - started).total_seconds() * 1000
if body_error:
return {
"success": False,
"checksum": checksum,
"stage": "endpoint",
"message": body_error,
"error": body_error,
"status_code": status_code,
**credential_context,
}
return { return {
"success": True, "success": True,
@@ -2,8 +2,6 @@
from __future__ import annotations from __future__ import annotations
from typing import Any
import httpx import httpx
from ..models import LocationCandidate, LocationQuery, ResolverOutput from ..models import LocationCandidate, LocationQuery, ResolverOutput
+327
View File
@@ -277,3 +277,330 @@ async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"] assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"] assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"] assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
@pytest.mark.asyncio
async def test_stream_turn_extracts_planet_scene_and_emits_scene_event(monkeypatch):
from app.services.ai.workflow_runtime import SceneSpec
reset_stream_quota_ledger()
async def fake_global_tool(*_args, **_kwargs):
return {
"domain": "global",
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
}
async def fake_recent_news(*_args, **_kwargs):
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
class _SceneStreamingClient(AIProviderClient):
def __init__(self):
super().__init__(
service_url="http://aiprovider.test",
llm_config={
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "secret-key",
"model": "MiniMax-M2.7",
},
)
async def stream_analyze(self, payload, request_id=None):
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
yield {"event": "text", "delta": "APEC 峰会影响聚焦中美俄及亚太经济体。"}
yield {"event": "text", "delta": "\n<planet_"}
yield {
"event": "text",
"delta": (
'scene>{"camera_hint":{"lat":28.0,"lon":128.0},'
'"influence_zones":[{"id":"apec-core","label":"核心与会国","color":"#ef4444",'
'"opacity":0.62,"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"west_to_east"},'
'"shape":{"mode":"countries","countries":["CHN","USA","RUS"]}}]}</planet_scene>'
),
}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 64}}
app = FastAPI()
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
app.dependency_overrides[get_ai_provider_client] = lambda: _SceneStreamingClient()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
res = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "请分析这条国际新闻:「APEC 中美俄元首会晤」在地缘上的影响范围",
"domain": "news",
"news_context": {
"id": "apec-1",
"title": "APEC 中美俄元首会晤",
"summary": "中美俄三方会晤与亚太经济体协同",
"source": "Reuters",
"region": "亚太",
},
},
)
assert res.status_code == 200
events = _parse_sse_text(res.text)
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
assert "<planet_scene>" not in text_deltas
assert "APEC 峰会影响聚焦中美俄及亚太经济体" in text_deltas
scene_events = [data for name, data in events if name == "scene"]
assert len(scene_events) == 1
zones = scene_events[0]["scene_spec"]["influence_zones"]
assert len(zones) == 1
assert zones[0]["id"] == "apec-core"
assert zones[0]["shape"]["countries"] == ["CHN", "USA", "RUS"]
done_ev = events[-1][1]
assert "<planet_scene>" not in done_ev["answer_markdown"]
assert done_ev["scene_spec"]["camera_hint"]["lat"] == 28.0
validated = SceneSpec.model_validate({
"domain": "global",
"influence_zones": zones,
})
assert validated.influence_zones[0].edge.style == "sharp"
@pytest.mark.asyncio
async def test_workflow_dag_stream_emits_influence_zones_for_red_sea_news(monkeypatch):
reset_stream_quota_ledger()
class _EmptyScalarResult:
def scalar_one_or_none(self):
return None
class _DagStubDb(_StubDb):
async def execute(self, *_args, **_kwargs):
return _EmptyScalarResult()
async def fake_global_tool(*_args, **_kwargs):
return {"domain": "global", "domain_summaries": [], "evidence": {}}
async def fake_recent_news(*_args, **_kwargs):
return {
"domain": "news",
"available": True,
"count": 1,
"items": [{"id": "n-redsea", "title": "红海安全成为埃及与索马里军方会谈重点"}],
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Red Sea News"}},
}
monkeypatch.setattr("app.services.ai.dag_executor.query_global_situational_tool", fake_global_tool)
monkeypatch.setattr("app.services.ai.dag_executor.query_recent_earth_news_tool", fake_recent_news)
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
captured_requests = []
class _DagSceneClient(AIProviderClient):
def __init__(self):
super().__init__(
service_url="http://aiprovider.test",
llm_config={
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "secret-key",
"model": "MiniMax-M3.1-Flash",
},
)
async def stream_analyze(self, payload, request_id=None):
captured_requests.append(payload)
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
yield {"event": "text", "delta": "红海安全会谈核心涉及埃及与索马里及曼德海峡航道。\n<planet_sce"}
yield {
"event": "text",
"delta": (
'ne>{"camera_hint":{"lat":18.0,"lon":39.0},"influence_zones":['
'{"id":"redsea-corridor","label":"红海—曼德海峡走廊","color":"#38bdf8","opacity":0.28,'
'"edge":{"style":"soft"},"animation":{"type":"radial"},'
'"shape":{"mode":"circle","center":[15.5,42.5],"radius_km":950}},'
'{"id":"egy-som","label":"埃及与索马里","color":"#f59e0b","opacity":0.55,'
'"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"north_to_south"},'
'"shape":{"mode":"countries","countries":["EGY","SOM"]}}]}</planet_scene>'
),
}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
app = FastAPI()
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
app.dependency_overrides[situational_awareness.get_db] = lambda: _DagStubDb()
app.dependency_overrides[get_ai_provider_client] = lambda: _DagSceneClient()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
res = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "该事件影响范围?",
"domain": "news",
"workflow_id": "earth.news.analysis",
},
)
assert res.status_code == 200
events = _parse_sse_text(res.text)
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
assert "<planet_scene>" not in text_deltas
assert "红海安全会谈核心涉及埃及与索马里" in text_deltas
scene_events = [data for name, data in events if name == "scene"]
assert len(scene_events) == 1
zones = scene_events[0]["scene_spec"]["influence_zones"]
assert [z["id"] for z in zones] == ["redsea-corridor", "egy-som"]
done_ev = events[-1][1]
assert "<planet_scene>" not in done_ev["answer_markdown"]
assert len(done_ev["scene_spec"]["influence_zones"]) == 2
assert captured_requests and "scene_overlay_guidance" in captured_requests[0].context
assert "<planet_scene>" in (captured_requests[0].system_prompt or "")
def test_scene_directives_tolerate_code_fences_and_llm_field_quirks():
from app.services.ai.scene_directives import extract_planet_scene_from_text
from app.services.ai.workflow_runtime import validate_influence_zones
raw = (
"直接影响地区为中国市场。\n"
"<planet_scene>\n"
"```json\n"
"{\n"
' "influence_zones": [\n'
" {\n"
' "name": "直接影响:中国",\n'
' "color": "red",\n'
' "edge": {"style": "sharp", "opacity": 0.55, "extra_ignored": true},\n'
' "animation": "sweep",\n'
' "countries": "CHN",\n'
' "extra_note": "ignore me",\n'
" },\n"
" {\n"
' "id": "corridor",\n'
' "color": "#38b",\n'
' "opacity": 1.4,\n'
' "shape": {"mode": "circle", "center": {"lat": 15.5, "lon": 42.5}, "radius_km": 5}\n'
" },\n"
" ],\n"
' "camera_hint": {"lat": 35.0, "lon": 104.0}\n'
"}\n"
"```\n"
"</planet_scene>"
)
cleaned, parsed = extract_planet_scene_from_text(raw)
assert cleaned == "直接影响地区为中国市场。"
assert parsed is not None
assert parsed["camera_hint"] == {"lat": 35.0, "lon": 104.0}
zones = parsed["influence_zones"]
assert len(zones) == 2
assert zones[0]["label"] == "直接影响:中国"
assert zones[0]["color"] == "#ef4444"
assert zones[0]["opacity"] == pytest.approx(0.55)
assert zones[0]["edge"]["style"] == "sharp"
assert zones[0]["animation"]["type"] == "sweep"
assert zones[0]["shape"]["mode"] == "countries"
assert zones[0]["shape"]["countries"] == ["CHN"]
assert zones[1]["color"] == "#3388bb"
assert zones[1]["opacity"] == pytest.approx(0.9)
assert zones[1]["shape"]["center"] == [15.5, 42.5]
assert zones[1]["shape"]["radius_km"] == pytest.approx(20.0)
# Also test validate_influence_zones directly with edge string + flat region_preset
direct = validate_influence_zones(
[{"id": "apec", "color": "#f59e0b", "edge": "soft", "region_preset": "APEC"}]
)
assert len(direct) == 1
assert direct[0].edge.style == "soft"
assert direct[0].shape.mode == "region_preset"
assert direct[0].shape.region_preset == "APEC"
def test_validate_influence_zones_normalizes_dprk_presets_polygons_and_rejects_empty():
from app.services.ai.workflow_runtime import validate_influence_zones
zones = validate_influence_zones(
[
{"id": "core", "color": "red", "countries": ["CHN", "DPRK", "朝鲜", "KP"]},
{"id": "ne-asia", "color": "amber", "region_preset": "东北亚"},
{"id": "ne-asia-en", "color": "amber", "shape": {"mode": "region_preset", "region_preset": "northeast-asia"}},
{"id": "poly2d", "color": "#38bdf8", "coordinates": [[120.0, 35.0], [126.0, 35.0], [126.0, 40.0]]},
{"id": "unknown-preset", "color": "#38bdf8", "shape": {"mode": "region_preset", "region_preset": "MARS_BELT"}},
{"id": "empty-countries", "color": "#ef4444", "shape": {"mode": "countries", "countries": []}},
]
)
assert [z.id for z in zones] == ["core", "ne-asia", "ne-asia-en", "poly2d"]
assert zones[0].shape.countries == ["CHN", "PRK"]
assert zones[1].shape.mode == "region_preset"
assert zones[1].shape.region_preset == "NORTHEAST_ASIA"
assert zones[2].shape.region_preset == "NORTHEAST_ASIA"
assert zones[3].shape.mode == "polygon"
assert len(zones[3].shape.coordinates) == 1
assert len(zones[3].shape.coordinates[0]) == 3
@pytest.mark.asyncio
async def test_stream_turn_cooperative_cancel_stops_stream_and_preserves_session_memory(monkeypatch):
from types import SimpleNamespace
import app.services.ai.stream_turn as st_mod
from app.services.ai.workflow_runtime import cancel_active_run_handle
from app.services.ai.access_policy import AccessContext
async def _fake_recent_news(*_args, **_kwargs):
return {"items": [], "evidence": {}}
async def _fake_global_tool(*_args, **_kwargs):
return {"domain_summaries": [], "evidence": {}}
monkeypatch.setattr(st_mod, "query_recent_earth_news_tool", _fake_recent_news)
monkeypatch.setattr(st_mod, "query_global_situational_tool", _fake_global_tool)
class FakeSlowClient:
llm_config = {"provider": "minimax", "model": "MiniMax-M3.1-Flash", "max_tokens": 4096}
async def is_ready(self):
return True, "minimax", "MiniMax-M3.1-Flash"
async def stream_analyze(self, req, request_id=None):
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
yield {"event": "text", "delta": "first chunk "}
# Simulate cooperative cancel triggered by overlapping turn before finishing
assert cancel_active_run_handle(request_id) is True
yield {"event": "text", "delta": "should not appear"}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash", "usage": {}}
class DummyDb:
async def commit(self):
return None
session = SimpleNamespace(
id="sess-cancel-test",
context_state={"recent_messages": [{"role": "user", "content": "keep me"}], "domain": "news"},
pinned_items=[],
)
access = AccessContext(tier="public_zero_cost", actor_key="test-actor", hourly_paid_quota=100)
events = []
async for raw_ev in st_mod.stream_session_turn(
DummyDb(),
request=None,
session=session,
question="旧提问",
context_override={"domain": "news"},
news_context={"id": "n1", "title": "中朝关系", "source": "BBC World"},
access=access,
ai_client=FakeSlowClient(),
client_run_id="run-cancel-1",
):
events.append(raw_ev)
joined = "".join(events)
assert "should not appear" not in joined
assert "event: done" not in joined
assert session.context_state["recent_messages"] == [{"role": "user", "content": "keep me"}]
@@ -0,0 +1,414 @@
"""Regression tests for collector auth_type, secret persistence, Space-Track config, and probes."""
from __future__ import annotations
import asyncio
import gzip
from types import SimpleNamespace
import httpx
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker
from app.core.enums import AuthType
from app.core.security import get_current_user
from app.core.websocket.broadcaster import broadcaster
from app.db.session import Base, get_db
from app.main import app
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.earth_news import EarthNewsItem
from app.models.system_setting import SystemSetting
from app.services import datasource_connectivity
from app.services.collectors.base import BaseCollector
from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector
from app.services.collectors.spacetrack import SpaceTrackTLECollector
class _SyncAsAsyncSession:
def __init__(self, sync_session):
self._s = sync_session
def add(self, obj):
return self._s.add(obj)
async def execute(self, stmt, *args, **kwargs):
return self._s.execute(stmt, *args, **kwargs)
async def scalar(self, stmt, *args, **kwargs):
return self._s.scalar(stmt, *args, **kwargs)
async def get(self, model, ident):
return self._s.get(model, ident)
async def delete(self, obj):
return self._s.delete(obj)
async def commit(self):
return self._s.commit()
async def rollback(self):
return self._s.rollback()
async def refresh(self, obj):
return self._s.refresh(obj)
async def close(self):
return self._s.close()
def _make_db():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
engine,
tables=[
DataSourceConfig.__table__,
DataSource.__table__,
CollectedData.__table__,
SystemSetting.__table__,
EarthNewsItem.__table__,
],
)
sync_factory = sessionmaker(engine, expire_on_commit=False)
class _Ctx:
def __call__(self):
return self
async def __aenter__(self):
self._sess = _SyncAsAsyncSession(sync_factory())
return self._sess
async def __aexit__(self, *_args):
await self._sess.close()
return engine, _Ctx()
def _mock_httpx_factory(handler):
real_async_client = httpx.AsyncClient
transport = httpx.MockTransport(handler)
def _factory(*_args, **kwargs):
kwargs.pop("follow_redirects", None)
kwargs["transport"] = transport
return real_async_client(**kwargs)
return _factory
@pytest.mark.asyncio
async def test_barentswatch_oauth_client_accepted_and_partial_update_preserves_secret(monkeypatch):
assert AuthType.OAUTH_CLIENT.value == "oauth_client"
engine, factory = _make_db()
captured: dict = {}
def handler(request: httpx.Request) -> httpx.Response:
captured["urls"] = [*captured.get("urls", []), str(request.url)]
if "barentswatch.no/connect/token" in str(request.url):
captured["token_body"] = request.content.decode()
return httpx.Response(200, json={"access_token": "tok_test_123"})
captured["auth_header"] = request.headers.get("Authorization")
return httpx.Response(200, json=[])
monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler))
async def override_db():
async with factory() as session:
yield session
def override_user():
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
app.dependency_overrides[get_db] = override_db
app.dependency_overrides[get_current_user] = override_user
try:
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
# 1. Create BarentsWatch config with auth_type=oauth_client (previously 422)
create_resp = await client.post(
"/api/v1/datasources/configs",
json={
"name": "barentswatch_vessels",
"source_type": "api",
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
"auth_type": "oauth_client",
"auth_config": {"client_id": "id-1", "client_secret": "real-secret-1"},
},
)
assert create_resp.status_code == 200, create_resp.text
cfg_id = create_resp.json()["id"]
# 2. Partial PUT updating client_id (omitting masked client_secret) preserves real-secret-1
put_resp = await client.put(
f"/api/v1/datasources/configs/{cfg_id}",
json={
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
"auth_type": "oauth_client",
"auth_config": {"client_id": "id-2", "client_secret": "••••••••"},
},
)
assert put_resp.status_code == 200, put_resp.text
async with factory() as db:
row = (await db.execute(select(DataSourceConfig).where(DataSourceConfig.id == cfg_id))).scalar_one()
assert row.auth_config["client_id"] == "id-2"
assert row.auth_config["client_secret"] == "real-secret-1"
# 3. Builtin connect with partial auth_config uses merged saved secret
conn_resp = await client.post(
"/api/v1/datasources/configs/builtin/connect",
json={
"name": "barentswatch_vessels",
"source_type": "api",
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
"auth_type": "oauth_client",
"auth_config": {"client_id": "id-2"},
},
)
assert conn_resp.status_code == 200, conn_resp.text
assert conn_resp.json()["success"] is True
assert "client_secret=real-secret-1" in captured["token_body"]
assert captured["auth_header"] == "Bearer tok_test_123"
finally:
app.dependency_overrides.clear()
engine.dispose()
@pytest.mark.asyncio
async def test_spacetrack_collector_uses_saved_database_credentials(monkeypatch):
engine, factory = _make_db()
monkeypatch.delenv("SPACETRACK_USERNAME", raising=False)
monkeypatch.delenv("SPACETRACK_PASSWORD", raising=False)
monkeypatch.setattr(datasource_connectivity, "_read_zshrc_env", lambda: {})
posted: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "POST" and "ajaxauth/login" in str(request.url):
posted.append(request.content.decode())
return httpx.Response(200, text="{}")
if request.method == "GET" and str(request.url).rstrip("/").endswith("space-track.org"):
return httpx.Response(200, text="ok")
return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}])
monkeypatch.setattr("app.services.collectors.spacetrack.httpx.AsyncClient", _mock_httpx_factory(handler))
try:
async with factory() as db:
db.add(
DataSourceConfig(
name="spacetrack_tle",
source_type="api",
endpoint="https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json",
auth_type="basic",
auth_config={"username": "db-user", "password": "db-password"},
is_active=True,
)
)
await db.commit()
collector = SpaceTrackTLECollector()
collector._db_session = db
collector._resolved_url = "https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json"
rows = await collector.fetch()
assert rows == [{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}]
assert posted and "identity=db-user" in posted[0] and "password=db-password" in posted[0]
finally:
engine.dispose()
@pytest.mark.asyncio
async def test_builtin_connectivity_probes_match_collector_protocols(monkeypatch):
seen_requests: list[tuple[str, dict[str, str]]] = []
def handler(request: httpx.Request) -> httpx.Response:
url = str(request.url)
seen_requests.append((url, dict(request.headers)))
if "broker.bgpstream.caida.org" in url:
if url.endswith("/v2"):
return httpx.Response(404)
return httpx.Response(200, json={"error": None, "data": {"resources": []}})
if "celestrak.org" in url:
if "CATNR=25544" not in url:
return httpx.Response(200, text='Invalid query: ""')
return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544}])
if "services.arcgis.com" in url:
if "f=json" not in url:
return httpx.Response(200, text="<html>ArcGIS HTML</html>")
return httpx.Response(200, json={"count": 42})
if "epoch.ai" in url:
if url.endswith("gpu-clusters"):
return httpx.Response(200, text="<!doctype html><html></html>", headers={"content-type": "text/html"})
return httpx.Response(200, text="Name,Country,Status\nFrontier,USA,Active\n", headers={"content-type": "text/csv"})
if "ris-live.ripe.net" in url:
assert "x-ris-subscribe" in request.headers
return httpx.Response(200, text='{"type":"ris_message","data":{}}\n', headers={"content-type": "application/x-ndjson"})
return httpx.Response(404)
monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler))
engine, factory = _make_db()
try:
async with factory() as db:
for source, endpoint in [
("bgpstream_bgp", "https://broker.bgpstream.caida.org/v2"),
("celestrak_tle", "https://celestrak.org/NORAD/elements/gp.php"),
("arcgis_cables", "https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query"),
("epoch_ai_gpu", "https://epoch.ai/data/gpu-clusters"),
("ris_live_bgp", "https://ris-live.ripe.net/v1/stream/?format=json&client=planet-ris-live"),
("media_news_archive", ""),
]:
res = await datasource_connectivity.test_builtin_connectivity(
source, endpoint, "none", {}, {"timeout": 10}, db=db
)
assert res["success"] is True, (source, res)
assert any("/v2/data?" in url and "intervals%5B%5D=" in url for url, _ in seen_requests)
# Reject fake HTTP 200 responses when content fails validation (e.g., ArcGIS/CelesTrak bad params)
bad_arcgis = await datasource_connectivity.test_builtin_connectivity(
"arcgis_cables",
"https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query?f=html",
"none",
{},
{"timeout": 10},
)
assert bad_arcgis["success"] is False
bad_celestrak = await datasource_connectivity.test_builtin_connectivity(
"celestrak_tle",
"https://celestrak.org/NORAD/elements/gp.php?BAD=1",
"none",
{},
{"timeout": 10},
)
assert bad_celestrak["success"] is False
finally:
engine.dispose()
class _StrictNonConcurrentSession:
"""Fake AsyncSession that fails immediately if commit() is entered concurrently."""
def __init__(self, task: SimpleNamespace) -> None:
self.task = task
self._in_commit = False
self.active_commits = 0
self.max_concurrent_commits = 0
self.commit_count = 0
self.committed_progress: list[int] = []
async def commit(self) -> None:
if self._in_commit:
raise RuntimeError("concurrent operations are not permitted")
self._in_commit = True
self.active_commits += 1
self.max_concurrent_commits = max(self.max_concurrent_commits, self.active_commits)
try:
self.committed_progress.append(int(self.task.records_processed or 0))
await asyncio.sleep(0.01)
self.commit_count += 1
finally:
self.active_commits -= 1
self._in_commit = False
def _make_task_stub(task_id: int = 29) -> SimpleNamespace:
return SimpleNamespace(
id=task_id,
status="running",
phase="downloading",
phase_progress=0.0,
phase_message="",
phase_current=0,
phase_total=0,
phase_unit="bytes",
progress=0.0,
records_processed=0,
total_records=0,
started_at=None,
completed_at=None,
error_message=None,
)
@pytest.mark.asyncio
async def test_iptoasn_parallel_download_progress_serializes_db_commits(tmp_path, monkeypatch):
v4_path = tmp_path / "ip2asn-v4.tsv.gz"
v6_path = tmp_path / "ip2asn-v6.tsv.gz"
with gzip.open(v4_path, "wt", encoding="utf-8") as f:
f.write("1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET\n")
with gzip.open(v6_path, "wt", encoding="utf-8") as f:
f.write("2606:4700::\t2606:4700::ffff\t13335\tUS\tCLOUDFLARENET\n")
async def _noop_broadcast(_payload):
return None
monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast)
collector = IPtoASNPrefixGeoCollector()
task = _make_task_stub(task_id=29)
strict_session = _StrictNonConcurrentSession(task)
collector._resolved_url = "https://iptoasn.com/data/ip2asn-combined.tsv.gz"
collector._db_session = strict_session
collector._current_task = task
async def _fake_fetch_remote_info(_client, _url):
return {"content_length": 10_000_000}
async def _fake_download_dataset_file(_client, url, *, progress_callback=None):
for step in (2_500_000, 5_000_000, 7_500_000, 10_000_000, 10_000_000):
if progress_callback:
await progress_callback(step, 10_000_000)
await asyncio.sleep(0)
return v4_path if "v4" in url else v6_path
async def _no_short_circuit(_db, *, file_sha256):
return None
monkeypatch.setattr(collector._downloader, "fetch_remote_info", _fake_fetch_remote_info)
monkeypatch.setattr(collector, "_download_dataset_file", _fake_download_dataset_file)
monkeypatch.setattr(collector, "_can_short_circuit_unchanged_file", _no_short_circuit)
rows = await collector.fetch()
assert len(rows) == 2
assert {row["asn"] for row in rows} == {"13335"}
assert strict_session.max_concurrent_commits == 1
assert strict_session.commit_count >= 2
assert strict_session.committed_progress == sorted(strict_session.committed_progress)
assert collector._current_task.records_processed == 20_000_000
@pytest.mark.asyncio
async def test_base_collector_serializes_concurrent_progress_and_phase_commits(monkeypatch):
class _DummyCollector(BaseCollector):
name = "dummy_concurrent_collector"
async def fetch(self):
return []
async def _noop_broadcast(_payload):
return None
monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast)
collector = _DummyCollector()
task = _make_task_stub(task_id=30)
task.total_records = 10
strict_session = _StrictNonConcurrentSession(task)
collector._current_task = task
collector._db_session = strict_session
await asyncio.gather(
collector.update_progress(1, commit=True, force=True),
collector.update_phase_progress(current=2, total=10, unit="rows", message="step 2", commit=True, force=True),
collector.set_phase("downloading", message="step 3"),
collector.update_progress(4, commit=True, force=True),
collector.update_phase_progress(current=5, total=10, unit="rows", message="step 5", commit=True, force=True),
collector.set_phase("parsing", message="step 6"),
)
assert strict_session.max_concurrent_commits == 1
assert strict_session.commit_count == 6
+21 -3
View File
@@ -102,6 +102,21 @@ async def _make_sqlite_session():
return engine, _Ctx() return engine, _Ctx()
async def _add_graded_fixture(client, workflow_id: str) -> None:
"""Graded fixture that the deterministic (no-AI) fallback answer satisfies on both A/B sides."""
resp = await client.post(
f"/api/v1/ai/workflows/{workflow_id}/fixtures",
json={
"name": "Graded baseline",
"sample_question": "全球态势摘要",
"context_json": {"domain": "global"},
"expect": {"must_include": ["全球态势摘要"]},
},
)
assert resp.status_code == 200
assert resp.json()["context_json"]["expect"] == {"must_include": ["全球态势摘要"]}
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_meta_workflow_seeded_excluded_from_public_and_single_level_recursion_locked(): async def test_meta_workflow_seeded_excluded_from_public_and_single_level_recursion_locked():
engine, factory = await _make_sqlite_session() engine, factory = await _make_sqlite_session()
@@ -316,15 +331,15 @@ async def test_evolution_policy_feedback_health_model_drift_and_dgm_archive(monk
assert health["model_drift_detected"] is True assert health["model_drift_detected"] is True
assert "query_global_situational" in health["unused_tools"] assert "query_global_situational" in health["unused_tools"]
# 4. Propose `model_adapt` (deterministic fallback fills minimal patch) # 4. Model explicitly returns an empty patch -> the engine must accept "no change"
prop_resp = await client.post( prop_resp = await client.post(
"/api/v1/ai/evolution/propose/default.general", "/api/v1/ai/evolution/propose/default.general",
json={"mode": "model_adapt", "apply_mode": "preview"}, json={"mode": "model_adapt", "apply_mode": "preview"},
) )
assert prop_resp.status_code == 200 assert prop_resp.status_code == 200
prop = prop_resp.json() prop = prop_resp.json()
assert prop["constitution_ok"] is True assert prop["applied_status"] == "no_change"
assert len(prop["changes"]) >= 1 assert prop["changes"] == []
# 5. Incubate new custom workflow from `default.general` BGP runs # 5. Incubate new custom workflow from `default.general` BGP runs
inc_resp = await client.post("/api/v1/ai/evolution/incubate") inc_resp = await client.post("/api/v1/ai/evolution/incubate")
@@ -377,6 +392,8 @@ async def test_canary_auto_rollback_and_meta_canary_rollback(monkeypatch):
assert meta_pub.json()["applied_status"] == "auto_published" assert meta_pub.json()["applied_status"] == "auto_published"
assert meta_pub.json()["new_revision"] == 2 assert meta_pub.json()["new_revision"] == 2
# Auto-publish requires a graded fixture A/B gate
await _add_graded_fixture(client, "default.general")
# Auto-publish default.general v2 (uses live meta v2) # Auto-publish default.general v2 (uses live meta v2)
evo_pub = await client.post( evo_pub = await client.post(
"/api/v1/ai/evolution/propose/default.general", "/api/v1/ai/evolution/propose/default.general",
@@ -548,6 +565,7 @@ async def test_lock_quota_cooldown_dgm_branching_canary_verify_and_ledger_dismis
"/api/v1/ai/evolution/policy", "/api/v1/ai/evolution/policy",
json={"locked_workflows": [], "daily_auto_budget": 2}, json={"locked_workflows": [], "daily_auto_budget": 2},
) )
await _add_graded_fixture(client, "default.general")
pub1 = await client.post( pub1 = await client.post(
"/api/v1/ai/evolution/propose/default.general", "/api/v1/ai/evolution/propose/default.general",
json={"mode": "optimize", "instruction": "Always cite verified telemetry", "apply_mode": "auto"}, json={"mode": "optimize", "instruction": "Always cite verified telemetry", "apply_mode": "auto"},
@@ -0,0 +1,609 @@
"""Regression tests for the v0.82.0 workflow review: Earth DAG data/evidence/card output and evolver safety."""
from __future__ import annotations
import copy
import json
from types import SimpleNamespace
import pytest
from sqlalchemy import create_engine, event, select
from sqlalchemy.orm import sessionmaker
from app.db.session import Base
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.earth_news import EarthNewsItem
from app.models.situational_assessment import WorkflowRun
from app.models.system_setting import SystemSetting
from app.services.ai import dag_executor
from app.services.ai.dag_executor import _execute_tool, run_workflow_dag_stream
from app.services.ai.workflow_evolver import (
META_WORKFLOW_ID,
_load_ledger_entries,
append_ledger_entry,
build_business_evolution_request,
evaluate_canary_and_maybe_rollback,
grade_fixture_result,
propose_meta_evolution,
propose_workflow_evolution,
run_fixture_ab_eval,
update_evolution_policy,
)
from app.services.ai.workflow_registry import (
_fallback_workflow_dict,
create_workflow,
discard_workflow_draft,
ensure_builtin_workflows,
list_public_workflow_bindings,
publish_workflow,
rollback_workflow,
save_workflow_draft,
)
class _SyncAsAsyncSession:
def __init__(self, sync_session):
self._s = sync_session
def add(self, obj):
return self._s.add(obj)
async def execute(self, stmt, *args, **kwargs):
return self._s.execute(stmt, *args, **kwargs)
async def scalar(self, stmt, *args, **kwargs):
return self._s.scalar(stmt, *args, **kwargs)
async def get(self, model, ident):
return self._s.get(model, ident)
async def delete(self, obj):
return self._s.delete(obj)
async def flush(self):
return self._s.flush()
async def commit(self):
return self._s.commit()
async def rollback(self):
return self._s.rollback()
async def refresh(self, obj):
return self._s.refresh(obj)
async def close(self):
return self._s.close()
def _make_db():
engine = create_engine("sqlite:///:memory:")
event.listen(
engine,
"connect",
lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v),
)
Base.metadata.create_all(
engine,
tables=[
AIWorkflow.__table__,
AIWorkflowRevision.__table__,
AIWorkflowFixture.__table__,
WorkflowRun.__table__,
SystemSetting.__table__,
BGPIncident.__table__,
CollectedData.__table__,
EarthNewsItem.__table__,
],
)
return engine, _SyncAsAsyncSession(sessionmaker(engine, expire_on_commit=False)())
async def _collect(stream) -> list[dict]:
return [ev async for ev in stream]
def _done(events: list[dict]) -> dict:
return next(ev["data"] for ev in events if ev["event"] == "done")
def _text(events: list[dict]) -> str:
return "".join(ev["data"]["delta"] for ev in events if ev["event"] == "text")
# ---------------------------------------------------------------------------
# 1. Cross-layer evidence: each source must query its own object regardless of click order
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_multi_select_targets_route_each_source_to_its_own_object(monkeypatch):
seen: dict[str, list] = {"bgp": [], "cable": [], "vessel": []}
async def fake_bgp(_db, *, incident_key=None, **_kw):
seen["bgp"].append(incident_key)
return []
async def fake_cable(_db, *, entity_id=None, **_kw):
seen["cable"].append(entity_id)
return {}
async def fake_vessel(_db, *, entity_id=None, **_kw):
seen["vessel"].append(entity_id)
return {}
monkeypatch.setattr(dag_executor, "query_bgp_incidents_tool", fake_bgp)
monkeypatch.setattr(dag_executor, "query_cable_posture_tool", fake_cable)
monkeypatch.setattr(dag_executor, "query_vessel_posture_tool", fake_vessel)
cable = {"entity_type": "cable", "entity_id": "cable-peace"}
vessel = {"entity_type": "vessel", "entity_id": "mmsi-413000000"}
bgp = {"entity_type": "bgp", "entity_id": "bgp-incident-77"}
for order in ([cable, vessel, bgp], [bgp, vessel, cable], [vessel, bgp, cable]):
for tool in ("query_bgp_incidents", "query_cable_posture", "query_vessel_posture"):
await _execute_tool(
None, tool, question="q", targets=order, earth_context={}, allow_external_tools=False
)
assert set(seen["bgp"]) == {"bgp-incident-77"}
assert set(seen["cable"]) == {"cable-peace"}
assert set(seen["vessel"]) == {"mmsi-413000000"}
# A source with no matching target gets no ID (never another layer's ID).
seen["vessel"].clear()
await _execute_tool(None, "query_vessel_posture", question="q", targets=[cable, bgp], earth_context={}, allow_external_tools=False)
assert seen["vessel"] == [None]
# ---------------------------------------------------------------------------
# 2. Compute comparison workflow must hand a ViewSpec workbench to the Earth copilot
# ---------------------------------------------------------------------------
_SERIES = {
"years": (2023, 2024),
"compute": [
{"year": 2023, "values": {"CN": 30.0, "US": 52.0}, "evidence_id": "ev-top500-2023"},
{"year": 2024, "values": {"CN": 37.0, "US": 50.0}, "evidence_id": "ev-top500-2024"},
],
"unit": "%",
"evidence": {
"ev-top500-2023": {"id": "ev-top500-2023", "title": "TOP500 2023", "publisher": "TOP500", "url": "https://top500.org/2023"},
"ev-top500-2024": {"id": "ev-top500-2024", "title": "TOP500 2024", "publisher": "TOP500", "url": "https://top500.org/2024"},
},
"time_basis": "retrospective",
}
class _ComputeBriefAI:
def __init__(self, content: str):
self.content = content
self.stream_calls = 0
async def is_ready(self):
return True, "fake", "fake-model"
async def analyze(self, req):
return SimpleNamespace(content=self.content, provider="fake", model="fake-model")
async def stream_analyze(self, req, request_id=None):
self.stream_calls += 1
yield {"event": "text", "delta": "should not stream"}
@pytest.mark.asyncio
@pytest.mark.parametrize("valid_brief", [True, False])
async def test_compute_comparison_workflow_emits_view_spec_and_no_raw_json(monkeypatch, valid_brief):
async def fake_compute(_db, countries, mode="global_share", **_kw):
return copy.deepcopy(_SERIES)
monkeypatch.setattr(dag_executor, "query_compute_posture_tool", fake_compute)
brief = {
"headline": "中国算力份额升至 37%",
"headline_en": "China share rises to 37%",
"executive_assertion": "2024 年中国全球算力份额为 37%。",
"executive_assertion_en": "China held 37% in 2024.",
"causes": [
{"label": "装机增长", "detail": "新增超算集中投运", "evidence_ids": ["ev-top500-2024" if valid_brief else "ev-made-up"]}
],
"breakthrough_levers": [],
"blind_spots": ["未覆盖商业云内部集群"],
"evidence_ids": ["ev-top500-2024"],
}
ai = _ComputeBriefAI(json.dumps(brief, ensure_ascii=False))
workflow = _fallback_workflow_dict("compute.comparison")
events = await _collect(
run_workflow_dag_stream(
db=None,
workflow=workflow,
question="对比中美算力",
earth_context={"selected_codes": ["CN", "US"], "mode": "global_share"},
ai_client=ai,
)
)
done = _done(events)
text = _text(events)
assert ai.stream_calls == 0
assert not text.lstrip().startswith("{") and '"headline"' not in text
assert isinstance(done["view_spec"], dict) and done["view_spec"].get("blocks")
late_meta = [ev["data"] for ev in events if ev["event"] == "meta" and ev["data"].get("view_spec")]
assert late_meta and late_meta[-1]["domain"] == "compute"
if valid_brief:
assert "中国算力份额升至 37%" in text
else:
assert "确定性研判" in text
# ---------------------------------------------------------------------------
# 3. Evidence guardrail failures must reach the user and the evaluator
# ---------------------------------------------------------------------------
def _guarded_graph(system_prompt: str = "研判 BGP 成因") -> dict:
return {
"nodes": [
{"id": "t", "node_type": "trigger", "title": "入口"},
{"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": system_prompt},
{"id": "gr", "node_type": "guardrail", "title": "证据校验", "guardrails": {"require_evidence": True}},
{"id": "out", "node_type": "output", "title": "输出"},
],
"edges": [
{"id": "e1", "source": "t", "target": "llm"},
{"id": "e2", "source": "llm", "target": "gr"},
{"id": "e3", "source": "gr", "target": "out"},
],
}
class _StreamAI:
"""Streams an answer chosen by the node system prompt (lets A/B graphs answer differently)."""
def __init__(self, answers: dict[str, str], default: str = "研判完成"):
self.answers = answers
self.default = default
async def is_ready(self):
return True, "fake", "fake-model"
async def analyze(self, req):
return SimpleNamespace(content=self._pick(req), provider="fake", model="fake-model")
async def stream_analyze(self, req, request_id=None):
yield {"event": "text", "delta": self._pick(req)}
def _pick(self, req) -> str:
for key, answer in self.answers.items():
if key in (req.system_prompt or ""):
return answer
return self.default
@pytest.mark.asyncio
async def test_missing_evidence_marks_run_unverified_and_delivers_pending_cause():
workflow = {"workflow_id": "custom.bgp_cause", "name": "BGP 成因", "published_graph": _guarded_graph()}
events = await _collect(
run_workflow_dag_stream(
db=None, workflow=workflow, question="AS4837 为什么异常", ai_client=_StreamAI({}, "成因是上游劫持。")
)
)
done = _done(events)
assert done["status"] == "unverified"
assert done["verification"]["passed"] is False
assert "原因待核实" in done["answer_markdown"] and "待查项" in done["answer_markdown"]
failures = grade_fixture_result(
{"answer": done["answer_markdown"], "error": "", "verification_passed": False, "verification_warnings": done["verification"]["warnings"]},
{},
)
assert any("护栏" in f for f in failures)
# ---------------------------------------------------------------------------
# 4. News: one click runs only the interactive branch
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_news_analysis_runs_only_the_branch_matching_the_trigger(monkeypatch):
async def fake_news(_db, region=None, limit=10):
return {"items": [{"title": "headline"}], "evidence": {}}
async def fake_global(_db, **_kw):
return {"items": [], "evidence": {}}
monkeypatch.setattr(dag_executor, "query_recent_earth_news_tool", fake_news)
monkeypatch.setattr(dag_executor, "query_global_situational_tool", fake_global)
calls: list[str] = []
class _AI:
async def is_ready(self):
return True, "fake", "fake-model"
async def analyze(self, req):
calls.append("analyze")
return SimpleNamespace(content='{"location": {}, "localizations": {}}', provider="fake", model="m")
async def stream_analyze(self, req, request_id=None):
calls.append("stream")
yield {"event": "text", "delta": "研判正文"}
workflow = _fallback_workflow_dict("earth.news.analysis")
events = await _collect(run_workflow_dag_stream(db=None, workflow=workflow, question="分析这条新闻", ai_client=_AI()))
skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"}
assert "news_enrich_node" in skipped
assert calls == ["stream"]
assert _text(events) == "研判正文"
calls.clear()
events = await _collect(
run_workflow_dag_stream(db=None, workflow=workflow, question="enrich", ai_client=_AI(), trigger_source="ingest")
)
skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"}
assert "news_analyst_node" in skipped
# ---------------------------------------------------------------------------
# 5. Draft bindings stay out of the public Earth entry until publish; rollback restores them
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_draft_bindings_do_not_touch_public_entry_and_roll_back_with_graph():
engine, db = _make_db()
try:
await ensure_builtin_workflows(db)
wf_id = "earth.news.analysis"
async def public_ids() -> set[str]:
return {item["workflow_id"] for item in await list_public_workflow_bindings(db)}
assert wf_id in await public_ids()
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
graph = copy.deepcopy(row.published_graph)
live_bindings = copy.deepcopy(row.bindings)
disabled = {**live_bindings, "enabled": False}
saved = await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin")
assert wf_id in await public_ids()
assert saved["draft_bindings"]["enabled"] is False
await discard_workflow_draft(db, wf_id)
assert wf_id in await public_ids()
enabled_rev = (await publish_workflow(db, wf_id, graph=graph, bindings=live_bindings))["active_revision"]
await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin")
await publish_workflow(db, wf_id)
assert wf_id not in await public_ids()
await rollback_workflow(db, wf_id, enabled_rev)
assert wf_id in await public_ids()
finally:
engine.dispose()
# ---------------------------------------------------------------------------
# 6. Canary rollback must not overwrite a newer manual publish
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_canary_rollback_is_superseded_by_manual_publish():
from datetime import UTC, datetime, timedelta
engine, db = _make_db()
try:
await ensure_builtin_workflows(db)
wf_id = "default.general"
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
graph = copy.deepcopy(row.published_graph)
await publish_workflow(db, wf_id, graph=graph, actor="system:auto_evolver") # v2 canary
await append_ledger_entry(
db,
{"workflow_id": wf_id, "status": "canary", "base_revision": 1, "target_revision": 2, "canary_runs_target": 5},
)
manual = copy.deepcopy(graph)
manual["nodes"][0]["description"] = "manual v3"
await publish_workflow(db, wf_id, graph=manual, actor="admin") # v3 manual
now = datetime.now(UTC) + timedelta(seconds=2)
for idx in range(2):
db.add(
WorkflowRun(
id=f"v2_fail_{idx}", workflow_id=wf_id, status="failed", access_tier="admin", actor_key="admin",
question="q", input_params={}, tool_trace=[], budget_used={"workflow_revision": 2},
error_message="boom", started_at=now + timedelta(seconds=idx), completed_at=now + timedelta(seconds=idx + 1),
)
)
await db.commit()
res = await evaluate_canary_and_maybe_rollback(db, wf_id)
assert res["action"] == "superseded"
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
assert row.active_revision == 3
assert row.published_graph["nodes"][0]["description"] == "manual v3"
finally:
engine.dispose()
# ---------------------------------------------------------------------------
# 7. Evolver can conclude "no change" (business + meta)
# ---------------------------------------------------------------------------
class _EmptyPatchAI:
async def is_ready(self):
return True, "fake", "fake-model"
async def analyze(self, req):
return SimpleNamespace(content='{"summary": "无需修改", "node_patches": []}')
@pytest.mark.asyncio
async def test_explicit_empty_patch_ends_round_without_new_version():
engine, db = _make_db()
try:
await ensure_builtin_workflows(db)
await update_evolution_policy(db, {"business_mode": "auto", "meta_mode": "auto"})
for wf_id in ("compute.comparison", "default.general"):
for apply_mode in ("preview", "draft", "auto"):
res = await propose_workflow_evolution(
db, wf_id, apply_mode=apply_mode, ai_client=_EmptyPatchAI(), trigger="manual"
)
assert res["applied_status"] == "no_change", (wf_id, apply_mode)
meta_res = await propose_meta_evolution(db, apply_mode="auto", ai_client=_EmptyPatchAI())
assert meta_res["applied_status"] == "no_change"
class _NoAI:
async def is_ready(self):
return False, "", ""
# No AI, no ledger outcomes, no instruction -> nothing to base a meta rule on.
meta_fallback = await propose_meta_evolution(db, apply_mode="auto", ai_client=_NoAI())
assert meta_fallback["applied_status"] == "no_change"
rows = (await db.execute(select(AIWorkflow))).scalars().all()
assert all(r.active_revision == 1 and r.draft_graph is None for r in rows)
assert await _load_ledger_entries(db) == []
finally:
engine.dispose()
# ---------------------------------------------------------------------------
# 8. Graded A/B: 37 vs 73 must be a regression, and auto-publish requires the gate
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_graded_fixture_ab_detects_wrong_number_and_gates_auto_publish(monkeypatch):
engine, db = _make_db()
try:
await ensure_builtin_workflows(db)
base_graph = {
"nodes": [
{"id": "t", "node_type": "trigger", "title": "入口"},
{"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": "PROMPT_BASE"},
{"id": "out", "node_type": "output", "title": "输出"},
],
"edges": [{"id": "e1", "source": "t", "target": "llm"}, {"id": "e2", "source": "llm", "target": "out"}],
}
await create_workflow(db, workflow_id="custom.metric", name="指标研判", graph=base_graph)
proposed = copy.deepcopy(base_graph)
proposed["nodes"][1]["system_prompt"] = "PROMPT_NEW"
ai = _StreamAI({"PROMPT_BASE": "观测值为 37。", "PROMPT_NEW": "观测值为 73。"})
async def fake_client(_db):
return ai
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client)
db.add(
AIWorkflowFixture(
workflow_id="custom.metric", name="观测值 37", sample_question="当前观测值是多少?",
context_json={"expect": {"numbers": [37]}},
)
)
await db.commit()
ab = await run_fixture_ab_eval(db, "custom.metric", proposed)
assert (ab["base_passed"], ab["proposed_passed"]) == (1, 0)
assert ab["verdict"] == "regressed" and ab["regressions"] == ["观测值 37"]
assert ab["graded_fixture_count"] == 1
# Auto-publish of that regressing candidate is blocked by the A/B gate.
await update_evolution_policy(db, {"business_mode": "auto"})
class _PatchAI(_StreamAI):
async def analyze(self, req):
return SimpleNamespace(
content=json.dumps(
{"summary": "调整提示词", "node_patches": [{"node_id": "llm", "field": "system_prompt", "after": "PROMPT_NEW", "reason": "test"}]}
)
)
res = await propose_workflow_evolution(
db, "custom.metric", apply_mode="auto", ai_client=_PatchAI(ai.answers), trigger="manual"
)
assert res["applied_status"] == "blocked"
assert "A/B" in res["blocked_reason"]
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == "custom.metric"))).scalar_one()
assert row.active_revision == 1
finally:
engine.dispose()
# ---------------------------------------------------------------------------
# 9. Auto evolution builds from the live revision and never ships human drafts
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_auto_evolution_ignores_unpublished_human_draft(monkeypatch):
engine, db = _make_db()
try:
await ensure_builtin_workflows(db)
wf_id = "default.general"
stream_ai = _StreamAI({}, "研判完成:态势稳定。")
async def fake_client(_db):
return stream_ai
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client)
db.add(
AIWorkflowFixture(
workflow_id=wf_id, name="稳定性", sample_question="全球态势",
context_json={"expect": {"must_include": ["研判完成"]}},
)
)
await db.commit()
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
human_draft = copy.deepcopy(row.published_graph)
for node in human_draft["nodes"][:3]:
node["description"] = "HUMAN EDIT"
await save_workflow_draft(db, wf_id, human_draft, actor="admin")
await update_evolution_policy(db, {"business_mode": "auto"})
class _PatchAI(_StreamAI):
async def analyze(self, req):
return SimpleNamespace(
content=json.dumps(
{"summary": "增加一步", "node_patches": [{"node_id": "advisor_agent", "field": "max_steps", "after": 4, "reason": "test"}]}
)
)
res = await propose_workflow_evolution(
db, wf_id, apply_mode="auto", trigger="auto_post_run", ai_client=_PatchAI({}, "研判完成:态势稳定。")
)
assert res["applied_status"] == "auto_published", res["blocked_reason"]
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
assert all(n.get("description") != "HUMAN EDIT" for n in row.published_graph["nodes"])
assert row.draft_graph is not None
assert sum(1 for n in row.draft_graph["nodes"] if n.get("description") == "HUMAN EDIT") == 3
assert [(c["node_id"], c["field"]) for c in res["changes_vs_live"]] == [("advisor_agent", "max_steps")]
ledger = await _load_ledger_entries(db)
assert ledger[0]["changes_vs_live"] == res["changes_vs_live"]
finally:
engine.dispose()
# ---------------------------------------------------------------------------
# 10. Every meta-evolvable field changes the downstream business request
# ---------------------------------------------------------------------------
def test_meta_evolvable_fields_change_business_request():
base_diag = {"system_prompt": "诊断系统", "prompt": "诊断任务 A", "thinking_enabled": True}
base_patch = {"system_prompt": "输出 JSON node_patches", "prompt": "补丁任务", "thinking_enabled": True}
def build(diag, patch):
req = build_business_evolution_request(
workflow_id="default.general", mode="optimize", instruction="", diag_node=diag, patch_node=patch,
schema={"type": "object"}, context={},
)
return req.model_dump()
baseline = build(base_diag, base_patch)
variants = {
("diag_node", "system_prompt"): build({**base_diag, "system_prompt": "诊断系统 v2"}, base_patch),
("diag_node", "prompt"): build({**base_diag, "prompt": "诊断任务 B"}, base_patch),
("patch_node", "system_prompt"): build(base_diag, {**base_patch, "system_prompt": "输出 JSON node_patches v2"}),
("patch_node", "prompt"): build(base_diag, {**base_patch, "prompt": "补丁任务 v2"}),
("patch_node", "thinking_enabled"): build(base_diag, {**base_patch, "thinking_enabled": False}),
}
from app.services.ai.workflow_evolver import META_EVOLVABLE_FIELDS
assert set(variants) == set(META_EVOLVABLE_FIELDS)
for key, req in variants.items():
assert req != baseline, key
assert META_WORKFLOW_ID == "meta.workflow_evolver"
+2 -2
View File
@@ -16,7 +16,7 @@
"pmtiles": "4.4.1", "pmtiles": "4.4.1",
"satellite.js": "5.0.0", "satellite.js": "5.0.0",
"simplex-noise": "4.0.1", "simplex-noise": "4.0.1",
"three": "0.128.0", "three": "0.160.1",
"typescript": "5.9.3", "typescript": "5.9.3",
}, },
}, },
@@ -595,7 +595,7 @@
"temp-file": ["temp-file@3.4.0", "https://registry.npmmirror.com/temp-file/-/temp-file-3.4.0.tgz", { "dependencies": { "async-exit-hook": "^2.0.1", "fs-extra": "^10.0.0" } }, "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg=="], "temp-file": ["temp-file@3.4.0", "https://registry.npmmirror.com/temp-file/-/temp-file-3.4.0.tgz", { "dependencies": { "async-exit-hook": "^2.0.1", "fs-extra": "^10.0.0" } }, "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg=="],
"three": ["three@0.128.0", "https://registry.npmmirror.com/three/-/three-0.128.0.tgz", {}, "sha512-i0ap/E+OaSfzw7bD1TtYnPo3VEplkl70WX5fZqZnfZsE3k3aSFudqrrC9ldFZfYFkn1zwDmBcdGfiIm/hnbyZA=="], "three": ["three@0.160.1", "", {}, "sha512-Bgl2wPJypDOZ1stAxwfWAcJ0WQf7QzlptsxkjYiURPz+n5k4RBDLsq+6f9Y75TYxn6aHLcWz+JNmwTOXWrQTBQ=="],
"tiny-async-pool": ["tiny-async-pool@1.3.0", "https://registry.npmmirror.com/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz", { "dependencies": { "semver": "^5.5.0" } }, "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA=="], "tiny-async-pool": ["tiny-async-pool@1.3.0", "https://registry.npmmirror.com/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz", { "dependencies": { "semver": "^5.5.0" } }, "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA=="],
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "planet-client", "name": "planet-client",
"version": "0.82.0", "version": "0.83.0",
"description": "Intelligent Planet Program - Native Electron Earth Viewer", "description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true, "private": true,
"packageManager": "bun@1", "packageManager": "bun@1",
@@ -26,7 +26,7 @@
"pmtiles": "4.4.1", "pmtiles": "4.4.1",
"satellite.js": "5.0.0", "satellite.js": "5.0.0",
"simplex-noise": "4.0.1", "simplex-noise": "4.0.1",
"three": "0.128.0", "three": "0.160.1",
"typescript": "5.9.3" "typescript": "5.9.3"
}, },
"scripts": { "scripts": {
+1 -1
View File
@@ -15,7 +15,7 @@ const bundleEarthDir = join(desktopRoot, '.earth-bundle/earth')
const require = createRequire(join(desktopRoot, 'package.json')) const require = createRequire(join(desktopRoot, 'package.json'))
const VENDOR_PACKAGES = [ const VENDOR_PACKAGES = [
{ id: 'three', outFile: 'three.mjs', resolvePath: 'three/build/three.module.js' }, { id: 'three', outFile: 'three.mjs' },
{ id: 'pmtiles', outFile: 'pmtiles.mjs' }, { id: 'pmtiles', outFile: 'pmtiles.mjs' },
{ id: '@mapbox/vector-tile', outFile: 'mapbox-vector-tile.mjs' }, { id: '@mapbox/vector-tile', outFile: 'mapbox-vector-tile.mjs' },
{ id: 'pbf', outFile: 'pbf.mjs' }, { id: 'pbf', outFile: 'pbf.mjs' },
+1 -1
View File
@@ -1,4 +1,4 @@
import { BrowserWindow, screen, type Display } from 'electron' import { BrowserWindow, screen } from 'electron'
import { getClientLocale } from './i18n' import { getClientLocale } from './i18n'
import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core' import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core'
+69 -88
View File
@@ -7,8 +7,7 @@ interface GlobePoint {
lat: number lat: number
lon: number lon: number
kind: 0 | 1 | 2 kind: 0 | 1 | 2
shardAngle: number dissolveOrder: number
shardSpeed: number
phase: number phase: number
} }
@@ -201,8 +200,7 @@ function buildGlobePoints(): GlobePoint[] {
lat, lat,
lon: (lonDeg * Math.PI) / 180, lon: (lonDeg * Math.PI) / 180,
kind: 2, kind: 2,
shardAngle: rand() * Math.PI * 2, dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35),
shardSpeed: 0.65 + rand() * 1.15,
phase: rand() * Math.PI * 2, phase: rand() * Math.PI * 2,
}) })
} else if (kind === 1 && y % 2 === 0 && x % interiorStep === 0) { } else if (kind === 1 && y % 2 === 0 && x % interiorStep === 0) {
@@ -211,8 +209,7 @@ function buildGlobePoints(): GlobePoint[] {
lat, lat,
lon: (lonDeg * Math.PI) / 180, lon: (lonDeg * Math.PI) / 180,
kind: 1, kind: 1,
shardAngle: rand() * Math.PI * 2, dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35),
shardSpeed: 0.5 + rand() * 0.9,
phase: rand() * Math.PI * 2, phase: rand() * Math.PI * 2,
}) })
} else if (kind === 0 && y % 5 === 0 && x % oceanStep === 0) { } else if (kind === 0 && y % 5 === 0 && x % oceanStep === 0) {
@@ -221,8 +218,7 @@ function buildGlobePoints(): GlobePoint[] {
lat, lat,
lon: (lonDeg * Math.PI) / 180, lon: (lonDeg * Math.PI) / 180,
kind: 0, kind: 0,
shardAngle: rand() * Math.PI * 2, dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35),
shardSpeed: 0.4 + rand() * 0.7,
phase: rand() * Math.PI * 2, phase: rand() * Math.PI * 2,
}) })
} }
@@ -921,31 +917,19 @@ export function createDesktopSplashController(options: {
cx: number, cx: number,
cy: number, cy: number,
) => { ) => {
const warp = exitRatio > 0 ? exitRatio * exitRatio : 0 const dolly = exitRatio > 0 ? 1 + exitRatio * exitRatio * 0.06 : 1
const exitFade = exitRatio > 0 ? 1 - smoothstep(0.12, 0.88, exitRatio) : 1
for (const star of stars) { for (const star of stars) {
const sx = star.x * w const sx = cx + (star.x * w - cx) * dolly
const sy = star.y * h const sy = cy + (star.y * h - cy) * dolly
const twinkle = 0.55 + 0.45 * Math.sin(elapsed * star.twinkleSpeed + star.phase) const twinkle = 0.55 + 0.45 * Math.sin(elapsed * star.twinkleSpeed + star.phase)
const alpha = star.alpha * twinkle * (1 - exitRatio * 0.75) const alpha = star.alpha * twinkle * exitFade
if (alpha <= 0.01) continue if (alpha <= 0.01) continue
ctx.fillStyle = `rgba(210, 232, 255, ${alpha.toFixed(3)})` ctx.fillStyle = `rgba(210, 232, 255, ${alpha.toFixed(3)})`
if (warp > 0.02) { ctx.beginPath()
const dx = sx - cx ctx.arc(sx, sy, star.size, 0, Math.PI * 2)
const dy = sy - cy ctx.fill()
const len = Math.max(1, Math.hypot(dx, dy))
const streak = warp * 44
ctx.strokeStyle = `rgba(176, 224, 255, ${(alpha * 0.85).toFixed(3)})`
ctx.lineWidth = star.size * 0.85
ctx.beginPath()
ctx.moveTo(sx, sy)
ctx.lineTo(sx + (dx / len) * streak, sy + (dy / len) * streak)
ctx.stroke()
} else {
ctx.beginPath()
ctx.arc(sx, sy, star.size, 0, Math.PI * 2)
ctx.fill()
}
} }
} }
@@ -967,7 +951,7 @@ export function createDesktopSplashController(options: {
const perspK = 3.25 const perspK = 3.25
const tiltX = -0.25 const tiltX = -0.25
const rollZ = -0.11 const rollZ = -0.11
const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 2.1) const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 0.32)
const eclipseR = radius * 0.955 const eclipseR = radius * 0.955
const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45 const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45
@@ -976,26 +960,26 @@ export function createDesktopSplashController(options: {
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72 const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72 const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
const coronaAlpha = dawnIntensity * fade const coronaAlpha = dawnIntensity * fade
const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 1.4)) const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 0.55))
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.9 * coronaAlpha).toFixed(3)})`) corona.addColorStop(0, `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.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(0.62, `rgba(48, 118, 212, ${(0.15 * coronaAlpha).toFixed(3)})`)
corona.addColorStop(1, 'rgba(1, 3, 8, 0)') corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
ctx.fillStyle = corona ctx.fillStyle = corona
ctx.beginPath() ctx.beginPath()
ctx.arc(cx, cy, eclipseR * (1.95 + burst * 1.4), 0, Math.PI * 2) ctx.arc(cx, cy, eclipseR * (1.95 + burst * 0.55), 0, Math.PI * 2)
ctx.fill() ctx.fill()
} }
if (coreReveal > 0.01) { if (coreReveal > 0.01) {
const haloAlpha = coreReveal * fade const haloAlpha = coreReveal * fade
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4)) const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 0.55))
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`) glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`)
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * haloAlpha).toFixed(3)})`) glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * haloAlpha).toFixed(3)})`)
glow.addColorStop(1, 'rgba(2, 4, 10, 0)') glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
ctx.fillStyle = glow ctx.fillStyle = glow
ctx.beginPath() ctx.beginPath()
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2) ctx.arc(cx, cy, radius * (1.85 + burst * 0.55), 0, Math.PI * 2)
ctx.fill() ctx.fill()
} }
@@ -1027,24 +1011,26 @@ export function createDesktopSplashController(options: {
ctx.stroke() ctx.stroke()
} }
// Act 2: Three tilted orbital rings drawing into full orbits, expanding on Act 3 burst // Act 2: Three tilted orbital rings drawing into full orbits, smoothly expanding & fading on Act 3 iris
if (orbitReveal > 0.01) { if (orbitReveal > 0.01) {
const ringEase = exitRatio > 0 ? 1 - Math.pow(1 - exitRatio, 2.6) : 0
const ringFade = fade * (1 - smoothstep(0.08, 0.82, exitRatio))
const ringConfigs = [ 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.36 + ringEase * 0.72), ry: radius * (0.4 + ringEase * 0.22), 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.56 + ringEase * 0.72), ry: radius * (0.5 + ringEase * 0.22), rot: 0.42, color: '146, 184, 255' },
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' }, { rx: radius * (1.18 + ringEase * 0.72), ry: radius * (0.34 + ringEase * 0.22), rot: 0.08, color: '214, 240, 255' },
] ]
for (let i = 0; i < ringConfigs.length; i += 1) { for (let i = 0; i < ringConfigs.length; i += 1) {
const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8) const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8)
if (ringReveal <= 0.005) continue if (ringReveal <= 0.005 || ringFade <= 0.005) continue
const ring = ringConfigs[i] const ring = ringConfigs[i]
const a = elapsed * (1.2 + i * 0.45) + i * 2.1 const a = elapsed * (1.2 + i * 0.45) + i * 2.1
ctx.save() ctx.save()
ctx.translate(cx, cy) ctx.translate(cx, cy)
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1)) ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * fade).toFixed(3)})` ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * ringFade).toFixed(3)})`
ctx.lineWidth = 1.15 ctx.lineWidth = Math.max(0.65, 1.05 * (1 - exitRatio * 0.35))
ctx.beginPath() ctx.beginPath()
if (ringReveal >= 0.995) { if (ringReveal >= 0.995) {
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2) ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
@@ -1055,31 +1041,26 @@ export function createDesktopSplashController(options: {
const sx = Math.cos(a) * ring.rx const sx = Math.cos(a) * ring.rx
const sy = Math.sin(a) * ring.ry const sy = Math.sin(a) * ring.ry
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * fade).toFixed(3)})` ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * ringFade).toFixed(3)})`
ctx.beginPath() ctx.beginPath()
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2) ctx.arc(sx, sy, Math.max(0.8, 2.4 * (1 - exitRatio * 0.55)), 0, Math.PI * 2)
ctx.fill() ctx.fill()
ctx.restore() ctx.restore()
} }
} }
// Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> radial scatter // Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> coherent iris dissolve
const oceanReveal = clamp01((coreReveal - 0.25) / 0.75) const oceanReveal = clamp01((coreReveal - 0.25) / 0.75)
const sphereScale = 1 + smoothstep(0, 1, exitRatio) * 0.22
const dotSizeFactor = 1 - exitRatio * 0.35
for (const pt of globePoints) { for (const pt of globePoints) {
const p = projectSpherePoint(pt.lat, pt.lon, yaw, tiltX, rollZ) const p = projectSpherePoint(pt.lat, pt.lon, yaw, tiltX, rollZ)
if (burst === 0 && p.nz < -0.22) continue if (exitRatio === 0 && p.nz < -0.22) continue
const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8) const depth = Math.max(0.25, perspD - p.nz)
const jitterX = Math.cos(pt.shardAngle) * burst * 0.28 const screenScale = (radius * perspK * sphereScale) / depth
const jitterY = Math.sin(pt.shardAngle) * burst * 0.28 const sx = cx + p.nx * screenScale
const px = p.nx * radialBoost + jitterX const sy = cy + p.ny * screenScale
const py = p.ny * radialBoost + jitterY
const pz = p.nz + burst * pt.shardSpeed * 1.1
const depth = Math.max(0.25, perspD - pz)
const screenScale = (radius * perspK) / depth
const sx = cx + px * screenScale
const sy = cy + py * screenScale
if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) continue if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) continue
const depthFade = p.nz >= 0 ? 1 : Math.max(0.14, 1 + p.nz * 2.2) const depthFade = p.nz >= 0 ? 1 : Math.max(0.14, 1 + p.nz * 2.2)
@@ -1102,31 +1083,20 @@ export function createDesktopSplashController(options: {
pointGain = oceanReveal * 0.28 * depthFade pointGain = oceanReveal * 0.28 * depthFade
} }
const alpha = pointGain * polarFade * fade const exitPointFade =
exitRatio > 0 ? 1 - smoothstep(pt.dissolveOrder * 0.32, pt.dissolveOrder * 0.32 + 0.44, exitRatio) : 1
const alpha = pointGain * polarFade * fade * exitPointFade
if (alpha <= 0.015) continue if (alpha <= 0.015) continue
if (burst > 0.03) { ctx.fillStyle = `rgba(${color}, ${alpha.toFixed(3)})`
const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst) ctx.beginPath()
const prevScale = (radius * perspK) / Math.max(0.3, perspD - p.nz) ctx.arc(sx, sy, Math.max(0.55, dotR * dotSizeFactor), 0, Math.PI * 2)
const ox = cx + p.nx * prevBoost * prevScale ctx.fill()
const oy = cy + p.ny * prevBoost * prevScale
ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})`
ctx.lineWidth = dotR
ctx.beginPath()
ctx.moveTo(ox, oy)
ctx.lineTo(sx, sy)
ctx.stroke()
} else {
ctx.fillStyle = `rgba(${color}, ${alpha.toFixed(3)})`
ctx.beginPath()
ctx.arc(sx, sy, dotR, 0, Math.PI * 2)
ctx.fill()
}
} }
// Intercontinental telemetry arcs across front hemisphere // Intercontinental telemetry arcs across front hemisphere
if (arcReveal > 0.01 && burst < 0.55) { if (arcReveal > 0.01 && exitRatio < 0.45) {
const arcAlpha = arcReveal * fade * Math.max(0, 1 - burst * 1.6) const arcAlpha = arcReveal * fade * (1 - smoothstep(0.0, 0.45, exitRatio))
for (const arc of ARC_DEFINITIONS) { for (const arc of ARC_DEFINITIONS) {
const p1 = projectSpherePoint((arc.lat1 * Math.PI) / 180, (arc.lon1 * Math.PI) / 180, yaw, tiltX, rollZ) 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) const p2 = projectSpherePoint((arc.lat2 * Math.PI) / 180, (arc.lon2 * Math.PI) / 180, yaw, tiltX, rollZ)
@@ -1138,7 +1108,7 @@ export function createDesktopSplashController(options: {
const y2 = cy + p2.ny * radius * 1.02 const y2 = cy + p2.ny * radius * 1.02
const mx = (p1.nx + p2.nx) * 0.5 const mx = (p1.nx + p2.nx) * 0.5
const my = (p1.ny + p2.ny) * 0.5 const my = (p1.ny + p2.ny) * 0.5
const lift = 1.24 + burst * 0.9 const lift = 1.24 + burst * 0.18
const cpx = cx + mx * radius * lift const cpx = cx + mx * radius * lift
const cpy = cy + my * radius * lift const cpy = cy + my * radius * lift
@@ -1160,14 +1130,25 @@ export function createDesktopSplashController(options: {
} }
} }
// Act 3: Climax shockwave ring on scatter burst // Act 3: Dual-layer refined optical aperture iris reveal
if (burst > 0.005) { if (exitRatio > 0.005) {
const shockR = radius * (0.88 + exitRatio * 5.2) const iris = 1 - Math.pow(1 - exitRatio, 3)
ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})` const irisFade = smoothstep(0.0, 0.12, exitRatio) * (1 - smoothstep(0.18, 0.82, exitRatio))
ctx.lineWidth = Math.max(1, 3.2 * (1 - exitRatio)) if (irisFade > 0.005) {
ctx.beginPath() const outerR = radius * (1.02 + iris * 1.55)
ctx.arc(cx, cy, shockR, 0, Math.PI * 2) ctx.strokeStyle = `rgba(162, 218, 255, ${(0.36 * irisFade).toFixed(3)})`
ctx.stroke() ctx.lineWidth = 1.0
ctx.beginPath()
ctx.arc(cx, cy, outerR, 0, Math.PI * 2)
ctx.stroke()
const companionR = radius * (0.98 + iris * 1.22)
ctx.strokeStyle = `rgba(98, 184, 255, ${(0.14 * irisFade).toFixed(3)})`
ctx.lineWidth = 2.6
ctx.beginPath()
ctx.arc(cx, cy, companionR, 0, Math.PI * 2)
ctx.stroke()
}
} }
} }
@@ -1217,13 +1198,13 @@ export function createDesktopSplashController(options: {
if (reducedMotion) { if (reducedMotion) {
rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(exitRatio, 1.35)).toFixed(3)}` rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(exitRatio, 1.35)).toFixed(3)}`
} else { } else {
// Portal cutout expands from center while particle bursts continue radiating over edges // Wide feathered optical iris handoff into the live 3D Earth
const holePct = Math.pow(exitRatio, 1.45) * 135 const holePct = Math.pow(exitRatio, 1.35) * 115
const edgePct = holePct + 18 const edgePct = holePct + 36
const maskValue = `radial-gradient(circle at ${cx.toFixed(1)}px ${cy.toFixed(1)}px, transparent ${holePct.toFixed(1)}%, #000 ${edgePct.toFixed(1)}%)` const maskValue = `radial-gradient(circle at ${cx.toFixed(1)}px ${cy.toFixed(1)}px, transparent ${holePct.toFixed(1)}%, #000 ${edgePct.toFixed(1)}%)`
rootEl.style.webkitMaskImage = maskValue rootEl.style.webkitMaskImage = maskValue
rootEl.style.maskImage = maskValue rootEl.style.maskImage = maskValue
rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(Math.max(0, exitRatio - 0.55) / 0.45, 1.5)).toFixed(3)}` rootEl.style.opacity = `${Math.max(0, 1 - smoothstep(0.28, 1, exitRatio)).toFixed(3)}`
} }
} }
+17 -1
View File
@@ -1,4 +1,4 @@
import { mkdtempSync, rmSync } from 'node:fs' import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import os from 'node:os' import os from 'node:os'
import path from 'node:path' import path from 'node:path'
@@ -275,4 +275,20 @@ describe('splash theme configuration and landmask', () => {
}) })
expect(capHit).toEqual({ targetProgress: 1, readyToExit: true }) expect(capHit).toEqual({ targetProgress: 1, readyToExit: true })
}) })
test('splash exit choreography uses calm coherent optical dissolve without outward radial streaks', () => {
const splashSrc = readFileSync(new URL('../src/preload/splash.ts', import.meta.url), 'utf8')
expect(splashSrc).not.toContain('shardSpeed')
expect(splashSrc).not.toContain('shardAngle')
expect(splashSrc).not.toContain('radialBoost')
expect(splashSrc).not.toContain('warp * 44')
let prevFade = 1
for (const ratio of [0, 0.25, 0.5, 0.75, 1]) {
const phase = computeSplashMorphPhases(1, ratio)
expect(phase.fade).toBeLessThanOrEqual(prevFade + 1e-9)
prevFade = phase.fade
}
expect(computeSplashMorphPhases(1, 1).fade).toBe(0)
})
}) })
+19
View File
@@ -8,6 +8,25 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1` - `bugfix` -> `+0.0.1`
## [0.83.0] — 2026-12-02
Released: 2026-12-02
### Highlights
- **Earth Phase 1–4 贴地影响范围与三维视觉升级**: 上线贴地影响范围着色器引擎(`influence-zones.js` + `scene_directives.py`,单次离屏模糊合成与层级叠序 `renderOrderBase = 0.965`)、本地云图 `earth_clouds_2048.png` 瑞利晨昏散射与地面云影、`surface-ribbon.js` 屏幕空间抗锯齿发光丝带(国界/雷达/弧线/海缆/航迹/轨道)及 GPU 投影 Iridium 足迹。
- **Earth 聚合徽标视觉统一与优先一折连线**: 聚合徽标统一为 `28px` 深色玻璃内核 + `2.5px` 纯色 / `conic-gradient` 比例分段环及子类别明细提示;卡片引导线升级为“能一折优先一折、最多一折”策略,短距与紧凑胶囊平滑退化。
- **AI 参谋自进化约束加固与数据源连通性修复**: 加固 `workflow_evolver.py` / `dag_executor.py` / `stream_turn.py` 的无变更结果、可判对错 A/B 样本、草稿隔离与灰度防覆盖机制;修复 Space-Track/ArcGIS/Epoch 等数据源连通性校验与凭据引导。
- **Electron 客户端启动动效、打包构建与双语统一**: 更新桌面端 `splash.ts` 启动页配置与 Earth 热更包构建,并完成控制台、登录、文档页品牌图标及中英文纯净度统一;清理近 3 日冗余死代码并同步规划与技术文档。
### Added / Changed
- Earth & Frontend: `influence-zones.js`、`surface-ribbon.js`、`earth-surface-material.js`、`cluster-presentation.js`、`callout-connector.js`、`admin-write-auth.js`、`datasourceConfigHelpers.ts`
- Backend: `scene_directives.py`、`dag_executor.py`、`workflow_evolver.py`、`workflow_runtime.py`、`stream_turn.py`、`datasource_connectivity.py`
- Desktop Client: `client/src/preload/splash.ts`、`client/scripts/build-earth-bundle.mjs`、`client/bun.lock`
---
## [0.82.0] — 2026-12-01 ## [0.82.0] — 2026-12-01
Released: 2026-12-01 Released: 2026-12-01
+2
View File
@@ -23,6 +23,8 @@
当前重点入口: 当前重点入口:
- [开发 Agent 模型分配与 Token 控制计划](development-agent-model-allocation-plan.md) - [开发 Agent 模型分配与 Token 控制计划](development-agent-model-allocation-plan.md)
- [Earth 贴地影响范围与电影级三维视觉升级方案](earth-influence-zones-and-vfx-upgrade-plan.md)
- [AI 参谋工作流可视化编排、客户端上下文与受控位置 Agent 方案](ai-advisor-workflow-and-location-agent-plan.md)
- [Earth 地理资源、空间浮动卡片与性能实施计划](earth-spatial-presentation-and-geographic-assets-plan.md) - [Earth 地理资源、空间浮动卡片与性能实施计划](earth-spatial-presentation-and-geographic-assets-plan.md)
- [算力与资源态势:展示、采集与 AI 迭代实施计划](compute-resource-intelligence-plan.md) - [算力与资源态势:展示、采集与 AI 迭代实施计划](compute-resource-intelligence-plan.md)
- [控制台 i18n 接入计划](/home/ray/dev/linkong/planet/docs/plans/admin-console-i18n-plan.md) - [控制台 i18n 接入计划](/home/ray/dev/linkong/planet/docs/plans/admin-console-i18n-plan.md)
@@ -1,6 +1,6 @@
# Earth 贴地影响范围与电影级三维视觉升级方案 # Earth 贴地影响范围与电影级三维视觉升级方案
> 状态:**规划待排期**(全量 Three.js / 着色器 / Agent 场景协议只读评估已完成,当前无需升级 `three@0.128.0` 亦不引入全屏后处理 `UnrealBloomPass`,全部效果可在核显与 Electron 60fps 录屏约束下通过轻量化自定义 Shader 实现)。 > 状态:**已落地实现(随 `v0.83.0` 发布)**。已完成 Phase 1–4 全部核心引擎与渲染管线交付([influence-zones.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/influence-zones.js)、[scene_directives.py](/home/ray/dev/linkong/planet/backend/app/services/ai/scene_directives.py)、[surface-ribbon.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/surface-ribbon.js)、[earth-surface-material.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface-material.js)、[iridium-footprint-adapter.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/iridium-footprint-adapter.js) 及本地云图 `earth_clouds_2048.png`),仍保持 `three@0.128.0` 无全屏后处理约束。
--- ---
@@ -312,3 +312,17 @@ hover / locked 使用少量 overlay:
| `frontend/public/earth/js/main.js` | 当前集中处理 hover、click、locked 和 info-card 入口 | 后续需要接入通用 icon picking 结果 | | `frontend/public/earth/js/main.js` | 当前集中处理 hover、click、locked 和 info-card 入口 | 后续需要接入通用 icon picking 结果 |
| `docs/technical/zh/earth-layer-style-reference.md` | 当前视觉参数参考 | 实现后同步默认 glow 和通用参数 | | `docs/technical/zh/earth-layer-style-reference.md` | 当前视觉参数参考 | 实现后同步默认 glow 和通用参数 |
| `docs/technical/zh/earth-render-layer-order.md` | 当前层级参考 | 实现后同步 surface icon 层级范围 | | `docs/technical/zh/earth-render-layer-order.md` | 当前层级参考 | 实现后同步 surface icon 层级范围 |
---
## 后续演进:跨图层聚合与屏幕空间防重叠(待排期)
当前聚合按图层控制器独立计算(`compute-centers`、`bgp-events`、`bgp-collectors`、`earth-interactables` 各自成簇),且仅使用固定球面世界距离(`CLUSTER_DISTANCE = 15`)与 `coLocatedGroups`(`0.00015°`)的展开态偏移。由此带来两个待解决的交互问题:
1. 当一个图层的折叠数字徽章(如 `compute-centers` 的 `2`)与另一图层的未聚合单点(如莫斯科同城 `bgp-collectors`)在低缩放下投影重合时,DOM 覆盖层 `.map-clusters` 会直接挡住底部 WebGL 图标并吞掉鼠标拾取事件。
2. 固定世界距离加上单种子贪心聚类的质心偏移,在拉远视角下容易使相邻点未合并却在屏幕像素空间重合。
待选演进方向(排期前二选一):
- **方案 A(优先推荐)**:跨图层统一聚合 + 基于当前相机缩放的屏幕像素距离自适应归并(单徽章多色分段环天然复用现有 `conic-gradient` 视觉契约)。
- **方案 B**:保持各图层语义独立,将折叠态聚合徽章纳入与异图层单点之间的屏幕空间碰撞避让,并补齐错位引导线以保证底层图标可独立拾取。
+8
View File
@@ -149,6 +149,14 @@ Implemented in [workflow_evolver.py](/home/ray/dev/linkong/planet/backend/app/se
- **Tier 0 (Immutable Python Constitution Kernel)**: enforces acyclic DAG structure and trigger/output preservation, blocks emptying `system_prompt`, restricts tools to allowlisted IDs, caps auto-mode blast radius (`<= 2` nodes and `<= 40%` of nodes), freezes the `verify_output` node on `meta.workflow_evolver`, blocks custom `meta.*` creation (single-level recursion lock), enforces `24h / 7d` cooldowns and daily auto-evolution quotas, and runs a **5-run canary window** with automatic rollback on consecutive failures or elevated bad-rating rates (with a 3-outcome meta-canary rollback guard on `meta.workflow_evolver`). - **Tier 0 (Immutable Python Constitution Kernel)**: enforces acyclic DAG structure and trigger/output preservation, blocks emptying `system_prompt`, restricts tools to allowlisted IDs, caps auto-mode blast radius (`<= 2` nodes and `<= 40%` of nodes), freezes the `verify_output` node on `meta.workflow_evolver`, blocks custom `meta.*` creation (single-level recursion lock), enforces `24h / 7d` cooldowns and daily auto-evolution quotas, and runs a **5-run canary window** with automatic rollback on consecutive failures or elevated bad-rating rates (with a 3-outcome meta-canary rollback guard on `meta.workflow_evolver`).
- **Tier 1 (Business Optimization & Model Drift Adaptation)**: `GET /api/v1/ai/evolution/health/{workflow_id}` computes 0-token health metrics, active model capability drift, unused tools, and DGM best-parent revision recommendations; `POST /api/v1/ai/evolution/propose/{workflow_id}` reads live `diag_node` / `patch_node` prompts from `meta.workflow_evolver` alongside historical ledger lessons; `POST /api/v1/ai/evolution/eval/{workflow_id}` runs Fixture A/B checks and `POST /api/v1/ai/evolution/incubate` proposes new workflows from frequent `default.general` queries. Non-blocking post-run hooks run via `schedule_post_run_evolution`. - **Tier 1 (Business Optimization & Model Drift Adaptation)**: `GET /api/v1/ai/evolution/health/{workflow_id}` computes 0-token health metrics, active model capability drift, unused tools, and DGM best-parent revision recommendations; `POST /api/v1/ai/evolution/propose/{workflow_id}` reads live `diag_node` / `patch_node` prompts from `meta.workflow_evolver` alongside historical ledger lessons; `POST /api/v1/ai/evolution/eval/{workflow_id}` runs Fixture A/B checks and `POST /api/v1/ai/evolution/incubate` proposes new workflows from frequent `default.general` queries. Non-blocking post-run hooks run via `schedule_post_run_evolution`.
- **Tier 2 (Meta-Evolution & Extensibility Hooks)**: `POST /api/v1/ai/evolution/meta-evolve` evolves `meta.workflow_evolver` prompts under an independent `meta_mode` (`off | draft | auto`) using objective ledger outcomes; `EvolutionSignalDetector` (`SIGNAL_DETECTORS`) and `EvolutionEvaluator` (`EVALUATORS`) provide clean `Protocol` extension points. - **Tier 2 (Meta-Evolution & Extensibility Hooks)**: `POST /api/v1/ai/evolution/meta-evolve` evolves `meta.workflow_evolver` prompts under an independent `meta_mode` (`off | draft | auto`) using objective ledger outcomes; `EvolutionSignalDetector` (`SIGNAL_DETECTORS`) and `EvolutionEvaluator` (`EVALUATORS`) provide clean `Protocol` extension points.
- **Evolution safety constraints (hardened after the v0.82.0 review)**:
- **"No change" is a valid outcome**: a valid empty `node_patches` list ends the round with `applied_status: no_change` (no revision, no ledger entry); the deterministic fallback only patches on real signals (failures/downvotes/model capability mismatch/admin instruction/ledger outcomes) and never pads prompts.
- **Gradable A/B fixtures**: fixtures accept `expect` (`numbers`, `must_include`, `must_not_include`, `require_uncertainty_without_evidence`, `min_evidence`, stored in `context_json.expect`) on `POST /api/v1/ai/workflows/{id}/fixtures`; grading covers execution errors, guardrail verification, and assertions, and any fixture that passes on live but fails on the candidate yields `regressed`. **Auto-publish requires the A/B gate**: missing fixtures, fixtures without assertions, or any regression block publication.
- **Live revision baseline**: background/auto-publish evolution always starts from the live revision, never reads or clears unpublished human drafts (auto-draft mode skips when a human draft exists), records the full candidate-vs-live diff in `changes_vs_live`, and applies the auto blast-radius limit to that full diff.
- **Canary cannot overwrite newer revisions**: before settling, the canary checks the live revision is still its target; if a manual publish/rollback superseded it, the entry becomes `superseded` without rollback (same for the meta canary).
- **Meta fields must take effect**: meta-evolution may only change `diag_node.system_prompt / prompt` and `patch_node.system_prompt / prompt / thinking_enabled`, all of which feed the business request (`build_business_evolution_request`); meta-evolution stays off by default.
- **Earth workflow data, evidence, and card output**: `dag_executor.py` selects each data source's own target ID by entity type (cable/vessel/BGP multi-select is order-independent); `interactive / ingest` edges route strictly by trigger source (a news click no longer runs the RSS localization branch); strict-JSON nodes such as `compute.posture.brief` run non-streaming, are verified via `StrategicPostureBrief` + evidence IDs, rendered as narrative, and the output node compiles the compute `view_spec` workbench (delivered via a closing `meta` event and `done.view_spec`); a failed `require_evidence` guardrail appends a "cause pending verification" block with follow-ups and marks `done.status` as `unverified` with `verification`.
- **Draft binding isolation**: Earth entry bindings edited in a draft live in `draft_graph.bindings` (returned as `draft_bindings`), apply only on publish, and are restored by discarding the draft; each published revision snapshots bindings in `graph_json.bindings` so rollback restores them. "Save bindings only" (`PATCH /workflows/{id}`) remains an explicit immediate action.
- **Feedback & Policy APIs**: `POST /api/v1/ai/runs/{run_id}/feedback`, `GET /api/v1/ai/runs?feedback=negative|positive`, `GET/PUT /api/v1/ai/evolution/policy`, `GET /api/v1/ai/evolution/ledger`, and `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss`. - **Feedback & Policy APIs**: `POST /api/v1/ai/runs/{run_id}/feedback`, `GET /api/v1/ai/runs?feedback=negative|positive`, `GET/PUT /api/v1/ai/evolution/policy`, `GET /api/v1/ai/evolution/ledger`, and `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss`.
Save, set-as-default, and connectivity testing remain three separate responsibilities. Runtime prompts resolve from published `AIWorkflow` nodes and versioned `default_prompts.json` resources while preserving `task_key` compatibility. Save, set-as-default, and connectivity testing remain three separate responsibilities. Runtime prompts resolve from published `AIWorkflow` nodes and versioned `default_prompts.json` resources while preserving `task_key` compatibility.
+8 -2
View File
@@ -376,7 +376,7 @@ If future cable, satellite, or news cruise is added, do not copy a new set of `m
`globe-navigation.js` retains the safe zoom-distance mapping. Mouse and single-touch drags uniformly use legacy screen deltas, 0.18 smoothing and release inertia, including movement outside the globe silhouette; ray/sphere intersection no longer gates dragging. Normal zoom retains legacy sensitivity. Once the globe exceeds the viewport, a smooth surface-distance/viewport cap limits excessive rotation at extreme zoom. Horizontal motion uses geographic yaw, vertical input changes tilt, and quaternion math prevents multi-revolution reversal. Pinch transitions and pointer capture remain intact. `globe-navigation.js` retains the safe zoom-distance mapping. Mouse and single-touch drags uniformly use legacy screen deltas, 0.18 smoothing and release inertia, including movement outside the globe silhouette; ray/sphere intersection no longer gates dragging. Normal zoom retains legacy sensitivity. Once the globe exceeds the viewport, a smooth surface-distance/viewport cap limits excessive rotation at extreme zoom. Horizontal motion uses geographic yaw, vertical input changes tilt, and quaternion math prevents multi-revolution reversal. Pinch transitions and pointer capture remain intact.
Surface markers retain category icons and fixed geographic cluster membership. Numbered solid circles expand through a 320ms tween above 250% zoom; zoom never regroups members, and 500% has no aggregate badges. Vessels retain independent heading arrows without clustering. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md). Surface markers retain category icons and fixed geographic cluster membership. `28px` dark translucent-core circular badges with colored outer rings expand through a 320ms tween above 250% zoom; zoom never regroups members, and 500% has no aggregate badges. Vessels retain independent heading arrows without clustering. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md).
Wheel input has two paths. Traditional mouse wheels keep the 10% step and short animation, using `wheelZoomTarget` as the logical base for continuous wheel input. Trackpads and high-precision wheels use the pixel delta for continuous zoom and call `setZoomLevel()` directly instead of passing through the 10% stepped animation. The trackpad path also filters a short-window, old-direction residual delta after a real direction change so inertia tails do not pull a just-reversed zoom back in the previous direction. Wheel input has two paths. Traditional mouse wheels keep the 10% step and short animation, using `wheelZoomTarget` as the logical base for continuous wheel input. Trackpads and high-precision wheels use the pixel delta for continuous zoom and call `setZoomLevel()` directly instead of passing through the 10% stepped animation. The trackpad path also filters a short-window, old-direction residual delta after a real direction change so inertia tails do not pull a just-reversed zoom back in the previous direction.
@@ -508,7 +508,7 @@ Focus state and per-type limits decide expanded cards versus capsules. Shared st
### Cluster badges and Spiderfy ### Cluster badges and Spiderfy
Ordinary surface markers retain GPU batches. Each aggregate uses the same projected children in `cluster-presentation.js` through collapse, expansion and the final resting state. A 26px solid numbered circle represents the group, with an amber ring for mixed categories. Membership changes only with data or filters, never through intermediate groups while zooming. Ordinary surface markers retain GPU batches. Each aggregate uses the same projected children in `cluster-presentation.js` through collapse, expansion and the final resting state. Badges share a `28px` dark-glass core with white tabular counts: single-type groups wear a `2.5px` solid `--cluster-color` ring, while mixed groups render a proportional `conic-gradient` ring (`--cluster-ring` with `4deg` dark dividers and a minimum minority arc floor) plus localized subtype breakdowns via `formatClusterTitle`. Membership changes only with data or filters, never through intermediate groups while zooming.
`cluster-motion.js` drives a 320ms cubic tween after visible icons are prepared and decoded, with encoded textures cached. Children interpolate from the group center to their real projections; `marker-stack.js` owns final display offsets. Animation and resting endpoints retain the same DOM nodes, with continuous reversal. `cluster-motion.js` drives a 320ms cubic tween after visible icons are prepared and decoded, with encoded textures cached. Children interpolate from the group center to their real projections; `marker-stack.js` owns final display offsets. Animation and resting endpoints retain the same DOM nodes, with continuous reversal.
@@ -614,3 +614,9 @@ When compute image configuration has no model/group rules, resolution uses a bou
- `workflow-bindings.js` fetches `/api/v1/earth/workflow-bindings` and dynamically projects published custom/built-in workflow actions onto matching Earth surfaces (info cards, news/topic cards, Copilot quick actions, and multi-target comparison tray). - `workflow-bindings.js` fetches `/api/v1/earth/workflow-bindings` and dynamically projects published custom/built-in workflow actions onto matching Earth surfaces (info cards, news/topic cards, Copilot quick actions, and multi-target comparison tray).
- Electron `screen-recorder.ts` captures `win.webContents.mainFrame` cleanly without framing chrome while preserving native Alt menu access, and Earth `i18n.js` / `index.html` keep `zh-CN` and `en-US` copy separated cleanly while syncing locale preferences with the console. - Electron `screen-recorder.ts` captures `win.webContents.mainFrame` cleanly without framing chrome while preserving native Alt menu access, and Earth `i18n.js` / `index.html` keep `zh-CN` and `en-US` copy separated cleanly while syncing locale preferences with the console.
### Surface Influence Zones, Cinematic Shading, and Prefer-One-Bend Callouts (v0.83.0)
- **Surface Influence Zones & Stage Directives** (`influence-zones.js` + `scene_directives.py`): renders geopolitical country/region presets and great-circle radius zones emitted by AI/stage directives via single-pass offscreen `scratchCanvas` soft-blur compositing and explicit `tier` / `z_index` stacking (`renderOrderBase = 0.965`, strictly between HD imagery `0.96` and borders `0.97`).
- **Rayleigh Scattering, Ribbons & GPU Iridium Projection**: `earth-surface-material.js` and `earth.js` pair with `earth_clouds_2048.png` for Rayleigh terminator shading, soft surface cloud shadows, and grazing water highlights; `surface-ribbon.js` unifies screen-space anti-aliased glowing ribbons for borders, BGP radar/stage arcs, cable pulses, vessel tracks, and selected satellite orbits; `iridium-footprint-adapter.js` moves Iridium footprint vertices onto GPU projection.
- **Prefer-One-Bend Callout Routing & Write Auth**: `callout-connector.js` (`applyPreferredOneBendAnchor`) shifts aligned perimeter anchors toward the card body/header when sufficient major-axis distance and edge span exist so connectors prefer one clean bend (never exceeding one bend, gracefully falling back to a 2-point line on compact capsules or short spans); `admin-write-auth.js` gates Earth-side compute location collection and saving behind admin token refresh and `/login` prompts.
@@ -1,6 +1,6 @@
# Earth interactable clustering # Earth interactable clustering
`interactable.js` owns fixed geographic membership, `cluster-motion.js` owns timed tweening, and `cluster-presentation.js` owns circular badges, projected children, picking and Spiderfy. Independent markers remain GPU Points. Each clustered child uses the same DOM icon throughout its animation and at the final position. `interactable.js` owns fixed geographic membership, `cluster-motion.js` owns timed tweening, and `cluster-presentation.js` owns `28px` dark-glass circular badges (`2.5px` solid or proportional `conic-gradient` multi-type rings), projected children, picking and Spiderfy. Independent markers remain GPU Points. Each clustered child uses the same DOM icon throughout its animation and at the final position.
## Membership and zoom ## Membership and zoom
@@ -20,8 +20,10 @@ Note: the layer control panel order and the registration / startup load order ar
| 0 | Earth base sphere | `earth.js` | `CONFIG.earthRadius` | Surface picking fallback target | Dark base; still visible when all optional map layers are off. | | 0 | Earth base sphere | `earth.js` | `CONFIG.earthRadius` | Surface picking fallback target | Dark base; still visible when all optional map layers are off. |
| 0.2 | Country dark tint | `country-boundaries.js` | `tintAltitudeOffset` | Raycast disabled | Used when HD texture is off. | | 0.2 | Country dark tint | `country-boundaries.js` | `tintAltitudeOffset` | Raycast disabled | Used when HD texture is off. |
| 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset = 0.32`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off; radius is separated from the base sphere to avoid far-zoom z-fighting. | | 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset = 0.32`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off; radius is separated from the base sphere to avoid far-zoom z-fighting. |
| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere. | | 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere; uses Rayleigh terminator shading and subtle grazing water reflection. |
| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering shares the surface pass; no fullscreen post-processing. | | 0.962 | Cloud shadow shell | `earth.js` | Shared HD surface radius with slight angular offset | `depthTest: true`, `depthWrite: false`, raycast disabled | Follows the cloud toggle and casts soft surface cloud shadows from `earth_clouds_2048.png`, strictly above `0.96` and below `0.965`. |
| 0.965 | Surface influence zones | `influence-zones.js`, `scene_directives.py` | Reuses the `128×128` spherical shell at `r = 100.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`); `renderOrderBase = 0.965`, stepping by `0.0003` per tier | `depthTest: true`, `depthWrite: false`, raycast disabled | Supports single-pass offscreen soft blur compositing for country presets and great-circle fragment shading for circular zones; stays above `0.96` HD imagery and strictly below `0.97` borders and all surface icons. |
| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 (`FrontSide` shader + `earth_clouds_2048.png`) | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering and Mie forward glow combine across the surface/atmosphere shells without fullscreen post-processing. |
| 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cables and landing-point anchors share the HD surface offset `0.48` and the same triangle-surface coordinates | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. | | 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cables and landing-point anchors share the HD surface offset `0.48` and the same triangle-surface coordinates | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. |
| 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. | | 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. |
| 2.05 | Grid lines | `earth.js` | `CONFIG.earthRadius + 0.14` | Raycast disabled | Low-opacity lines over HD texture. | | 2.05 | Grid lines | `earth.js` | `CONFIG.earthRadius + 0.14` | Raycast disabled | Low-opacity lines over HD texture. |
@@ -108,4 +110,4 @@ Co-located markers share a compact projection stack across categories; screen co
Regional news and compute retain the `#earth-region-callouts` root (z-index 20) and share flank/corridor assignment with object details through `callout-stage-arbitrator.js`, which assigns symmetric left and right flanks to bilateral `CN` and `US` spotlight peers via `bilateralPeerKey`. Expanded cards inside the regional root use 50, drag foreground 55, hover expansion 60–65, ordinary capsules 30, and dimmed/shrunk rear capsules 8, whereas spotlight and hover-expanded cards stay 100% opaque on the rear hemisphere while switching their connector to a dashed `.is-rear` rim guide and exposing a header rotate-to-front button. Regional news and compute retain the `#earth-region-callouts` root (z-index 20) and share flank/corridor assignment with object details through `callout-stage-arbitrator.js`, which assigns symmetric left and right flanks to bilateral `CN` and `US` spotlight peers via `bilateralPeerKey`. Expanded cards inside the regional root use 50, drag foreground 55, hover expansion 60–65, ordinary capsules 30, and dimmed/shrunk rear capsules 8, whereas spotlight and hover-expanded cards stay 100% opaque on the rear hemisphere while switching their connector to a dashed `.is-rear` rim guide and exposing a header rotate-to-front button.
Compute hub drill-down overlays and stage logical AS route arcs follow strict shell separation and batching rules: China's eight National Compute Hubs render through a single GPU-instanced `createInteractableLayer` at `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` (`renderOrder = 4.58`); western green-hub `AdditiveBlending` pulse rings use `renderOrder = 4.42` (`depthWrite: false`), and East-West synergy arcs batch into one elevated `LineSegments` (`renderOrder = 4.55`) to prevent far-zoom z-fighting; stage logical AS route arcs render as high-altitude before/after trajectories (`renderOrder = 4.72` / `4.76`) and dispose geometry and materials immediately on hide or tour exit. Compute hub drill-down overlays and stage logical AS route arcs follow strict shell separation and batching rules: China's eight National Compute Hubs render through a single GPU-instanced `createInteractableLayer` at `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` (`renderOrder = 4.58`); western green-hub `AdditiveBlending` pulse rings use `renderOrder = 4.42` (`depthWrite: false`); East-West synergy arcs, stage logical AS routes, country hover highlights, selected cable pulses, vessel tracks, and selected satellite orbits share the screen-space anti-aliased `surface-ribbon.js` pipeline (avoiding the Windows ANGLE 1px `THREE.Line` cap); and Iridium footprints run through GPU vertex projection in `iridium-footprint-adapter.js`, disposing geometry and materials immediately on hide or tour exit.
+8
View File
@@ -149,6 +149,14 @@ Admin 的 AI 页面已按模型配置与参谋编排拆分为两部分:
- **Tier 0(Python 不可变宪法内核)**:强制校验 DAG 无环与入口/输出保留、禁止清空 `system_prompt`、禁止使用非白名单工具、限制自动变更半径(单次 `<= 2` 个且 `<= 40%` 节点)、永久冻结元引擎 `verify_output` 节点、禁止自定义 `meta.*` 命名空间(单层元递归锁)、按 `24h / 7d` 冷却与每日自动预算加锁,并在自动发布后启动 **5 次运行灰度观察窗**(连续 2 次失败或差评/失败率超阈即自动回滚,元引擎自身受下游 3 次结果窗口自动回退保护)。 - **Tier 0(Python 不可变宪法内核)**:强制校验 DAG 无环与入口/输出保留、禁止清空 `system_prompt`、禁止使用非白名单工具、限制自动变更半径(单次 `<= 2` 个且 `<= 40%` 节点)、永久冻结元引擎 `verify_output` 节点、禁止自定义 `meta.*` 命名空间(单层元递归锁)、按 `24h / 7d` 冷却与每日自动预算加锁,并在自动发布后启动 **5 次运行灰度观察窗**(连续 2 次失败或差评/失败率超阈即自动回滚,元引擎自身受下游 3 次结果窗口自动回退保护)。
- **Tier 1(业务自优化与模型漂移适配)**:`GET /api/v1/ai/evolution/health/{workflow_id}` 执行 0-Token 健康度与活跃模型能力漂移诊断并计算 DGM 历史最佳父版本;`POST /api/v1/ai/evolution/propose/{workflow_id}` 结合 `meta.workflow_evolver` 线上发布的 `diag_node` / `patch_node` 提示词及历史进化台账正负经验产出补丁;`POST /api/v1/ai/evolution/eval/{workflow_id}` 与 `POST /api/v1/ai/evolution/incubate` 分别支持样本 A/B 对照与从 `default.general` 高频提问孵化新工作流。运行完成后通过 `schedule_post_run_evolution` 异步非阻塞检查灰度与冷却条件。 - **Tier 1(业务自优化与模型漂移适配)**:`GET /api/v1/ai/evolution/health/{workflow_id}` 执行 0-Token 健康度与活跃模型能力漂移诊断并计算 DGM 历史最佳父版本;`POST /api/v1/ai/evolution/propose/{workflow_id}` 结合 `meta.workflow_evolver` 线上发布的 `diag_node` / `patch_node` 提示词及历史进化台账正负经验产出补丁;`POST /api/v1/ai/evolution/eval/{workflow_id}` 与 `POST /api/v1/ai/evolution/incubate` 分别支持样本 A/B 对照与从 `default.general` 高频提问孵化新工作流。运行完成后通过 `schedule_post_run_evolution` 异步非阻塞检查灰度与冷却条件。
- **Tier 2(元进化 & 可扩展注册表)**:`POST /api/v1/ai/evolution/meta-evolve` 按独立开关(`off | draft | auto`)迭代 `meta.workflow_evolver` 提示词策略;同时通过 `EvolutionSignalDetector`(`SIGNAL_DETECTORS`)与 `EvolutionEvaluator`(`EVALUATORS`)协议方便后续扩展新探针或评测器。 - **Tier 2(元进化 & 可扩展注册表)**:`POST /api/v1/ai/evolution/meta-evolve` 按独立开关(`off | draft | auto`)迭代 `meta.workflow_evolver` 提示词策略;同时通过 `EvolutionSignalDetector`(`SIGNAL_DETECTORS`)与 `EvolutionEvaluator`(`EVALUATORS`)协议方便后续扩展新探针或评测器。
- **进化安全约束(v0.82.0 复核后补强)**:
- **允许「无需修改」**:模型返回合法的空 `node_patches` 时本轮以 `applied_status: no_change` 正常结束,不生成新版本与台账;确定性兜底仅在检测到真实信号(失败/差评/模型能力不匹配/管理员指令/台账结果)时才出补丁,不再追加泛化提示词。
- **可判对错的 A/B 样本**:样本可在 `POST /api/v1/ai/workflows/{id}/fixtures` 的 `expect` 中声明 `numbers`、`must_include`、`must_not_include`、`require_uncertainty_without_evidence`、`min_evidence`(存于 `context_json.expect`);评测同时判定执行错误、护栏校验与断言,任一样本在候选版本上由通过变失败即判 `regressed`。**自动发布前强制执行 A/B 门禁**:没有样本、样本无断言或存在退化都会拦截发布。
- **以线上版本为基线**:后台/自动发布进化始终基于当前生效版本生成候选,不读取也不清空未发布的人工草稿(自动草稿模式遇到人工草稿直接跳过),台账 `changes_vs_live` 记录候选相对线上版本的完整差异,自动发布变更半径也按完整差异计算。
- **灰度防覆盖**:灰度结算前核对当前生效版本仍是本轮灰度目标,若已被人工发布或回滚取代则标记 `superseded` 且不回滚(元引擎灰度同理)。
- **元进化字段必须生效**:元进化仅允许修改 `diag_node.system_prompt / prompt` 与 `patch_node.system_prompt / prompt / thinking_enabled`,这些字段都会进入业务进化请求(`build_business_evolution_request`);元进化默认保持关闭。
- **地球工作流取数、证据与卡片输出**:`dag_executor.py` 按实体类型为每个数据源选取各自对象 ID(多选海缆/船舶/BGP 时与点击顺序无关);`interactive / ingest` 边按实际触发来源路由(前台新闻分析不再执行后台汉化分支);`compute.posture.brief` 等严格 JSON 节点以非流式执行,经 `StrategicPostureBrief` 与证据 ID 核验后渲染为正文,并在输出节点编译算力 `view_spec` 工作台(通过收尾 `meta` 事件与 `done.view_spec` 下发);`require_evidence` 护栏未通过时向用户追加「原因待核实」与待查项,`done.status` 记为 `unverified` 并附 `verification`。
- **草稿绑定隔离**:草稿中的地球入口绑定保存在 `draft_graph.bindings`(详情返回 `draft_bindings`),仅在发布时生效、丢弃草稿即恢复;每个发布版本的 `graph_json.bindings` 同时快照绑定,回滚时一并恢复。「仅保存绑定」(`PATCH /workflows/{id}`)仍为即时生效的显式操作。
- **反馈与运行记录接口**:`POST /api/v1/ai/runs/{run_id}/feedback`(提交 `-1 | 0 | 1` 评价与原因备注,差评实时复核灰度健康)与 `GET /api/v1/ai/runs?feedback=negative|positive`;战略策略与台账维护由 `GET/PUT /api/v1/ai/evolution/policy`、`GET /api/v1/ai/evolution/ledger` 与 `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss` 提供。 - **反馈与运行记录接口**:`POST /api/v1/ai/runs/{run_id}/feedback`(提交 `-1 | 0 | 1` 评价与原因备注,差评实时复核灰度健康)与 `GET /api/v1/ai/runs?feedback=negative|positive`;战略策略与台账维护由 `GET/PUT /api/v1/ai/evolution/policy`、`GET /api/v1/ai/evolution/ledger` 与 `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss` 提供。
保存、设为默认和连通性测试是三个独立职责:保存只持久化表单,设为默认只切换默认 provider/tool,连通性测试只验证当前草稿是否可用,不应隐式保存或切换默认项。 保存、设为默认和连通性测试是三个独立职责:保存只持久化表单,设为默认只切换默认 provider/tool,连通性测试只验证当前草稿是否可用,不应隐式保存或切换默认项。
+8 -2
View File
@@ -433,7 +433,7 @@ asset 图标大小由 `Interactable` 的 `icon.fitSize` 控制。SVG / 图片文
跨 Interactable 的同坐标关系也在公共层记录,但真实位置必须始终以 `icon_base_position` 为准。缩放、避让、聚合和后续 spiderfy 展开都只能改变屏幕表现,不能写回 `marker.position` 或 `THREE.Points` 里的业务锚点;巡航定位、详情卡、搜索定位和 picking 返回对象都必须落回真实经纬度。多个图标归入同一个经纬度 key 时,公共层只写 `icon_avoidance_*` 元数据,供业务层弱化 halo 或显示聚合提示;真正的低缩放聚合应通过独立 cluster glyph / screen layout 层实现,而不是把对象沿地表切平面挪开。 跨 Interactable 的同坐标关系也在公共层记录,但真实位置必须始终以 `icon_base_position` 为准。缩放、避让、聚合和后续 spiderfy 展开都只能改变屏幕表现,不能写回 `marker.position` 或 `THREE.Points` 里的业务锚点;巡航定位、详情卡、搜索定位和 picking 返回对象都必须落回真实经纬度。多个图标归入同一个经纬度 key 时,公共层只写 `icon_avoidance_*` 元数据,供业务层弱化 halo 或显示聚合提示;真正的低缩放聚合应通过独立 cluster glyph / screen layout 层实现,而不是把对象沿地表切平面挪开。
地表标记保留分类图标,聚合使用固定地理成员及带数量的实心圆。缩放只驱动 320ms 展开/收拢补间,不重新分档聚类;超过 250% 展开,500% 无聚合圆标。船只关闭聚合,保留独立航向箭头。实现与验收见 [聚合说明](/home/ray/dev/linkong/planet/docs/technical/zh/earth-interactable-clustering.md)。 地表标记保留分类图标,聚合使用固定地理成员及 `28px` 深色半透明内核搭配分色外环的圆形徽标。缩放只驱动 320ms 展开/收拢补间,不重新分档聚类;超过 250% 展开,500% 无聚合圆标。船只关闭聚合,保留独立航向箭头。实现与验收见 [聚合说明](/home/ray/dev/linkong/planet/docs/technical/zh/earth-interactable-clustering.md)。
接口细节、生命周期和接入示例见: 接口细节、生命周期和接入示例见:
@@ -641,7 +641,7 @@ Earth 由 `earth-runtime-plugin.mjs` 将本地模块合并为带内容哈希的
### 聚合圆标与 Spiderfy ### 聚合圆标与 Spiderfy
普通地表标记继续由 `interactable.js` 批量绘制;聚合组使用 `cluster-presentation.js` 的同一组投影节点贯穿合并、展开和展开后停留。圆标为 26px 实心渐变圆,显示真实成员数,混合类别带琥珀外圈。分组只随数据或筛选更新,缩放过程中不反复拆成中间子簇。 普通地表标记继续由 `interactable.js` 批量绘制;聚合组使用 `cluster-presentation.js` 的同一组投影节点贯穿合并、展开和展开后停留。圆标统一采用 `28px` 深色半透明玻璃内核与白字计数,单类别使用 `2.5px` 纯色圆环,混合类别由 `buildClusterRingGradient` 生成按占比分段(带 `4°` 深色分隔与最小可见扇区下限)的 `conic-gradient` 多色圆环,并通过 `formatClusterTitle` 输出本地化大类/子类别明细。分组只随数据或筛选更新,缩放过程中不反复拆成中间子簇。
`cluster-motion.js` 用固定 320ms 三次缓动控制进度。可见图标准备和解码完成后才开始计时,纹理编码按缓存复用;子点从组中心补间到真实标记投影,最终显示偏移由 `marker-stack.js` 统一计算。动画与终点保持同一个 DOM 节点,反向切换从当前进度续接。 `cluster-motion.js` 用固定 320ms 三次缓动控制进度。可见图标准备和解码完成后才开始计时,纹理编码按缓存复用;子点从组中心补间到真实标记投影,最终显示偏移由 `marker-stack.js` 统一计算。动画与终点保持同一个 DOM 节点,反向切换从当前进度续接。
@@ -753,3 +753,9 @@ BGP 观测站以 collector 编号建立标记索引。共享索引不登记空 I
- `workflow-bindings.js` 拉取 `/api/v1/earth/workflow-bindings` 发布的白名单工作流绑定,依据当前选中实体类型与交互界面位面(信息卡、新闻卡、算力专题卡、Copilot 快捷动作与多选对比托盘)动态渲染专项分析动作。 - `workflow-bindings.js` 拉取 `/api/v1/earth/workflow-bindings` 发布的白名单工作流绑定,依据当前选中实体类型与交互界面位面(信息卡、新闻卡、算力专题卡、Copilot 快捷动作与多选对比托盘)动态渲染专项分析动作。
- Electron 客户端 `screen-recorder.ts` 以 `win.webContents.mainFrame` 捕获无边框纯净画面并保持 Windows 原生 Alt 菜单兼容;`i18n.js` 与 `index.html` 对齐 `zh-CN` / `en-US` 纯净语种映射并同步管理台语言偏好。 - Electron 客户端 `screen-recorder.ts` 以 `win.webContents.mainFrame` 捕获无边框纯净画面并保持 Windows 原生 Alt 菜单兼容;`i18n.js` 与 `index.html` 对齐 `zh-CN` / `en-US` 纯净语种映射并同步管理台语言偏好。
### 贴地影响范围、三维视觉升级与优先一折连线(v0.83.0)
- **贴地影响范围与阶段导演指令**(`influence-zones.js` + `scene_directives.py`):支持 AI / 场景指令下发 `influence_zones`(国家/区域预设多边形及大圆辐射区),通过单次离屏 `scratchCanvas` 模糊合成与层级排序(`tier` / `z_index`)渲染可配置颜色、透明度、`edge_mode`(`sharp` / `soft`)及入场扫光;保持 `renderOrderBase = 0.965`,位于高清地表之上、国界与交互图标之下。
- **行星本体光影与丝带管线**:`earth-surface-material.js` 与 `earth.js` 结合本地 `earth_clouds_2048.png` 实现三阶瑞利散射晨昏过渡、海面掠射高光与地表云影投影;`surface-ribbon.js` 为国界 hover、BGP 雷达/高空路由、选中海缆流光、船舶尾迹及选中卫星轨道提供统一屏幕空间抗锯齿发光丝带;`iridium-footprint-adapter.js` 将 Iridium 足迹迁入 GPU 顶点投影。
- **卡片连线优先一折与管理写鉴权**:`callout-connector.js`(`applyPreferredOneBendAnchor`)在主轴跨度与卡片可用边长充足时优先偏出单一折点(严格保持 `<= 1` 折,短距或紧凑胶囊平滑退化为 2 点直线);`admin-write-auth.js` 统一管控 Earth 侧算力中心位置采集与保存的管理员会话鉴权及 `/login` 引导。
@@ -1,6 +1,6 @@
# 智能星球可交互图标聚合 # 智能星球可交互图标聚合
`interactable.js` 负责固定地理成员,`cluster-motion.js` 负责时间补间,`cluster-presentation.js` 负责圆形聚合、展开图标、拾取与 Spiderfy。普通独立标记继续使用 GPU Points;聚合成员从动画开始到终点由同一 DOM 图标显示,不再切回另一套位置。 `interactable.js` 负责固定地理成员,`cluster-motion.js` 负责时间补间,`cluster-presentation.js` 负责 `28px` 深色玻璃内核搭配 `2.5px` 纯色或按子类别占比分段的 `conic-gradient` 圆环聚合徽标、展开图标、拾取与 Spiderfy。普通独立标记继续使用 GPU Points;聚合成员从动画开始到终点由同一 DOM 图标显示,不再切回另一套位置。
## 成员与缩放 ## 成员与缩放
@@ -21,8 +21,10 @@
| 0 | 智能星球基座球 | `earth.js` | `CONFIG.earthRadius` | 地表拾取兜底目标 | 深色基座,所有可选地图层关闭时仍可见。 | | 0 | 智能星球基座球 | `earth.js` | `CONFIG.earthRadius` | 地表拾取兜底目标 | 深色基座,所有可选地图层关闭时仍可见。 |
| 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset = 0.32`,与海陆填色共用网格及半径 | depthTest=true、depthWrite=false,禁用 raycast | 加载占位及高清材质关闭时使用;填色就绪后按 renderOrder 覆盖。 | | 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset = 0.32`,与海陆填色共用网格及半径 | depthTest=true、depthWrite=false,禁用 raycast | 加载占位及高清材质关闭时使用;填色就绪后按 renderOrder 覆盖。 |
| 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 | | 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 |
| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距。 | | 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距;支持三阶瑞利散射晨昏过渡与海面掠射光。 |
| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3 | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照并入高清地表,不新增全屏后处理。 | | 0.962 | 云影投影球壳 | `earth.js` | 与高清材质共用球半径、微角偏移 | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 随大气云图开关联动,基于 `earth_clouds_2048.png` 投射柔和地表云影,严格位于 `0.96` 之上、`0.965` 之下。 |
| 0.965 | 贴地影响范围层 | `influence-zones.js`, `scene_directives.py` | 复用 `r = 100.48`(`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`)`128×128` 球壳;`renderOrderBase = 0.965`,按 `tier` / `z_index` 递增 `0.0003` | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 支持区域预设单次离屏模糊合成与圆形大圆距离片元着色,严格压在 `0.96` 高清地表之上且低于国界线 `0.97` 与全部交互图标。 |
| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3(`FrontSide` Shader + `earth_clouds_2048.png`) | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照与 Mie 前向散射并入高清地表与大气壳,不新增全屏后处理。 |
| 1 | 海缆 / 登陆点 | `cables.js`, `cable-batches.js` | 海缆全量线段合并为一个 `LineSegments`;登陆点全量使用实例化 billboard;`renderOrder = 1`、海缆与登陆点统一使用高清地表 `0.48` 偏移和同源三角表面坐标 | 原始 `Line` / `Sprite` 仅作为逐项拾取和选择状态对象,材质不再单独绘制;登陆点仍按球体遮挡判断背面可见性,批量材质 `depthTest: false` | 样式通过线缆样式纹理和登陆点实例属性同步;保留颜色、脉冲、尺寸、显隐与点击语义。 | | 1 | 海缆 / 登陆点 | `cables.js`, `cable-batches.js` | 海缆全量线段合并为一个 `LineSegments`;登陆点全量使用实例化 billboard;`renderOrder = 1`、海缆与登陆点统一使用高清地表 `0.48` 偏移和同源三角表面坐标 | 原始 `Line` / `Sprite` 仅作为逐项拾取和选择状态对象,材质不再单独绘制;登陆点仍按球体遮挡判断背面可见性,批量材质 `depthTest: false` | 样式通过线缆样式纹理和登陆点实例属性同步;保留颜色、脉冲、尺寸、显隐与点击语义。 |
| 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 | | 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 |
| 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 | | 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 |
@@ -110,4 +112,4 @@ Earth 的地表不是单一 mesh,而是多层近似同心球:基座球、海
区域新闻与算力保留 `#earth-region-callouts` 根节点(z-index 20),并与物件详情共享 `callout-stage-arbitrator.js` 的左右侧及纵向走廊;中美双主舞台对比卡通过 `bilateralPeerKey` 对称分配左右走廊。区域根内展开卡片为 50、拖拽前景为 55,悬停展开层为 60–65;普通胶囊为 30,背面胶囊为 8 并渐淡缩小,而主舞台及悬停展开卡在背面时保持正文 100% 不透明,仅将连线切换为 `.is-rear` 虚线边缘引导并激活标题栏“转至正面视角”按钮。 区域新闻与算力保留 `#earth-region-callouts` 根节点(z-index 20),并与物件详情共享 `callout-stage-arbitrator.js` 的左右侧及纵向走廊;中美双主舞台对比卡通过 `bilateralPeerKey` 对称分配左右走廊。区域根内展开卡片为 50、拖拽前景为 55,悬停展开层为 60–65;普通胶囊为 30,背面胶囊为 8 并渐淡缩小,而主舞台及悬停展开卡在背面时保持正文 100% 不透明,仅将连线切换为 `.is-rear` 虚线边缘引导并激活标题栏“转至正面视角”按钮。
算力专题下钻图层与逻辑路由演出弧线严格遵守同心壳深度与合批规则:中国“东数西算”八大国家算力枢纽复用 `createInteractableLayer` 单次实例化合批,贴地偏移为 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`、`renderOrder = 4.58`;西部绿电枢纽双环 `AdditiveBlending` 脉冲环 `renderOrder = 4.42`(`depthWrite: false`),东西部协同弧线合批为单次 `LineSegments`(`renderOrder = 4.55`,顶点抬升高于球面壳避免远景 z-fighting);BGP 舞台回放逻辑 AS 路由弧线以高空虚线/实线绘制(`renderOrder = 4.72` / `4.76`),退出或隐藏图层时立即 `dispose()` 几何与材质。 算力专题下钻图层与逻辑路由演出弧线严格遵守同心壳深度与合批规则:中国“东数西算”八大国家算力枢纽复用 `createInteractableLayer` 单次实例化合批,贴地偏移为 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`、`renderOrder = 4.58`;西部绿电枢纽双环 `AdditiveBlending` 脉冲环 `renderOrder = 4.42`(`depthWrite: false`),东西部协同弧线与高空 BGP 逻辑路由、国界 hover、选中海缆流光、船舶尾迹及选中卫星轨道共用 `surface-ribbon.js` 屏幕空间抗锯齿发光丝带底层(摆脱 Windows ANGLE 下 `THREE.Line` 1px 限制),Iridium 足迹通过 `iridium-footprint-adapter.js` 迁入 GPU 顶点投影;退出或隐藏图层时立即 `dispose()` 几何与材质。
+2 -1
View File
@@ -16,12 +16,13 @@
## Current Version ## Current Version
- `main` 当前主线历史推导到:`0.16.5` - `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.82.0` - `dev` 当前开发分支历史推导到:`0.83.0`
## Timeline ## Timeline
| Version | Type | Branch | Commit | Summary | | Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| `0.83.0` | feature | `dev` | `v0.83.0` | Earth Phase 1–4 贴地影响范围与三维视觉升级、聚合分色环与优先一折连线、AI 参谋自进化加固与数据源连通性修复、桌面客户端启动与资源包更新及代码文档清理 |
| `0.82.0` | feature | `dev` | `v0.82.0` | AI 参谋 3 层工作流自进化与元进化(Tier-0 安全内核/金丝雀回滚/Fixture A/B 评测/多模态 Playground 与地球绑定)、Electron 无边框录屏与 i18n、AI 模型目录升级及 README Mermaid 架构图 | | `0.82.0` | feature | `dev` | `v0.82.0` | AI 参谋 3 层工作流自进化与元进化(Tier-0 安全内核/金丝雀回滚/Fixture A/B 评测/多模态 Playground 与地球绑定)、Electron 无边框录屏与 i18n、AI 模型目录升级及 README Mermaid 架构图 |
| `0.81.0` | feature | `dev` | `v0.81.0` | 重构 AI 参谋(纯聊天 Playground/本地上下文抽屉/React Flow 9 工作流编排/AI Diff 调优/运行审计)与告警观测台,升级 L0–L4 Tool-Calling 位置 Agent、防爬鉴权与 X-API-Key、桌面录屏及多模型聚合目录 | | `0.81.0` | feature | `dev` | `v0.81.0` | 重构 AI 参谋(纯聊天 Playground/本地上下文抽屉/React Flow 9 工作流编排/AI Diff 调优/运行审计)与告警观测台,升级 L0–L4 Tool-Calling 位置 Agent、防爬鉴权与 X-API-Key、桌面录屏及多模型聚合目录 |
| `0.80.3` | improvement | `dev` | `v0.80.3` | 发布含全平台最新客户端安装包与 Earth 热更包的 0.80.3;固化仅含客户端更新才创建 Gitea Release 与 OCI release-manifest 发现规则 | | `0.80.3` | improvement | `dev` | `v0.80.3` | 发布含全平台最新客户端安装包与 Earth 热更包的 0.80.3;固化仅含客户端更新才创建 Gitea Release 与 OCI release-manifest 发现规则 |
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "planet-frontend", "name": "planet-frontend",
"version": "0.82.0", "version": "0.83.0",
"private": true, "private": true,
"packageManager": "bun@1", "packageManager": "bun@1",
"dependencies": { "dependencies": {
Binary file not shown.

After

Width:  |  Height:  |  Size: 761 KiB

+21 -2
View File
@@ -1308,15 +1308,28 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
position: absolute; position: absolute;
z-index: 162; z-index: 162;
left: 50%; left: 50%;
bottom: calc(86px * var(--hud-scale)); bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1));
transform: translateX(-50%); transform: translateX(-50%);
width: min(calc(760px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); width: min(calc(640px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset)));
padding: 0; padding: 0;
border-radius: 0; border-radius: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0; gap: 0;
border-color: rgba(145, 195, 255, 0.38); border-color: rgba(145, 195, 255, 0.38);
transition: bottom 0.24s ease;
}
body:has(.earth-bottom-dock > :not([hidden])) .stage-narrative-bar {
bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1) + 48px);
}
body:has(.earth-toolbar-cluster.is-expanded) .stage-narrative-bar {
bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1));
}
body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidden])) .stage-narrative-bar {
bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1) + 48px);
} }
.stage-narrative-bar__top { .stage-narrative-bar__top {
@@ -4163,6 +4176,12 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
background: rgba(120, 180, 255, 0.2); background: rgba(120, 180, 255, 0.2);
} }
.wb-action-pill.is-active {
border-color: rgba(164, 214, 255, 0.56);
background: rgba(92, 180, 255, 0.24);
color: #e0f2fe;
}
.wb-action-pill .material-symbols-rounded { .wb-action-pill .material-symbols-rounded {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
+175 -17
View File
@@ -4031,15 +4031,14 @@ label.is-disabled.earth-mobile-settings-card {
max-height: calc(30px * var(--hud-scale)); max-height: calc(30px * var(--hud-scale));
aspect-ratio: 1 / 1; aspect-ratio: 1 / 1;
padding: 0; padding: 0;
border: 1px solid rgba(122, 180, 255, 0.24); border: 1px solid rgba(212, 227, 244, 0.16);
border-radius: 50%; border-radius: 50%;
background: background: rgba(255, 255, 255, 0.045);
radial-gradient(circle at 35% 22%, rgba(255, 255, 255, 0.2), transparent 58%),
linear-gradient(180deg, rgba(121, 159, 207, 0.18), rgba(72, 101, 139, 0.24));
color: var(--hud-title); color: var(--hud-title);
cursor: pointer; cursor: pointer;
vertical-align: middle; vertical-align: middle;
transition: transition:
background 0.16s ease,
border-color 0.18s ease, border-color 0.18s ease,
color 0.18s ease, color 0.18s ease,
transform 0.18s ease, transform 0.18s ease,
@@ -4065,7 +4064,8 @@ label.is-disabled.earth-mobile-settings-card {
.earth-settings-reload-action:hover { .earth-settings-reload-action:hover {
transform: translateY(-1px); transform: translateY(-1px);
border-color: rgba(125, 197, 255, 0.46); background: rgba(255, 255, 255, 0.09);
border-color: rgba(148, 197, 255, 0.36);
} }
.earth-settings-reload-action:disabled { .earth-settings-reload-action:disabled {
@@ -4577,20 +4577,26 @@ label.is-disabled.earth-mobile-settings-card {
.earth-shortcut-key { .earth-shortcut-key {
min-width: calc(68px * var(--hud-scale)); min-width: calc(68px * var(--hud-scale));
border: 1px solid rgba(122, 180, 255, 0.24); border: 1px solid rgba(212, 227, 244, 0.16);
border-radius: calc(6px * var(--hud-scale)); border-radius: 0;
background: background: rgba(255, 255, 255, 0.04);
radial-gradient(circle at 35% 22%, rgba(255, 255, 255, 0.16), transparent 58%),
linear-gradient(180deg, rgba(121, 159, 207, 0.16), rgba(72, 101, 139, 0.2));
color: var(--hud-title); color: var(--hud-title);
padding: calc(6px * var(--hud-scale)) calc(10px * var(--hud-scale)); padding: calc(6px * var(--hud-scale)) calc(10px * var(--hud-scale));
font: inherit; font: inherit;
font-size: calc(0.68rem * var(--hud-scale)); font-size: calc(0.68rem * var(--hud-scale));
font-weight: 800; font-weight: 700;
letter-spacing: 0.04em;
cursor: pointer; cursor: pointer;
transition: background 0.16s ease, border-color 0.16s ease, color 0.16s ease;
}
.earth-shortcut-key:hover {
background: rgba(255, 255, 255, 0.08);
border-color: rgba(148, 197, 255, 0.34);
} }
.earth-shortcut-key.is-capturing { .earth-shortcut-key.is-capturing {
background: rgba(52, 211, 153, 0.12);
border-color: rgba(110, 226, 188, 0.52); border-color: rgba(110, 226, 188, 0.52);
color: #d8fff3; color: #d8fff3;
} }
@@ -5095,13 +5101,18 @@ label.is-disabled.earth-mobile-settings-card {
.legend-filter { .legend-filter {
width: 100%; width: 100%;
border: 0; border: 0;
border-radius: calc(4px * var(--hud-scale));
background: transparent; background: transparent;
color: inherit; color: inherit;
font: inherit; font: inherit;
text-align: left; text-align: left;
cursor: pointer; cursor: pointer;
transition: opacity 0.16s ease, background 0.16s ease;
} }
.legend-filter:hover { background: rgba(255, 255, 255, 0.06); }
.legend-filter[aria-pressed="false"] { opacity: 0.35; } .legend-filter[aria-pressed="false"] { opacity: 0.35; }
.legend-filter[aria-pressed="false"]:hover,
.legend-filter[aria-pressed="false"]:focus-visible { opacity: 0.95; }
.legend-filter:focus-visible { outline: 1px solid #7dd3fc; outline-offset: -1px; } .legend-filter:focus-visible { outline: 1px solid #7dd3fc; outline-offset: -1px; }
.satellite-labels { position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 6; contain: layout style paint; } .satellite-labels { position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 6; contain: layout style paint; }
@@ -5119,13 +5130,14 @@ label.is-disabled.earth-mobile-settings-card {
.map-clusters { position:absolute; inset:0; pointer-events:none; z-index:5; } .map-clusters { position:absolute; inset:0; pointer-events:none; z-index:5; }
.map-clusters__legs { position:absolute; inset:0; width:100%; height:100%; overflow:visible; pointer-events:none; } .map-clusters__legs { position:absolute; inset:0; width:100%; height:100%; overflow:visible; pointer-events:none; }
.map-clusters__legs line { stroke:#94a3b8; stroke-width:1; } .map-clusters__legs line { stroke:#94a3b8; stroke-width:1; }
.map-cluster-badge { position:absolute; width:26px; height:26px; padding:0; display:grid; place-items:center; .map-cluster-badge { position:absolute; width:28px; height:28px; padding:0; display:grid; place-items:center;
transform:translate(-50%,-50%); border-radius:50%; border:1.5px solid color-mix(in srgb,var(--cluster-color,#a855f7),#ffffff 68%); transform:translate(-50%,-50%); border-radius:50%; border:2.5px solid transparent;
background:linear-gradient(135deg,var(--cluster-color,#a855f7),color-mix(in srgb,var(--cluster-color,#a855f7),#020617 40%)); background:linear-gradient(155deg,rgba(15,25,42,0.92),rgba(7,13,24,0.95)) padding-box,linear-gradient(var(--cluster-color,#a855f7),var(--cluster-color,#a855f7)) border-box;
box-shadow:0 0 14px color-mix(in srgb,var(--cluster-color,#a855f7),transparent 30%),0 4px 10px #0008; box-shadow:inset 0 1px 0 rgba(255,255,255,0.16),0 0 12px color-mix(in srgb,var(--cluster-color,#38bdf8),transparent 64%),0 4px 10px #0008;
color:white; font:800 11px system-ui,sans-serif; cursor:pointer; pointer-events:auto; } color:white; font:800 11px system-ui,sans-serif; font-variant-numeric:tabular-nums; cursor:pointer; pointer-events:auto; }
.map-cluster-badge:hover { transform:translate(-50%,-50%) scale(1.18); } .map-cluster-badge:hover { transform:translate(-50%,-50%) scale(1.18); }
.map-cluster-badge.is-mixed::after { content:""; position:absolute; inset:-4px; border:1.5px solid #f59e0b; border-radius:50%; pointer-events:none; } .map-cluster-badge.is-mixed {
background:linear-gradient(155deg,rgba(15,25,42,0.92),rgba(7,13,24,0.95)) padding-box,var(--cluster-ring,conic-gradient(#14b8a6,#a855f7)) border-box; }
.map-cluster-child { position:absolute; left:0; top:0; width:36px; height:36px; border:0; padding:0; background:transparent; cursor:pointer; pointer-events:auto; } .map-cluster-child { position:absolute; left:0; top:0; width:36px; height:36px; border:0; padding:0; background:transparent; cursor:pointer; pointer-events:auto; }
.map-cluster-child img { width:100%; height:100%; pointer-events:none; } .map-cluster-child img { width:100%; height:100%; pointer-events:none; }
.map-cluster-badge[hidden],.map-cluster-child[hidden] { display:none; } .map-cluster-badge[hidden],.map-cluster-child[hidden] { display:none; }
@@ -5147,3 +5159,149 @@ label.is-disabled.earth-mobile-settings-card {
@media (prefers-reduced-motion:reduce) { .has-bgp > .map-cluster-bgp-pulse { animation:none; display:none; } } @media (prefers-reduced-motion:reduce) { .has-bgp > .map-cluster-bgp-pulse { animation:none; display:none; } }
.map-cluster-child.is-selected img { filter:drop-shadow(0 0 5px var(--member-color,#38bdf8)) brightness(1.15); } .map-cluster-child.is-selected img { filter:drop-shadow(0 0 5px var(--member-color,#38bdf8)) brightness(1.15); }
.earth-bottom-dock {
position: fixed;
left: 50%;
bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1));
transform: translateX(-50%);
z-index: 160;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 8px;
width: max-content;
max-width: min(94vw, 1080px);
pointer-events: none;
transition: bottom 0.24s ease;
}
body:has(.earth-toolbar-cluster.is-expanded) .earth-bottom-dock {
bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1));
}
.layout-mode-mobile .earth-bottom-dock {
bottom: calc(88px + var(--safe-bottom, 0px));
flex-direction: column-reverse;
max-width: calc(100vw - 16px);
}
.earth-influence-pill {
position: relative;
flex: 0 1 auto;
display: flex;
align-items: center;
gap: 12px;
height: 38px;
box-sizing: border-box;
max-width: min(86vw, 680px);
padding: 6px 10px 6px 12px;
border-radius: 999px;
pointer-events: auto;
}
.earth-bottom-dock:has(#earth-target-tray:not([hidden])) .earth-influence-pill {
max-width: min(56vw, 520px);
}
.layout-mode-mobile .earth-bottom-dock:has(#earth-target-tray:not([hidden])) .earth-influence-pill {
max-width: calc(100vw - 16px);
}
.earth-influence-pill[hidden] {
display: none;
}
.earth-influence-pill__viewport {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
display: flex;
align-items: center;
}
.earth-influence-pill__viewport.is-marquee {
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%);
mask-image: linear-gradient(90deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%);
}
.earth-influence-pill__track {
display: inline-flex;
align-items: center;
gap: 24px;
width: max-content;
}
.earth-influence-pill__viewport.is-marquee .earth-influence-pill__track {
animation: earthInfluenceMarquee var(--marquee-duration, 18s) linear infinite;
}
.earth-influence-pill:hover .earth-influence-pill__track {
animation-play-state: paused;
}
.earth-influence-pill__group {
display: inline-flex;
align-items: center;
gap: 12px;
flex: none;
}
@keyframes earthInfluenceMarquee {
from {
transform: translateX(0);
}
to {
transform: translateX(calc(-50% - 12px));
}
}
@media (prefers-reduced-motion: reduce) {
.earth-influence-pill__viewport.is-marquee {
overflow-x: auto;
scrollbar-width: none;
-webkit-mask-image: none;
mask-image: none;
}
.earth-influence-pill__viewport.is-marquee .earth-influence-pill__track {
animation: none;
}
}
.earth-influence-pill__item {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
line-height: 1.2;
color: rgba(241, 245, 249, 0.92);
white-space: nowrap;
}
.earth-influence-pill__dot {
width: 8px;
height: 8px;
border-radius: 999px;
flex: none;
background: var(--zone-color, #38bdf8);
}
.earth-influence-pill__slider-wrap {
display: inline-flex;
align-items: center;
gap: 6px;
padding-left: 8px;
border-left: 1px solid rgba(148, 163, 184, 0.22);
}
.earth-influence-pill__slider {
width: 72px;
accent-color: #38bdf8;
cursor: pointer;
}
.earth-influence-pill__clear {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
padding: 0;
border: 0;
border-radius: 999px;
background: rgba(148, 163, 184, 0.16);
color: rgba(226, 232, 240, 0.9);
cursor: pointer;
}
.earth-influence-pill__clear:hover {
background: rgba(148, 163, 184, 0.28);
}
.earth-influence-pill__clear .earth-influence-pill-icon.material-symbols-rounded {
font-size: 16px;
width: 16px;
height: 16px;
line-height: 16px;
}
+29 -12
View File
@@ -829,6 +829,19 @@ body[data-callout-line-style="bold"] .callout-connector circle {
font-size: calc(0.7rem * var(--hud-scale)); font-size: calc(0.7rem * var(--hud-scale));
} }
.info-card-auth-link {
display: inline-block;
margin-left: calc(6px * var(--hud-scale));
color: var(--hud-accent);
font-weight: 500;
text-decoration: none;
}
.info-card-auth-link:hover,
.info-card-auth-link:focus-visible {
text-decoration: underline;
}
.info-card-compute-collect-candidates { .info-card-compute-collect-candidates {
margin-top: calc(6px * var(--hud-scale)); margin-top: calc(6px * var(--hud-scale));
display: flex; display: flex;
@@ -995,7 +1008,7 @@ body[data-callout-line-style="bold"] .callout-connector circle {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 3px; gap: 3px;
border-radius: 12px; border-radius: 0;
letter-spacing: 0; letter-spacing: 0;
} }
@@ -1063,19 +1076,19 @@ body[data-callout-line-style="bold"] .callout-connector circle {
} }
.earth-target-tray { .earth-target-tray {
position: fixed; position: relative;
left: 50%; flex: 0 1 auto;
bottom: calc(var(--hud-offset, 16px) + 4px); max-width: min(90vw, 640px);
transform: translateX(-50%); min-height: 38px;
z-index: 160; box-sizing: border-box;
max-width: min(720px, calc(100vw - 24px)); padding: 5px 8px;
padding: 6px 8px; border-radius: 999px;
border-radius: 14px;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
flex-wrap: wrap; flex-wrap: wrap;
letter-spacing: 0; letter-spacing: 0;
pointer-events: auto;
} }
.earth-target-tray[hidden] { .earth-target-tray[hidden] {
@@ -1137,9 +1150,9 @@ body[data-callout-line-style="bold"] .callout-connector circle {
} }
.earth-target-tray__analyze { .earth-target-tray__analyze {
height: 28px; height: 26px;
padding: 0 10px; padding: 0 11px;
border-radius: 8px; border-radius: 999px;
border: 1px solid rgba(92, 200, 255, 0.35); border: 1px solid rgba(92, 200, 255, 0.35);
background: rgba(92, 200, 255, 0.22); background: rgba(92, 200, 255, 0.22);
color: #e6f7ff; color: #e6f7ff;
@@ -1152,6 +1165,10 @@ body[data-callout-line-style="bold"] .callout-connector circle {
letter-spacing: 0; letter-spacing: 0;
} }
.earth-target-tray .hud-panel__action {
border-radius: 999px;
}
.earth-target-tray__analyze:hover { .earth-target-tray__analyze:hover {
background: rgba(92, 200, 255, 0.32); background: rgba(92, 200, 255, 0.32);
} }
+9 -1
View File
@@ -205,11 +205,19 @@
transition: color 0.18s ease; transition: color 0.18s ease;
} }
/* Icon brightens when layer is active */ /* Icon brightens when layer is active or hovered */
.layer-row:has(.layer-row-toggle.active) .layer-row-icon { .layer-row:has(.layer-row-toggle.active) .layer-row-icon {
color: var(--hud-accent); color: var(--hud-accent);
} }
.layer-row:hover:not(:has(.layer-row-toggle.is-disabled)) .layer-row-icon {
color: var(--hud-title);
}
.layer-row:hover:has(.layer-row-toggle.active) .layer-row-icon {
color: var(--hud-accent);
}
.layer-row-copy { .layer-row-copy {
flex: 1 1 auto; flex: 1 1 auto;
min-width: 0; min-width: 0;
+5
View File
@@ -368,6 +368,11 @@
line-height: 1; line-height: 1;
} }
.earth-zoom-toolbar .earth-zoom-btn:hover,
.earth-zoom-toolbar .earth-zoom-btn:focus-visible {
color: #38bdf8;
}
.earth-zoom-toolbar .earth-zoom-value { .earth-zoom-toolbar .earth-zoom-value {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
+1 -1
View File
@@ -9,7 +9,7 @@
<script type="importmap"> <script type="importmap">
{ {
"imports": { "imports": {
"three": "https://esm.sh/three@0.128.0", "three": "https://esm.sh/three@0.160.1",
"pmtiles": "https://esm.sh/pmtiles@4.4.1", "pmtiles": "https://esm.sh/pmtiles@4.4.1",
"@mapbox/vector-tile": "https://esm.sh/@mapbox/vector-tile@2.0.4", "@mapbox/vector-tile": "https://esm.sh/@mapbox/vector-tile@2.0.4",
"pbf": "https://esm.sh/pbf@4.0.1", "pbf": "https://esm.sh/pbf@4.0.1",
@@ -0,0 +1,220 @@
export const ADMIN_AUTH_STORAGE_KEY = "auth-storage";
export const ADMIN_AUTH_REFRESH_ENDPOINT = "/api/v1/auth/refresh";
export const ADMIN_AUTH_REQUIRED_CODE = "ADMIN_AUTH_REQUIRED";
export const ADMIN_AUTH_REQUIRED_MESSAGE = "需要管理员登录后才能采集或保存算力中心位置";
const pendingRefreshByStorage = new WeakMap();
export function getAdminLoginUrl() {
return "/login";
}
export function createAdminAuthRequiredError(status, message = ADMIN_AUTH_REQUIRED_MESSAGE) {
const error = new Error(message || ADMIN_AUTH_REQUIRED_MESSAGE);
error.code = ADMIN_AUTH_REQUIRED_CODE;
error.status = status;
error.loginUrl = getAdminLoginUrl();
return error;
}
export function isAdminAuthRequiredError(error) {
return Boolean(
error &&
(error.code === ADMIN_AUTH_REQUIRED_CODE || error.status === 401 || error.status === 403),
);
}
function resolveStorage(storage) {
if (storage !== undefined) return storage;
try {
return globalThis.localStorage ?? null;
} catch {
return null;
}
}
export function readStoredAdminAuthState(storage) {
const targetStorage = resolveStorage(storage);
const empty = { rawEnvelope: null, token: "", refreshToken: "", user: undefined };
if (!targetStorage || typeof targetStorage.getItem !== "function") {
return empty;
}
try {
const raw = targetStorage.getItem(ADMIN_AUTH_STORAGE_KEY);
if (!raw) return empty;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object") return empty;
const state = parsed.state && typeof parsed.state === "object" ? parsed.state : {};
const token = typeof state.token === "string" ? state.token.trim() : "";
const refreshToken = typeof state.refreshToken === "string" ? state.refreshToken.trim() : "";
return {
rawEnvelope: parsed,
token,
refreshToken,
user: state.user,
};
} catch {
return empty;
}
}
export function persistStoredAdminAuthState({ token, refreshToken, user }, storage) {
const targetStorage = resolveStorage(storage);
if (!targetStorage || typeof targetStorage.setItem !== "function") {
return;
}
const { rawEnvelope } = readStoredAdminAuthState(targetStorage);
const baseEnvelope = rawEnvelope && typeof rawEnvelope === "object" ? rawEnvelope : { version: 0 };
const baseState =
baseEnvelope.state && typeof baseEnvelope.state === "object" ? baseEnvelope.state : {};
const nextState = {
...baseState,
token: token ?? null,
refreshToken: refreshToken ?? null,
...(user !== undefined ? { user } : {}),
};
try {
targetStorage.setItem(
ADMIN_AUTH_STORAGE_KEY,
JSON.stringify({
...baseEnvelope,
state: nextState,
}),
);
} catch {
// Ignore storage quota / security errors.
}
}
export function clearStoredAdminAuthTokens(storage) {
const targetStorage = resolveStorage(storage);
if (!targetStorage || typeof targetStorage.setItem !== "function") {
return;
}
const { rawEnvelope } = readStoredAdminAuthState(targetStorage);
if (!rawEnvelope) return;
persistStoredAdminAuthState({ token: null, refreshToken: null }, targetStorage);
}
export async function refreshStoredAdminAuthToken({
fetchImpl = globalThis.fetch,
storage,
} = {}) {
const targetStorage = resolveStorage(storage);
const { refreshToken } = readStoredAdminAuthState(targetStorage);
if (!refreshToken || typeof fetchImpl !== "function") {
return null;
}
const storageKey = targetStorage && typeof targetStorage === "object" ? targetStorage : null;
if (storageKey && pendingRefreshByStorage.has(storageKey)) {
const existing = pendingRefreshByStorage.get(storageKey);
if (existing.fetchImpl === fetchImpl) {
return existing.promise;
}
}
const refreshPromise = (async () => {
try {
const response = await fetchImpl(ADMIN_AUTH_REFRESH_ENDPOINT, {
method: "POST",
headers: {
Authorization: `Bearer ${refreshToken}`,
},
});
if (response.status === 401 || response.status === 403) {
clearStoredAdminAuthTokens(targetStorage);
return null;
}
if (!response.ok) {
return null;
}
const payload = await response.json().catch(() => null);
const nextToken =
typeof payload?.access_token === "string" ? payload.access_token.trim() : "";
if (!nextToken) {
return null;
}
const nextRefreshToken =
typeof payload?.refresh_token === "string" && payload.refresh_token.trim()
? payload.refresh_token.trim()
: refreshToken;
persistStoredAdminAuthState(
{
token: nextToken,
refreshToken: nextRefreshToken,
...(payload?.user !== undefined ? { user: payload.user } : {}),
},
targetStorage,
);
return nextToken;
} catch {
return null;
}
})();
if (storageKey) {
const entry = { fetchImpl, promise: refreshPromise };
pendingRefreshByStorage.set(storageKey, entry);
refreshPromise.finally(() => {
if (pendingRefreshByStorage.get(storageKey) === entry) {
pendingRefreshByStorage.delete(storageKey);
}
});
}
return refreshPromise;
}
export function buildAdminWriteHeaders(tokenOverride, storage) {
const headers = { "Content-Type": "application/json" };
const token =
typeof tokenOverride === "string"
? tokenOverride.trim()
: readStoredAdminAuthState(storage).token;
if (token) {
headers.Authorization = `Bearer ${token}`;
}
return headers;
}
export async function fetchAdminWriteJson(
endpoint,
payload = {},
{
fetchImpl = globalThis.fetch,
storage,
authMessage = ADMIN_AUTH_REQUIRED_MESSAGE,
} = {},
) {
if (!endpoint) throw new Error("endpoint is required");
const targetStorage = resolveStorage(storage);
let { token, refreshToken } = readStoredAdminAuthState(targetStorage);
if (!token && refreshToken) {
token = (await refreshStoredAdminAuthToken({ fetchImpl, storage: targetStorage })) || "";
}
let response = await fetchImpl(endpoint, {
method: "POST",
headers: buildAdminWriteHeaders(token, targetStorage),
body: JSON.stringify(payload || {}),
});
if (response.status === 401) {
const nextToken = await refreshStoredAdminAuthToken({ fetchImpl, storage: targetStorage });
if (nextToken && nextToken !== token) {
response = await fetchImpl(endpoint, {
method: "POST",
headers: buildAdminWriteHeaders(nextToken, targetStorage),
body: JSON.stringify(payload || {}),
});
}
}
if (response.status === 401 || response.status === 403) {
throw createAdminAuthRequiredError(response.status, authMessage);
}
return response;
}
@@ -0,0 +1,268 @@
import { expect, test } from "bun:test";
import {
ADMIN_AUTH_REFRESH_ENDPOINT,
ADMIN_AUTH_REQUIRED_CODE,
ADMIN_AUTH_STORAGE_KEY,
fetchAdminWriteJson,
isAdminAuthRequiredError,
readStoredAdminAuthState,
} from "./admin-write-auth.js";
function createMemoryStorage(initialState = null) {
const store = new Map();
if (initialState !== null) {
store.set(ADMIN_AUTH_STORAGE_KEY, JSON.stringify(initialState));
}
return {
getItem(key) {
return store.has(key) ? store.get(key) : null;
},
setItem(key, value) {
store.set(key, String(value));
},
removeItem(key) {
store.delete(key);
},
};
}
function jsonResponse(status, body) {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}
test("refreshes expired access token on 401, persists tokens, and retries write request", async () => {
const storage = createMemoryStorage({
version: 0,
state: {
token: "expired-access",
refreshToken: "valid-refresh-1",
user: { id: 1, role: "admin" },
},
});
const calls = [];
const fetchImpl = async (url, init = {}) => {
calls.push({ url, method: init.method, auth: init.headers?.Authorization });
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
return jsonResponse(200, {
access_token: "fresh-access-2",
refresh_token: "fresh-refresh-2",
user: { id: 1, role: "admin", username: "ops" },
});
}
if (init.headers?.Authorization === "Bearer expired-access") {
return jsonResponse(401, { detail: "Token expired" });
}
if (init.headers?.Authorization === "Bearer fresh-access-2") {
return jsonResponse(200, { success: true, candidates: [{ latitude: 1.2, longitude: 3.4 }] });
}
return jsonResponse(401, { detail: "Unexpected auth header" });
};
const response = await fetchAdminWriteJson(
"/api/v1/visualization/compute-centers/cc-1/collect-location",
{ name: "AI-03" },
{ fetchImpl, storage },
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
success: true,
candidates: [{ latitude: 1.2, longitude: 3.4 }],
});
expect(calls).toEqual([
{
url: "/api/v1/visualization/compute-centers/cc-1/collect-location",
method: "POST",
auth: "Bearer expired-access",
},
{
url: ADMIN_AUTH_REFRESH_ENDPOINT,
method: "POST",
auth: "Bearer valid-refresh-1",
},
{
url: "/api/v1/visualization/compute-centers/cc-1/collect-location",
method: "POST",
auth: "Bearer fresh-access-2",
},
]);
const persisted = readStoredAdminAuthState(storage);
expect(persisted.token).toBe("fresh-access-2");
expect(persisted.refreshToken).toBe("fresh-refresh-2");
expect(persisted.user).toEqual({ id: 1, role: "admin", username: "ops" });
});
test("proactively refreshes when access token is missing but refresh token exists", async () => {
const storage = createMemoryStorage({
version: 0,
state: {
token: null,
refreshToken: "valid-refresh-only",
},
});
const calls = [];
const fetchImpl = async (url, init = {}) => {
calls.push({ url, auth: init.headers?.Authorization });
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
return jsonResponse(200, {
access_token: "proactive-access",
refresh_token: "valid-refresh-only",
});
}
return jsonResponse(200, { saved: true });
};
const response = await fetchAdminWriteJson(
"/api/v1/visualization/compute-centers/cc-2/location",
{ latitude: 10, longitude: 20 },
{ fetchImpl, storage },
);
expect(response.status).toBe(200);
expect(calls).toEqual([
{ url: ADMIN_AUTH_REFRESH_ENDPOINT, auth: "Bearer valid-refresh-only" },
{ url: "/api/v1/visualization/compute-centers/cc-2/location", auth: "Bearer proactive-access" },
]);
});
test("deduplicates concurrent /auth/refresh calls when multiple writes hit 401 simultaneously", async () => {
const storage = createMemoryStorage({
version: 0,
state: {
token: "stale-token",
refreshToken: "shared-refresh",
},
});
let refreshCount = 0;
const fetchImpl = async (url, init = {}) => {
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
refreshCount += 1;
await Promise.resolve();
return jsonResponse(200, {
access_token: "deduped-token",
refresh_token: "shared-refresh",
});
}
if (init.headers?.Authorization === "Bearer stale-token") {
return jsonResponse(401, { detail: "Expired" });
}
return jsonResponse(200, { ok: true, url });
};
const [resA, resB] = await Promise.all([
fetchAdminWriteJson("/api/v1/visualization/compute-centers/a/collect-location", {}, { fetchImpl, storage }),
fetchAdminWriteJson("/api/v1/visualization/compute-centers/b/collect-location", {}, { fetchImpl, storage }),
]);
expect(resA.status).toBe(200);
expect(resB.status).toBe(200);
expect(refreshCount).toBe(1);
});
test("throws typed ADMIN_AUTH_REQUIRED error and clears stale tokens when refresh rejects with 401", async () => {
const storage = createMemoryStorage({
version: 0,
state: {
token: "dead-access",
refreshToken: "dead-refresh",
},
});
const fetchImpl = async (url) => {
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
return jsonResponse(401, { detail: "Invalid refresh token" });
}
return jsonResponse(401, { detail: "Invalid access token" });
};
let caught = null;
try {
await fetchAdminWriteJson(
"/api/v1/visualization/compute-centers/cc-3/collect-location",
{},
{ fetchImpl, storage },
);
} catch (error) {
caught = error;
}
expect(isAdminAuthRequiredError(caught)).toBe(true);
expect(caught?.code).toBe(ADMIN_AUTH_REQUIRED_CODE);
expect(caught?.status).toBe(401);
expect(caught?.loginUrl).toBe("/login");
const persisted = readStoredAdminAuthState(storage);
expect(persisted.token).toBe("");
expect(persisted.refreshToken).toBe("");
});
test("throws typed ADMIN_AUTH_REQUIRED immediately on 403 without refreshing or clearing storage", async () => {
const storage = createMemoryStorage({
version: 0,
state: {
token: "non-admin-access",
refreshToken: "non-admin-refresh",
},
});
let refreshCalls = 0;
const fetchImpl = async (url) => {
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
refreshCalls += 1;
}
return jsonResponse(403, { detail: "Administrator privileges required" });
};
let caught = null;
try {
await fetchAdminWriteJson(
"/api/v1/visualization/compute-centers/cc-4/collect-location",
{},
{ fetchImpl, storage },
);
} catch (error) {
caught = error;
}
expect(refreshCalls).toBe(0);
expect(isAdminAuthRequiredError(caught)).toBe(true);
expect(caught?.code).toBe(ADMIN_AUTH_REQUIRED_CODE);
expect(caught?.status).toBe(403);
const persisted = readStoredAdminAuthState(storage);
expect(persisted.token).toBe("non-admin-access");
expect(persisted.refreshToken).toBe("non-admin-refresh");
});
test("preserves existing refresh token when /auth/refresh fails with transient 500", async () => {
const storage = createMemoryStorage({
version: 0,
state: {
token: "maybe-expired",
refreshToken: "keep-this-refresh",
},
});
const fetchImpl = async (url) => {
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
return jsonResponse(500, { detail: "Temporary upstream failure" });
}
return jsonResponse(401, { detail: "Expired" });
};
let caught = null;
try {
await fetchAdminWriteJson(
"/api/v1/visualization/compute-centers/cc-5/collect-location",
{},
{ fetchImpl, storage },
);
} catch (error) {
caught = error;
}
expect(isAdminAuthRequiredError(caught)).toBe(true);
expect(caught?.status).toBe(401);
const persisted = readStoredAdminAuthState(storage);
expect(persisted.refreshToken).toBe("keep-this-refresh");
});
+99 -131
View File
@@ -940,114 +940,141 @@ function projectLatLon(lat, lon, bearingDeg, distanceDeg) {
}; };
} }
function createCoverageBoundaryLine(points, color, opacity = 0.3) { const BGP_RADAR_VERTEX_SHADER = `
const geometry = new THREE.BufferGeometry().setFromPoints(points); attribute vec2 aPolar;
const material = new THREE.LineBasicMaterial({ varying vec2 vPolar;
color,
transparent: true, void main() {
opacity, vPolar = aPolar;
depthWrite: false, gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
blending: THREE.AdditiveBlending, }
}); `;
return new THREE.Line(geometry, material);
} const BGP_RADAR_FRAGMENT_SHADER = `
uniform vec3 uColor;
uniform float uOpacity;
uniform float uTime;
uniform float uScanSpeed;
uniform float uSectorHalfSpan;
varying vec2 vPolar;
void main() {
float r = clamp(vPolar.x, 0.0, 1.0);
float angle = vPolar.y;
float pxR = clamp(fwidth(r), 0.0006, 0.0045);
float sweepAngle = mod(uTime * uScanSpeed, 6.2831853);
float delta = mod(sweepAngle - angle + 6.2831853, 6.2831853);
float span = clamp(uSectorHalfSpan * 2.0, 0.35, 2.2);
float beamTrail = (1.0 - smoothstep(0.0, span, delta)) * smoothstep(0.03, 0.96, r) * (1.0 - r * 0.25);
float leadingArm = exp(-(delta * delta) / 0.0018) * step(0.03, r);
// Precision ~1.25px hairline concentric rings via WebGL2 fwidth()
float ring1 = 1.0 - smoothstep(0.0, pxR * 1.35, abs(r - 0.333));
float ring2 = 1.0 - smoothstep(0.0, pxR * 1.35, abs(r - 0.666));
float outerRim = 1.0 - smoothstep(0.0, pxR * 1.55, abs(r - 0.993));
float ticks = smoothstep(0.955, 0.992, r) * (1.0 - step(0.996, r)) * pow(abs(cos(angle * 6.0)), 42.0);
float hairline = max(max(ring1, ring2) * 0.42, max(outerRim * 0.82, ticks * 0.55));
float ambientTint = 0.025 * (1.0 - smoothstep(0.0, 1.0, r));
float alpha = clamp((ambientTint + beamTrail * 0.22 + leadingArm * 0.45 + hairline * 0.65) * uOpacity * 3.4, 0.0, 0.85);
if (alpha < 0.003) discard;
vec3 beamColor = mix(uColor, vec3(0.94, 0.97, 1.0), clamp(leadingArm * 0.28 + outerRim * 0.14, 0.0, 0.35));
gl_FragColor = vec4(beamColor, alpha);
#include <colorspace_fragment>
}
`;
function createCoverageSectorMesh( function createCoverageSectorMesh(
anchorLatitude, anchorLatitude,
anchorLongitude, anchorLongitude,
startBearingDeg, _startBearingDeg,
endBearingDeg, _endBearingDeg,
reachDeg, reachDeg,
altitude, altitude,
color, color,
opacity = 0.12, opacity = 0.24,
radialSegments = 8, radialSegments = 14,
angularSegments = 28, angularSegments = 96,
scanSpeed = 0.72,
sectorHalfSpan = Math.PI * 0.22,
) { ) {
const positions = []; const positions = [];
const polarCoords = [];
for (let radialIndex = 0; radialIndex < radialSegments; radialIndex += 1) { for (let radialIndex = 0; radialIndex < radialSegments; radialIndex += 1) {
const innerDistance = (reachDeg * radialIndex) / radialSegments; const rInnerNorm = radialIndex / radialSegments;
const outerDistance = (reachDeg * (radialIndex + 1)) / radialSegments; const rOuterNorm = (radialIndex + 1) / radialSegments;
const innerDistance = reachDeg * rInnerNorm;
const outerDistance = reachDeg * rOuterNorm;
for (let angularIndex = 0; angularIndex < angularSegments; angularIndex += 1) { for (let angularIndex = 0; angularIndex < angularSegments; angularIndex += 1) {
const startProgress = angularIndex / angularSegments; const startAngle = (angularIndex / angularSegments) * Math.PI * 2;
const endProgress = (angularIndex + 1) / angularSegments; const endAngle = ((angularIndex + 1) / angularSegments) * Math.PI * 2;
const startBearing = startBearingDeg + (endBearingDeg - startBearingDeg) * startProgress; const startBearing = (startAngle * 180) / Math.PI;
const endBearing = startBearingDeg + (endBearingDeg - startBearingDeg) * endProgress; const endBearing = (endAngle * 180) / Math.PI;
const innerStart = projectLatLon(anchorLatitude, anchorLongitude, startBearing, innerDistance); const innerStart = projectLatLon(anchorLatitude, anchorLongitude, startBearing, innerDistance);
const innerEnd = projectLatLon(anchorLatitude, anchorLongitude, endBearing, innerDistance); const innerEnd = projectLatLon(anchorLatitude, anchorLongitude, endBearing, innerDistance);
const outerStart = projectLatLon(anchorLatitude, anchorLongitude, startBearing, outerDistance); const outerStart = projectLatLon(anchorLatitude, anchorLongitude, startBearing, outerDistance);
const outerEnd = projectLatLon(anchorLatitude, anchorLongitude, endBearing, outerDistance); const outerEnd = projectLatLon(anchorLatitude, anchorLongitude, endBearing, outerDistance);
const innerStartVector = latLonToVector3(innerStart.latitude, innerStart.longitude, altitude); const vIS = latLonToVector3(innerStart.latitude, innerStart.longitude, altitude);
const innerEndVector = latLonToVector3(innerEnd.latitude, innerEnd.longitude, altitude); const vIE = latLonToVector3(innerEnd.latitude, innerEnd.longitude, altitude);
const outerStartVector = latLonToVector3(outerStart.latitude, outerStart.longitude, altitude); const vOS = latLonToVector3(outerStart.latitude, outerStart.longitude, altitude);
const outerEndVector = latLonToVector3(outerEnd.latitude, outerEnd.longitude, altitude); const vOE = latLonToVector3(outerEnd.latitude, outerEnd.longitude, altitude);
positions.push( positions.push(
innerStartVector.x, innerStartVector.y, innerStartVector.z, vIS.x, vIS.y, vIS.z,
outerStartVector.x, outerStartVector.y, outerStartVector.z, vOS.x, vOS.y, vOS.z,
outerEndVector.x, outerEndVector.y, outerEndVector.z, vOE.x, vOE.y, vOE.z,
vIS.x, vIS.y, vIS.z,
vOE.x, vOE.y, vOE.z,
vIE.x, vIE.y, vIE.z,
); );
positions.push( polarCoords.push(
innerStartVector.x, innerStartVector.y, innerStartVector.z, rInnerNorm, startAngle,
outerEndVector.x, outerEndVector.y, outerEndVector.z, rOuterNorm, startAngle,
innerEndVector.x, innerEndVector.y, innerEndVector.z, rOuterNorm, endAngle,
rInnerNorm, startAngle,
rOuterNorm, endAngle,
rInnerNorm, endAngle,
); );
} }
} }
const geometry = new THREE.BufferGeometry(); const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("aPolar", new THREE.Float32BufferAttribute(polarCoords, 2));
geometry.computeVertexNormals(); geometry.computeVertexNormals();
const material = new THREE.MeshBasicMaterial({ const material = new THREE.ShaderMaterial({
color, uniforms: {
uColor: { value: color instanceof THREE.Color ? color.clone() : new THREE.Color(color) },
uOpacity: { value: opacity },
uTime: { value: (typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001 },
uScanSpeed: { value: scanSpeed },
uSectorHalfSpan: { value: sectorHalfSpan },
},
extensions: { derivatives: true },
vertexShader: BGP_RADAR_VERTEX_SHADER,
fragmentShader: BGP_RADAR_FRAGMENT_SHADER,
transparent: true, transparent: true,
opacity,
side: THREE.DoubleSide, side: THREE.DoubleSide,
depthWrite: false, depthWrite: false,
depthTest: true,
polygonOffset: true, polygonOffset: true,
polygonOffsetFactor: 1, polygonOffsetFactor: 1,
polygonOffsetUnits: 1, polygonOffsetUnits: 1,
blending: THREE.AdditiveBlending, blending: THREE.NormalBlending,
toneMapped: false,
}); });
return new THREE.Mesh(geometry, material); return new THREE.Mesh(geometry, material);
} }
function createRadialBoundaryPoints(
anchorLatitude,
anchorLongitude,
bearingDeg,
reachDeg,
altitude,
segments = 18,
) {
const points = [];
for (let step = 0; step <= segments; step += 1) {
const progress = step / segments;
const projected = projectLatLon(
anchorLatitude,
anchorLongitude,
bearingDeg,
reachDeg * progress,
);
points.push(
latLonToVector3(
projected.latitude,
projected.longitude,
altitude,
),
);
}
return points;
}
function attachCollectorEffectSprites(marker) { function attachCollectorEffectSprites(marker) {
const activity = marker.userData.activity; const activity = marker.userData.activity;
const heatHalo = createOverlaySprite({ const heatHalo = createOverlaySprite({
@@ -1792,34 +1819,6 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
const coverageColor = collectorBaseColor; const coverageColor = collectorBaseColor;
const boundaryAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.44; const boundaryAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.44;
const fillAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.4; const fillAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.4;
const leftBoundaryPoints = createRadialBoundaryPoints(
anchorLatitude,
anchorLongitude,
startBearing,
corridorReach,
boundaryAltitude,
);
const rightBoundaryPoints = createRadialBoundaryPoints(
anchorLatitude,
anchorLongitude,
endBearing,
corridorReach,
boundaryAltitude,
);
const outerArcPoints = [];
const outerArcSteps = 28;
for (let step = 0; step <= outerArcSteps; step += 1) {
const progress = step / outerArcSteps;
const bearingDeg = startBearing + (endBearing - startBearing) * progress;
const projected = projectLatLon(anchorLatitude, anchorLongitude, bearingDeg, corridorReach);
outerArcPoints.push(
latLonToVector3(
projected.latitude,
projected.longitude,
boundaryAltitude,
),
);
}
const sectorFill = createCoverageSectorMesh( const sectorFill = createCoverageSectorMesh(
anchorLatitude, anchorLatitude,
@@ -1829,40 +1828,16 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
corridorReach, corridorReach,
fillAltitude, fillAltitude,
coverageColor, coverageColor,
0.12, 0.24,
); );
sectorFill.renderOrder = 2; sectorFill.renderOrder = 2;
bgpCollectorRadarGroup.add(sectorFill); bgpCollectorRadarGroup.add(sectorFill);
const outerArc = createCoverageBoundaryLine(
outerArcPoints,
coverageColor,
0.9,
);
outerArc.renderOrder = 3;
bgpCollectorRadarGroup.add(outerArc);
const leftBoundary = createCoverageBoundaryLine(
leftBoundaryPoints,
coverageColor,
0.76,
);
leftBoundary.renderOrder = 3;
bgpCollectorRadarGroup.add(leftBoundary);
const rightBoundary = createCoverageBoundaryLine(
rightBoundaryPoints,
coverageColor,
0.76,
);
rightBoundary.renderOrder = 3;
bgpCollectorRadarGroup.add(rightBoundary);
activeCollectorOverlayContext = { activeCollectorOverlayContext = {
marker, marker,
earth, earth,
baseRotation, baseRotation,
lastRebuildAt: performance.now(), radarMaterial: sectorFill.material,
}; };
bgpOverlayGroup.visible = showBGP; bgpOverlayGroup.visible = showBGP;
} }
@@ -1883,17 +1858,10 @@ function updateCollectorOverlayScan(lockedObjectType, lockedObject) {
return; return;
} }
const now = performance.now(); const uniforms = activeCollectorOverlayContext.radarMaterial?.uniforms;
if (now - activeCollectorOverlayContext.lastRebuildAt < COLLECTOR_SCAN_REBUILD_MS) { if (uniforms?.uTime) {
return; uniforms.uTime.value = (typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001;
} }
const rotationOffsetRad = now * COLLECTOR_SCAN_SPEED_RAD;
showBGPCollectorCoverageOverlay(
activeCollectorOverlayContext.marker,
activeCollectorOverlayContext.earth,
{ rotationOffsetRad },
);
} }
export function getBGPLegendItems() { export function getBGPLegendItems() {
+5 -3
View File
@@ -91,10 +91,11 @@ export function createCableLineBatch(lines) {
vec3 color = vStyle.rgb; vec3 color = vStyle.rgb;
if (vStyle.a < 0.0) { if (vStyle.a < 0.0) {
float pulse = smoothstep(0.6, 1.0, fract(vProgress * ${CABLE_CONFIG.visual.pulseRepeats.toFixed(1)} - uTime * ${CABLE_CONFIG.visual.pulseSpeed.toFixed(1)})); float pulse = smoothstep(0.6, 1.0, fract(vProgress * ${CABLE_CONFIG.visual.pulseRepeats.toFixed(1)} - uTime * ${CABLE_CONFIG.visual.pulseSpeed.toFixed(1)}));
color = mix(vec3(0.3, 0.8, 1.0), vec3(0.7, 1.0, 1.0), pulse); color = mix(vec3(0.073, 0.604, 1.0), vec3(0.448, 1.0, 1.0), pulse);
alpha = max(alpha, 0.8 + pulse * 0.2); alpha = max(alpha, 0.8 + pulse * 0.2);
} }
gl_FragColor = vec4(color, alpha); gl_FragColor = vec4(color, alpha);
#include <colorspace_fragment>
} }
`, `,
}); });
@@ -184,17 +185,18 @@ export function createLandingPointBatch(markers, texture) {
float radius = distance(coreUv, vec2(0.5)); float radius = distance(coreUv, vec2(0.5));
float border = smoothstep(0.242, 0.254, radius) * (1.0 - smoothstep(0.283, 0.296, radius)); float border = smoothstep(0.242, 0.254, radius) * (1.0 - smoothstep(0.283, 0.296, radius));
float brightness = max(vStyle.r, max(vStyle.g, vStyle.b)); float brightness = max(vStyle.r, max(vStyle.g, vStyle.b));
color.rgb = mix(color.rgb, vec3(1.0, 0.86, 0.3) * brightness, border); color.rgb = mix(color.rgb, vec3(1.0, 0.71, 0.073) * brightness, border);
// The normal yellow core stays unchanged; only related points glow. // The normal yellow core stays unchanged; only related points glow.
float halo = exp(-radius * radius * ${CABLE_CONFIG.landingPointVisual.related.haloFalloff.toFixed(1)}) float halo = exp(-radius * radius * ${CABLE_CONFIG.landingPointVisual.related.haloFalloff.toFixed(1)})
* smoothstep(0.29, 0.32, radius) * smoothstep(0.29, 0.32, radius)
* (1.0 - smoothstep(0.7, 0.82, radius)) * vEmphasis; * (1.0 - smoothstep(0.7, 0.82, radius)) * vEmphasis;
float haloAlpha = halo * vStyle.a; float haloAlpha = halo * vStyle.a;
float alpha = color.a + haloAlpha * (1.0 - color.a); float alpha = color.a + haloAlpha * (1.0 - color.a);
color.rgb = (color.rgb * color.a + vec3(1.0, 0.63, 0.08) * haloAlpha * (1.0 - color.a)) / max(alpha, 0.001); color.rgb = (color.rgb * color.a + vec3(1.0, 0.355, 0.007) * haloAlpha * (1.0 - color.a)) / max(alpha, 0.001);
color.a = alpha; color.a = alpha;
if (color.a < 0.01) discard; if (color.a < 0.01) discard;
gl_FragColor = color; gl_FragColor = color;
#include <colorspace_fragment>
} }
`, `,
}); });
@@ -26,6 +26,7 @@ test("only related landing points get a glow and clearing selection removes it",
return marker; return marker;
}); });
const batch = createLandingPointBatch(markers, texture); const batch = createLandingPointBatch(markers, texture);
expect(batch.object.material.fragmentShader).toContain("#include <colorspace_fragment>");
batch.object.onBeforeRender(); batch.object.onBeforeRender();
const emphasis = batch.object.geometry.attributes.emphasis; const emphasis = batch.object.geometry.attributes.emphasis;
expect(emphasis.getX(0)).toBe(0); expect(emphasis.getX(0)).toBe(0);
+56 -1
View File
@@ -3,6 +3,7 @@ import { isLegendItemEnabled } from "./legend-filters.js";
import * as THREE from "three"; import * as THREE from "three";
import { createCableLineBatch, createLandingPointBatch } from "./cable-batches.js"; import { createCableLineBatch, createLandingPointBatch } from "./cable-batches.js";
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
import { cableSurfacePoint, calculateGreatCirclePoints } from "./cable-surface.js"; import { cableSurfacePoint, calculateGreatCirclePoints } from "./cable-surface.js";
import { configureColorTexture } from "./texture-colors.js"; import { configureColorTexture } from "./texture-colors.js";
@@ -28,6 +29,15 @@ let cableStates = new Map();
let cablesVisible = true; let cablesVisible = true;
let cableLineBatch = null; let cableLineBatch = null;
let landingPointBatch = null; let landingPointBatch = null;
let lockedCableRibbonMesh = null;
function clearLockedCableRibbon() {
if (!lockedCableRibbonMesh) return;
lockedCableRibbonMesh.parent?.remove?.(lockedCableRibbonMesh);
lockedCableRibbonMesh.geometry?.dispose?.();
lockedCableRibbonMesh.material?.dispose?.();
lockedCableRibbonMesh = null;
}
const _lpEarthWorldPos = new THREE.Vector3(); const _lpEarthWorldPos = new THREE.Vector3();
const _lpWorldPos = new THREE.Vector3(); const _lpWorldPos = new THREE.Vector3();
const _lpCameraRel = new THREE.Vector3(); const _lpCameraRel = new THREE.Vector3();
@@ -43,10 +53,11 @@ let landingPointTexture = null;
function getLandingPointDimColor() { function getLandingPointDimColor() {
const dimColor = CABLE_CONFIG.landingPointVisual.dimmed.colorRGB; const dimColor = CABLE_CONFIG.landingPointVisual.dimmed.colorRGB;
const brightness = CABLE_CONFIG.landingPointVisual.dimBrightness; const brightness = CABLE_CONFIG.landingPointVisual.dimBrightness;
const color = new THREE.Color( const color = new THREE.Color().setRGB(
(dimColor.r * brightness) / 255, (dimColor.r * brightness) / 255,
(dimColor.g * brightness) / 255, (dimColor.g * brightness) / 255,
(dimColor.b * brightness) / 255, (dimColor.b * brightness) / 255,
...(THREE.SRGBColorSpace ? [THREE.SRGBColorSpace] : []),
); );
return `#${color.getHexString()}`; return `#${color.getHexString()}`;
} }
@@ -435,13 +446,56 @@ export async function loadLandingPoints(scene, earthObj, options = {}) {
} }
export function handleCableClick(cable) { export function handleCableClick(cable) {
clearLockedCableRibbon();
lockedCable = cable; lockedCable = cable;
if (cable) {
const cableId = cable.userData?.id;
const segments = (cableId ? getCablesById(cableId) : [cable]).filter(Boolean);
const polylines = [];
for (const line of segments) {
const posAttr = line?.geometry?.attributes?.position;
if (!posAttr || posAttr.count < 2) continue;
const pts = [];
for (let i = 0; i < posAttr.count; i += 1) {
pts.push(new THREE.Vector3(posAttr.getX(i), posAttr.getY(i), posAttr.getZ(i)));
}
if (pts.length >= 2) polylines.push(pts);
}
const parent = cable.parent || cableLineBatch?.object?.parent;
if (parent && polylines.length > 0) {
const color = cable.userData?.originalColor ?? 0x38bdf8;
const ribbonGeo = createSurfaceRibbonGeometry(polylines);
const ribbonMat = createSurfaceRibbonMaterial({
color,
halfWidthPx: 4.8,
opacity: 0.92,
pulseSpeed: 0.65,
pulseFreq: 2.6,
pulseIntensity: 0.68,
additive: true,
});
lockedCableRibbonMesh = new THREE.Mesh(ribbonGeo, ribbonMat);
lockedCableRibbonMesh.name = "locked-cable-glow-ribbon";
lockedCableRibbonMesh.renderOrder = (CABLE_CONFIG.lineRenderOrder || 1.1) + 0.08;
lockedCableRibbonMesh.raycast = () => {};
lockedCableRibbonMesh.visible = cablesVisible;
const startedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
lockedCableRibbonMesh.onBeforeRender = () => {
const now = typeof performance !== "undefined" ? performance.now() : Date.now();
ribbonMat.uniforms.uTime.value = (now - startedAt) * 0.001;
};
parent.add(lockedCableRibbonMesh);
}
}
setLegendItems("cables", getCableLegendItems()); setLegendItems("cables", getCableLegendItems());
setLegendMode("cables"); setLegendMode("cables");
} }
export function clearCableSelection() { export function clearCableSelection() {
clearLockedCableRibbon();
lockedCable = null; lockedCable = null;
setLegendItems("cables", getCableLegendItems()); setLegendItems("cables", getCableLegendItems());
} }
@@ -605,6 +659,7 @@ export function toggleCables(show) {
cablesVisible = show; cablesVisible = show;
if (cableLineBatch) cableLineBatch.object.visible = show; if (cableLineBatch) cableLineBatch.object.visible = show;
if (landingPointBatch) landingPointBatch.object.visible = show; if (landingPointBatch) landingPointBatch.object.visible = show;
if (lockedCableRibbonMesh) lockedCableRibbonMesh.visible = Boolean(show);
cableLines.forEach((cable) => { cableLines.forEach((cable) => {
cable.visible = cablesVisible && isLegendItemEnabled("cables", cable.userData?.name || "未知线缆"); cable.visible = cablesVisible && isLegendItemEnabled("cables", cable.userData?.name || "未知线缆");
}); });
@@ -0,0 +1,97 @@
import { expect, test } from "bun:test";
import { createConnectorPath, createSlidingConnectorPoints } from "./callout-connector.js";
const detailCard = { x: 80, y: 120, width: 320, height: 380 };
test("aligned horizontal detail card prefers one balanced upward bend toward header", () => {
const source = { x: 640, y: 310 };
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
expect(path).not.toBeNull();
expect(path.points).toHaveLength(3);
const [p0, p1, p2] = path.points;
expect(p0).toEqual(source);
expect(p2.x).toBe(408);
expect(p2.y).toBeLessThan(source.y);
expect(p2.y).toBeGreaterThanOrEqual(detailCard.y + 12);
expect(p2.y).toBeLessThanOrEqual(detailCard.y + detailCard.height - 12);
expect(p1.y).toBe(p2.y);
const seg1 = Math.hypot(p1.x - p0.x, p1.y - p0.y);
const seg2 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
const total = seg1 + seg2;
expect(seg1 / total).toBeGreaterThanOrEqual(0.44);
expect(seg1 / total).toBeLessThanOrEqual(0.56);
expect(p1.x).toBeLessThanOrEqual(p0.x);
expect(p1.x).toBeGreaterThanOrEqual(p2.x);
});
test("aligned horizontal point near card top bends downward smoothly into card body", () => {
const source = { x: 640, y: 140 };
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
expect(path).not.toBeNull();
expect(path.points).toHaveLength(3);
const [, p1, p2] = path.points;
expect(p2.x).toBe(408);
expect(p2.y).toBeGreaterThan(source.y);
expect(p2.y).toBeLessThanOrEqual(detailCard.y + detailCard.height - 12);
expect(p1.y).toBe(p2.y);
});
test("small natural offset outside safe span preserves direction and deepens to crisp bend", () => {
const source = { x: 640, y: 124 };
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
expect(path).not.toBeNull();
expect(path.points).toHaveLength(3);
const [, , p2] = path.points;
expect(p2.x).toBe(408);
expect(p2.y).toBeGreaterThan(source.y + 18);
expect(p2.y).toBeLessThanOrEqual(detailCard.y + detailCard.height - 12);
});
test("short compact capsule and close-range sources fall back cleanly to straight line", () => {
const capsule = { x: 80, y: 200, width: 220, height: 42 };
const capsulePath = createSlidingConnectorPoints({ x: 480, y: 221 }, capsule, { targetGapPx: 8 });
expect(capsulePath).not.toBeNull();
expect(capsulePath.points).toHaveLength(2);
const closePath = createSlidingConnectorPoints({ x: 444, y: 310 }, detailCard, { targetGapPx: 8 });
expect(closePath).not.toBeNull();
expect(closePath.points).toHaveLength(2);
});
test("aligned vertical entrance produces one horizontal bend within safe corner padding", () => {
const source = { x: 240, y: 640 };
const path = createSlidingConnectorPoints(source, detailCard, { targetGapPx: 8 });
expect(path).not.toBeNull();
expect(path.points).toHaveLength(3);
const [, p1, p2] = path.points;
expect(p2.y).toBe(508);
expect(p2.x).toBeLessThan(source.x);
expect(p2.x).toBeGreaterThanOrEqual(detailCard.x + 12);
expect(p2.x).toBeLessThanOrEqual(detailCard.x + detailCard.width - 12);
expect(p1.x).toBe(p2.x);
});
test("preferBend false preserves straight line for aligned cards", () => {
const path = createConnectorPath({ x: 640, y: 310 }, detailCard, {
targetGapPx: 8,
preferBend: false,
});
expect(path).not.toBeNull();
expect(path.points).toHaveLength(2);
});
test("connector sweep never exceeds one bend across surrounding positions", () => {
for (let x = 20; x <= 760; x += 60) {
for (let y = 40; y <= 620; y += 45) {
const path = createSlidingConnectorPoints({ x, y }, detailCard, { targetGapPx: 8 });
expect(path).not.toBeNull();
expect(path.points.length === 2 || path.points.length === 3).toBe(true);
}
}
});
@@ -10,6 +10,13 @@ const DEFAULT_CLASS_NAME = "callout-connector";
const DEFAULT_DRAW_ANIMATION_NAME = "calloutConnectorDraw"; const DEFAULT_DRAW_ANIMATION_NAME = "calloutConnectorDraw";
const DEFAULT_SOURCE_ANCHOR_GAP_PX = 6; const DEFAULT_SOURCE_ANCHOR_GAP_PX = 6;
const MIN_SOURCE_ANCHOR_GAP_PX = 4; const MIN_SOURCE_ANCHOR_GAP_PX = 4;
const MIN_BEND_MAJOR_PX = 48;
const MIN_BEND_MINOR_PX = 18;
const PREFERRED_BEND_MIN_PX = 24;
const PREFERRED_BEND_MAX_PX = 72;
const PREFERRED_BEND_RATIO = 0.24;
const MAX_BEND_SLOPE_RATIO = 0.42;
const BEND_CORNER_PADDING_PX = 12;
// A connector only needs a surface around its own path, not a full-screen // A connector only needs a surface around its own path, not a full-screen
// SVG per card. Include the node animation and selection shadow extents. // SVG per card. Include the node animation and selection shadow extents.
@@ -527,6 +534,58 @@ function createAdaptiveConnectorPoints(source, target, options = {}) {
}; };
} }
function applyPreferredOneBendAnchor(start, end, targetRect) {
if (!start || !end || !targetRect) return end;
const isHorizontalEntrance = end.side === "left" || end.side === "right";
const dMajor = isHorizontalEntrance ? Math.abs(end.x - start.x) : Math.abs(end.y - start.y);
if (dMajor < MIN_BEND_MAJOR_PX) return end;
const startAxis = isHorizontalEntrance ? start.y : start.x;
const endAxis = isHorizontalEntrance ? end.y : end.x;
const dMinor = Math.abs(endAxis - startAxis);
const desiredMinor = Math.min(
clamp(dMajor * PREFERRED_BEND_RATIO, PREFERRED_BEND_MIN_PX, PREFERRED_BEND_MAX_PX),
dMajor * MAX_BEND_SLOPE_RATIO,
);
if (dMinor >= desiredMinor) return end;
const rectMin = isHorizontalEntrance ? targetRect.top : targetRect.left;
const rectMax = isHorizontalEntrance ? targetRect.bottom : targetRect.right;
const edgeLength = Math.max(0, rectMax - rectMin);
const cornerPadding = Math.min(BEND_CORNER_PADDING_PX, edgeLength * 0.5);
const edgeMin = rectMin + cornerPadding;
const edgeMax = rectMax - cornerPadding;
if (edgeMax - edgeMin < MIN_BEND_MINOR_PX) return end;
let nextAxis = endAxis;
if (dMinor >= 4) {
const sign = endAxis >= startAxis ? 1 : -1;
const candidate = clamp(startAxis + sign * desiredMinor, edgeMin, edgeMax);
const gain = Math.abs(candidate - startAxis);
if (gain < MIN_BEND_MINOR_PX || gain <= dMinor) return end;
nextAxis = candidate;
} else {
const candMin = clamp(startAxis - desiredMinor, edgeMin, edgeMax);
const candMax = clamp(startAxis + desiredMinor, edgeMin, edgeMax);
const gainMin = startAxis - candMin;
const gainMax = candMax - startAxis;
if (gainMin >= desiredMinor - 0.5) {
nextAxis = candMin;
} else if (gainMax >= desiredMinor - 0.5) {
nextAxis = candMax;
} else if (Math.max(gainMin, gainMax) >= MIN_BEND_MINOR_PX) {
nextAxis = gainMin >= gainMax ? candMin : candMax;
} else {
return end;
}
}
const ratio = (nextAxis - rectMin) / Math.max(1, edgeLength);
return isHorizontalEntrance
? { ...end, y: nextAxis, ratio }
: { ...end, x: nextAxis, ratio };
}
export function createSlidingConnectorPoints(source, target, options = {}) { export function createSlidingConnectorPoints(source, target, options = {}) {
const resolvedSource = resolveConnectorAnchor(source); const resolvedSource = resolveConnectorAnchor(source);
if (!resolvedSource) return null; if (!resolvedSource) return null;
@@ -579,6 +638,10 @@ export function createSlidingConnectorPoints(source, target, options = {}) {
} }
if (!end) return null; if (!end) return null;
if (options.preferBend !== false && candidateSides.length > 0) {
end = applyPreferredOneBendAnchor(start, end, targetRect);
}
const normal = { left: [-1, 0], right: [1, 0], top: [0, -1], bottom: [0, 1] }[end.side]; const normal = { left: [-1, 0], right: [1, 0], top: [0, -1], bottom: [0, 1] }[end.side];
const deltaX = Math.abs(end.x - start.x); const deltaX = Math.abs(end.x - start.x);
const deltaY = Math.abs(end.y - start.y); const deltaY = Math.abs(end.y - start.y);
+176 -11
View File
@@ -1,9 +1,169 @@
import * as THREE from "three"; import * as THREE from "three";
import { CONFIG, BGP_CONFIG } from "./constants.js"; import { CONFIG, BGP_CONFIG } from "./constants.js";
import { COMPUTE_SITE_TYPES } from "./compute-site-types.js";
import { getEarthLocale, translateText } from "./i18n.js";
import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js"; import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js";
import { createClusterTween } from "./cluster-motion.js"; import { createClusterTween } from "./cluster-motion.js";
import { markerPresentationId, markerStackGroups, markerStackLayout } from "./marker-stack.js"; import { markerPresentationId, markerStackGroups, markerStackLayout } from "./marker-stack.js";
const CLUSTER_RING_GAP_DEG = 4;
const CLUSTER_RING_DIVIDER_COLOR = "rgba(6, 13, 24, 0.92)";
export const CLUSTER_KIND_PRIORITY = Object.freeze({
supercomputer: 0,
gpu_cluster: 1,
data_center: 2,
cloud_center: 3,
edge_node: 4,
critical: 10,
high: 11,
medium: 12,
low: 13,
hot: 20,
idle: 24,
military: 30,
passenger: 31,
cargo: 32,
tanker: 33,
fishing: 34,
other: 35,
});
const BGP_SEVERITY_LABELS = Object.freeze({
critical: "严重事件",
high: "高危事件",
medium: "中危事件",
low: "低危事件",
});
const BGP_COLLECTOR_TIER_LABELS = Object.freeze({
hot: "高活跃观测站",
high: "高活跃观测站",
medium: "中活跃观测站",
low: "低活跃观测站",
idle: "静态观测站",
});
const VESSEL_KIND_LABELS = Object.freeze({
cargo: "货轮",
tanker: "油轮",
passenger: "客船",
fishing: "渔船",
military: "军舰",
other: "其他船只",
});
export function getClusterKindLabel(type, kind) {
if (kind && Object.hasOwn(COMPUTE_SITE_TYPES, kind)) {
return translateText(COMPUTE_SITE_TYPES[kind].label);
}
if (type === "bgp" && kind && Object.hasOwn(BGP_SEVERITY_LABELS, kind)) {
return translateText(BGP_SEVERITY_LABELS[kind]);
}
if (type === "bgp_collector" && kind && Object.hasOwn(BGP_COLLECTOR_TIER_LABELS, kind)) {
return translateText(BGP_COLLECTOR_TIER_LABELS[kind]);
}
if (type === "vessel" && kind && Object.hasOwn(VESSEL_KIND_LABELS, kind)) {
return translateText(VESSEL_KIND_LABELS[kind]);
}
return "";
}
function resolveKindPriority(type, kind) {
if (type === "bgp_collector" && kind === "high") return 21;
if (type === "bgp_collector" && kind === "medium") return 22;
if (type === "bgp_collector" && kind === "low") return 23;
if (kind && Object.hasOwn(CLUSTER_KIND_PRIORITY, kind)) {
return CLUSTER_KIND_PRIORITY[kind];
}
return 999;
}
export function summarizeClusterComposition(members, getOwner) {
const byTypeKind = new Map();
for (const marker of members) {
const type = String(marker?.userData?.type || "");
const kind = String(marker?.userData?.icon_kind || "");
const key = `${type}:${kind}`;
const existing = byTypeKind.get(key);
if (existing) {
existing.count += 1;
continue;
}
const owner = getOwner?.(marker);
const color = owner?.getMarkerColor?.(marker) || "#38bdf8";
byTypeKind.set(key, { key, type, kind, color, count: 1 });
}
const groups = [...byTypeKind.values()].sort((a, b) => (
b.count - a.count
|| resolveKindPriority(a.type, a.kind) - resolveKindPriority(b.type, b.kind)
|| a.key.localeCompare(b.key)
));
return {
groups,
total: members.length,
isMixed: groups.length > 1,
dominantColor: groups[0]?.color || "#38bdf8",
};
}
export function buildClusterRingGradient(groups, total) {
if (!Array.isArray(groups) || groups.length <= 1 || total <= 0) {
return "none";
}
const available = 360 - groups.length * CLUSTER_RING_GAP_DEG;
const minDeg = Math.min(20, available / (groups.length * 2));
const rawDegrees = groups.map((group) => (group.count / total) * available);
let deficit = 0;
let totalSurplus = 0;
for (const deg of rawDegrees) {
if (deg < minDeg) deficit += minDeg - deg;
else totalSurplus += deg - minDeg;
}
const degrees = rawDegrees.map((deg) => {
if (deg < minDeg) return minDeg;
if (deficit > 0 && totalSurplus > 0) {
return deg - deficit * ((deg - minDeg) / totalSurplus);
}
return deg;
});
const stops = [];
let cursor = 0;
groups.forEach((group, index) => {
const start = cursor;
const end = start + degrees[index];
const gapEnd = index === groups.length - 1 ? 360 : end + CLUSTER_RING_GAP_DEG;
stops.push(`${group.color} ${start.toFixed(1)}deg ${end.toFixed(1)}deg`);
stops.push(`${CLUSTER_RING_DIVIDER_COLOR} ${end.toFixed(1)}deg ${gapEnd.toFixed(1)}deg`);
cursor = gapEnd;
});
return `conic-gradient(from 0deg, ${stops.join(", ")})`;
}
export function formatClusterTitle(members, composition) {
const sampleNames = members
.slice(0, 3)
.map((marker) => marker.userData?.name || marker.userData?.collector || marker.userData?.title || marker.userData?.type)
.filter(Boolean)
.join(" / ");
if (composition.isMixed) {
const breakdown = composition.groups
.map((group) => {
const label = getClusterKindLabel(group.type, group.kind);
return label ? `${label} ${group.count}` : `${group.kind || group.type} ${group.count}`;
})
.join(" / ");
return `${members.length} · ${breakdown}${sampleNames ? ` · ${sampleNames}` : ""}`;
}
const sole = composition.groups[0];
const soleLabel = sole ? getClusterKindLabel(sole.type, sole.kind) : "";
if (soleLabel) {
return `${members.length} ${soleLabel}${sampleNames ? ` · ${sampleNames}` : ""}`;
}
return `${members.length} · ${sampleNames}`;
}
export function createClusterPresentation({ getOwner, onHiddenChange }) { export function createClusterPresentation({ getOwner, onHiddenChange }) {
const entries = new Map(); const entries = new Map();
let root = null, svg = null, expandedId = null, previousZoom = null; let root = null, svg = null, expandedId = null, previousZoom = null;
@@ -204,17 +364,22 @@ export function createClusterPresentation({ getOwner, onHiddenChange }) {
} }
const owner = getOwner(members[0]); const owner = getOwner(members[0]);
const center = project(entry.record.position, owner, camera); const center = project(entry.record.position, owner, camera);
const types = new Set(members.map(marker => `${marker.userData.type}:${marker.userData.icon_kind}`)); const composition = summarizeClusterComposition(members, getOwner);
const color = owner.getMarkerColor(members[0]); const hasBgp = members.some(marker => ["bgp", "bgp_collector"].includes(marker.userData.type));
entry.button.style.setProperty("--cluster-color", color); const visualKey = `${getEarthLocale()}|${composition.groups.map(group => `${group.key}:${group.count}:${group.color}`).join(",")}|${members.slice(0, 3).map(idOf).join(",")}|${hasBgp}`;
entry.button.classList.toggle("is-mixed", types.size > 1); if (entry.visualKey !== visualKey) {
entry.button.classList.toggle("has-bgp", members.some(marker => ["bgp","bgp_collector"].includes(marker.userData.type))); entry.visualKey = visualKey;
const countText = String(members.length); entry.button.style.setProperty("--cluster-color", composition.dominantColor);
if (entry.count.textContent !== countText) entry.count.textContent = countText; entry.button.style.setProperty("--cluster-ring", buildClusterRingGradient(composition.groups, composition.total));
const title = `${members.length} · ${members.slice(0,3).map(marker => marker.userData.name || marker.userData.collector || marker.userData.type).join(" / ")}`; entry.button.classList.toggle("is-mixed", composition.isMixed);
if (entry.button.title !== title) { entry.button.classList.toggle("has-bgp", hasBgp);
entry.button.title = title; const countText = String(members.length);
entry.button.setAttribute("aria-label", title); if (entry.count.textContent !== countText) entry.count.textContent = countText;
const title = formatClusterTitle(members, composition);
if (entry.button.title !== title) {
entry.button.title = title;
entry.button.setAttribute("aria-label", title);
}
} }
const ariaExpanded = String(progress > 0.5); const ariaExpanded = String(progress > 0.5);
if (entry.ariaExpanded !== ariaExpanded) { if (entry.ariaExpanded !== ariaExpanded) {
@@ -2,10 +2,14 @@ import {expect,test,spyOn} from "bun:test";
import * as THREE from "three"; import * as THREE from "three";
import {createInteractableLayer,updateInteractableClusters,clearInteractableClusters} from "./interactable.js"; import {createInteractableLayer,updateInteractableClusters,clearInteractableClusters} from "./interactable.js";
import {distanceForGlobeZoom} from "./globe-navigation.js"; import {distanceForGlobeZoom} from "./globe-navigation.js";
import {createClusterPresentation} from "./cluster-presentation.js"; import {
buildClusterRingGradient,
createClusterPresentation,
summarizeClusterComposition,
} from "./cluster-presentation.js";
class Node { class Node {
constructor(tag){this.tag=tag;this.children=[];this.style={setProperty(){}};this.classes=new Set();this.classList={add:(name)=>this.classes.add(name),toggle:(name,on)=>on?this.classes.add(name):this.classes.delete(name)};this.attrs={};this.events={};this.hidden=false;} constructor(tag){this.tag=tag;this.children=[];this.vars={};this.style={setProperty:(k,v)=>{this.vars[k]=v;}};this.classes=new Set();this.classList={add:(name)=>this.classes.add(name),toggle:(name,on)=>on?this.classes.add(name):this.classes.delete(name)};this.attrs={};this.events={};this.hidden=false;}
toDataURL(){return "data:image/png;base64,";} toDataURL(){return "data:image/png;base64,";}
getContext(){return new Proxy({}, {get:()=>()=>{}});} getContext(){return new Proxy({}, {get:()=>()=>{}});}
append(node){node.parent=this;this.children.push(node);} append(node){node.parent=this;this.children.push(node);}
@@ -192,3 +196,58 @@ test("500% co-located groups finish spiderfy, keep source positions and clean up
}); });
}finally{liveLayer?.clearData();clearInteractableClusters();presentation.destroy();clock.mockRestore();Object.assign(globalThis,original);} }finally{liveLayer?.clearData();clearInteractableClusters();presentation.destroy();clock.mockRestore();Object.assign(globalThis,original);}
}); });
test("cluster badge renders dark glass core with proportional conic-gradient ring for mixed clusters and dominant tie-breaks",()=>{
const original={document:globalThis.document,window:globalThis.window,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight};
const root=new Node("root");
globalThis.document={createElement:tag=>new Node(tag),createElementNS:(_,tag)=>new Node(tag),getElementById:()=>root,addEventListener(){},removeEventListener(){}};
globalThis.window={addEventListener(){},removeEventListener(){},dispatchEvent(){}};
globalThis.innerWidth=1200;globalThis.innerHeight=800;
const earth=new THREE.Object3D(),group=new THREE.Group();earth.add(group);earth.updateMatrixWorld(true);
const camera=new THREE.PerspectiveCamera(75,1.5,.1,5000);camera.position.z=350;camera.updateMatrixWorld();
const colors={supercomputer:"#a855f7",gpu_cluster:"#14b8a6",data_center:"#818cf8"};
const owner={group,isMarkerVisible:()=>true,getMarkerColor:(m)=>colors[m.userData.icon_kind]||"#38bdf8",getMarkerImage:()=>"data:image/png;base64,"};
const makeMarker=(id,kind)=>{const m=new THREE.Object3D();m.position.set(0,0,100.5);m.userData={id,name:`site-${id}`,type:"compute_center",icon_layer_id:"compute",icon_kind:kind};return m;};
const presentation=createClusterPresentation({getOwner:()=>owner,onHiddenChange(){}});
try {
// 1. Single-type cluster keeps solid color fill and no ring gradient.
const singleMarkers=[makeMarker("s1","gpu_cluster"),makeMarker("s2","gpu_cluster")];
presentation.update([{clusterId:"single",position:new THREE.Vector3(0,0,100.5),markers:singleMarkers,expanded:false}],camera,1,singleMarkers,null);
const singleBadge=root.children[0].children.find(n=>n.className==="map-cluster-badge"&&n.children.some(c=>c.textContent==="2"));
expect(singleBadge.classes.has("is-mixed")).toBe(false);
expect(singleBadge.vars["--cluster-color"]).toBe("#14b8a6");
expect(singleBadge.vars["--cluster-ring"]).toBe("none");
expect(singleBadge.title).toContain("GPU 集群");
// 2. Mixed cluster puts majority type (#a855f7, 10) first in ring & dominantColor even if minority markers come first.
const mixedMarkers=[
...Array.from({length:4},(_,i)=>makeMarker(`a-gpu-${i}`,"gpu_cluster")),
...Array.from({length:10},(_,i)=>makeMarker(`z-super-${i}`,"supercomputer")),
];
presentation.update([{clusterId:"mixed",position:new THREE.Vector3(0,0,100.5),markers:mixedMarkers,expanded:false}],camera,1,mixedMarkers,null);
const mixedBadge=root.children[0].children.find(n=>n.className==="map-cluster-badge"&&n.children.some(c=>c.textContent==="14"));
expect(mixedBadge.classes.has("is-mixed")).toBe(true);
expect(mixedBadge.vars["--cluster-color"]).toBe("#a855f7");
expect(mixedBadge.vars["--cluster-ring"]).toStartWith("conic-gradient(from 0deg, #a855f7 0.0deg");
expect(mixedBadge.vars["--cluster-ring"]).toContain("#14b8a6");
expect(mixedBadge.vars["--cluster-ring"]).toContain("360.0deg");
expect(mixedBadge.title).toContain("超算中心 10 / GPU 集群 4");
// 3. Minority 1-of-50 stays visible with >= 15deg arc and ends cleanly at 360.0deg.
const skewedMarkers=[
makeMarker("minority","gpu_cluster"),
...Array.from({length:49},(_,i)=>makeMarker(`maj-${i}`,"data_center")),
];
const skewedComp=summarizeClusterComposition(skewedMarkers,()=>owner);
const skewedRing=buildClusterRingGradient(skewedComp.groups,skewedComp.total);
const gpuSliceMatch=skewedRing.match(/#14b8a6\s+([\d.]+)deg\s+([\d.]+)deg/);
expect(gpuSliceMatch).not.toBeNull();
expect(Number(gpuSliceMatch[2])-Number(gpuSliceMatch[1])).toBeGreaterThanOrEqual(15);
expect(skewedRing).toEndWith("360.0deg)");
// 4. Equal-count tie breaks deterministically by business priority (supercomputer over gpu_cluster).
const tiedComp=summarizeClusterComposition([makeMarker("a","gpu_cluster"),makeMarker("b","supercomputer")],()=>owner);
expect(tiedComp.groups.map(g=>g.kind)).toEqual(["supercomputer","gpu_cluster"]);
expect(tiedComp.dominantColor).toBe("#a855f7");
}finally{presentation.destroy();Object.assign(globalThis,original);}
});
+115 -104
View File
@@ -9,6 +9,8 @@ import {
SURFACE_AVOIDANCE_PROFILES, SURFACE_AVOIDANCE_PROFILES,
} from "./interactable.js"; } from "./interactable.js";
import { latLonToVector3 } from "./utils.js"; import { latLonToVector3 } from "./utils.js";
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
import { fetchAdminWriteJson } from "./admin-write-auth.js";
const COMPUTE_CENTER_RENDER_ORDER = 4.5; const COMPUTE_CENTER_RENDER_ORDER = 4.5;
const COMPUTE_CENTER_POINT_SIZE = 36; const COMPUTE_CENTER_POINT_SIZE = 36;
@@ -38,28 +40,6 @@ let computeTopicQuery = null;
let loadGeneration = 0; let loadGeneration = 0;
let loadController = null; let loadController = null;
function readStoredAdminAuthToken() {
try {
const raw = globalThis.localStorage?.getItem("auth-storage");
if (!raw) return null;
const parsed = JSON.parse(raw);
return typeof parsed?.state?.token === "string" && parsed.state.token.trim()
? parsed.state.token.trim()
: null;
} catch {
return null;
}
}
function buildAdminWriteHeaders() {
const headers = { "Content-Type": "application/json" };
const token = readStoredAdminAuthToken();
if (token) {
headers.Authorization = `Bearer ${token}`;
}
return headers;
}
export function setComputeTopicQuery(query) { export function setComputeTopicQuery(query) {
computeTopicQuery = query; computeTopicQuery = query;
loadGeneration += 1; loadGeneration += 1;
@@ -481,21 +461,13 @@ export function getUnresolvedComputeCenters() {
// keys) is domain-specific; the request/response envelope is unified // keys) is domain-specific; the request/response envelope is unified
// (success / candidates / attempted_queries / failure_reason / context). // (success / candidates / attempted_queries / failure_reason / context).
export async function collectLocationCandidates(endpoint, payload = {}) { export async function collectLocationCandidates(endpoint, payload = {}) {
if (!endpoint) throw new Error("endpoint is required"); const response = await fetchAdminWriteJson(endpoint, payload);
const response = await fetch(endpoint, {
method: "POST",
headers: buildAdminWriteHeaders(),
body: JSON.stringify(payload || {}),
});
if (!response.ok) { if (!response.ok) {
if (response.status === 401 || response.status === 403) {
throw new Error("需要管理员登录后才能采集或保存算力中心位置");
}
const text = await response.text().catch(() => ""); const text = await response.text().catch(() => "");
let detail = ""; let detail = "";
try { try {
const payload = JSON.parse(text); const parsed = JSON.parse(text);
detail = payload?.detail?.reason || payload?.detail?.message || payload?.detail || ""; detail = parsed?.detail?.reason || parsed?.detail?.message || parsed?.detail || "";
} catch { } catch {
detail = text; detail = text;
} }
@@ -561,32 +533,25 @@ export async function saveComputeCenterLocation(sourceId, candidate = {}, contex
throw new Error("candidate latitude/longitude are required"); throw new Error("candidate latitude/longitude are required");
} }
const url = `${COLLECT_LOCATION_API_BASE}/${encodeURIComponent(sourceId)}/location`; const url = `${COLLECT_LOCATION_API_BASE}/${encodeURIComponent(sourceId)}/location`;
const response = await fetch(url, { const response = await fetchAdminWriteJson(url, {
method: "POST", source: context?.source ?? null,
headers: buildAdminWriteHeaders(), name: context?.name ?? candidate?.matched_location_name ?? candidate?.display_name ?? null,
body: JSON.stringify({ operator: context?.operator ?? null,
source: context?.source ?? null, site: context?.site ?? null,
name: context?.name ?? candidate?.matched_location_name ?? candidate?.display_name ?? null, city: candidate?.city ?? context?.city ?? null,
operator: context?.operator ?? null, country: candidate?.country ?? context?.country ?? null,
site: context?.site ?? null, latitude,
city: candidate?.city ?? context?.city ?? null, longitude,
country: candidate?.country ?? context?.country ?? null, precision: candidate?.precision ?? "city",
latitude, confidence: candidate?.confidence ?? null,
longitude, location_source: candidate?.source ?? "manual_selection",
precision: candidate?.precision ?? "city", source_url: candidate?.source_url ?? null,
confidence: candidate?.confidence ?? null, source_note: candidate?.source_note ?? null,
location_source: candidate?.source ?? "manual_selection", raw_payload: candidate || {},
source_url: candidate?.source_url ?? null, needs_confirmation: false,
source_note: candidate?.source_note ?? null, verification_status: "verified",
raw_payload: candidate || {},
needs_confirmation: false,
verification_status: "verified",
}),
}); });
if (!response.ok) { if (!response.ok) {
if (response.status === 401 || response.status === 403) {
throw new Error("需要管理员登录后才能采集或保存算力中心位置");
}
const text = await response.text().catch(() => ""); const text = await response.text().catch(() => "");
throw new Error( throw new Error(
`Save compute center location failed: HTTP ${response.status} ${text}`.trim(), `Save compute center location failed: HTTP ${response.status} ${text}`.trim(),
@@ -733,6 +698,7 @@ let nationalHubSynergyGroup = null;
let nationalHubSynergyMaterial = null; let nationalHubSynergyMaterial = null;
let nationalHubPulseEntries = []; let nationalHubPulseEntries = [];
let stageLogicalArcGroup = null; let stageLogicalArcGroup = null;
let stageLogicalArcEntries = [];
const _hubWorldVec = new THREE.Vector3(); const _hubWorldVec = new THREE.Vector3();
const _earthCenterVec = new THREE.Vector3(); const _earthCenterVec = new THREE.Vector3();
const _hubNormalVec = new THREE.Vector3(); const _hubNormalVec = new THREE.Vector3();
@@ -956,7 +922,37 @@ export async function setNationalComputeHubsOverlay(
return { active: true, count: markerItems.length }; return { active: true, count: markerItems.length };
} }
function buildElevatedArcPolyline(
fromLat,
fromLon,
toLat,
toLon,
{
baseOffset = COMPUTE_CENTER_CONFIG.altitudeOffset + 0.08,
peakLift = 4.2,
segments = 44,
} = {},
) {
const vStart = latLonToVector3(fromLat, fromLon, 1).normalize();
const vEnd = latLonToVector3(toLat, toLon, 1).normalize();
const pts = [];
const tempVec = new THREE.Vector3();
for (let i = 0; i <= segments; i += 1) {
const t = i / segments;
tempVec.copy(vStart).lerp(vEnd, t);
if (tempVec.lengthSq() < 1e-6) {
tempVec.set(0, 1, 0);
} else {
tempVec.normalize();
}
const radius = CONFIG.earthRadius + baseOffset + Math.sin(Math.PI * t) * peakLift;
pts.push(tempVec.clone().multiplyScalar(radius));
}
return pts;
}
export function clearStageLogicalArcsOverlay() { export function clearStageLogicalArcsOverlay() {
stageLogicalArcEntries = [];
if (!stageLogicalArcGroup) return; if (!stageLogicalArcGroup) return;
disposeThreeGroupChildren(stageLogicalArcGroup); disposeThreeGroupChildren(stageLogicalArcGroup);
stageLogicalArcGroup.parent?.remove?.(stageLogicalArcGroup); stageLogicalArcGroup.parent?.remove?.(stageLogicalArcGroup);
@@ -971,10 +967,8 @@ export function setStageLogicalArcsOverlay(earth, arcs = []) {
stageLogicalArcGroup.name = "stage-logical-as-routes"; stageLogicalArcGroup.name = "stage-logical-as-routes";
earth.add(stageLogicalArcGroup); earth.add(stageLogicalArcGroup);
const beforePos = []; const beforePolylines = [];
const beforeCol = []; const afterPolylines = [];
const afterPos = [];
const afterCol = [];
for (const arc of arcs) { for (const arc of arcs) {
const fLat = Number(arc?.from_lat); const fLat = Number(arc?.from_lat);
@@ -983,55 +977,71 @@ export function setStageLogicalArcsOverlay(earth, arcs = []) {
const tLon = Number(arc?.to_lon); const tLon = Number(arc?.to_lon);
if (![fLat, fLon, tLat, tLon].every(Number.isFinite)) continue; if (![fLat, fLon, tLat, tLon].every(Number.isFinite)) continue;
const isBefore = arc.phase === "before"; const isBefore = arc.phase === "before";
const seg = buildElevatedArcSegments(fLat, fLon, tLat, tLon, { const poly = buildElevatedArcPolyline(fLat, fLon, tLat, tLon, {
baseOffset: COMPUTE_CENTER_CONFIG.altitudeOffset + 0.35, baseOffset: COMPUTE_CENTER_CONFIG.altitudeOffset + 0.35,
peakLift: isBefore ? 6.4 : 8.6, peakLift: isBefore ? 6.4 : 8.6,
segments: 44, segments: 44,
startColor: new THREE.Color(isBefore ? 0x64748b : 0xf59e0b),
endColor: new THREE.Color(isBefore ? 0x94a3b8 : 0xfb7185),
dashed: isBefore,
}); });
if (isBefore) { if (isBefore) beforePolylines.push(poly);
beforePos.push(...seg.positions); else afterPolylines.push(poly);
beforeCol.push(...seg.colors); }
} else {
afterPos.push(...seg.positions); const startedAtMs = typeof performance !== "undefined" ? performance.now() : Date.now();
afterCol.push(...seg.colors);
if (beforePolylines.length) {
const geom = createSurfaceRibbonGeometry(beforePolylines);
const mat = createSurfaceRibbonMaterial({
color: 0x64748b,
glowColor: 0x94a3b8,
halfWidthPx: 2.6,
opacity: 0.68,
pulseSpeed: 0.25,
pulseFreq: 1.5,
pulseIntensity: 0.18,
reveal: 1.0,
additive: false,
});
const mesh = new THREE.Mesh(geom, mat);
mesh.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.22;
mesh.raycast = () => {};
stageLogicalArcGroup.add(mesh);
stageLogicalArcEntries.push({ material: mat, startedAtMs, revealDurationMs: 0 });
}
if (afterPolylines.length) {
const geom = createSurfaceRibbonGeometry(afterPolylines);
const mat = createSurfaceRibbonMaterial({
color: 0xf59e0b,
glowColor: 0xfb7185,
halfWidthPx: 4.8,
opacity: 0.94,
pulseSpeed: 0.72,
pulseFreq: 2.4,
pulseIntensity: 0.75,
reveal: 0.0,
additive: true,
});
const mesh = new THREE.Mesh(geom, mat);
mesh.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.24;
mesh.raycast = () => {};
stageLogicalArcGroup.add(mesh);
stageLogicalArcEntries.push({ material: mat, startedAtMs, revealDurationMs: 650 });
}
}
export function updateStageLogicalArcsAnimation() {
if (!stageLogicalArcEntries.length) return;
const nowMs = typeof performance !== "undefined" ? performance.now() : Date.now();
const nowSec = nowMs * 0.001;
for (const entry of stageLogicalArcEntries) {
const uniforms = entry.material?.uniforms;
if (!uniforms) continue;
uniforms.uTime.value = nowSec;
if (entry.revealDurationMs > 0) {
const linear = Math.max(0, Math.min(1, (nowMs - entry.startedAtMs) / entry.revealDurationMs));
uniforms.uReveal.value = 1 - Math.pow(1 - linear, 2.2);
} }
} }
if (beforePos.length) {
const geom = new THREE.BufferGeometry();
geom.setAttribute("position", new THREE.Float32BufferAttribute(beforePos, 3));
geom.setAttribute("color", new THREE.Float32BufferAttribute(beforeCol, 3));
const mat = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.62,
depthTest: true,
depthWrite: false,
});
const line = new THREE.LineSegments(geom, mat);
line.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.22;
stageLogicalArcGroup.add(line);
}
if (afterPos.length) {
const geom = new THREE.BufferGeometry();
geom.setAttribute("position", new THREE.Float32BufferAttribute(afterPos, 3));
geom.setAttribute("color", new THREE.Float32BufferAttribute(afterCol, 3));
const mat = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.92,
depthTest: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
});
const line = new THREE.LineSegments(geom, mat);
line.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.24;
stageLogicalArcGroup.add(line);
}
} }
export function focusComputeEntityById(earth, entityId) { export function focusComputeEntityById(earth, entityId) {
@@ -1103,6 +1113,7 @@ export function getComputeCenterPointerIntersections(options) {
export function updateComputeCenterVisualState(lockedObjectType, lockedObject, camera) { export function updateComputeCenterVisualState(lockedObjectType, lockedObject, camera) {
updateComputeCenterLocationPreview(); updateComputeCenterLocationPreview();
updateNationalHubPulses(camera); updateNationalHubPulses(camera);
updateStageLogicalArcsAnimation();
if (nationalHubOverlayActive) { if (nationalHubOverlayActive) {
nationalComputeHubLayer.updateVisualState(lockedObjectType, lockedObject, camera); nationalComputeHubLayer.updateVisualState(lockedObjectType, lockedObject, camera);
} }
+11 -3
View File
@@ -536,10 +536,12 @@ export const GRID_CONFIG = {
export const CLOUD_LAYER_CONFIG = { export const CLOUD_LAYER_CONFIG = {
radiusOffset: 3, radiusOffset: 3,
shadowAltitudeOffset: 0.52,
widthSegments: 64, widthSegments: 64,
heightSegments: 64, heightSegments: 64,
opacity: 0.15, opacity: 0.34,
textureUrl: "./assets/earth_clouds_1024.png", shadowOpacity: 0.08,
textureUrl: "./assets/earth_clouds_2048.png",
}; };
export const EARTH_MATERIAL_CONFIG = { export const EARTH_MATERIAL_CONFIG = {
@@ -572,15 +574,21 @@ export const EARTH_MATERIAL_CONFIG = {
oceanTint: [0.008, 0.016, 0.024], oceanTint: [0.008, 0.016, 0.024],
oceanAmbient: [0.0015, 0.004, 0.012], oceanAmbient: [0.0015, 0.004, 0.012],
}, },
terminator: [-0.075, 0.16], terminator: [-0.14, 0.22],
oceanReflection: [0.025, 0.12, 0.32], oceanReflection: [0.025, 0.12, 0.32],
atmosphereColor: [0.08, 0.28, 0.65], atmosphereColor: [0.08, 0.28, 0.65],
innerRimStrength: 0.28, innerRimStrength: 0.28,
twilightWarmColor: [0.95, 0.38, 0.12],
twilightWarmStrength: 0.0,
sunglintStrength: 0.0,
landReliefStrength: 0.12,
}, },
atmosphere: { atmosphere: {
radiusFactor: 1.025, radiusFactor: 1.025,
color: [0.18, 0.48, 0.88], color: [0.18, 0.48, 0.88],
strength: 0.65, strength: 0.65,
mieColor: [0.92, 0.56, 0.30],
mieStrength: 0.18,
}, },
dayNight: { dayNight: {
+18 -1
View File
@@ -1,5 +1,20 @@
const REASONING_TAG_NAMES = ["think", "thinking", "reasoning", "analysis", "thought", "reflection"]; const REASONING_TAG_NAMES = ["think", "thinking", "reasoning", "analysis", "thought", "reflection"];
const REASONING_TAG_RE = /<\s*(\/?)\s*(think|thinking|reasoning|analysis|thought|reflection)\b[^>]*>/gi; const REASONING_TAG_RE = /<\s*(\/?)\s*(think|thinking|reasoning|analysis|thought|reflection)\b[^>]*>/gi;
const PLANET_SCENE_BLOCK_RE = /<\s*planet_scene\b[^>]*>[\s\S]*?<\s*\/\s*planet_scene\s*>/gi;
const PLANET_SCENE_OPEN_TAIL_RE = /<\s*planet_scene\b[\s\S]*$/i;
function stripPlanetSceneMarkup(text) {
let cleaned = String(text ?? "").replace(PLANET_SCENE_BLOCK_RE, "");
cleaned = cleaned.replace(PLANET_SCENE_OPEN_TAIL_RE, "");
const lastLt = cleaned.lastIndexOf("<");
if (lastLt !== -1) {
const tail = cleaned.slice(lastLt);
if (tail.length < "<planet_scene>".length && "<planet_scene>".startsWith(tail.toLowerCase())) {
cleaned = cleaned.slice(0, lastLt);
}
}
return cleaned;
}
function withoutPartialReasoningTag(value) { function withoutPartialReasoningTag(value) {
const start = value.lastIndexOf("<"); const start = value.lastIndexOf("<");
@@ -18,7 +33,7 @@ function withoutPartialReasoningTag(value) {
* Supports both structured reasoning deltas and inline `<think>...</think>` blocks. * Supports both structured reasoning deltas and inline `<think>...</think>` blocks.
*/ */
export function splitCopilotResponse(value, structuredReasoning = "") { export function splitCopilotResponse(value, structuredReasoning = "") {
const completeValue = withoutPartialReasoningTag(String(value ?? "")); const completeValue = withoutPartialReasoningTag(stripPlanetSceneMarkup(value));
const answerParts = []; const answerParts = [];
const reasoningParts = []; const reasoningParts = [];
let currentReasoning = ""; let currentReasoning = "";
@@ -139,6 +154,8 @@ export async function consumeCopilotStream(
if (typeof parsed.delta === "string" && parsed.delta) { if (typeof parsed.delta === "string" && parsed.delta) {
callbacks.onTextDelta?.(parsed.delta, parsed); callbacks.onTextDelta?.(parsed.delta, parsed);
} }
} else if (eventName === "scene") {
callbacks.onScene?.(parsed);
} else if (eventName === "done") { } else if (eventName === "done") {
donePayload = parsed; donePayload = parsed;
callbacks.onDone?.(parsed); callbacks.onDone?.(parsed);
@@ -67,4 +67,48 @@ describe("copilot-stream SSE & reasoning utilities", () => {
expect(seen.text).toBe("国际局势摘要"); expect(seen.text).toBe("国际局势摘要");
expect(seen.done?.generation_mode).toBe("llm_verified"); expect(seen.done?.generation_mode).toBe("llm_verified");
}); });
it("strips <planet_scene> markup from streamed markdown and dispatches event: scene", async () => {
const midTag = splitCopilotResponse("分析结论正文。<planet_sc", "");
expect(midTag.markdown).toBe("分析结论正文。");
const fullTag = splitCopilotResponse(
"分析结论正文。\n<planet_scene>{\"influence_zones\":[{\"id\":\"z1\"}]}</planet_scene>",
"",
);
expect(fullTag.markdown).toBe("分析结论正文。");
const encoder = new TextEncoder();
const chunks = [
"event: text\ndata: {\"delta\":\"APEC 核心影响。\"}\n\n",
"event: scene\ndata: {\"scene_spec\":{\"domain\":\"global\",\"influence_zones\":[{\"id\":\"core\",\"color\":\"#ef4444\"}]}}\n\n",
"event: done\ndata: {\"generation_mode\":\"llm_verified\",\"zero_token\":false}\n\n",
];
let index = 0;
const fakeResponse = {
headers: new Headers({ "content-type": "text/event-stream" }),
body: {
getReader() {
return {
async read() {
if (index >= chunks.length) return { done: true, value: undefined };
return { done: false, value: encoder.encode(chunks[index++]) };
},
async cancel() {},
releaseLock() {},
};
},
},
};
const seen = { text: "", scene: null };
await consumeCopilotStream(fakeResponse, {
onTextDelta: (d) => { seen.text += d; },
onScene: (s) => { seen.scene = s; },
});
expect(seen.text).toBe("APEC 核心影响。");
expect(seen.scene?.scene_spec?.influence_zones).toHaveLength(1);
expect(seen.scene?.scene_spec?.influence_zones[0]?.id).toBe("core");
});
}); });
+306 -13
View File
@@ -7,7 +7,9 @@ import Pbf from "pbf";
import { CONFIG, COUNTRY_BOUNDARY_CONFIG } from "./constants.js"; import { CONFIG, COUNTRY_BOUNDARY_CONFIG } from "./constants.js";
import { screenToEarthCoords, vector3ToLatLon } from "./utils.js"; import { screenToEarthCoords, vector3ToLatLon } from "./utils.js";
import { appendSurfaceSegments, createEarthSurfaceGeometry } from "./earth-surface.js"; import { appendSurfaceSegments, createEarthSurfaceGeometry } from "./earth-surface.js";
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
import { setEarthLandMask } from "./earth.js"; import { setEarthLandMask } from "./earth.js";
import { configureColorTexture } from "./texture-colors.js";
// ─── Module state ────────────────────────────────────────────────────────────── // ─── Module state ──────────────────────────────────────────────────────────────
let _earthObj = null; let _earthObj = null;
@@ -43,6 +45,8 @@ let _tintEnabled = false;
let _landTexture = null; let _landTexture = null;
let _loaded = false; let _loaded = false;
let _loadPromise = null; let _loadPromise = null;
let _geoFeaturesCache = null;
let _geoFeaturesPromise = null;
let _tileAssetVersion = ""; let _tileAssetVersion = "";
const _countryAnchorCandidateCache = new Map(); const _countryAnchorCandidateCache = new Map();
@@ -128,6 +132,7 @@ const OCEAN_HEX = 0x010609;
// ─── Equirectangular land/ocean fill texture ────────────────────────────────── // ─── Equirectangular land/ocean fill texture ──────────────────────────────────
function configureLandMaskTexture(texture) { function configureLandMaskTexture(texture) {
configureColorTexture(texture);
texture.wrapS = THREE.ClampToEdgeWrapping; texture.wrapS = THREE.ClampToEdgeWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping; texture.wrapT = THREE.ClampToEdgeWrapping;
texture.minFilter = THREE.LinearMipmapLinearFilter; texture.minFilter = THREE.LinearMipmapLinearFilter;
@@ -305,6 +310,50 @@ function featureToSegments(geom, radius, faces = null) {
return pts; return pts;
} }
function segmentsToContinuousPolylines(segmentPairs) {
const polylines = [];
let current = null;
for (let i = 0; i + 1 < segmentPairs.length; i += 2) {
const a = segmentPairs[i];
const b = segmentPairs[i + 1];
if (!a || !b) continue;
if (current && current[current.length - 1].distanceToSquared(a) < 1e-4) {
current.push(b);
} else {
if (current && current.length >= 2) polylines.push(current);
current = [a, b];
}
}
if (current && current.length >= 2) polylines.push(current);
return polylines;
}
function featureListToPolylines(features, radius) {
const polylines = [];
for (const feature of features) {
const geom = feature?.geometry;
if (!geom) continue;
const rings = geom.type === "Polygon"
? [geom.coordinates[0]]
: geom.type === "MultiPolygon"
? geom.coordinates.map(poly => poly[0])
: geom.type === "LineString"
? [geom.coordinates]
: geom.type === "MultiLineString"
? geom.coordinates
: [];
for (const ring of rings) {
if (!Array.isArray(ring) || ring.length < 2) continue;
const segs = [];
appendSurfaceSegments(ring, radius, segs, null);
for (const poly of segmentsToContinuousPolylines(segs)) {
polylines.push(poly);
}
}
}
return polylines;
}
let boundaryLineLod = null; let boundaryLineLod = null;
function buildBoundaryLines(features) { function buildBoundaryLines(features) {
const r = boundaryLineRadius(); const r = boundaryLineRadius();
@@ -692,23 +741,33 @@ export function buildHoverLines() {
} }
export function buildHoverGlowLines() { export function buildHoverGlowLines() {
const mat = new THREE.LineBasicMaterial({ const mat = createSurfaceRibbonMaterial({
color: COUNTRY_BOUNDARY_CONFIG.hoverLineColor, color: 0xff4b33,
transparent: true, glowColor: 0xff6e54,
opacity: COUNTRY_BOUNDARY_CONFIG.hoverGlowOpacity, underlayColor: 0x060c18,
underlayOpacity: 0.42,
halfWidthPx: 4.2,
opacity: 0.68,
pulseSpeed: 0.22,
pulseFreq: 1.0,
pulseIntensity: 0.14,
depthTest: true, depthTest: true,
depthWrite: false, depthWrite: false,
blending: THREE.AdditiveBlending, additive: false,
linewidth: COUNTRY_BOUNDARY_CONFIG.hoverGlowLineWidth,
}); });
const lines = new THREE.LineSegments(new THREE.BufferGeometry(), mat); const mesh = new THREE.Mesh(createSurfaceRibbonGeometry([]), mat);
lines.name = "country-hover-glow"; mesh.name = "country-hover-glow";
lines.renderOrder = mesh.renderOrder =
COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder - COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder -
COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset; COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset;
lines.visible = false; mesh.visible = false;
lines.raycast = () => {}; mesh.raycast = () => {};
return lines; const startedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
mesh.onBeforeRender = () => {
const now = typeof performance !== "undefined" ? performance.now() : Date.now();
mat.uniforms.uTime.value = (now - startedAt) * 0.001;
};
return mesh;
} }
function setBoundaryLinesDimmed(dimmed) { function setBoundaryLinesDimmed(dimmed) {
@@ -788,7 +847,7 @@ function getHoverGeometries(groupKey, features) {
makeLineGeometry(featureListToSegments(features, coreRadius)), makeLineGeometry(featureListToSegments(features, coreRadius)),
), ),
glow: markCachedHoverGeometry( glow: markCachedHoverGeometry(
makeLineGeometry(featureListToSegments(features, glowRadius)), createSurfaceRibbonGeometry(featureListToPolylines(features, glowRadius)),
), ),
}; };
_hoverGeometryCache.set(cacheKey, geometries); _hoverGeometryCache.set(cacheKey, geometries);
@@ -1059,6 +1118,7 @@ export async function loadCountryBoundaries() {
_hoverLines = buildHoverLines(); _hoverLines = buildHoverLines();
_earthObj.add(_hoverLines); _earthObj.add(_hoverLines);
_geoFeaturesCache = _features;
_loaded = true; _loaded = true;
return _features.length; return _features.length;
})(); })();
@@ -1310,3 +1370,236 @@ export function applyCountryBoundaryLegendFilter() {
uniforms.uLegendOcean.value = isLegendItemEnabled("countryBoundaries", "ocean") ? 1 : 0; uniforms.uLegendOcean.value = isLegendItemEnabled("countryBoundaries", "ocean") ? 1 : 0;
} }
} }
export const REGION_PRESET_ISO3_MAP = Object.freeze({
APEC: [
"AUS", "BRN", "CAN", "CHL", "CHN", "IDN", "JPN", "KOR", "MEX", "MYS",
"NZL", "PER", "PHL", "PNG", "RUS", "SGP", "THA", "USA", "VNM",
],
ASIA_PACIFIC: [
"AUS", "BRN", "CHN", "IDN", "IND", "JPN", "KHM", "KOR", "LAO", "MMR",
"MYS", "NZL", "PHL", "PNG", "PRK", "RUS", "SGP", "THA", "TLS", "VNM",
],
NORTHEAST_ASIA: ["CHN", "PRK", "KOR", "JPN", "MNG", "RUS"],
EAST_ASIA: ["CHN", "PRK", "KOR", "JPN", "MNG"],
KOREAN_PENINSULA: ["PRK", "KOR"],
SOUTHEAST_ASIA: ["BRN", "IDN", "KHM", "LAO", "MMR", "MYS", "PHL", "SGP", "THA", "TLS", "VNM"],
SOUTH_ASIA: ["AFG", "BGD", "BTN", "IND", "LKA", "MDV", "NPL", "PAK"],
CENTRAL_ASIA: ["KAZ", "KGZ", "TJK", "TKM", "UZB"],
INDO_PACIFIC: [
"AUS", "BRN", "CAN", "CHN", "IDN", "IND", "JPN", "KHM", "KOR", "LAO",
"MMR", "MYS", "NZL", "PHL", "PNG", "PRK", "RUS", "SGP", "THA", "TLS",
"USA", "VNM",
],
ASEAN: ["BRN", "IDN", "KHM", "LAO", "MMR", "MYS", "PHL", "SGP", "THA", "VNM"],
EU: [
"AUT", "BEL", "BGR", "CYP", "CZE", "DEU", "DNK", "ESP", "EST", "FIN",
"FRA", "GRC", "HRV", "HUN", "IRL", "ITA", "LTU", "LUX", "LVA", "NLD",
"POL", "PRT", "ROU", "SVK", "SVN", "SWE",
],
EUROPE: [
"ALB", "AUT", "BEL", "BGR", "BIH", "BLR", "CHE", "CZE", "DEU", "DNK",
"ESP", "EST", "FIN", "FRA", "GBR", "GRC", "HRV", "HUN", "IRL", "ISL",
"ITA", "LTU", "LUX", "LVA", "MDA", "MKD", "MNE", "NLD", "NOR", "POL",
"PRT", "ROU", "SRB", "SVK", "SVN", "SWE", "UKR",
],
EASTERN_EUROPE: [
"BGR", "BLR", "CZE", "EST", "HUN", "LTU", "LVA", "MDA", "POL", "ROU",
"SVK", "UKR",
],
NORTHERN_EUROPE: ["DNK", "EST", "FIN", "ISL", "LTU", "LVA", "NOR", "SWE"],
WESTERN_EUROPE: ["AUT", "BEL", "CHE", "DEU", "FRA", "GBR", "IRL", "LUX", "NLD"],
G7: ["CAN", "DEU", "FRA", "GBR", "ITA", "JPN", "USA"],
BRICS: ["BRA", "CHN", "EGY", "ETH", "IND", "IRN", "RUS", "ZAF", "ARE"],
NATO: [
"ALB", "BEL", "BGR", "CAN", "CZE", "DEU", "DNK", "ESP", "EST", "FIN",
"FRA", "GBR", "GRC", "HRV", "HUN", "ISL", "ITA", "LTU", "LUX", "LVA",
"MKD", "MNE", "NLD", "NOR", "POL", "PRT", "ROU", "SVK", "SVN", "SWE",
"TUR", "USA",
],
MIDDLE_EAST: [
"ARE", "EGY", "IRN", "IRQ", "ISR", "JOR", "KWT", "LBN", "OMN", "PSE",
"QAT", "SAU", "SYR", "TUR", "YEM",
],
MENA: [
"ARE", "DZA", "EGY", "IRN", "IRQ", "ISR", "JOR", "KWT", "LBN", "LBY",
"MAR", "OMN", "PSE", "QAT", "SAU", "SDN", "SYR", "TUN", "TUR", "YEM",
],
AMERICAS: [
"ARG", "BOL", "BRA", "CAN", "CHL", "COL", "CRI", "CUB", "DOM", "ECU",
"GTM", "GUY", "HND", "HTI", "JAM", "MEX", "NIC", "PAN", "PER", "PRY",
"SLV", "SUR", "URY", "USA", "VEN",
],
NORTH_AMERICA: ["CAN", "MEX", "USA"],
SOUTH_AMERICA: [
"ARG", "BOL", "BRA", "CHL", "COL", "ECU", "GUY", "PER", "PRY", "SUR",
"URY", "VEN",
],
AFRICA: [
"AGO", "BDI", "BEN", "BFA", "BWA", "CAF", "CIV", "CMR", "COD", "COG",
"DJI", "DZA", "EGY", "ERI", "ETH", "GAB", "GHA", "GIN", "GMB", "GNB",
"GNQ", "KEN", "LBR", "LBY", "LSO", "MAR", "MDG", "MLI", "MOZ", "MRT",
"MWI", "NAM", "NER", "NGA", "RWA", "SDN", "SEN", "SLE", "SOM", "SSD",
"SWZ", "TCD", "TGO", "TUN", "TZA", "UGA", "ZAF", "ZMB", "ZWE",
],
});
const INFLUENCE_COUNTRY_ALIAS_MAP = Object.freeze({
CN: "CHN", CHINA: "CHN", 中国: "CHN", PRC: "CHN",
HK: "CHN", HKG: "CHN", 香港: "CHN", MO: "CHN", MAC: "CHN", 澳门: "CHN",
TW: "CHN", TWN: "CHN", 台湾: "CHN",
KP: "PRK", PRK: "PRK", DPRK: "PRK", NK: "PRK", NKR: "PRK", "NORTH KOREA": "PRK", 朝鲜: "PRK", 北朝鲜: "PRK", 朝鲜民主主义人民共和国: "PRK",
KR: "KOR", KOR: "KOR", ROK: "KOR", KOREA: "KOR", "SOUTH KOREA": "KOR", 韩国: "KOR", 南韩: "KOR", 大韩民国: "KOR",
US: "USA", USA: "USA", 美国: "USA", AMERICA: "USA",
RU: "RUS", RUS: "RUS", RUSSIA: "RUS", 俄罗斯: "RUS", 俄国: "RUS",
FR: "FRA", FRA: "FRA", FRANCE: "FRA", 法国: "FRA",
NO: "NOR", NOR: "NOR", NORWAY: "NOR", 挪威: "NOR",
UK: "GBR", GB: "GBR", GBR: "GBR", BRITAIN: "GBR", 英国: "GBR",
DE: "DEU", DEU: "DEU", GERMANY: "DEU", 德国: "DEU",
JP: "JPN", JPN: "JPN", JAPAN: "JPN", 日本: "JPN",
IN: "IND", IND: "IND", INDIA: "IND", 印度: "IND",
AU: "AUS", AUS: "AUS", AUSTRALIA: "AUS", 澳大利亚: "AUS", 澳洲: "AUS",
CA: "CAN", CAN: "CAN", CANADA: "CAN", 加拿大: "CAN",
BR: "BRA", BRA: "BRA", BRAZIL: "BRA", 巴西: "BRA",
SG: "SGP", SGP: "SGP", SINGAPORE: "SGP", 新加坡: "SGP",
ID: "IDN", IDN: "IDN", INDONESIA: "IDN", 印尼: "IDN", 印度尼西亚: "IDN",
VN: "VNM", VNM: "VNM", VIETNAM: "VNM", 越南: "VNM",
TH: "THA", THA: "THA", THAILAND: "THA", 泰国: "THA",
MY: "MYS", MYS: "MYS", MALAYSIA: "MYS", 马来西亚: "MYS",
PH: "PHL", PHL: "PHL", PHILIPPINES: "PHL", 菲律宾: "PHL",
NZ: "NZL", NZL: "NZL", 新西兰: "NZL",
MX: "MEX", MEX: "MEX", MEXICO: "MEX", 墨西哥: "MEX",
CL: "CHL", CHL: "CHL", CHILE: "CHL", 智利: "CHL",
PE: "PER", PER: "PER", PERU: "PER", 秘鲁: "PER",
UA: "UKR", UKR: "UKR", UKRAINE: "UKR", 乌克兰: "UKR",
IR: "IRN", IRN: "IRN", IRAN: "IRN", 伊朗: "IRN",
SA: "SAU", SAU: "SAU", 沙特: "SAU", 沙特阿拉伯: "SAU",
TR: "TUR", TUR: "TUR", TURKEY: "TUR", 土耳其: "TUR",
IL: "ISR", ISR: "ISR", ISRAEL: "ISR", 以色列: "ISR",
EG: "EGY", EGY: "EGY", EGYPT: "EGY", 埃及: "EGY",
ZA: "ZAF", ZAF: "ZAF", 南非: "ZAF",
IT: "ITA", ITA: "ITA", ITALY: "ITA", 意大利: "ITA",
ES: "ESP", ESP: "ESP", SPAIN: "ESP", 西班牙: "ESP",
AE: "ARE", ARE: "ARE", UAE: "ARE", 阿联酋: "ARE",
SO: "SOM", SOM: "SOM", SOMALIA: "SOM", 索马里: "SOM",
YE: "YEM", YEM: "YEM", YEMEN: "YEM", 也门: "YEM",
SY: "SYR", SYR: "SYR", SYRIA: "SYR", 叙利亚: "SYR",
IQ: "IRQ", IRQ: "IRQ", IRAQ: "IRQ", 伊拉克: "IRQ",
PK: "PAK", PAK: "PAK", PAKISTAN: "PAK", 巴基斯坦: "PAK",
KZ: "KAZ", KAZ: "KAZ", KAZAKHSTAN: "KAZ", 哈萨克斯坦: "KAZ",
MN: "MNG", MNG: "MNG", MONGOLIA: "MNG", 蒙古: "MNG",
PL: "POL", POL: "POL", POLAND: "POL", 波兰: "POL",
FI: "FIN", FIN: "FIN", FINLAND: "FIN", 芬兰: "FIN",
SE: "SWE", SWE: "SWE", SWEDEN: "SWE", 瑞典: "SWE",
NL: "NLD", NLD: "NLD", NETHERLANDS: "NLD", 荷兰: "NLD",
BE: "BEL", BEL: "BEL", BELGIUM: "BEL", 比利时: "BEL",
CH: "CHE", CHE: "CHE", SWITZERLAND: "CHE", 瑞士: "CHE",
AT: "AUT", AUT: "AUT", AUSTRIA: "AUT", 奥地利: "AUT",
GR: "GRC", GRC: "GRC", GREECE: "GRC", 希腊: "GRC",
CZ: "CZE", CZE: "CZE", CZECHIA: "CZE", 捷克: "CZE",
RO: "ROU", ROU: "ROU", ROMANIA: "ROU", 罗马尼亚: "ROU",
HU: "HUN", HUN: "HUN", HUNGARY: "HUN", 匈牙利: "HUN",
BY: "BLR", BLR: "BLR", BELARUS: "BLR", 白俄罗斯: "BLR",
EE: "EST", EST: "EST", ESTONIA: "EST", 爱沙尼亚: "EST",
LV: "LVA", LVA: "LVA", LATVIA: "LVA", 拉脱维亚: "LVA",
LT: "LTU", LTU: "LTU", LITHUANIA: "LTU", 立陶宛: "LTU",
DK: "DNK", DNK: "DNK", DENMARK: "DNK", 丹麦: "DNK",
IE: "IRL", IRL: "IRL", IRELAND: "IRL", 爱尔兰: "IRL",
PT: "PRT", PRT: "PRT", PORTUGAL: "PRT", 葡萄牙: "PRT",
RS: "SRB", SRB: "SRB", SERBIA: "SRB", 塞尔维亚: "SRB",
HR: "HRV", HRV: "HRV", CROATIA: "HRV", 克罗地亚: "HRV",
BG: "BGR", BGR: "BGR", BULGARIA: "BGR", 保加利亚: "BGR",
SK: "SVK", SVK: "SVK", SLOVAKIA: "SVK", 斯洛伐克: "SVK",
SI: "SVN", SVN: "SVN", SLOVENIA: "SVN", 斯洛文尼亚: "SVN",
IS: "ISL", ISL: "ISL", ICELAND: "ISL", 冰岛: "ISL",
AR: "ARG", ARG: "ARG", ARGENTINA: "ARG", 阿根廷: "ARG",
CO: "COL", COL: "COL", COLOMBIA: "COL", 哥伦比亚: "COL",
VE: "VEN", VEN: "VEN", VENEZUELA: "VEN", 委内瑞拉: "VEN",
CU: "CUB", CUB: "CUB", CUBA: "CUB", 古巴: "CUB",
NG: "NGA", NGA: "NGA", NIGERIA: "NGA", 尼日利亚: "NGA",
KE: "KEN", KEN: "KEN", KENYA: "KEN", 肯尼亚: "KEN",
ET: "ETH", ETH: "ETH", ETHIOPIA: "ETH", 埃塞俄比亚: "ETH",
MA: "MAR", MAR: "MAR", MOROCCO: "MAR", 摩洛哥: "MAR",
DZ: "DZA", DZA: "DZA", ALGERIA: "DZA", 阿尔及利亚: "DZA",
LY: "LBY", LBY: "LBY", LIBYA: "LBY", 利比亚: "LBY",
QA: "QAT", QAT: "QAT", QATAR: "QAT", 卡塔尔: "QAT",
KW: "KWT", KWT: "KWT", KUWAIT: "KWT", 科威特: "KWT",
OM: "OMN", OMN: "OMN", OMAN: "OMN", 阿曼: "OMN",
JO: "JOR", JOR: "JOR", JORDAN: "JOR", 约旦: "JOR",
LB: "LBN", LBN: "LBN", LEBANON: "LBN", 黎巴嫩: "LBN",
PS: "PSE", PSE: "PSE", PALESTINE: "PSE", 巴勒斯坦: "PSE",
MM: "MMR", MMR: "MMR", MYANMAR: "MMR", 缅甸: "MMR",
KH: "KHM", KHM: "KHM", CAMBODIA: "KHM", 柬埔寨: "KHM",
LA: "LAO", LAO: "LAO", LAOS: "LAO", 老挝: "LAO",
BD: "BGD", BGD: "BGD", BANGLADESH: "BGD", 孟加拉国: "BGD",
LK: "LKA", LKA: "LKA", "SRI LANKA": "LKA", 斯里兰卡: "LKA",
AF: "AFG", AFG: "AFG", AFGHANISTAN: "AFG", 阿富汗: "AFG",
UZ: "UZB", UZB: "UZB", UZBEKISTAN: "UZB", 乌兹别克斯坦: "UZB",
});
/** Resolve primary ISO-3 code for a GeoJSON country feature, skipping '-99' placeholders. */
export function resolveCountryIso3(feature) {
const props = feature?.properties || {};
const candidates = [props.ISO_A3, props.ADM0_A3, props.SOV_A3];
for (const raw of candidates) {
if (!raw) continue;
const code = String(raw).trim().toUpperCase();
if (code && code !== "-99") return code;
}
return "";
}
function normalizeQueryCountryToken(token) {
const raw = String(token ?? "").trim();
if (!raw) return "";
const upper = raw.toUpperCase();
return INFLUENCE_COUNTRY_ALIAS_MAP[raw] || INFLUENCE_COUNTRY_ALIAS_MAP[upper] || upper;
}
/** Return all GeoJSON features matching any requested ISO-3 / ISO-2 / alias tokens. */
export function resolveCountryFeaturesByCodes(features, codes) {
if (!Array.isArray(features) || !Array.isArray(codes) || codes.length === 0) {
return [];
}
const wanted = new Set();
for (const code of codes) {
const normalized = normalizeQueryCountryToken(code);
if (normalized) wanted.add(normalized);
}
if (wanted.size === 0) return [];
return features.filter(feature => {
const iso3 = resolveCountryIso3(feature);
if (iso3 && wanted.has(iso3)) return true;
const props = feature?.properties || {};
const secondary = [props.ISO_A2, props.ISO_A2_EH, props.ADM0_A3, props.NAME_EN, props.NAME, props.ADMIN, props.NAME_ZH]
.filter(Boolean)
.map(v => String(v).trim().toUpperCase())
.filter(v => v && v !== "-99");
return secondary.some(code => wanted.has(code));
});
}
/** Lazy-load and cache policy country GeoJSON features for influence zones without DOM assumptions. */
export async function ensureCountryGeoFeatures() {
if (_loaded && Array.isArray(_features) && _features.length > 0) {
_geoFeaturesCache = _features;
return _geoFeaturesCache;
}
if (Array.isArray(_geoFeaturesCache) && _geoFeaturesCache.length > 0) {
return _geoFeaturesCache;
}
if (!_geoFeaturesPromise) {
_geoFeaturesPromise = fetchJsonAsset(POLICY_FALLBACK_URL, { required: true })
.then(geojson => {
const list = (geojson?.features || []).filter(f => f && f.geometry);
_geoFeaturesCache = list;
return list;
})
.catch(err => {
_geoFeaturesPromise = null;
throw err;
});
}
return _geoFeaturesPromise;
}
@@ -53,6 +53,10 @@ export const SURFACE_FRAGMENT_SHADER = `
uniform vec3 uOceanReflection; uniform vec3 uOceanReflection;
uniform vec3 uAtmosphereColor; uniform vec3 uAtmosphereColor;
uniform float uInnerRimStrength; uniform float uInnerRimStrength;
uniform vec3 uTwilightWarmColor;
uniform float uTwilightWarmStrength;
uniform float uSunglintStrength;
uniform float uLandReliefStrength;
varying vec2 vUv; varying vec2 vUv;
varying vec3 vWorldNormal; varying vec3 vWorldNormal;
varying vec3 vWorldPosition; varying vec3 vWorldPosition;
@@ -63,8 +67,9 @@ export const SURFACE_FRAGMENT_SHADER = `
source = surfaceLinear(source); source = surfaceLinear(source);
#endif #endif
vec3 normal = normalize(vWorldNormal); vec3 normal = normalize(vWorldNormal);
vec3 sunDir = normalize(uSunDirectionWorld);
vec3 viewDirection = normalize(cameraPosition - vWorldPosition); vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float sunFacing = dot(normal, normalize(uSunDirectionWorld)); float sunFacing = dot(normal, sunDir);
float daylight = mix(1.0, smoothstep(uTerminator.x, uTerminator.y, sunFacing), uDayNightEnabled); float daylight = mix(1.0, smoothstep(uTerminator.x, uTerminator.y, sunFacing), uDayNightEnabled);
float luminance = dot(source, vec3(0.2126, 0.7152, 0.0722)); float luminance = dot(source, vec3(0.2126, 0.7152, 0.0722));
// Until geography is ready use a conservative blue-chroma estimate. Once // Until geography is ready use a conservative blue-chroma estimate. Once
@@ -78,11 +83,23 @@ export const SURFACE_FRAGMENT_SHADER = `
// Ice retains its source appearance, even over ocean polygons. // Ice retains its source appearance, even over ocean polygons.
ocean *= 1.0 - smoothstep(0.45, 0.8, min(source.r, min(source.g, source.b))); ocean *= 1.0 - smoothstep(0.45, 0.8, min(source.r, min(source.g, source.b)));
vec3 land = mix(vec3(luminance), source, uLandSaturation); vec3 land = mix(vec3(luminance), source, uLandSaturation);
vec3 base = mix(land, source * uOceanAbsorption + uOceanDeepColor, ocean); // Extension-free 2-tap UV finite differences for sunlit continental micro-relief
vec3 sampleDx = texture2D(uDayMap, vUv + vec2(0.00045, 0.0)).rgb;
vec3 sampleDy = texture2D(uDayMap, vUv + vec2(0.0, 0.0009)).rgb;
#ifdef LEGACY_TEXTURE_ENCODING
sampleDx = surfaceLinear(sampleDx);
sampleDy = surfaceLinear(sampleDy);
#endif
float lumDx = dot(sampleDx, vec3(0.2126, 0.7152, 0.0722));
float lumDy = dot(sampleDy, vec3(0.2126, 0.7152, 0.0722));
float reliefShade = clamp((luminance - lumDx) * 1.4 + (luminance - lumDy) * 1.4, -0.35, 0.35);
float landRelief = 1.0 + reliefShade * uLandReliefStrength * (1.0 - ocean) * mix(0.35, 1.0, daylight);
vec3 base = mix(land * landRelief, source * uOceanAbsorption + uOceanDeepColor, ocean);
float diffuse = mix(1.0, 0.78 + 0.22 * max(sunFacing, 0.0), uDayNightEnabled); float diffuse = mix(1.0, 0.78 + 0.22 * max(sunFacing, 0.0), uDayNightEnabled);
vec3 color = base * diffuse; vec3 color = base * diffuse;
float fresnel = pow(1.0 - clamp(dot(normal, viewDirection), 0.0, 1.0), 3.4); float fresnel = pow(1.0 - clamp(dot(normal, viewDirection), 0.0, 1.0), 3.4);
// No white specular lobe: only grazing-angle sky reflection on water. // Grazing-angle sky reflection on water (no glass-ball specular highlight)
color += uOceanReflection * fresnel * ocean * daylight; color += uOceanReflection * fresnel * ocean * daylight;
float rimLight = mix(1.0, smoothstep(-0.18, 0.45, sunFacing), uDayNightEnabled); float rimLight = mix(1.0, smoothstep(-0.18, 0.45, sunFacing), uDayNightEnabled);
color += uAtmosphereColor * pow(fresnel, 1.6) * uInnerRimStrength * rimLight; color += uAtmosphereColor * pow(fresnel, 1.6) * uInnerRimStrength * rimLight;
@@ -98,6 +115,7 @@ export const SURFACE_FRAGMENT_SHADER = `
`; `;
export function createEarthSurfaceMaterial(config, sunDirection, enabled) { export function createEarthSurfaceMaterial(config, sunDirection, enabled) {
const twilightWarm = config.twilightWarmColor || [0.95, 0.38, 0.12];
return new THREE.ShaderMaterial({ return new THREE.ShaderMaterial({
uniforms: { uniforms: {
uDayMap: { value: null }, uDayMap: { value: null },
@@ -120,6 +138,10 @@ export function createEarthSurfaceMaterial(config, sunDirection, enabled) {
uOceanReflection: { value: new THREE.Vector3(...config.oceanReflection) }, uOceanReflection: { value: new THREE.Vector3(...config.oceanReflection) },
uAtmosphereColor: { value: new THREE.Vector3(...config.atmosphereColor) }, uAtmosphereColor: { value: new THREE.Vector3(...config.atmosphereColor) },
uInnerRimStrength: { value: config.innerRimStrength }, uInnerRimStrength: { value: config.innerRimStrength },
uTwilightWarmColor: { value: new THREE.Vector3(...twilightWarm) },
uTwilightWarmStrength: { value: config.twilightWarmStrength ?? 0.0 },
uSunglintStrength: { value: config.sunglintStrength ?? 0.0 },
uLandReliefStrength: { value: config.landReliefStrength ?? 0.12 },
}, },
defines: LEGACY_TEXTURE_ENCODING ? { LEGACY_TEXTURE_ENCODING: 1 } : {}, defines: LEGACY_TEXTURE_ENCODING ? { LEGACY_TEXTURE_ENCODING: 1 } : {},
vertexShader: SURFACE_VERTEX_SHADER, vertexShader: SURFACE_VERTEX_SHADER,
@@ -133,12 +155,15 @@ export function createEarthSurfaceMaterial(config, sunDirection, enabled) {
} }
export function createEarthAtmosphereMaterial(config, sunDirection, enabled) { export function createEarthAtmosphereMaterial(config, sunDirection, enabled) {
const mieColor = config.mieColor || [0.92, 0.56, 0.30];
return new THREE.ShaderMaterial({ return new THREE.ShaderMaterial({
uniforms: { uniforms: {
uSunDirectionWorld: { value: sunDirection.clone() }, uSunDirectionWorld: { value: sunDirection.clone() },
uDayNightEnabled: { value: enabled ? 1 : 0 }, uDayNightEnabled: { value: enabled ? 1 : 0 },
uColor: { value: new THREE.Vector3(...config.color) }, uColor: { value: new THREE.Vector3(...config.color) },
uStrength: { value: config.strength }, uStrength: { value: config.strength },
uMieColor: { value: new THREE.Vector3(...mieColor) },
uMieStrength: { value: config.mieStrength ?? 0.18 },
}, },
vertexShader: SURFACE_VERTEX_SHADER, vertexShader: SURFACE_VERTEX_SHADER,
fragmentShader: ` fragmentShader: `
@@ -146,16 +171,24 @@ export function createEarthAtmosphereMaterial(config, sunDirection, enabled) {
uniform float uDayNightEnabled; uniform float uDayNightEnabled;
uniform vec3 uColor; uniform vec3 uColor;
uniform float uStrength; uniform float uStrength;
uniform vec3 uMieColor;
uniform float uMieStrength;
varying vec3 vWorldNormal; varying vec3 vWorldNormal;
varying vec3 vWorldPosition; varying vec3 vWorldPosition;
void main() { void main() {
vec3 normal = normalize(vWorldNormal); vec3 normal = normalize(vWorldNormal);
vec3 sunDir = normalize(uSunDirectionWorld);
vec3 viewDirection = normalize(cameraPosition - vWorldPosition); vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float facing = clamp(abs(dot(normal, viewDirection)), 0.0, 1.0); float facing = clamp(abs(dot(normal, viewDirection)), 0.0, 1.0);
float rim = pow(1.0 - facing, 3.0) * smoothstep(0.0, 0.22, facing); float rim = pow(1.0 - facing, 3.0) * smoothstep(0.0, 0.22, facing);
float daylight = smoothstep(-0.22, 0.45, dot(normal, normalize(uSunDirectionWorld))); float sunDot = dot(normal, sunDir);
float daylight = smoothstep(-0.22, 0.45, sunDot);
float illumination = mix(1.0, mix(0.12, 1.0, daylight), uDayNightEnabled); float illumination = mix(1.0, mix(0.12, 1.0, daylight), uDayNightEnabled);
gl_FragColor = vec4(uColor, rim * illumination * uStrength); float forwardScatter = pow(max(dot(-viewDirection, sunDir), 0.0), 3.6);
float mieWeight = uDayNightEnabled * uMieStrength * clamp(forwardScatter, 0.0, 1.0);
vec3 haloColor = mix(uColor, uMieColor, clamp(mieWeight * 0.85, 0.0, 0.45));
float alpha = rim * illumination * uStrength + rim * mieWeight * 0.25;
gl_FragColor = vec4(haloColor, clamp(alpha, 0.0, 1.0));
} }
`, `,
side: THREE.BackSide, side: THREE.BackSide,
@@ -166,3 +199,111 @@ export function createEarthAtmosphereMaterial(config, sunDirection, enabled) {
toneMapped: false, toneMapped: false,
}); });
} }
export function createEarthCloudMaterial(config, sunDirection, enabled) {
return new THREE.ShaderMaterial({
uniforms: {
uCloudMap: { value: null },
uSunDirectionWorld: { value: sunDirection.clone() },
uDayNightEnabled: { value: enabled ? 1 : 0 },
uOpacity: { value: config?.opacity ?? 0.34 },
},
vertexShader: SURFACE_VERTEX_SHADER,
fragmentShader: `
uniform sampler2D uCloudMap;
uniform vec3 uSunDirectionWorld;
uniform float uDayNightEnabled;
uniform float uOpacity;
varying vec2 vUv;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
float cloudHash(vec2 p) {
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
}
float cloudNoise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
float a = cloudHash(i);
float b = cloudHash(i + vec2(1.0, 0.0));
float c = cloudHash(i + vec2(0.0, 1.0));
float d = cloudHash(i + vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
void main() {
vec4 tex = texture2D(uCloudMap, vUv);
float baseDensity = min(tex.a, dot(tex.rgb, vec3(0.3333)));
if (baseDensity < 0.03) discard;
// Delicate high-frequency cirrus modulation only inside existing clean clouds
vec2 sphereNoiseUv = vec2(vUv.x * 96.0, vUv.y * 48.0);
float cirrus = 0.72 * cloudNoise(sphereNoiseUv) + 0.28 * cloudNoise(sphereNoiseUv * 2.3 + 4.7);
float wispyDensity = clamp(baseDensity * mix(0.84, 1.14, cirrus), 0.0, 1.0);
float density = smoothstep(0.03, 0.85, wispyDensity);
vec3 normal = normalize(vWorldNormal);
vec3 sunDir = normalize(uSunDirectionWorld);
float sunDot = dot(normal, sunDir);
float dayLit = mix(1.0, smoothstep(-0.22, 0.34, sunDot), uDayNightEnabled);
float twilight = smoothstep(-0.16, 0.04, sunDot) * (1.0 - smoothstep(0.04, 0.22, sunDot)) * uDayNightEnabled;
vec3 dayColor = vec3(0.95, 0.97, 1.0) * (0.76 + 0.24 * max(sunDot, 0.0));
vec3 nightColor = vec3(0.08, 0.13, 0.22);
vec3 warmEdge = vec3(0.92, 0.66, 0.45);
vec3 cloudRgb = mix(nightColor, dayColor, dayLit) + warmEdge * (twilight * 0.14 * density);
float alpha = pow(density, 1.05) * uOpacity * mix(0.24, 1.15, dayLit);
if (alpha < 0.004) discard;
gl_FragColor = vec4(cloudRgb, clamp(alpha, 0.0, 0.72));
}
`,
side: THREE.FrontSide,
transparent: true,
depthWrite: false,
depthTest: true,
toneMapped: false,
});
}
export function createEarthCloudShadowMaterial(config, sunDirection, enabled) {
return new THREE.ShaderMaterial({
uniforms: {
uCloudMap: { value: null },
uSunDirectionWorld: { value: sunDirection.clone() },
uDayNightEnabled: { value: enabled ? 1 : 0 },
uShadowOpacity: { value: config?.shadowOpacity ?? 0.08 },
},
vertexShader: SURFACE_VERTEX_SHADER,
fragmentShader: `
uniform sampler2D uCloudMap;
uniform vec3 uSunDirectionWorld;
uniform float uDayNightEnabled;
uniform float uShadowOpacity;
varying vec2 vUv;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vec3 normal = normalize(vWorldNormal);
vec3 sunDir = normalize(uSunDirectionWorld);
float sunDot = dot(normal, sunDir);
float dayLit = mix(1.0, smoothstep(0.02, 0.42, sunDot), uDayNightEnabled);
if (dayLit < 0.02 || uShadowOpacity <= 0.001) discard;
vec2 shadowUv = fract(vUv + vec2(0.0018, -0.0011));
vec4 tex = texture2D(uCloudMap, shadowUv);
float density = min(tex.a, dot(tex.rgb, vec3(0.3333)));
float alpha = smoothstep(0.42, 0.92, density) * uShadowOpacity * dayLit;
if (alpha < 0.004) discard;
gl_FragColor = vec4(0.01, 0.02, 0.04, alpha);
}
`,
side: THREE.FrontSide,
transparent: true,
depthWrite: false,
depthTest: true,
toneMapped: false,
});
}
@@ -1,10 +1,16 @@
import { expect, test } from "bun:test"; import { expect, test } from "bun:test";
import * as THREE from "three"; import * as THREE from "three";
import { import {
createEarth, getEarthSurfacePickTarget, setDayNightEnabled, createClouds, createEarth, getEarthSurfacePickTarget, setDayNightEnabled,
setEarthLandMask, setEarthSunDirection, setEarthTextureVisible, setEarthLandMask, setEarthSunDirection, setEarthTextureVisible, toggleClouds,
} from "./earth.js"; } from "./earth.js";
import { CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET } from "./constants.js"; import { CLOUD_LAYER_CONFIG, CONFIG, EARTH_MATERIAL_CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET } from "./constants.js";
import {
createEarthAtmosphereMaterial,
createEarthCloudMaterial,
createEarthCloudShadowMaterial,
createEarthSurfaceMaterial,
} from "./earth-surface-material.js";
import { createCableLineBatch } from "./cable-batches.js"; import { createCableLineBatch } from "./cable-batches.js";
test("the real texture shell retains its geometry and pick target, with one atmosphere draw", () => { test("the real texture shell retains its geometry and pick target, with one atmosphere draw", () => {
@@ -59,6 +65,7 @@ test("cable pulses use arc length while keeping original pick objects and indepe
const originalPositions = lines[0].geometry.attributes.position.array.slice(); const originalPositions = lines[0].geometry.attributes.position.array.slice();
const originalRaycast = lines[0].raycast; const originalRaycast = lines[0].raycast;
const batch = createCableLineBatch(lines); const batch = createCableLineBatch(lines);
expect(batch.object.material.fragmentShader).toContain("#include <colorspace_fragment>");
const progress = batch.object.geometry.attributes.progress; const progress = batch.object.geometry.attributes.progress;
expect([...progress.array.slice(0, 4)]).toEqual([0, 0.25, 0.25, 1]); expect([...progress.array.slice(0, 4)]).toEqual([0, 0.25, 0.25, 1]);
lines[0].material.userData.cableSelected = true; lines[0].material.userData.cableSelected = true;
@@ -75,3 +82,46 @@ test("cable pulses use arc length while keeping original pick objects and indepe
batch.dispose(); batch.dispose();
expect(lines[0].geometry.attributes.position.count).toBe(3); expect(lines[0].geometry.attributes.position.count).toBe(3);
}); });
test("upgraded Earth surface, Mie atmosphere, and FrontSide cloud/shadow shaders expose physical uniforms", () => {
const sun = new THREE.Vector3(1, 0.2, 0.4).normalize();
const surfaceMat = createEarthSurfaceMaterial(EARTH_MATERIAL_CONFIG.surface, sun, true);
expect(surfaceMat.uniforms.uTwilightWarmStrength.value).toBeCloseTo(EARTH_MATERIAL_CONFIG.surface.twilightWarmStrength);
expect(surfaceMat.uniforms.uSunglintStrength.value).toBeCloseTo(EARTH_MATERIAL_CONFIG.surface.sunglintStrength);
expect(surfaceMat.uniforms.uLandReliefStrength.value).toBeCloseTo(EARTH_MATERIAL_CONFIG.surface.landReliefStrength);
expect(surfaceMat.fragmentShader).not.toContain("dFdx");
expect(surfaceMat.fragmentShader).not.toContain("dFdy");
expect(surfaceMat.fragmentShader).not.toContain("halfVec");
const atmoMat = createEarthAtmosphereMaterial(EARTH_MATERIAL_CONFIG.atmosphere, sun, true);
expect(atmoMat.uniforms.uMieStrength.value).toBeCloseTo(EARTH_MATERIAL_CONFIG.atmosphere.mieStrength);
const cloudMat = createEarthCloudMaterial(CLOUD_LAYER_CONFIG, sun, true);
expect(cloudMat.side).toBe(THREE.FrontSide);
expect(cloudMat.transparent).toBe(true);
expect(cloudMat.depthWrite).toBe(false);
expect(cloudMat.uniforms.uCloudMap.value).toBeNull();
expect(cloudMat.fragmentShader).toContain("min(tex.a");
const shadowMat = createEarthCloudShadowMaterial(CLOUD_LAYER_CONFIG, sun, true);
expect(shadowMat.side).toBe(THREE.FrontSide);
expect(shadowMat.depthWrite).toBe(false);
const scene = new THREE.Scene();
const earth = createEarth(scene);
expect(earth.children.filter(child => child.material?.isShaderMaterial)).toHaveLength(2);
const cloudsMesh = createClouds(scene, earth);
expect(cloudsMesh.material.side).toBe(THREE.FrontSide);
const shadowChild = cloudsMesh.getObjectByName("earth-cloud-shadow");
expect(shadowChild).toBeTruthy();
expect(shadowChild.renderOrder).toBeLessThan(1);
const nextSun = new THREE.Vector3(-1, 0, 0);
setEarthSunDirection(nextSun);
expect(cloudsMesh.material.uniforms.uSunDirectionWorld.value.x).toBeCloseTo(-1);
expect(shadowChild.material.uniforms.uSunDirectionWorld.value.x).toBeCloseTo(-1);
toggleClouds(true);
expect(cloudsMesh.visible).toBe(false);
});
@@ -50,6 +50,10 @@ test("all boundary emphasis stays below landing points and uses surface occlusio
expect(lines.material.depthWrite).toBe(false); expect(lines.material.depthWrite).toBe(false);
lines.geometry.dispose(); lines.material.dispose(); lines.geometry.dispose(); lines.material.dispose();
} }
const hoverGlow = buildHoverGlowLines();
expect(hoverGlow.material.uniforms.uHalfWidthPx.value).toBeGreaterThanOrEqual(3.5);
expect(hoverGlow.material.uniforms.uUnderlayOpacity.value).toBeGreaterThan(0);
hoverGlow.geometry.dispose(); hoverGlow.material.dispose();
}); });
test("country loading tint cannot intersect the base before any map data arrives", () => { test("country loading tint cannot intersect the base before any map data arrives", () => {
+50 -16
View File
@@ -14,11 +14,17 @@ import { createEarthSurfaceGeometry } from './earth-surface.js';
import { configureColorTexture, preserveTextureOutput, shaderOutputMarker } from './texture-colors.js'; import { configureColorTexture, preserveTextureOutput, shaderOutputMarker } from './texture-colors.js';
import { createEarthMapController } from './earth-map-sources.js'; import { createEarthMapController } from './earth-map-sources.js';
import { earthTextureImages } from './earth-texture-image.js'; import { earthTextureImages } from './earth-texture-image.js';
import { createEarthAtmosphereMaterial, createEarthSurfaceMaterial } from './earth-surface-material.js'; import {
createEarthAtmosphereMaterial,
createEarthCloudMaterial,
createEarthCloudShadowMaterial,
createEarthSurfaceMaterial,
} from './earth-surface-material.js';
import { isDetachedImageBitmap } from './webgl-recovery.js'; import { isDetachedImageBitmap } from './webgl-recovery.js';
export let earth = null; export let earth = null;
export let clouds = null; export let clouds = null;
let _cloudShadow = null;
export let terrain = null; export let terrain = null;
let showGridLines = false; let showGridLines = false;
let showClouds = true; let showClouds = true;
@@ -191,29 +197,45 @@ export function createClouds(scene, earthObj) {
CLOUD_LAYER_CONFIG.widthSegments, CLOUD_LAYER_CONFIG.widthSegments,
CLOUD_LAYER_CONFIG.heightSegments, CLOUD_LAYER_CONFIG.heightSegments,
); );
const material = new THREE.MeshBasicMaterial({ const material = createEarthCloudMaterial(
transparent: true, CLOUD_LAYER_CONFIG,
opacity: CLOUD_LAYER_CONFIG.opacity, _earthSunDirection,
depthTest: true, _dayNightEnabled,
depthWrite: false, );
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide
});
applyEarthDayNightShader(material);
clouds = new THREE.Mesh(geometry, material); clouds = new THREE.Mesh(geometry, material);
clouds.name = "earth-atmosphere-clouds"; clouds.name = "earth-atmosphere-clouds";
clouds.renderOrder = 1.1; clouds.renderOrder = 1.1;
clouds.visible = false; clouds.visible = false;
clouds.raycast = () => {};
_earthShaders.push(material);
const shadowGeometry = new THREE.SphereGeometry(
CONFIG.earthRadius + (CLOUD_LAYER_CONFIG.shadowAltitudeOffset ?? 0.52),
CLOUD_LAYER_CONFIG.widthSegments,
CLOUD_LAYER_CONFIG.heightSegments,
);
const shadowMaterial = createEarthCloudShadowMaterial(
CLOUD_LAYER_CONFIG,
_earthSunDirection,
_dayNightEnabled,
);
_cloudShadow = new THREE.Mesh(shadowGeometry, shadowMaterial);
_cloudShadow.name = "earth-cloud-shadow";
_cloudShadow.renderOrder = 0.962;
_cloudShadow.raycast = () => {};
_earthShaders.push(shadowMaterial);
clouds.add(_cloudShadow);
earthObj.add(clouds); earthObj.add(clouds);
return clouds; return clouds;
} }
export function toggleClouds(visible) { export function toggleClouds(visible) {
showClouds = Boolean(visible); showClouds = Boolean(visible);
if (clouds) { if (clouds) {
clouds.visible = showClouds && Boolean(clouds.material?.map); clouds.visible = showClouds && Boolean(clouds.material?.uniforms?.uCloudMap?.value);
} }
} }
@@ -236,7 +258,13 @@ export function loadCloudTexture() {
(texture) => { (texture) => {
configureColorTexture(texture); configureColorTexture(texture);
_cloudTexture = texture; _cloudTexture = texture;
clouds.material.map = texture; if (clouds.material.uniforms?.uCloudMap) {
clouds.material.uniforms.uCloudMap.value = texture;
}
if (_cloudShadow?.material?.uniforms?.uCloudMap) {
_cloudShadow.material.uniforms.uCloudMap.value = texture;
_cloudShadow.material.needsUpdate = true;
}
clouds.material.needsUpdate = true; clouds.material.needsUpdate = true;
clouds.visible = showClouds; clouds.visible = showClouds;
resolve(texture); resolve(texture);
@@ -440,8 +468,11 @@ export function reloadEarthTextureAfterContextRestore() {
if (_cloudTexture) { if (_cloudTexture) {
if (isDetachedImageBitmap(_cloudTexture.image)) { if (isDetachedImageBitmap(_cloudTexture.image)) {
_cloudTexture = null; _cloudTexture = null;
if (clouds?.material) { if (clouds?.material?.uniforms?.uCloudMap) {
clouds.material.map = null; clouds.material.uniforms.uCloudMap.value = null;
}
if (_cloudShadow?.material?.uniforms?.uCloudMap) {
_cloudShadow.material.uniforms.uCloudMap.value = null;
} }
void loadCloudTexture().catch(() => {}); void loadCloudTexture().catch(() => {});
} else { } else {
@@ -449,6 +480,9 @@ export function reloadEarthTextureAfterContextRestore() {
if (clouds?.material) { if (clouds?.material) {
clouds.material.needsUpdate = true; clouds.material.needsUpdate = true;
} }
if (_cloudShadow?.material) {
_cloudShadow.material.needsUpdate = true;
}
} }
} }
+3
View File
@@ -963,6 +963,7 @@ const EXACT_TRANSLATIONS = {
"其他船只": "Other Vessels", "其他船只": "Other Vessels",
"中活跃观测站": "Medium-Activity Collector", "中活跃观测站": "Medium-Activity Collector",
"高活跃观测站": "High-Activity Collector", "高活跃观测站": "High-Activity Collector",
"低活跃观测站": "Low-Activity Collector",
"观测范围示意": "Observation Coverage", "观测范围示意": "Observation Coverage",
"严重事件": "Critical Events", "严重事件": "Critical Events",
"高危事件": "High-Risk Events", "高危事件": "High-Risk Events",
@@ -1323,6 +1324,8 @@ const EXACT_TRANSLATIONS = {
"采集坐标候选": "Collect coordinate candidates", "采集坐标候选": "Collect coordinate candidates",
"一键定位并采用最高置信候选": "Locate all and apply highest-confidence candidates", "一键定位并采用最高置信候选": "Locate all and apply highest-confidence candidates",
"一键定位": "Locate All", "一键定位": "Locate All",
"需要管理员登录后才能采集或保存算力中心位置": "Admin login required to collect or save compute center locations",
"前往管理员登录": "Admin Login",
"正在检查 Web Search 状态,稍候即可定位。": "Checking Web Search status; location will be available shortly.", "正在检查 Web Search 状态,稍候即可定位。": "Checking Web Search status; location will be available shortly.",
"Web Search 未开启,无法进行事实核查定位。": "Web Search is disabled, so fact-checked location is unavailable.", "Web Search 未开启,无法进行事实核查定位。": "Web Search is disabled, so fact-checked location is unavailable.",
"精确": "Precise", "精确": "Precise",
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,277 @@
import { describe, expect, it } from "bun:test";
import { readFileSync } from "node:fs";
import * as THREE from "three";
import {
CABLE_CONFIG,
COUNTRY_BOUNDARY_CONFIG,
EARTH_MATERIAL_CONFIG,
} from "./constants.js";
import {
REGION_PRESET_ISO3_MAP,
resolveCountryFeaturesByCodes,
resolveCountryIso3,
} from "./country-boundaries.js";
import {
computeFeatureSphericalSweep,
computeInfluenceZonePriority,
computePolygonsGeoBounds,
createInfluenceZonesController,
normalizeInfluenceZoneSpec,
resolveRegionPresetCodes,
} from "./influence-zones.js";
import { latLonToVector3 } from "./utils.js";
describe("influence-zones country index & shader controller", () => {
it("resolves ISO-3 falling back past -99 placeholders and aggregates multi-feature states", () => {
const mockFeatures = [
{ properties: { ADMIN: "China", ISO_A3: "CHN", ISO_A2: "CN" }, geometry: { type: "Polygon", coordinates: [] } },
{ properties: { ADMIN: "Hong Kong S.A.R.", ISO_A3: "CHN", ADM0_A3: "HKG", ISO_A2: "HK" }, geometry: { type: "Polygon", coordinates: [] } },
{ properties: { ADMIN: "France", ISO_A3: "-99", ADM0_A3: "FRA", ISO_A2: "-99", ISO_A2_EH: "FR" }, geometry: { type: "Polygon", coordinates: [] } },
{ properties: { ADMIN: "Norway", ISO_A3: "-99", ADM0_A3: "NOR", ISO_A2: "-99", ISO_A2_EH: "NO" }, geometry: { type: "Polygon", coordinates: [] } },
{ properties: { ADMIN: "United States of America", ISO_A3: "USA", ISO_A2: "US" }, geometry: { type: "Polygon", coordinates: [] } },
];
expect(resolveCountryIso3(mockFeatures[2])).toBe("FRA");
expect(resolveCountryIso3(mockFeatures[3])).toBe("NOR");
const chnMatches = resolveCountryFeaturesByCodes(mockFeatures, ["中国"]);
expect(chnMatches).toHaveLength(2);
const fraNorMatches = resolveCountryFeaturesByCodes(mockFeatures, ["FRA", "NO"]);
expect(fraNorMatches.map(resolveCountryIso3)).toEqual(["FRA", "NOR"]);
const prkFeatures = [
{ properties: { ADMIN: "North Korea", NAME_EN: "North Korea", ISO_A3: "PRK", ISO_A2: "KP" }, geometry: { type: "Polygon", coordinates: [] } },
];
for (const token of ["PRK", "DPRK", "KP", "朝鲜", "North Korea"]) {
expect(resolveCountryFeaturesByCodes(prkFeatures, [token]).map(resolveCountryIso3)).toEqual(["PRK"]);
}
});
it("provides APEC and major regional ISO-3 presets", () => {
const apec = resolveRegionPresetCodes("apec");
expect(apec).toContain("CHN");
expect(apec).toContain("USA");
expect(apec).toContain("RUS");
expect(apec).toContain("JPN");
expect(apec).toContain("AUS");
expect(REGION_PRESET_ISO3_MAP.G7).toContain("FRA");
expect(resolveRegionPresetCodes("NORTHEAST_ASIA")).toEqual(["CHN", "PRK", "KOR", "JPN", "MNG", "RUS"]);
expect(resolveRegionPresetCodes("东北亚")).toEqual(["CHN", "PRK", "KOR", "JPN", "MNG", "RUS"]);
expect(resolveRegionPresetCodes("KOREAN_PENINSULA")).toEqual(["PRK", "KOR"]);
expect(resolveRegionPresetCodes("NORTHERN_EUROPE")).toContain("NOR");
expect(resolveRegionPresetCodes("MENA")).toContain("EGY");
});
it("normalizes and clamps influence zone parameters safely", () => {
const spec = normalizeInfluenceZoneSpec({
id: "core-trilateral",
color: "#ef4444",
opacity: 2.5,
edge: { style: "sharp", feather_px: 120, border_width: 2.2 },
animation: { type: "sweep", direction: "west_to_east", duration_ms: 2100 },
shape: { mode: "countries", countries: ["CHN", "USA", "RUS"] },
}, 0);
expect(spec.id).toBe("core-trilateral");
expect(spec.opacity).toBe(0.9);
expect(spec.edge.style).toBe("sharp");
expect(spec.edge.featherPx).toBe(48);
expect(spec.animation.type).toBe("sweep");
expect(spec.animation.durationMs).toBe(2100);
expect(spec.shape.countries).toEqual(["CHN", "USA", "RUS"]);
});
it("orders west_to_east and north_to_south spherical sweeps monotonically", () => {
const chinaSamplePts = [
{ lat: 35, lon: 76 },
{ lat: 35, lon: 104 },
{ lat: 35, lon: 124 },
{ lat: 50, lon: 104 },
{ lat: 20, lon: 104 },
];
const eastSweep = computeFeatureSphericalSweep(chinaSamplePts, "west_to_east");
const westProj = latLonToVector3(35, 76, 1).normalize().dot(eastSweep.sweepDir);
const midProj = latLonToVector3(35, 104, 1).normalize().dot(eastSweep.sweepDir);
const eastProj = latLonToVector3(35, 124, 1).normalize().dot(eastSweep.sweepDir);
expect(westProj).toBeLessThan(midProj);
expect(midProj).toBeLessThan(eastProj);
const southSweep = computeFeatureSphericalSweep(chinaSamplePts, "north_to_south");
const northProj = latLonToVector3(50, 104, 1).normalize().dot(southSweep.sweepDir);
const southProj = latLonToVector3(20, 104, 1).normalize().dot(southSweep.sweepDir);
expect(northProj).toBeLessThan(southProj);
});
it("mounts influence zones in a THREE.Group within (0.96, 0.97) renderOrder and advances animation", async () => {
const earth = new THREE.Mesh(
new THREE.SphereGeometry(100, 16, 16),
new THREE.MeshBasicMaterial(),
);
const controller = createInfluenceZonesController(earth, {
widthSegments: 16,
heightSegments: 16,
});
expect(controller.rootGroup.isGroup).toBe(true);
// Must not add direct ShaderMaterial children to earth itself (earth-surface-material.test.js invariant)
expect(earth.children.filter(c => c.material?.isShaderMaterial)).toHaveLength(0);
await controller.setZones([
{
id: "pacific-storm",
color: "#f59e0b",
opacity: 0.45,
edge: { style: "soft", feather_px: 24, border_width: 1.5 },
animation: { type: "radial", duration_ms: 1000, delay_ms: 0 },
shape: { mode: "circle", center: [22.3, 114.2], radius_km: 1200 },
},
], { scope: "copilot" });
const stateStart = controller.getState();
expect(stateStart.zoneCount).toBe(1);
const ro = stateStart.zones[0].renderOrder;
expect(ro).toBeGreaterThan(EARTH_MATERIAL_CONFIG.textureOverlayRenderOrder);
expect(ro).toBeLessThan(Math.min(COUNTRY_BOUNDARY_CONFIG.lineRenderOrder, CABLE_CONFIG.landingPoint.renderOrder));
const mesh = controller.rootGroup.children[0];
expect(mesh.material.transparent).toBe(true);
expect(mesh.material.depthWrite).toBe(false);
expect(mesh.material.depthTest).toBe(true);
let notifiedCount = 0;
const unsub = controller.onChange((state) => {
if (state) notifiedCount += 1;
});
controller.setOpacityScale(0.5);
expect(controller.getOpacityScale()).toBeCloseTo(0.5);
expect(mesh.material.uniforms.uOpacity.value).toBeCloseTo(0.225);
expect(notifiedCount).toBe(1);
unsub();
const farFutureMs = (typeof performance !== "undefined" ? performance.now() : Date.now()) + 10000;
controller.update(farFutureMs, new THREE.Vector3(1, 0, 0), true);
expect(controller.getState().zones[0].progress).toBe(1);
controller.clearScope("copilot");
expect(controller.getState().zoneCount).toBe(0);
expect(controller.getState().hasArchived).toBe(true);
const restored = await controller.restoreLast();
expect(restored).toBe(true);
expect(controller.getState().zoneCount).toBe(1);
controller.clearAll();
expect(controller.getState().zoneCount).toBe(0);
expect(controller.getState().hasArchived).toBe(true);
controller.dispose();
});
it("computes tight local high-res bounds for regional and antimeridian-crossing polygons", () => {
const chinaPolys = [[[[73.6, 18.2], [134.8, 18.2], [134.8, 53.6], [73.6, 53.6], [73.6, 18.2]]]];
const sharpBounds = computePolygonsGeoBounds(chinaPolys, { style: "sharp", featherPx: 1 });
expect(sharpBounds.isGlobal).toBe(false);
expect(sharpBounds.lonSpan).toBeLessThan(80);
expect(sharpBounds.width).toBeGreaterThanOrEqual(2048);
// Russia spanning eastern Europe to Chukotka (-179..-169) should wrap cleanly without exploding to 360deg
const russiaPolys = [
[[[20, 42], [179.9, 42], [179.9, 77], [20, 77], [20, 42]]],
[[[-179.9, 64], [-169.5, 64], [-169.5, 70], [-179.9, 70], [-179.9, 64]]],
];
const russiaBounds = computePolygonsGeoBounds(russiaPolys, { style: "sharp", featherPx: 1 });
expect(russiaBounds.isGlobal).toBe(false);
expect(russiaBounds.lonSpan).toBeLessThan(200);
// Global spread across Americas + Europe + Oceania falls back cleanly to full-globe 4096x2048
const globalPolys = [
[[[-165, 25], [-70, 25], [-70, 60], [-165, 60], [-165, 25]]],
[[[70, -35], [175, -35], [175, 55], [70, 55], [70, -35]]],
[[[-10, 35], [40, 35], [40, 65], [-10, 65], [-10, 35]]],
];
const globalBounds = computePolygonsGeoBounds(globalPolys, { style: "soft", featherPx: 22 });
expect(globalBounds.isGlobal).toBe(true);
expect(globalBounds.lonSpan).toBe(360);
expect(globalBounds.width).toBe(4096);
});
it("prioritizes core sharp countries above soft spillover/circle zones and uses opaque canvas masks", async () => {
const core = normalizeInfluenceZoneSpec({
id: "core-chn",
z_index: 0,
edge: { style: "sharp" },
shape: { mode: "countries", countries: ["CHN", "PRK"] },
}, 0);
const spillover = normalizeInfluenceZoneSpec({
id: "spill-apac",
z_index: 0,
edge: { style: "soft", feather_px: 22 },
shape: { mode: "region_preset", region_preset: "ASIA_PACIFIC" },
}, 1);
const corridor = normalizeInfluenceZoneSpec({
id: "sea-corridor",
z_index: 0,
edge: { style: "soft", feather_px: 26 },
shape: { mode: "circle", center: [36.5, 123.5], radius_km: 680 },
}, 2);
expect(core.zIndex).toBe(0);
expect(spillover.zIndex).toBe(0);
expect(corridor.zIndex).toBe(0);
const pCore = computeInfluenceZonePriority(core, 0);
const pSpill = computeInfluenceZonePriority(spillover, 1);
const pCorridor = computeInfluenceZonePriority(corridor, 2);
expect(pCore).toBeGreaterThan(pSpill);
expect(pSpill).toBeGreaterThan(pCorridor);
// Explicit z_index still overrides automatic tier ranking
const explicitTop = normalizeInfluenceZoneSpec({
id: "top-circle",
z_index: 2,
edge: { style: "soft" },
shape: { mode: "circle", center: [36.5, 123.5], radius_km: 500 },
}, 3);
expect(computeInfluenceZonePriority(explicitTop, 3)).toBeGreaterThan(pCore);
// Controller renders higher-priority zones at higher renderOrder while exposing core-first in getState().zones
const earth = new THREE.Mesh(
new THREE.SphereGeometry(100, 16, 16),
new THREE.MeshBasicMaterial(),
);
const controller = createInfluenceZonesController(earth, { widthSegments: 16, heightSegments: 16 });
await controller.setZones([
{
id: "low",
label: "Low Circle",
color: "#38bdf8",
z_index: 0,
edge: { style: "soft" },
shape: { mode: "circle", center: [20, 110], radius_km: 800 },
},
{
id: "high",
label: "High Circle",
color: "#ef4444",
z_index: 2,
edge: { style: "sharp" },
shape: { mode: "circle", center: [22, 114], radius_km: 500 },
},
], { scope: "copilot" });
const state = controller.getState();
expect(state.zones.map(z => z.id)).toEqual(["high", "low"]);
expect(state.zones[0].renderOrder).toBeGreaterThan(state.zones[1].renderOrder);
controller.dispose();
// Ensure opaque mask initialization (no transparent fillCtx.clearRect leading to WebGL un-premultiply edge aliasing),
// single-pass offscreen blur compositing, and circle polygon exclude-mask shader support are present
const source = readFileSync(new URL("./influence-zones.js", import.meta.url), "utf8");
expect(source).not.toContain("fillCtx.clearRect(");
expect(source).toContain('fillCtx.fillStyle = "#000000"');
expect(source).toContain("compositeBlurredPolygons");
expect(source).toContain("drawImage(scratchCanvas");
expect(source).toContain("uHasExcludeMask");
});
});
+84 -48
View File
@@ -4,6 +4,11 @@ import { cardImageIdentity, mountCardImage, createCardImagePresenter } from "./c
import { sharedHudFocusStack } from "./hud-focus-stack.js"; import { sharedHudFocusStack } from "./hud-focus-stack.js";
import { createTypewriter, waitForTypewriter } from "./typewriter.js"; import { createTypewriter, waitForTypewriter } from "./typewriter.js";
import { addTargetToCompare, normalizeEarthTarget, openWorkflowActionPicker } from "./workflow-bindings.js"; import { addTargetToCompare, normalizeEarthTarget, openWorkflowActionPicker } from "./workflow-bindings.js";
import {
ADMIN_AUTH_REQUIRED_MESSAGE,
getAdminLoginUrl,
isAdminAuthRequiredError,
} from './admin-write-auth.js';
// info-card.js - Unified info card module // info-card.js - Unified info card module
import { showStatusMessage } from './ui.js'; import { showStatusMessage } from './ui.js';
import { import {
@@ -34,6 +39,7 @@ let computeCenterLocationCapabilityPromise = null;
let computeCenterUnresolvedBatchState = { let computeCenterUnresolvedBatchState = {
running: false, running: false,
statusText: '', statusText: '',
authRequired: false,
total: 0, total: 0,
processed: 0, processed: 0,
saved: 0, saved: 0,
@@ -87,17 +93,6 @@ function setLocationCollectState(contextOrKey, patch = {}) {
return next; return next;
} }
function clearLocationCollectState(contextOrKey) {
const key = typeof contextOrKey === 'string'
? contextOrKey
: getLocationCollectCacheKey(contextOrKey);
if (!key) return;
locationCollectStateCache.delete(key);
locationCollectContextCache.delete(key);
locationCollectCandidatesByKey.delete(key);
updateLocationCollectDomFromState(key);
}
function getWebSearchDisabledTitle(capability = computeCenterLocationCapability) { function getWebSearchDisabledTitle(capability = computeCenterLocationCapability) {
if (!capability) return infoText('正在检查 WebSearch 状态,稍候即可定位。'); if (!capability) return infoText('正在检查 WebSearch 状态,稍候即可定位。');
return infoText(capability.reason || 'WebSearch 未开启,无法进行事实核查定位。'); return infoText(capability.reason || 'WebSearch 未开启,无法进行事实核查定位。');
@@ -164,9 +159,30 @@ function setLocationButtonLoading(button, loading, label) {
updateComputeCenterLocationCapabilityDom(); updateComputeCenterLocationCapabilityDom();
} }
function applyLocationStatusElement(statusEl, statusText, authRequired = false) {
if (!statusEl) return;
statusEl.textContent = statusText || '';
if (!authRequired || !statusText || typeof document === 'undefined') return;
const link = document.createElement('a');
link.className = 'info-card-auth-link';
link.href = getAdminLoginUrl();
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.textContent = `${infoText('前往管理员登录')} ↗`;
link.addEventListener('click', (event) => {
event.stopPropagation();
});
statusEl.appendChild(document.createTextNode(' '));
statusEl.appendChild(link);
}
function updateUnresolvedBatchDom() { function updateUnresolvedBatchDom() {
document.querySelectorAll('[data-unresolved-batch-status]').forEach((statusEl) => { document.querySelectorAll('[data-unresolved-batch-status]').forEach((statusEl) => {
statusEl.textContent = computeCenterUnresolvedBatchState.statusText || ''; applyLocationStatusElement(
statusEl,
computeCenterUnresolvedBatchState.statusText || '',
computeCenterUnresolvedBatchState.authRequired === true,
);
}); });
document.querySelectorAll('[data-unresolved-adopt-all]').forEach((button) => { document.querySelectorAll('[data-unresolved-adopt-all]').forEach((button) => {
if (!(button instanceof HTMLButtonElement)) return; if (!(button instanceof HTMLButtonElement)) return;
@@ -270,12 +286,6 @@ function getNewsSummaryText(data) {
return getNewsDisplaySummary(data); return getNewsDisplaySummary(data);
} }
function getNewsSummaryPreview(data, maxLength = 34) {
const text = getNewsSummaryText(data).replace(/\s+/g, ' ').trim();
if (text.length <= maxLength) return text;
return `${text.slice(0, Math.max(0, maxLength - 1))}…`;
}
function getNewsCardTitle(data) { function getNewsCardTitle(data) {
const directTitle = String(data?.title ?? '').replace(/\s+/g, ' ').trim(); const directTitle = String(data?.title ?? '').replace(/\s+/g, ' ').trim();
return directTitle || getNewsDisplayTitle(data); return directTitle || getNewsDisplayTitle(data);
@@ -633,22 +643,6 @@ function renderNativeMobileDetail(type, config, data) {
bindMobileDetailActions(); bindMobileDetailActions();
} }
function getMobileDetailRenderKey(type, data) {
if (type !== 'news') return null;
return [
type,
data?.id ?? '',
data?.url ?? '',
data?.published_at ?? '',
data?.title ?? '',
].join('|');
}
function isMobileDetailsDrawerActive() {
const detailsSlot = document.querySelector('[data-drawer-slot="details"]');
return detailsSlot instanceof HTMLElement && detailsSlot.classList.contains('is-active');
}
function ensureMobileDetailsListener() { function ensureMobileDetailsListener() {
if (mobileDetailsListenerBound) return; if (mobileDetailsListenerBound) return;
mobileDetailsListenerBound = true; mobileDetailsListenerBound = true;
@@ -972,7 +966,9 @@ function hydrateLocationCollectRoot(root, state) {
const statusEl = root.querySelector('[data-collect-status], [data-unresolved-status]'); const statusEl = root.querySelector('[data-collect-status], [data-unresolved-status]');
const candidatesEl = root.querySelector('[data-collect-candidates], [data-unresolved-candidates]'); const candidatesEl = root.querySelector('[data-collect-candidates], [data-unresolved-candidates]');
const button = root.querySelector('[data-collect-action="run"], [data-unresolved-collect]'); const button = root.querySelector('[data-collect-action="run"], [data-unresolved-collect]');
if (statusEl) statusEl.textContent = infoText(state?.statusText || ''); if (statusEl) {
applyLocationStatusElement(statusEl, infoText(state?.statusText || ''), state?.authRequired === true);
}
if (candidatesEl) candidatesEl.innerHTML = renderCachedCollectCandidates(state); if (candidatesEl) candidatesEl.innerHTML = renderCachedCollectCandidates(state);
if (button instanceof HTMLButtonElement) { if (button instanceof HTMLButtonElement) {
button.classList.toggle('is-loading', state?.loading === true); button.classList.toggle('is-loading', state?.loading === true);
@@ -1066,17 +1062,18 @@ function ensureCandidateActionBindings(rootOrChild, context) {
if (typeof actionContext.save !== 'function') return; if (typeof actionContext.save !== 'function') return;
const statusEl = root.querySelector('[data-collect-status], [data-unresolved-status]'); const statusEl = root.querySelector('[data-collect-status], [data-unresolved-status]');
button.disabled = true; button.disabled = true;
if (statusEl) statusEl.textContent = infoText('正在保存所选坐标...'); applyLocationStatusElement(statusEl, infoText('正在保存所选坐标...'), false);
try { try {
const saveResult = await actionContext.save(candidate); const saveResult = await actionContext.save(candidate);
setLocationCollectState(actionContext, { setLocationCollectState(actionContext, {
loading: false, loading: false,
statusText: infoText('坐标已保存'), statusText: infoText('坐标已保存'),
authRequired: false,
candidates: [], candidates: [],
savedCandidate: candidate, savedCandidate: candidate,
saveResult, saveResult,
}); });
if (statusEl) statusEl.textContent = infoText('坐标已保存'); applyLocationStatusElement(statusEl, infoText('坐标已保存'), false);
window.dispatchEvent( window.dispatchEvent(
new CustomEvent('earth:compute-center-location-saved', { new CustomEvent('earth:compute-center-location-saved', {
detail: { detail: {
@@ -1090,7 +1087,11 @@ function ensureCandidateActionBindings(rootOrChild, context) {
); );
} catch (error) { } catch (error) {
console.error('save compute-center location failed', error); console.error('save compute-center location failed', error);
if (statusEl) statusEl.textContent = infoText(`保存失败:${error?.message || error}`); applyLocationStatusElement(
statusEl,
infoText(`保存失败:${error?.message || error}`),
isAdminAuthRequiredError(error),
);
button.disabled = false; button.disabled = false;
} }
}); });
@@ -1134,6 +1135,7 @@ function bindLocationCollectControls(content, context) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: true, loading: true,
statusText: infoText('正在采集坐标候选...'), statusText: infoText('正在采集坐标候选...'),
authRequired: false,
candidates: [], candidates: [],
}); });
try { try {
@@ -1142,6 +1144,7 @@ function bindLocationCollectControls(content, context) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`未能采集到坐标:${formatLocationCollectFailure(result)}`), statusText: infoText(`未能采集到坐标:${formatLocationCollectFailure(result)}`),
authRequired: false,
candidates: [], candidates: [],
result, result,
}); });
@@ -1151,6 +1154,7 @@ function bindLocationCollectControls(content, context) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`共找到 ${candidates.length} 个候选位置`), statusText: infoText(`共找到 ${candidates.length} 个候选位置`),
authRequired: false,
candidates, candidates,
result, result,
}); });
@@ -1159,6 +1163,7 @@ function bindLocationCollectControls(content, context) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`采集失败:${error?.message || error}`), statusText: infoText(`采集失败:${error?.message || error}`),
authRequired: isAdminAuthRequiredError(error),
candidates: [], candidates: [],
}); });
} finally { } finally {
@@ -1350,6 +1355,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
setLocationCollectState(context, { setLocationCollectState(context, {
loading: true, loading: true,
statusText: infoText(progressLabel || '正在一键定位并采用最高置信候选...'), statusText: infoText(progressLabel || '正在一键定位并采用最高置信候选...'),
authRequired: false,
}); });
const { mod, result, candidates } = await collectUnresolvedComputeCenterCandidates( const { mod, result, candidates } = await collectUnresolvedComputeCenterCandidates(
context, context,
@@ -1359,6 +1365,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`未找到可采用候选:${formatLocationCollectFailure(result)}`), statusText: infoText(`未找到可采用候选:${formatLocationCollectFailure(result)}`),
authRequired: false,
candidates: [], candidates: [],
result, result,
}); });
@@ -1367,6 +1374,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
setLocationCollectState(context, { setLocationCollectState(context, {
loading: true, loading: true,
statusText: infoText(`找到 ${candidates.length} 个候选,正在保存最高置信位置...`), statusText: infoText(`找到 ${candidates.length} 个候选,正在保存最高置信位置...`),
authRequired: false,
candidates, candidates,
result, result,
}); });
@@ -1375,6 +1383,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText('未找到包含有效经纬度的候选'), statusText: infoText('未找到包含有效经纬度的候选'),
authRequired: false,
candidates, candidates,
result, result,
}); });
@@ -1384,6 +1393,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText('坐标已保存,等待图层刷新'), statusText: infoText('坐标已保存,等待图层刷新'),
authRequired: false,
candidates, candidates,
result, result,
savedCandidate: bestCandidate, savedCandidate: bestCandidate,
@@ -1424,11 +1434,13 @@ async function runUnresolvedComputeCenterBatch(contexts) {
processed: 0, processed: 0,
saved: 0, saved: 0,
missed: 0, missed: 0,
authRequired: false,
statusText: infoText(`一键定位进行中 0/${contexts.length}...`), statusText: infoText(`一键定位进行中 0/${contexts.length}...`),
}); });
let savedCount = 0; let savedCount = 0;
let missedCount = 0; let missedCount = 0;
let authRequiredError = null;
try { try {
for (const [index, context] of contexts.entries()) { for (const [index, context] of contexts.entries()) {
const progressText = infoText(`正在定位并采用最高置信候选 ${index + 1}/${contexts.length}...`); const progressText = infoText(`正在定位并采用最高置信候选 ${index + 1}/${contexts.length}...`);
@@ -1439,26 +1451,46 @@ async function runUnresolvedComputeCenterBatch(contexts) {
else missedCount += 1; else missedCount += 1;
} catch (error) { } catch (error) {
console.error('adopt unresolved compute-center location failed', error); console.error('adopt unresolved compute-center location failed', error);
if (isAdminAuthRequiredError(error)) {
authRequiredError = error;
setLocationCollectState(context, {
loading: false,
statusText: '',
authRequired: false,
candidates: [],
});
break;
}
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`一键定位失败:${error?.message || error}`), statusText: infoText(`一键定位失败:${error?.message || error}`),
authRequired: false,
candidates: [], candidates: [],
}); });
missedCount += 1; missedCount += 1;
} finally { } finally {
setUnresolvedBatchState({ if (!authRequiredError) {
processed: index + 1, setUnresolvedBatchState({
saved: savedCount, processed: index + 1,
missed: missedCount, saved: savedCount,
statusText: infoText(`一键定位进行中 ${index + 1}/${contexts.length},已保存 ${savedCount} 个${missedCount ? `,失败 ${missedCount} 个` : ''}`), missed: missedCount,
}); statusText: infoText(`一键定位进行中 ${index + 1}/${contexts.length},已保存 ${savedCount} 个${missedCount ? `,失败 ${missedCount} 个` : ''}`),
});
}
} }
} }
const finalStatus = savedCount > 0 if (authRequiredError) {
? infoText(`已定位并采用 ${savedCount} 个最高置信候选${missedCount ? `,${missedCount} 个仍需手动处理` : ''}`) setUnresolvedBatchState({
: infoText(`${missedCount} 个都没有可自动采用的候选,需要手动处理`); statusText: infoText(authRequiredError.message || ADMIN_AUTH_REQUIRED_MESSAGE),
setUnresolvedBatchState({ statusText: finalStatus }); authRequired: true,
});
} else {
const finalStatus = savedCount > 0
? infoText(`已定位并采用 ${savedCount} 个最高置信候选${missedCount ? `,${missedCount} 个仍需手动处理` : ''}`)
: infoText(`${missedCount} 个都没有可自动采用的候选,需要手动处理`);
setUnresolvedBatchState({ statusText: finalStatus, authRequired: false });
}
if (savedCount > 0) { if (savedCount > 0) {
window.dispatchEvent( window.dispatchEvent(
new CustomEvent('earth:compute-center-location-saved', { new CustomEvent('earth:compute-center-location-saved', {
@@ -1515,6 +1547,7 @@ function bindComputeCenterUnresolvedControls(content) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: true, loading: true,
statusText: infoText('正在采集坐标候选...'), statusText: infoText('正在采集坐标候选...'),
authRequired: false,
candidates: [], candidates: [],
}); });
try { try {
@@ -1523,6 +1556,7 @@ function bindComputeCenterUnresolvedControls(content) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`未能采集到坐标:${formatLocationCollectFailure(result)}`), statusText: infoText(`未能采集到坐标:${formatLocationCollectFailure(result)}`),
authRequired: false,
candidates: [], candidates: [],
result, result,
}); });
@@ -1531,6 +1565,7 @@ function bindComputeCenterUnresolvedControls(content) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`共找到 ${candidates.length} 个候选位置`), statusText: infoText(`共找到 ${candidates.length} 个候选位置`),
authRequired: false,
candidates, candidates,
result, result,
}); });
@@ -1546,6 +1581,7 @@ function bindComputeCenterUnresolvedControls(content) {
setLocationCollectState(context, { setLocationCollectState(context, {
loading: false, loading: false,
statusText: infoText(`采集失败:${error?.message || error}`), statusText: infoText(`采集失败:${error?.message || error}`),
authRequired: isAdminAuthRequiredError(error),
candidates: [], candidates: [],
}); });
} finally { } finally {
+2
View File
@@ -5,6 +5,7 @@ import { drawMarkerBadge } from "./marker-badges.js";
import * as THREE from "three"; import * as THREE from "three";
import { CONFIG } from "./constants.js"; import { CONFIG } from "./constants.js";
import { configureColorTexture } from "./texture-colors.js";
import { getSurfaceMarkerCameraScale, latLonToVector3 } from "./utils.js"; import { getSurfaceMarkerCameraScale, latLonToVector3 } from "./utils.js";
// Focused markers must win across interactable layers, not only within their // Focused markers must win across interactable layers, not only within their
@@ -728,6 +729,7 @@ export function createInteractableLayer(options = {}) {
context.restore(); context.restore();
const texture = new THREE.CanvasTexture(canvas); const texture = new THREE.CanvasTexture(canvas);
configureColorTexture(texture);
texture.generateMipmaps = false; texture.generateMipmaps = false;
texture.minFilter = THREE.LinearFilter; texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter; texture.magFilter = THREE.LinearFilter;
@@ -12,6 +12,76 @@ const FILL_RINGS = 12;
const FILL_SEGMENTS = 48; const FILL_SEGMENTS = 48;
const RING_SEGMENTS = 72; const RING_SEGMENTS = 72;
const IRIDIUM_VERTEX_SHADER = `
attribute vec2 aUv;
uniform vec3 uCenterNormal;
uniform vec3 uAlongTrack;
uniform vec3 uCrossTrack;
uniform float uAlongKm;
uniform float uCrossKm;
uniform float uEarthRadiusKm;
uniform float uSurfaceRadius;
varying vec2 vUv;
void main() {
vUv = aUv;
vec3 safeNormal = length(uCenterNormal) > 0.0001 ? normalize(uCenterNormal) : vec3(0.0, 1.0, 0.0);
vec3 safeAlong = length(uAlongTrack) > 0.0001 ? normalize(uAlongTrack) : vec3(1.0, 0.0, 0.0);
vec3 safeCross = length(uCrossTrack) > 0.0001 ? normalize(uCrossTrack) : vec3(0.0, 0.0, 1.0);
vec3 worldOffset = safeNormal * uEarthRadiusKm
+ safeAlong * (aUv.x * uAlongKm)
+ safeCross * (aUv.y * uCrossKm);
vec3 projected = normalize(worldOffset) * uSurfaceRadius;
gl_Position = projectionMatrix * modelViewMatrix * vec4(projected, 1.0);
}
`;
const IRIDIUM_FILL_FRAGMENT_SHADER = `
uniform vec3 uColor;
uniform float uOpacity;
uniform float uTime;
varying vec2 vUv;
void main() {
float r2 = dot(vUv, vUv);
if (r2 > 1.0) discard;
float r = sqrt(r2);
float coreGlow = exp(-r2 * 1.65) * (1.0 - smoothstep(0.76, 1.0, r));
float innerRing = exp(-pow((r - 0.54) * 32.0, 2.0)) * 0.14;
float scanPhase = fract(r * 1.15 - uTime * 0.28);
float scanWave = exp(-pow((scanPhase - 0.5) * 4.8, 2.0)) * (1.0 - r * 0.4) * 0.11;
float rim = smoothstep(0.93, 0.985, r) * (1.0 - smoothstep(0.988, 1.0, r));
float intensity = coreGlow * 0.58 + innerRing + scanWave + rim * 0.38;
float alpha = clamp(intensity * uOpacity, 0.0, 0.78);
if (alpha <= 0.002) discard;
vec3 rgb = mix(uColor, vec3(1.0), clamp(rim * 0.24 + scanWave * 0.22, 0.0, 0.32));
gl_FragColor = vec4(rgb, alpha);
#include <colorspace_fragment>
}
`;
const IRIDIUM_RING_FRAGMENT_SHADER = `
uniform vec3 uColor;
uniform float uOpacity;
uniform float uTime;
varying vec2 vUv;
void main() {
float angle = atan(vUv.y, vUv.x);
float wave = 0.85 + 0.15 * sin(angle * 2.0 - uTime * 1.6);
vec3 rgb = mix(uColor, vec3(1.0), 0.18 * wave);
gl_FragColor = vec4(rgb, clamp(uOpacity * wave, 0.0, 1.0));
#include <colorspace_fragment>
}
`;
function disposeMaterial(material) { function disposeMaterial(material) {
if (!material) return; if (!material) return;
if (Array.isArray(material)) { if (Array.isArray(material)) {
@@ -29,70 +99,49 @@ function disposeObjectTree(object) {
}); });
} }
function createIridiumFillMaterial() { function createSharedUniforms(earthRadiusWorld, opacity) {
const surfaceRadius = earthRadiusWorld * SURFACE_SCALE + SURFACE_OFFSET;
return {
uColor: { value: new THREE.Color(IRIDIUM_OVERLAY_COLOR) },
uOpacity: { value: opacity },
uTime: { value: 0 },
uCenterNormal: { value: new THREE.Vector3(0, 1, 0) },
uAlongTrack: { value: new THREE.Vector3(1, 0, 0) },
uCrossTrack: { value: new THREE.Vector3(0, 0, 1) },
uAlongKm: { value: CLUSTER_RADIUS_KM_BASE * 1.18 },
uCrossKm: { value: CLUSTER_RADIUS_KM_BASE * 0.96 },
uEarthRadiusKm: { value: EARTH_RADIUS_KM },
uSurfaceRadius: { value: surfaceRadius },
};
}
function createIridiumFillMaterial(earthRadiusWorld) {
return new THREE.ShaderMaterial({ return new THREE.ShaderMaterial({
transparent: true, transparent: true,
side: THREE.DoubleSide, side: THREE.DoubleSide,
depthTest: true, depthTest: true,
depthWrite: false, depthWrite: false,
blending: THREE.AdditiveBlending, blending: THREE.AdditiveBlending,
uniforms: { toneMapped: false,
uColor: { value: new THREE.Color(IRIDIUM_OVERLAY_COLOR) }, uniforms: createSharedUniforms(earthRadiusWorld, 0.48),
uOpacity: { value: 0.55 }, vertexShader: IRIDIUM_VERTEX_SHADER,
}, fragmentShader: IRIDIUM_FILL_FRAGMENT_SHADER,
vertexShader: `
attribute vec2 aUv;
varying vec2 vUv;
void main() {
vUv = aUv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uColor;
uniform float uOpacity;
varying vec2 vUv;
void main() {
float r2 = dot(vUv, vUv);
float glow = exp(-r2 * 1.4) * (1.0 - smoothstep(0.72, 1.0, r2));
float alpha = glow * uOpacity;
if (alpha <= 0.001) discard;
gl_FragColor = vec4(uColor, alpha);
}
`,
}); });
} }
function createIridiumRingMaterial() { function createIridiumRingMaterial(earthRadiusWorld) {
return new THREE.LineBasicMaterial({ return new THREE.ShaderMaterial({
color: new THREE.Color(IRIDIUM_OVERLAY_COLOR),
transparent: true, transparent: true,
opacity: 0.75,
blending: THREE.AdditiveBlending,
depthTest: true, depthTest: true,
depthWrite: false, depthWrite: false,
blending: THREE.AdditiveBlending,
toneMapped: false,
uniforms: createSharedUniforms(earthRadiusWorld, 0.76),
vertexShader: IRIDIUM_VERTEX_SHADER,
fragmentShader: IRIDIUM_RING_FRAGMENT_SHADER,
}); });
} }
function projectOffsetToSurface(
centerNormal,
alongTrack,
crossTrack,
alongKm,
crossKm,
earthRadiusWorld,
) {
const worldUnitsPerKm = earthRadiusWorld / EARTH_RADIUS_KM;
const surfaceRadius = earthRadiusWorld * SURFACE_SCALE + SURFACE_OFFSET;
return centerNormal
.clone()
.multiplyScalar(earthRadiusWorld)
.addScaledVector(alongTrack, alongKm * worldUnitsPerKm)
.addScaledVector(crossTrack, crossKm * worldUnitsPerKm)
.normalize()
.multiplyScalar(surfaceRadius);
}
function computeClusterRadiusKm(altitudeKm) { function computeClusterRadiusKm(altitudeKm) {
const altitudeScale = THREE.MathUtils.clamp( const altitudeScale = THREE.MathUtils.clamp(
(Number(altitudeKm) || IRIDIUM_REFERENCE_ALTITUDE_KM) / IRIDIUM_REFERENCE_ALTITUDE_KM, (Number(altitudeKm) || IRIDIUM_REFERENCE_ALTITUDE_KM) / IRIDIUM_REFERENCE_ALTITUDE_KM,
@@ -102,31 +151,42 @@ function computeClusterRadiusKm(altitudeKm) {
return CLUSTER_RADIUS_KM_BASE * altitudeScale; return CLUSTER_RADIUS_KM_BASE * altitudeScale;
} }
function buildFillGeometry() { function buildStaticFillGeometry() {
// Radial grid: center + FILL_RINGS rings × FILL_SEGMENTS points each.
// Positions are updated in world space each frame; indices are static.
const vertexCount = 1 + FILL_RINGS * FILL_SEGMENTS; const vertexCount = 1 + FILL_RINGS * FILL_SEGMENTS;
const positions = new Float32Array(vertexCount * 3); const positions = new Float32Array(vertexCount * 3);
const uvs = new Float32Array(vertexCount * 2); const uvs = new Float32Array(vertexCount * 2);
// Center vertex: uv = (0,0) // Center at index 0 -> position (0,0,0), aUv (0,0)
// Edge vertices: uv on unit circle, r = ring/FILL_RINGS for (let r = 1; r <= FILL_RINGS; r++) {
const t = r / FILL_RINGS;
for (let s = 0; s < FILL_SEGMENTS; s++) {
const angle = (s / FILL_SEGMENTS) * Math.PI * 2;
const u = t * Math.cos(angle);
const v = t * Math.sin(angle);
const vi = 1 + (r - 1) * FILL_SEGMENTS + s;
positions[vi * 3] = u;
positions[vi * 3 + 1] = v;
uvs[vi * 2] = u;
uvs[vi * 2 + 1] = v;
}
}
const indices = []; const indices = [];
// Center to first ring: triangle fan
for (let s = 0; s < FILL_SEGMENTS; s++) { for (let s = 0; s < FILL_SEGMENTS; s++) {
const a = 1 + s; const a = 1 + s;
const b = 1 + (s + 1) % FILL_SEGMENTS; const b = 1 + (s + 1) % FILL_SEGMENTS;
indices.push(0, a, b); indices.push(0, a, b);
} }
// Ring to ring
for (let r = 0; r < FILL_RINGS - 1; r++) { for (let r = 0; r < FILL_RINGS - 1; r++) {
const ringBase = 1 + r * FILL_SEGMENTS; const ringBase = 1 + r * FILL_SEGMENTS;
const nextBase = ringBase + FILL_SEGMENTS; const nextBase = ringBase + FILL_SEGMENTS;
for (let s = 0; s < FILL_SEGMENTS; s++) { for (let s = 0; s < FILL_SEGMENTS; s++) {
const s1 = (s + 1) % FILL_SEGMENTS; const nextS = (s + 1) % FILL_SEGMENTS;
indices.push(ringBase + s, nextBase + s, ringBase + s1); const a = ringBase + s;
indices.push(nextBase + s, nextBase + s1, ringBase + s1); const b = ringBase + nextS;
const c = nextBase + s;
const d = nextBase + nextS;
indices.push(a, c, d, a, d, b);
} }
} }
@@ -137,10 +197,21 @@ function buildFillGeometry() {
return geometry; return geometry;
} }
function buildRingGeometry() { function buildStaticRingGeometry() {
const positions = new Float32Array(RING_SEGMENTS * 3); const positions = new Float32Array(RING_SEGMENTS * 3);
const uvs = new Float32Array(RING_SEGMENTS * 2);
for (let k = 0; k < RING_SEGMENTS; k++) {
const angle = (k / RING_SEGMENTS) * Math.PI * 2;
const u = Math.cos(angle);
const v = Math.sin(angle);
positions[k * 3] = u;
positions[k * 3 + 1] = v;
uvs[k * 2] = u;
uvs[k * 2 + 1] = v;
}
const geometry = new THREE.BufferGeometry(); const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3)); geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("aUv", new THREE.BufferAttribute(uvs, 2));
return geometry; return geometry;
} }
@@ -151,22 +222,25 @@ export function createIridiumFootprintAdapter({
}) { }) {
if (!earthObj) return null; if (!earthObj) return null;
const resolvedEarthRadius = Number(earthRadiusWorld) || EARTH_RADIUS_KM;
const group = new THREE.Group(); const group = new THREE.Group();
group.name = "iridium-footprint-overlay"; group.name = "iridium-footprint-overlay";
group.renderOrder = renderOrder; group.renderOrder = renderOrder;
group.userData = { earthRadiusWorld, fill: null, outerRing: null }; group.userData = { earthRadiusWorld: resolvedEarthRadius, fill: null, outerRing: null };
const fill = new THREE.Mesh(buildFillGeometry(), createIridiumFillMaterial()); const fill = new THREE.Mesh(buildStaticFillGeometry(), createIridiumFillMaterial(resolvedEarthRadius));
fill.name = "iridium-cluster-fill"; fill.name = "iridium-cluster-fill";
fill.renderOrder = renderOrder; fill.renderOrder = renderOrder;
fill.frustumCulled = false; fill.frustumCulled = false;
fill.raycast = () => {};
group.add(fill); group.add(fill);
group.userData.fill = fill; group.userData.fill = fill;
const outerRing = new THREE.LineLoop(buildRingGeometry(), createIridiumRingMaterial()); const outerRing = new THREE.LineLoop(buildStaticRingGeometry(), createIridiumRingMaterial(resolvedEarthRadius));
outerRing.name = "iridium-outer-ring"; outerRing.name = "iridium-outer-ring";
outerRing.renderOrder = renderOrder; outerRing.renderOrder = renderOrder;
outerRing.frustumCulled = false; outerRing.frustumCulled = false;
outerRing.raycast = () => {};
group.add(outerRing); group.add(outerRing);
group.userData.outerRing = outerRing; group.userData.outerRing = outerRing;
@@ -181,64 +255,24 @@ export function updateIridiumFootprintAdapter(
if (!group || !position || !alongTrack || !crossTrack) return; if (!group || !position || !alongTrack || !crossTrack) return;
const earthRadiusWorld = group.userData?.earthRadiusWorld || EARTH_RADIUS_KM; const earthRadiusWorld = group.userData?.earthRadiusWorld || EARTH_RADIUS_KM;
const surfaceRadius = earthRadiusWorld * SURFACE_SCALE + SURFACE_OFFSET;
const centerNormal = position.clone().normalize(); const centerNormal = position.clone().normalize();
const clusterRadiusKm = computeClusterRadiusKm(altitudeKm); const clusterRadiusKm = computeClusterRadiusKm(altitudeKm);
const alongRadiusKm = clusterRadiusKm * 1.18; const alongRadiusKm = clusterRadiusKm * 1.18;
const crossRadiusKm = clusterRadiusKm * 0.96; const crossRadiusKm = clusterRadiusKm * 0.96;
const nowSec = (typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001;
const fill = group.userData?.fill; for (const child of [group.userData?.fill, group.userData?.outerRing]) {
if (fill) { const uniforms = child?.material?.uniforms;
const posAttr = fill.geometry.attributes.position; if (!uniforms) continue;
const uvAttr = fill.geometry.attributes.aUv; uniforms.uCenterNormal.value.copy(centerNormal);
uniforms.uAlongTrack.value.copy(alongTrack);
// Center vertex uniforms.uCrossTrack.value.copy(crossTrack);
const center = projectOffsetToSurface( uniforms.uAlongKm.value = alongRadiusKm;
centerNormal, alongTrack, crossTrack, 0, 0, earthRadiusWorld, uniforms.uCrossKm.value = crossRadiusKm;
); uniforms.uEarthRadiusKm.value = EARTH_RADIUS_KM;
posAttr.setXYZ(0, center.x, center.y, center.z); uniforms.uSurfaceRadius.value = surfaceRadius;
uvAttr.setXY(0, 0, 0); uniforms.uTime.value = nowSec;
// Ring vertices
for (let r = 1; r <= FILL_RINGS; r++) {
const t = r / FILL_RINGS;
const aKm = alongRadiusKm * t;
const cKm = crossRadiusKm * t;
for (let s = 0; s < FILL_SEGMENTS; s++) {
const angle = (s / FILL_SEGMENTS) * Math.PI * 2;
const cosA = Math.cos(angle);
const sinA = Math.sin(angle);
const pt = projectOffsetToSurface(
centerNormal, alongTrack, crossTrack,
aKm * cosA,
cKm * sinA,
earthRadiusWorld,
);
const vi = 1 + (r - 1) * FILL_SEGMENTS + s;
posAttr.setXYZ(vi, pt.x, pt.y, pt.z);
uvAttr.setXY(vi, t * cosA, t * sinA);
}
}
posAttr.needsUpdate = true;
uvAttr.needsUpdate = true;
fill.geometry.computeBoundingSphere();
}
const outerRing = group.userData?.outerRing;
if (outerRing) {
const posAttr = outerRing.geometry.attributes.position;
for (let k = 0; k < RING_SEGMENTS; k++) {
const angle = (k / RING_SEGMENTS) * Math.PI * 2;
const pt = projectOffsetToSurface(
centerNormal, alongTrack, crossTrack,
alongRadiusKm * Math.cos(angle),
crossRadiusKm * Math.sin(angle),
earthRadiusWorld,
);
posAttr.setXYZ(k, pt.x, pt.y, pt.z);
}
posAttr.needsUpdate = true;
outerRing.geometry.computeBoundingSphere();
} }
} }
@@ -0,0 +1,53 @@
import { describe, expect, it } from "bun:test";
import * as THREE from "three";
import {
createIridiumFootprintAdapter,
disposeIridiumFootprintAdapter,
updateIridiumFootprintAdapter,
} from "./iridium-footprint-adapter.js";
describe("iridium-footprint-adapter GPU projection", () => {
it("projects static geometry via uniforms with zero CPU vertex re-uploads on update", () => {
const earth = new THREE.Group();
const overlay = createIridiumFootprintAdapter({
earthObj: earth,
earthRadiusWorld: 100,
renderOrder: 3.2,
});
expect(overlay).toBeTruthy();
const fill = overlay.userData.fill;
const outerRing = overlay.userData.outerRing;
expect(fill.material.isShaderMaterial).toBe(true);
expect(outerRing.material.isShaderMaterial).toBe(true);
const initialFillPosVersion = fill.geometry.attributes.position.version;
const initialRingPosVersion = outerRing.geometry.attributes.position.version;
updateIridiumFootprintAdapter(overlay, {
position: new THREE.Vector3(105, 10, 0),
alongTrack: new THREE.Vector3(0, 1, 0),
crossTrack: new THREE.Vector3(0, 0, 1),
altitudeKm: 780,
});
updateIridiumFootprintAdapter(overlay, {
position: new THREE.Vector3(90, 45, 25),
alongTrack: new THREE.Vector3(0, 0.8, -0.6).normalize(),
crossTrack: new THREE.Vector3(0, 0.6, 0.8).normalize(),
altitudeKm: 810,
});
// GPU shader updates uniforms only — static vertex buffers must never mutate/re-upload
expect(fill.geometry.attributes.position.version).toBe(initialFillPosVersion);
expect(outerRing.geometry.attributes.position.version).toBe(initialRingPosVersion);
expect(fill.material.uniforms.uCenterNormal.value.length()).toBeCloseTo(1, 5);
expect(fill.material.uniforms.uAlongKm.value).toBeGreaterThan(2000);
expect(fill.material.fragmentShader).not.toContain("hexEdgeDistance");
expect(fill.material.fragmentShader).toContain("#include <colorspace_fragment>");
expect(outerRing.material.fragmentShader).toContain("#include <colorspace_fragment>");
disposeIridiumFootprintAdapter(overlay, earth);
expect(earth.children).toHaveLength(0);
});
});
+185 -19
View File
@@ -1,7 +1,7 @@
import { bgpEventIdentity } from "./bgp-identity.js"; import { bgpEventIdentity } from "./bgp-identity.js";
import { normalizeComputeSiteType } from "./compute-site-types.js"; import { normalizeComputeSiteType } from "./compute-site-types.js";
import { refreshEarthUpdateBatch } from "./earth-update-batch.js"; import { refreshEarthUpdateBatch } from "./earth-update-batch.js";
import { loadWorkflowBindings } from "./workflow-bindings.js"; import { ensureEarthBottomDock, loadWorkflowBindings } from "./workflow-bindings.js";
import { createFrameProfile } from "./frame-profile.js"; import { createFrameProfile } from "./frame-profile.js";
import { createFrameStageRunner } from "./frame-stages.js"; import { createFrameStageRunner } from "./frame-stages.js";
import { initNewsRegionCards } from "./news-region-cards.js"; import { initNewsRegionCards } from "./news-region-cards.js";
@@ -91,6 +91,8 @@ import {
toggleTerrain, toggleTerrain,
} from "./earth.js"; } from "./earth.js";
import { registerTerrainMesh, clearTerrainData, sampleElevationAt } from "./terrain.js"; import { registerTerrainMesh, clearTerrainData, sampleElevationAt } from "./terrain.js";
import { createInfluenceZonesController } from "./influence-zones.js";
import { updateAllRibbonResolutions } from "./surface-ribbon.js";
import { import {
initCelestialLayer, initCelestialLayer,
loadCelestialStarMap, loadCelestialStarMap,
@@ -437,6 +439,9 @@ let calloutConnector = null;
let computeTopic = null; let computeTopic = null;
let stageNarrativePlayer = null; let stageNarrativePlayer = null;
let situationalCopilot = null; let situationalCopilot = null;
let influenceZones = null;
let influenceZonesPill = null;
let unsubscribeInfluencePill = null;
let newsRegionCards = null; let newsRegionCards = null;
let regionCallouts = null; let regionCallouts = null;
const frameStages = createFrameStageRunner(); const frameStages = createFrameStageRunner();
@@ -678,6 +683,7 @@ function syncRendererViewport() {
); );
if (renderer.getPixelRatio() !== pixelRatio) renderer.setPixelRatio(pixelRatio); if (renderer.getPixelRatio() !== pixelRatio) renderer.setPixelRatio(pixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight); renderer.setSize(window.innerWidth, window.innerHeight);
updateAllRibbonResolutions(window.innerWidth, window.innerHeight);
updateCachedCanvasRect(); updateCachedCanvasRect();
} }
@@ -806,6 +812,7 @@ export function clearLockedObject() {
clearComputeCenterSelection(); clearComputeCenterSelection();
clearVesselSelection(); clearVesselSelection();
clearEarthInteractableSelection(); clearEarthInteractableSelection();
influenceZones?.clearScope("interactable");
clearRelatedSatelliteHighlights(); clearRelatedSatelliteHighlights();
setSatelliteRingState(null, "none", null); setSatelliteRingState(null, "none", null);
clearRuntimeSelection(); clearRuntimeSelection();
@@ -1844,6 +1851,15 @@ function confirmInteractionCandidate(candidate, { showConfirmationFeedback = tru
setEarthInteractableMarkerState(marker, "locked"); setEarthInteractableMarkerState(marker, "locked");
lockedObject = marker; lockedObject = marker;
lockedObjectType = "earth_interactable"; lockedObjectType = "earth_interactable";
const itemZones = marker.userData?.properties?.influence_zones
|| marker.userData?.influence_zones
|| marker.userData?.data?.properties?.influence_zones
|| [];
if (Array.isArray(itemZones) && itemZones.length > 0) {
void influenceZones?.setZones(itemZones, { scope: "interactable" });
} else {
influenceZones?.clearScope("interactable");
}
} else if (candidate.type === "cable") { } else if (candidate.type === "cable") {
const cable = candidate.object; const cable = candidate.object;
setCableState(cable.userData.cableId, CABLE_STATE.LOCKED); setCableState(cable.userData.cableId, CABLE_STATE.LOCKED);
@@ -4007,11 +4023,11 @@ function applyCableVisualState() {
CABLE_CONFIG.lockedOpacityMax, CABLE_CONFIG.lockedOpacityMax,
pulse, pulse,
); );
cable.material.color.setRGB(0.92, 0.98, 1.0); cable.material.color.setRGB(0.92, 0.98, 1.0, ...(THREE.SRGBColorSpace ? [THREE.SRGBColorSpace] : []));
break; break;
case CABLE_STATE.HOVERED: case CABLE_STATE.HOVERED:
cable.material.opacity = CABLE_CONFIG.lockedOpacityMax; cable.material.opacity = CABLE_CONFIG.lockedOpacityMax;
cable.material.color.setRGB(0.92, 0.98, 1.0); cable.material.color.setRGB(0.92, 0.98, 1.0, ...(THREE.SRGBColorSpace ? [THREE.SRGBColorSpace] : []));
break; break;
case CABLE_STATE.NORMAL: case CABLE_STATE.NORMAL:
default: default:
@@ -4023,6 +4039,7 @@ function applyCableVisualState() {
(((origColor >> 16) & 255) / 255) * brightness, (((origColor >> 16) & 255) / 255) * brightness,
(((origColor >> 8) & 255) / 255) * brightness, (((origColor >> 8) & 255) / 255) * brightness,
((origColor & 255) / 255) * brightness, ((origColor & 255) / 255) * brightness,
...(THREE.SRGBColorSpace ? [THREE.SRGBColorSpace] : []),
); );
} else { } else {
cable.material.opacity = CABLE_CONFIG.visual.normalOpacity; cable.material.opacity = CABLE_CONFIG.visual.normalOpacity;
@@ -4630,6 +4647,12 @@ export function init() {
computeTopic.closeCards?.(); computeTopic.closeCards?.();
toggleComputeCenters(true); toggleComputeCenters(true);
} }
if (!isOpen) {
influenceZones?.clearScope("copilot");
}
},
onClearSceneZones() {
influenceZones?.clearScope("copilot");
}, },
onPlayPresentation(key) { onPlayPresentation(key) {
if (key === "compute-posture-cn-us") { if (key === "compute-posture-cn-us") {
@@ -4642,17 +4665,30 @@ export function init() {
void stageNarrativePlayer?.play(key, { focusSource: "user" }); void stageNarrativePlayer?.play(key, { focusSource: "user" });
}, },
onApplySceneSpec(sceneSpec) { onApplySceneSpec(sceneSpec) {
if (sceneSpec?.fly_to && camera) { const hasZones = Array.isArray(sceneSpec?.influence_zones) && sceneSpec.influence_zones.length > 0;
const lat = Number(sceneSpec.fly_to.lat); const cameraTarget = hasZones
const lon = Number(sceneSpec.fly_to.lon); ? (sceneSpec?.camera_hint || sceneSpec?.fly_to)
if (Number.isFinite(lat) && Number.isFinite(lon)) { : (sceneSpec?.fly_to || sceneSpec?.camera_hint);
void focusEarthView(camera, { const lat = cameraTarget ? Number(cameraTarget.lat) : NaN;
lat, const lon = cameraTarget ? Number(cameraTarget.lon) : NaN;
lon, const hasCameraTarget = Boolean(cameraTarget && camera && Number.isFinite(lat) && Number.isFinite(lon));
zoom: Number(sceneSpec.fly_to.zoom) || Math.max(getZoomLevel(), 1.35), if (hasZones || hasCameraTarget) {
duration: 850, setAutoRotate(false);
suppressStatus: true, }
}); if (hasCameraTarget) {
void focusEarthView(camera, {
lat,
lon,
zoom: Number(cameraTarget.zoom) || Math.max(getZoomLevel(), 1.35),
duration: 850,
suppressStatus: true,
});
}
if (Array.isArray(sceneSpec?.influence_zones)) {
if (sceneSpec.influence_zones.length > 0) {
void influenceZones?.setZones(sceneSpec.influence_zones, { scope: "copilot" });
} else {
influenceZones?.clearScope("copilot");
} }
} }
if (sceneSpec?.domain === "compute" && sceneSpec.enable_national_hubs) { if (sceneSpec?.domain === "compute" && sceneSpec.enable_national_hubs) {
@@ -4709,8 +4745,16 @@ export function init() {
const earth = getEarth(); const earth = getEarth();
if (earth) setStageLogicalArcsOverlay(earth, arcs); if (earth) setStageLogicalArcsOverlay(earth, arcs);
}, },
onInfluenceZones(zones) {
if (Array.isArray(zones) && zones.length > 0) {
void influenceZones?.setZones(zones, { scope: "stage" });
} else {
influenceZones?.clearScope("stage");
}
},
onClearOverlays() { onClearOverlays() {
clearStageLogicalArcsOverlay(); clearStageLogicalArcsOverlay();
influenceZones?.clearScope("stage");
}, },
onInterruptAmbientCruise() { onInterruptAmbientCruise() {
interruptCruisePresentation({ resetLoop: true }); interruptCruisePresentation({ resetLoop: true });
@@ -4909,6 +4953,119 @@ export function init() {
setLegendItems("vessels", getVesselLegendItems()); setLegendItems("vessels", getVesselLegendItems());
setLegendItems("bgp", getBGPLegendItems()); setLegendItems("bgp", getBGPLegendItems());
const earthObj = createEarth(scene); const earthObj = createEarth(scene);
influenceZones = createInfluenceZonesController(earthObj);
if (typeof window !== "undefined") {
window.__PLANET_INFLUENCE_ZONES__ = influenceZones;
}
if (typeof document !== "undefined" && document.body && !influenceZonesPill) {
const pill = document.createElement("aside");
pill.id = "earth-influence-pill";
pill.className = "hud-panel earth-influence-pill";
pill.hidden = true;
pill.setAttribute("aria-live", "polite");
const viewport = document.createElement("div");
viewport.className = "earth-influence-pill__viewport";
const track = document.createElement("div");
track.className = "earth-influence-pill__track";
const primaryGroup = document.createElement("div");
primaryGroup.className = "earth-influence-pill__group";
track.append(primaryGroup);
viewport.append(track);
const sliderWrap = document.createElement("label");
sliderWrap.className = "earth-influence-pill__slider-wrap";
const slider = document.createElement("input");
slider.type = "range";
slider.className = "earth-influence-pill__slider";
slider.min = "0.2";
slider.max = "1.4";
slider.step = "0.05";
slider.value = "1";
slider.setAttribute("aria-label", "调整影响范围透明度");
slider.addEventListener("input", () => {
influenceZones?.setOpacityScale(Number(slider.value));
});
sliderWrap.append(slider);
const clearBtn = document.createElement("button");
clearBtn.type = "button";
clearBtn.className = "earth-influence-pill__clear";
clearBtn.setAttribute("aria-label", "清除影响范围");
const clearIcon = document.createElement("span");
clearIcon.className = "material-symbols-rounded earth-influence-pill-icon";
clearIcon.setAttribute("aria-hidden", "true");
clearIcon.textContent = "close";
clearBtn.append(clearIcon);
clearBtn.addEventListener("click", () => {
influenceZones?.clearAll();
});
const syncInfluencePillMarquee = () => {
track.querySelectorAll(".earth-influence-pill__group--clone").forEach((el) => el.remove());
viewport.classList.remove("is-marquee");
track.style.removeProperty("--marquee-duration");
if (pill.hidden || primaryGroup.childElementCount === 0) return;
const overflowPx = primaryGroup.scrollWidth - viewport.clientWidth;
if (overflowPx > 4) {
const clone = primaryGroup.cloneNode(true);
clone.classList.add("earth-influence-pill__group--clone");
clone.setAttribute("aria-hidden", "true");
track.append(clone);
const distance = primaryGroup.scrollWidth + 24;
const durationSec = Math.max(10, Math.min(48, distance / 26));
track.style.setProperty("--marquee-duration", `${durationSec.toFixed(1)}s`);
viewport.classList.add("is-marquee");
}
};
if (typeof ResizeObserver === "function") {
const marqueeObserver = new ResizeObserver(() => {
syncInfluencePillMarquee();
});
marqueeObserver.observe(viewport);
}
pill.append(viewport, sliderWrap, clearBtn);
const dock = ensureEarthBottomDock() || document.body;
const existingTray = document.getElementById("earth-target-tray");
if (existingTray && existingTray.parentNode === dock) {
dock.insertBefore(pill, existingTray);
} else {
dock.append(pill);
}
influenceZonesPill = pill;
unsubscribeInfluencePill = influenceZones.onChange((state) => {
situationalCopilot?.syncActiveZonesState?.(state);
if (!influenceZonesPill) return;
if (!state || state.zoneCount === 0) {
influenceZonesPill.hidden = true;
primaryGroup.replaceChildren();
syncInfluencePillMarquee();
return;
}
const nextNodes = state.zones.map((z) => {
const chip = document.createElement("span");
chip.className = "earth-influence-pill__item";
const dot = document.createElement("span");
dot.className = "earth-influence-pill__dot";
dot.style.setProperty("--zone-color", z.color || "#38bdf8");
const label = document.createElement("span");
label.textContent = z.label || z.id;
chip.append(dot, label);
return chip;
});
primaryGroup.replaceChildren(...nextNodes);
slider.value = String(state.opacityScale ?? 1);
influenceZonesPill.hidden = false;
if (typeof requestAnimationFrame === "function") {
requestAnimationFrame(() => syncInfluencePillMarquee());
} else {
syncInfluencePillMarquee();
}
});
}
applyImmediateView(earthObj, camera); applyImmediateView(earthObj, camera);
targetRotation = { targetRotation = {
x: earthObj.rotation.x, x: earthObj.rotation.x,
@@ -6675,8 +6832,7 @@ function onMouseMove(event) {
if ( if (
hoveredBGPMarker && hoveredBGPMarker &&
getShowBGP() && getShowBGP() &&
lockedObjectType !== "bgp" && hoveredBGPMarker !== lockedObject
lockedObjectType !== "bgp_collector"
) { ) {
applyBGPHoverState(hoveredBGPMarker); applyBGPHoverState(hoveredBGPMarker);
if (hoveredBGPMarker.userData?.type === "bgp") { if (hoveredBGPMarker.userData?.type === "bgp") {
@@ -6688,7 +6844,7 @@ function onMouseMove(event) {
} else if ( } else if (
hoveredComputeCenterMarker && hoveredComputeCenterMarker &&
getShowComputeCenters() && getShowComputeCenters() &&
lockedObjectType !== "compute_center" hoveredComputeCenterMarker !== lockedObject
) { ) {
applyComputeCenterHoverState(hoveredComputeCenterMarker); applyComputeCenterHoverState(hoveredComputeCenterMarker);
showTooltip( showTooltip(
@@ -6701,7 +6857,7 @@ function onMouseMove(event) {
vesselPick.checked && vesselPick.checked &&
hoveredVesselMarker && hoveredVesselMarker &&
getShowVessels() && getShowVessels() &&
lockedObjectType !== "vessel" hoveredVesselMarker !== lockedObject
) { ) {
applyVesselHoverState(hoveredVesselMarker); applyVesselHoverState(hoveredVesselMarker);
showTooltip( showTooltip(
@@ -6712,7 +6868,7 @@ function onMouseMove(event) {
objectTooltipShown = true; objectTooltipShown = true;
} else if ( } else if (
hoveredEarthInteractableMarker && hoveredEarthInteractableMarker &&
lockedObjectType !== "earth_interactable" hoveredEarthInteractableMarker !== lockedObject
) { ) {
applyEarthInteractableHoverState(hoveredEarthInteractableMarker); applyEarthInteractableHoverState(hoveredEarthInteractableMarker);
showTooltip( showTooltip(
@@ -7212,6 +7368,7 @@ function animate() {
const currentSunDirection = getSunDirection(); const currentSunDirection = getSunDirection();
setEarthSunDirection(currentSunDirection); setEarthSunDirection(currentSunDirection);
setSatelliteSunDirection(currentSunDirection); setSatelliteSunDirection(currentSunDirection);
influenceZones?.update(performance.now(), currentSunDirection, getDayNightEnabled());
}); });
stage("mobile-country-highlight", () => updateMobileCenterCountryHighlight({ stage("mobile-country-highlight", () => updateMobileCenterCountryHighlight({
camera, camera,
@@ -7324,6 +7481,15 @@ export function destroy() {
clearBGPData(getEarth()); clearBGPData(getEarth());
clearComputeCenterData(getEarth()); clearComputeCenterData(getEarth());
clearCountryBoundaryData(); clearCountryBoundaryData();
unsubscribeInfluencePill?.();
unsubscribeInfluencePill = null;
influenceZonesPill?.remove?.();
influenceZonesPill = null;
influenceZones?.dispose?.();
influenceZones = null;
if (typeof window !== "undefined" && window.__PLANET_INFLUENCE_ZONES__) {
delete window.__PLANET_INFLUENCE_ZONES__;
}
clearEarthTexture(); clearEarthTexture();
abortPendingSatelliteLoad(); abortPendingSatelliteLoad();
resetSatelliteState(); resetSatelliteState();
@@ -50,6 +50,7 @@ export function createOrbitFlowMaterial(color) {
float phase = fract(vProgress * ${ORBIT_VISUAL.flowRepeats.toFixed(1)} - uTime * ${ORBIT_VISUAL.flowSpeed.toFixed(2)}); float phase = fract(vProgress * ${ORBIT_VISUAL.flowRepeats.toFixed(1)} - uTime * ${ORBIT_VISUAL.flowSpeed.toFixed(2)});
float pulse = smoothstep(0.45, 0.95, phase) * (1.0 - smoothstep(0.95, 1.0, phase)); float pulse = smoothstep(0.45, 0.95, phase) * (1.0 - smoothstep(0.95, 1.0, phase));
gl_FragColor = vec4(mix(uColor, vec3(1.0), pulse * 0.65), 0.56 + 0.44 * pulse); gl_FragColor = vec4(mix(uColor, vec3(1.0), pulse * 0.65), 0.56 + 0.44 * pulse);
#include <colorspace_fragment>
} }
`, `,
}); });
@@ -1,6 +1,11 @@
import { expect, test } from "bun:test"; import { expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import * as THREE from "three"; import * as THREE from "three";
import { openOrbitSampleTimes, createOrbitFlowGeometry } from "./satellite-orbit-visual.js"; import {
openOrbitSampleTimes,
createOrbitFlowGeometry,
createOrbitFlowMaterial,
} from "./satellite-orbit-visual.js";
test("prediction retains a full orbit and its natural endpoint without a forced closing chord", () => { test("prediction retains a full orbit and its natural endpoint without a forced closing chord", () => {
for (const period of [5573.7, 86400]) { for (const period of [5573.7, 86400]) {
@@ -30,3 +35,34 @@ test("flow progress follows distance and chronological direction across unequal
expect([...degenerate.attributes.orbitProgress.array]).toEqual([0,0]); expect([...degenerate.attributes.orbitProgress.array]).toEqual([0,0]);
degenerate.dispose(); degenerate.dispose();
}); });
test("showPredictedOrbit renders crisp THREE.Line orbit flow track without thick ribbons", () => {
const satSource = readFileSync(new URL("./satellites.js", import.meta.url), "utf8");
const showOrbitFn = satSource.slice(
satSource.indexOf("export function showPredictedOrbit("),
satSource.indexOf("export function hidePredictedOrbit("),
);
expect(showOrbitFn).toContain("createOrbitFlowGeometry");
expect(showOrbitFn).toContain("createOrbitFlowMaterial");
expect(showOrbitFn).toContain("new THREE.Line(geometry, material)");
expect(satSource).not.toContain("createOrbitRibbon");
});
test("satellite linear-color shaders encode output with colorspace_fragment", () => {
const flowMat = createOrbitFlowMaterial(0x3399ff);
expect(flowMat.fragmentShader).toContain("#include <colorspace_fragment>");
flowMat.dispose();
const satSource = readFileSync(new URL("./satellites.js", import.meta.url), "utf8");
const footprintFn = satSource.slice(
satSource.indexOf("function createGroundFootprintMaterial()"),
satSource.indexOf("function smoothstep("),
);
expect(footprintFn).toContain("#include <colorspace_fragment>");
const haloFn = satSource.slice(
satSource.indexOf("function createLockedHaloMaterial("),
satSource.indexOf("function createGroundFootprintMaterial()"),
);
expect(haloFn).toContain("#include <colorspace_fragment>");
expect(satSource).toContain("gl_FragColor = vec4(vColor, vAlpha);\n #include <colorspace_fragment>");
});
+12 -1
View File
@@ -7,7 +7,11 @@ import {
satelliteCategory, satelliteCategory,
satellitePixelSize, satellitePixelSize,
} from "./satellite-display.js"; } from "./satellite-display.js";
import { openOrbitSampleTimes, createOrbitFlowGeometry, createOrbitFlowMaterial } from "./satellite-orbit-visual.js"; import {
openOrbitSampleTimes,
createOrbitFlowGeometry,
createOrbitFlowMaterial,
} from "./satellite-orbit-visual.js";
import { createSatelliteMotion } from "./satellite-motion.js"; import { createSatelliteMotion } from "./satellite-motion.js";
import { decodeSatellitePayload } from "./satellite-catalog.js"; import { decodeSatellitePayload } from "./satellite-catalog.js";
import { import {
@@ -25,6 +29,7 @@ import {
SATELLITE_CONFIG, SATELLITE_CONFIG,
} from "./constants.js"; } from "./constants.js";
import { latLonToVector3 } from "./utils.js"; import { latLonToVector3 } from "./utils.js";
import { configureColorTexture } from "./texture-colors.js";
import { import {
createIridiumFootprintAdapter, createIridiumFootprintAdapter,
disposeIridiumFootprintAdapter, disposeIridiumFootprintAdapter,
@@ -179,6 +184,7 @@ const TRAIL_RIBBON_FRAGMENT_SHADER = /* glsl */ `
varying float vAlpha; varying float vAlpha;
void main() { void main() {
gl_FragColor = vec4(vColor, vAlpha); gl_FragColor = vec4(vColor, vAlpha);
#include <colorspace_fragment>
} }
`; `;
@@ -533,6 +539,7 @@ function createRingTexture(innerRadius, outerRadius, color = "#ffffff", lineWidt
ctx.stroke(); ctx.stroke();
const texture = new THREE.CanvasTexture(canvas); const texture = new THREE.CanvasTexture(canvas);
configureColorTexture(texture);
texture.needsUpdate = true; texture.needsUpdate = true;
return texture; return texture;
} }
@@ -552,6 +559,7 @@ function createFilledCircleTexture(color = "#ffcc00") {
ctx.fill(); ctx.fill();
const texture = new THREE.CanvasTexture(canvas); const texture = new THREE.CanvasTexture(canvas);
configureColorTexture(texture);
texture.needsUpdate = true; texture.needsUpdate = true;
return texture; return texture;
} }
@@ -1644,6 +1652,7 @@ function createLockedHaloMaterial(color = "#ffbf47") {
float alpha = outerFade * innerFade * uOpacity; float alpha = outerFade * innerFade * uOpacity;
if (alpha <= 0.001) discard; if (alpha <= 0.001) discard;
gl_FragColor = vec4(uColor, alpha); gl_FragColor = vec4(uColor, alpha);
#include <colorspace_fragment>
} }
`, `,
}); });
@@ -1746,6 +1755,7 @@ function createGroundFootprintMaterial() {
// opacity; it must never recolor the same coverage patch yellow. // opacity; it must never recolor the same coverage patch yellow.
if (alpha <= 0.001) discard; if (alpha <= 0.001) discard;
gl_FragColor = vec4(uColor, alpha); gl_FragColor = vec4(uColor, alpha);
#include <colorspace_fragment>
} }
`, `,
}); });
@@ -2517,6 +2527,7 @@ export function showPredictedOrbit(satellite) {
const geometry = createOrbitFlowGeometry(points); const geometry = createOrbitFlowGeometry(points);
const material = createOrbitFlowMaterial(getSatelliteLegendRule(satellite.properties).color); const material = createOrbitFlowMaterial(getSatelliteLegendRule(satellite.properties).color);
predictedOrbitLine = new THREE.Line(geometry, material); predictedOrbitLine = new THREE.Line(geometry, material);
predictedOrbitLine.raycast = () => {};
const startedAt = performance.now(); const startedAt = performance.now();
predictedOrbitLine.onBeforeRender = () => { predictedOrbitLine.onBeforeRender = () => {
material.uniforms.uTime.value = (performance.now() - startedAt) / 1000; material.uniforms.uTime.value = (performance.now() - startedAt) / 1000;
+207 -5
View File
@@ -28,6 +28,23 @@ const escape = (val) =>
"'": "&#39;", "'": "&#39;",
})[ch]); })[ch]);
const LOCAL_ZONE_EXCLUDES_RE = /(分析|对比|比较|评估|为什么|怎么|原因|扩大|缩小|新增|修改|改成|改为|预测|推演|重算|\b(?:analyze|analyse|compare|evaluate|why|how|expand|shrink|change|predict)\b)/i;
const LOCAL_ZONE_NOUN_RE = /(影响范围|影响地区|影响区域|影响域|辐射范围|区域范围|范围条|范围层|范围|地区范围|区域|zones?|overlay)/i;
const LOCAL_ZONE_SHOW_VERB_RE = /^(?:请|帮我|麻烦)?(?:把|将)?(?:之前的?|刚才的?|上次的?)?(?:重新)?(?:开启|打开|显示|复现|恢复|拉起|展开|切回|调出|亮起|reopen|restore|show|display|enable)(?:一下)?/i;
const LOCAL_ZONE_HIDE_VERB_RE = /^(?:请|帮我|麻烦)?(?:把|将)?(?:当前|这个)?(?:关闭|关掉|隐藏|收起|清除|清掉|去掉|取消|hide|close|clear|disable)(?:一下)?/i;
export function matchLocalInfluenceZoneCommand(question) {
const normalized = String(question || "")
.trim()
.replace(/[。!!??,,、\s]+$/g, "");
if (!normalized || normalized.length > 28) return null;
if (LOCAL_ZONE_EXCLUDES_RE.test(normalized)) return null;
if (!LOCAL_ZONE_NOUN_RE.test(normalized)) return null;
if (LOCAL_ZONE_HIDE_VERB_RE.test(normalized)) return "hide";
if (LOCAL_ZONE_SHOW_VERB_RE.test(normalized)) return "show";
return null;
}
/** /**
* Normalizes LLM replies that flatten headings and `- **` bullets onto one line. * Normalizes LLM replies that flatten headings and `- **` bullets onto one line.
*/ */
@@ -300,6 +317,7 @@ export function initSituationalCopilot({
store = null, store = null,
onHighlightEntities, onHighlightEntities,
onApplySceneSpec, onApplySceneSpec,
onClearSceneZones,
onPlayPresentation, onPlayPresentation,
onPreemptStage, onPreemptStage,
onReleaseStage, onReleaseStage,
@@ -329,6 +347,8 @@ export function initSituationalCopilot({
let sessionPromise = null; let sessionPromise = null;
let activeRunId = null; let activeRunId = null;
let requestEpoch = 0; let requestEpoch = 0;
let activeZoneTurnId = null;
let activeZonesCount = 0;
async function fetchWithTimeout(url, options = {}, timeoutMs = 0) { async function fetchWithTimeout(url, options = {}, timeoutMs = 0) {
const parentSignal = options?.signal; const parentSignal = options?.signal;
@@ -1164,18 +1184,26 @@ export function initSituationalCopilot({
? text(`答案由 ${turn.model} 提供`, `Answered by ${turn.model}`) ? text(`答案由 ${turn.model} 提供`, `Answered by ${turn.model}`)
: (!turn.zeroToken : (!turn.zeroToken
? text("答案由 AI 参谋提供", "Answered by AI Copilot") ? text("答案由 AI 参谋提供", "Answered by AI Copilot")
: (turn.generationMode === "deterministic_fallback" : (turn.generationMode === "local_scene_replay"
? text("由内置结构化规则核验", "Verified by structured telemetry") ? text("本地快速复现 · 0 Token", "Local replay · 0 tokens")
: text("由内置遥测核验", "Verified by built-in telemetry"))); : (turn.generationMode === "deterministic_fallback"
? text("由内置结构化规则核验", "Verified by structured telemetry")
: text("由内置遥测核验", "Verified by built-in telemetry"))));
const modelBadgeHtml = `<span class="copilot-model-badge ${turn.model || !turn.zeroToken ? "copilot-model-badge--ai" : "copilot-model-badge--fallback"}">${escape(modelAttributionText)}</span>`; const modelBadgeHtml = `<span class="copilot-model-badge ${turn.model || !turn.zeroToken ? "copilot-model-badge--ai" : "copilot-model-badge--fallback"}">${escape(modelAttributionText)}</span>`;
const showFooterToolbar = Boolean(viewSpec || turn.model || !isStreaming); const hasZones = Array.isArray(turn.sceneSpec?.influence_zones) && turn.sceneSpec.influence_zones.length > 0;
const isTurnZoneActive = hasZones && activeZonesCount > 0 && activeZoneTurnId === turn.id;
const showFooterToolbar = Boolean(viewSpec || turn.model || hasZones || !isStreaming);
const turnActions = showFooterToolbar const turnActions = showFooterToolbar
? `<div class="wb-turn-toolbar"> ? `<div class="wb-turn-toolbar">
${viewSpec ? `<button type="button" class="wb-action-pill" data-copilot-pin-turn="${escape(turn.id)}" title="${escape(text("将本轮结果固定到对照槽或标签栏", "Pin this result for side-by-side comparison"))}"> ${viewSpec ? `<button type="button" class="wb-action-pill" data-copilot-pin-turn="${escape(turn.id)}" title="${escape(text("将本轮结果固定到对照槽或标签栏", "Pin this result for side-by-side comparison"))}">
<span class="material-symbols-rounded" aria-hidden="true">push_pin</span> <span class="material-symbols-rounded" aria-hidden="true">push_pin</span>
<span>${escape(text("固定对照", "Pin Result"))}</span> <span>${escape(text("固定对照", "Pin Result"))}</span>
</button>` : ""} </button>` : ""}
${hasZones ? `<button type="button" class="wb-action-pill ${isTurnZoneActive ? "is-active" : ""}" data-copilot-toggle-zones="${escape(turn.id)}" aria-pressed="${String(isTurnZoneActive)}" title="${escape(isTurnZoneActive ? text("从地球隐藏本轮影响范围", "Hide these influence zones on 3D globe") : text("在地球重新显示本轮影响范围", "Show these influence zones on 3D globe"))}">
<span class="material-symbols-rounded" aria-hidden="true">${isTurnZoneActive ? "visibility_off" : "layers"}</span>
<span>${escape(isTurnZoneActive ? text("隐藏影响范围", "Hide Zones") : text("显示影响范围", "Show Zones"))}</span>
</button>` : ""}
${turn.sceneSpec?.presentation_key ? `<button type="button" class="wb-action-pill" data-copilot-play-key="${escape(turn.sceneSpec.presentation_key)}" title="${escape(text("在三维地球上播放多幕推演分镜", "Play multi-act tour on 3D globe"))}"> ${turn.sceneSpec?.presentation_key ? `<button type="button" class="wb-action-pill" data-copilot-play-key="${escape(turn.sceneSpec.presentation_key)}" title="${escape(text("在三维地球上播放多幕推演分镜", "Play multi-act tour on 3D globe"))}">
<span class="material-symbols-rounded" aria-hidden="true">public</span> <span class="material-symbols-rounded" aria-hidden="true">public</span>
<span>${escape(text("地球推演", "Globe Tour"))}</span> <span>${escape(text("地球推演", "Globe Tour"))}</span>
@@ -1652,7 +1680,20 @@ export function initSituationalCopilot({
function syncSceneEffectsForTurn(turn, data) { function syncSceneEffectsForTurn(turn, data) {
if (turn.sceneSpec) { if (turn.sceneSpec) {
onApplySceneSpec?.(turn.sceneSpec); let sceneKey = "";
try {
sceneKey = JSON.stringify(turn.sceneSpec);
} catch (_err) {
sceneKey = String(Date.now());
}
if (turn._lastAppliedSceneKey !== sceneKey) {
turn._lastAppliedSceneKey = sceneKey;
if (Array.isArray(turn.sceneSpec.influence_zones) && turn.sceneSpec.influence_zones.length > 0) {
activeZoneTurnId = turn.id;
activeZonesCount = turn.sceneSpec.influence_zones.length;
}
onApplySceneSpec?.(turn.sceneSpec);
}
if (turn.sceneSpec.auto_play_presentation && turn.sceneSpec.presentation_key) { if (turn.sceneSpec.auto_play_presentation && turn.sceneSpec.presentation_key) {
onPlayPresentation?.(turn.sceneSpec.presentation_key); onPlayPresentation?.(turn.sceneSpec.presentation_key);
} }
@@ -1663,6 +1704,32 @@ export function initSituationalCopilot({
} }
} }
function findLatestZoneTurn(preferredId = activeZoneTurnId) {
if (preferredId) {
const preferred = turns.find(
(t) => t.id === preferredId && Array.isArray(t.sceneSpec?.influence_zones) && t.sceneSpec.influence_zones.length > 0,
);
if (preferred) return preferred;
}
for (let i = turns.length - 1; i >= 0; i -= 1) {
const candidate = turns[i];
if (Array.isArray(candidate?.sceneSpec?.influence_zones) && candidate.sceneSpec.influence_zones.length > 0) {
return candidate;
}
}
return null;
}
function replayInfluenceZonesForTurn(targetTurn) {
if (!targetTurn?.sceneSpec?.influence_zones?.length) return false;
activeZoneTurnId = targetTurn.id;
activeZonesCount = targetTurn.sceneSpec.influence_zones.length;
targetTurn._lastAppliedSceneKey = null;
syncSceneEffectsForTurn(targetTurn, { scene_spec: targetTurn.sceneSpec });
render();
return true;
}
async function askQuestion(question, { presetOverride = null, newsContextOverride = undefined } = {}) { async function askQuestion(question, { presetOverride = null, newsContextOverride = undefined } = {}) {
const trimmed = String(question || "").trim(); const trimmed = String(question || "").trim();
if (trimmed.length < 2) return; if (trimmed.length < 2) return;
@@ -1672,6 +1739,103 @@ export function initSituationalCopilot({
onPreemptStage?.("user_investigation"); onPreemptStage?.("user_investigation");
inlinePinnedPreviewId = null; inlinePinnedPreviewId = null;
const localZoneCmd = matchLocalInfluenceZoneCommand(trimmed);
if (localZoneCmd) {
const targetTurn = findLatestZoneTurn();
if (localZoneCmd === "show" && targetTurn) {
draftInputValue = "";
const inputEl = panel.querySelector('input[name="question"]');
if (inputEl) inputEl.value = "";
const replayTurnId = `turn-${++turnCounter}`;
replayInfluenceZonesForTurn(targetTurn);
activeZoneTurnId = replayTurnId;
const zoneNames = targetTurn.sceneSpec.influence_zones
.map((z) => z.label || z.id)
.filter(Boolean)
.join("、");
const replayMd = text(
`已从本地直接恢复上一轮影响范围(未重新调用大模型):${zoneNames || `${targetTurn.sceneSpec.influence_zones.length} 个区域`}。`,
`Restored previous influence zones locally without re-running analysis: ${zoneNames || `${targetTurn.sceneSpec.influence_zones.length} zone(s)`}.`,
);
turns.push({
id: replayTurnId,
runId: null,
domain: targetTurn.domain || ctx.domain || "global",
question: trimmed,
newsContext: targetTurn.newsContext || null,
status: "done",
stageText: "",
stageBadge: "",
reply: { answer_markdown: replayMd, evidence_ids: [] },
rawText: replayMd,
rawReasoning: "",
provider: null,
model: null,
generationMode: "local_scene_replay",
thinkingUserToggled: false,
viewSpec: null,
sceneSpec: targetTurn.sceneSpec,
resultId: ctx.resultId,
revision: ctx.revision,
zeroToken: true,
evidence: {},
activeEvidenceId: null,
matrixModeOverride: null,
collapsedBlocks: {},
errorIcon: "error",
errorText: "",
});
if (turns.length > MAX_TURNS) turns = turns.slice(-MAX_TURNS);
void persistCurrentSession();
render({ scrollToBottom: true });
return;
}
if (localZoneCmd === "hide") {
draftInputValue = "";
const inputEl = panel.querySelector('input[name="question"]');
if (inputEl) inputEl.value = "";
activeZoneTurnId = null;
activeZonesCount = 0;
onClearSceneZones?.();
const hideMd = text(
"已关闭当前地球影响范围覆盖层;如需再次查看,可点击上方“显示影响范围”或发送“重新开启范围”。",
"Hid current influence zone overlays; click “Show Zones” above or ask “show zones” to restore.",
);
turns.push({
id: `turn-${++turnCounter}`,
runId: null,
domain: ctx.domain || "global",
question: trimmed,
newsContext: null,
status: "done",
stageText: "",
stageBadge: "",
reply: { answer_markdown: hideMd, evidence_ids: [] },
rawText: hideMd,
rawReasoning: "",
provider: null,
model: null,
generationMode: "local_scene_replay",
thinkingUserToggled: false,
viewSpec: null,
sceneSpec: null,
resultId: ctx.resultId,
revision: ctx.revision,
zeroToken: true,
evidence: {},
activeEvidenceId: null,
matrixModeOverride: null,
collapsedBlocks: {},
errorIcon: "error",
errorText: "",
});
if (turns.length > MAX_TURNS) turns = turns.slice(-MAX_TURNS);
void persistCurrentSession();
render({ scrollToBottom: true });
return;
}
}
const priorHistoryPayload = buildTurnHistoryPayload(turns, { maxMessages: 24 }); const priorHistoryPayload = buildTurnHistoryPayload(turns, { maxMessages: 24 });
const pinnedSummariesPayload = pinnedItems const pinnedSummariesPayload = pinnedItems
.map((p) => `${p.shortLabel}: ${p.title || ""}`.trim()) .map((p) => `${p.shortLabel}: ${p.title || ""}`.trim())
@@ -1971,6 +2135,14 @@ export function initSituationalCopilot({
turn.rawText += delta; turn.rawText += delta;
scheduleStreamRender(); scheduleStreamRender();
}, },
onScene: (sceneEvt) => {
if (myEpoch !== requestEpoch) return;
const nextSceneSpec = sceneEvt?.scene_spec || sceneEvt;
if (nextSceneSpec && typeof nextSceneSpec === "object") {
turn.sceneSpec = nextSceneSpec;
syncSceneEffectsForTurn(turn, { scene_spec: nextSceneSpec });
}
},
onDone: (done) => { onDone: (done) => {
if (myEpoch !== requestEpoch) return; if (myEpoch !== requestEpoch) return;
clearStreamRenderTimer(); clearStreamRenderTimer();
@@ -2488,6 +2660,24 @@ export function initSituationalCopilot({
return; return;
} }
const toggleZonesBtn = event.target.closest("[data-copilot-toggle-zones]");
if (toggleZonesBtn) {
const tid = toggleZonesBtn.dataset.copilotToggleZones;
const targetTurn = turns.find((t) => t.id === tid) || findLatestZoneTurn(tid);
if (targetTurn) {
const currentlyActive = activeZonesCount > 0 && activeZoneTurnId === targetTurn.id;
if (currentlyActive) {
activeZoneTurnId = null;
activeZonesCount = 0;
onClearSceneZones?.();
render();
} else {
replayInfluenceZonesForTurn(targetTurn);
}
}
return;
}
const playKeyBtn = event.target.closest("[data-copilot-play-key]"); const playKeyBtn = event.target.closest("[data-copilot-play-key]");
if (playKeyBtn) { if (playKeyBtn) {
const key = playKeyBtn.dataset.copilotPlayKey; const key = playKeyBtn.dataset.copilotPlayKey;
@@ -2761,12 +2951,24 @@ export function initSituationalCopilot({
return startNewSession(); return startNewSession();
}, },
cancelActiveRun, cancelActiveRun,
syncActiveZonesState(state) {
const nextCount = Number(state?.zoneCount || 0);
const changed = nextCount !== activeZonesCount;
activeZonesCount = nextCount;
if (nextCount === 0) {
activeZoneTurnId = null;
}
if (changed && !panel.hidden) {
render();
}
},
close() { close() {
cancelActiveRun(); cancelActiveRun();
basisMenu.close(); basisMenu.close();
panel.hidden = true; panel.hidden = true;
pinnedSlot.hidden = true; pinnedSlot.hidden = true;
onOpenStateChange?.(false); onOpenStateChange?.(false);
onClearSceneZones?.();
onReleaseStage?.(); onReleaseStage?.();
}, },
isOpen() { isOpen() {
@@ -3,6 +3,7 @@ import { createTimeBasisMenu } from "./hud-select-menu.js";
import { createCopilotStore } from "./copilot-store.js"; import { createCopilotStore } from "./copilot-store.js";
import { import {
initSituationalCopilot, initSituationalCopilot,
matchLocalInfluenceZoneCommand,
normalizeCopilotMarkdown, normalizeCopilotMarkdown,
renderSafeMarkdown, renderSafeMarkdown,
} from "./situational-copilot.js"; } from "./situational-copilot.js";
@@ -1768,4 +1769,17 @@ describe("Shared HUD Select Menu for Time Basis", () => {
globalThis.window = prevWin; globalThis.window = prevWin;
} }
}); });
it("matches local zero-token influence zone replay/hide commands without intercepting analytical queries", () => {
expect(matchLocalInfluenceZoneCommand("重新开启范围")).toBe("show");
expect(matchLocalInfluenceZoneCommand("恢复影响范围")).toBe("show");
expect(matchLocalInfluenceZoneCommand("打开之前的范围")).toBe("show");
expect(matchLocalInfluenceZoneCommand("show zones")).toBe("show");
expect(matchLocalInfluenceZoneCommand("关闭范围")).toBe("hide");
expect(matchLocalInfluenceZoneCommand("隐藏影响范围")).toBe("hide");
expect(matchLocalInfluenceZoneCommand("hide zones")).toBe("hide");
expect(matchLocalInfluenceZoneCommand("重新分析中美影响范围")).toBeNull();
expect(matchLocalInfluenceZoneCommand("对比影响范围")).toBeNull();
expect(matchLocalInfluenceZoneCommand("我是说影响地区范围")).toBeNull();
});
}); });
@@ -201,6 +201,7 @@ export function initStageNarrativePlayer({
cancelCameraFlight, cancelCameraFlight,
onComputeStep, onComputeStep,
onLogicalArcs, onLogicalArcs,
onInfluenceZones,
onClearOverlays, onClearOverlays,
onInterruptAmbientCruise, onInterruptAmbientCruise,
onOpenCopilot, onOpenCopilot,
@@ -388,6 +389,7 @@ export function initStageNarrativePlayer({
} else { } else {
onLogicalArcs?.(step.logical_arcs || []); onLogicalArcs?.(step.logical_arcs || []);
} }
onInfluenceZones?.(Array.isArray(step.influence_zones) ? step.influence_zones : []);
if (allowCameraFlight && !reducedMotion && step.camera && flyCamera) { if (allowCameraFlight && !reducedMotion && step.camera && flyCamera) {
await flyCamera({ await flyCamera({
@@ -538,6 +540,7 @@ export function initStageNarrativePlayer({
presentationQueue.clear(); presentationQueue.clear();
sovereignty.release(); sovereignty.release();
onLogicalArcs?.([]); onLogicalArcs?.([]);
onInfluenceZones?.([]);
onClearOverlays?.(); onClearOverlays?.();
renderBar(); renderBar();
} }
+323
View File
@@ -0,0 +1,323 @@
import * as THREE from "three";
const DEFAULT_RESOLUTION = typeof window !== "undefined"
? [window.innerWidth || 1280, window.innerHeight || 720]
: [1280, 720];
const activeRibbonMaterials = new Set();
export function registerRibbonMaterial(material) {
if (!material) return material;
activeRibbonMaterials.add(material);
if (!material.userData?.__ribbonDisposeHooked) {
const originalDispose = material.dispose?.bind(material);
material.userData = { ...(material.userData || {}), __ribbonDisposeHooked: true };
material.dispose = () => {
activeRibbonMaterials.delete(material);
if (originalDispose) originalDispose();
};
}
return material;
}
export function unregisterRibbonMaterial(material) {
activeRibbonMaterials.delete(material);
}
export function updateAllRibbonResolutions(width, height) {
const w = Math.max(1, Number(width) || 1280);
const h = Math.max(1, Number(height) || 720);
DEFAULT_RESOLUTION[0] = w;
DEFAULT_RESOLUTION[1] = h;
for (const mat of activeRibbonMaterials) {
if (mat?.uniforms?.uResolution?.value) {
mat.uniforms.uResolution.value.set(w, h);
}
}
}
export function getActiveRibbonMaterialCount() {
return activeRibbonMaterials.size;
}
const SURFACE_RIBBON_VERTEX_SHADER = `
attribute vec3 aPrev;
attribute vec3 aNext;
attribute float aSide;
attribute float aProgress;
uniform vec2 uResolution;
uniform float uHalfWidthPx;
varying float vSide;
varying float vProgress;
vec2 clipToScreenPx(vec4 clip, vec2 res) {
float safeW = max(abs(clip.w), 0.001);
return (clip.xy / safeW) * (res * 0.5);
}
void main() {
vSide = aSide;
vProgress = aProgress;
vec4 clipCurr = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
vec4 clipPrev = projectionMatrix * modelViewMatrix * vec4(aPrev, 1.0);
vec4 clipNext = projectionMatrix * modelViewMatrix * vec4(aNext, 1.0);
vec2 res = max(uResolution, vec2(1.0, 1.0));
vec2 pxCurr = clipToScreenPx(clipCurr, res);
vec2 pxPrev = clipToScreenPx(clipPrev, res);
vec2 pxNext = clipToScreenPx(clipNext, res);
vec2 deltaNext = pxNext - pxCurr;
vec2 deltaPrev = pxCurr - pxPrev;
vec2 dir = vec2(0.0, 0.0);
if (dot(deltaNext, deltaNext) > 0.0001) {
dir += normalize(deltaNext);
}
if (dot(deltaPrev, deltaPrev) > 0.0001) {
dir += normalize(deltaPrev);
}
if (dot(dir, dir) < 0.0001) {
dir = vec2(1.0, 0.0);
} else {
dir = normalize(dir);
}
vec2 normalPx = vec2(-dir.y, dir.x);
vec2 offsetPx = normalPx * aSide * uHalfWidthPx;
float wGuard = max(abs(clipCurr.w), 0.001);
clipCurr.xy += (offsetPx / (res * 0.5)) * wGuard;
gl_Position = clipCurr;
}
`;
const SURFACE_RIBBON_FRAGMENT_SHADER = `
uniform vec3 uColor;
uniform vec3 uGlowColor;
uniform vec3 uUnderlayColor;
uniform float uUnderlayOpacity;
uniform float uOpacity;
uniform float uTime;
uniform float uPulseSpeed;
uniform float uPulseFreq;
uniform float uPulseIntensity;
uniform float uReveal;
uniform float uTailFade;
varying float vSide;
varying float vProgress;
void main() {
float revealEdge = smoothstep(uReveal + 0.015, max(0.0, uReveal - 0.06), vProgress);
if (revealEdge < 0.004) discard;
float d = clamp(abs(vSide), 0.0, 1.0);
float core = 1.0 - smoothstep(0.0, 0.36, d);
float halo = exp(-d * d * 3.8) * (1.0 - smoothstep(0.76, 1.0, d));
float phase = fract(vProgress * uPulseFreq - uTime * uPulseSpeed);
float pulse = pow(max(0.0, 1.0 - abs(phase - 0.5) * 3.2), 2.4) * uPulseIntensity;
float launchFlare = 0.0;
if (uReveal < 0.995) {
float headDist = abs(vProgress - uReveal);
launchFlare = exp(-(headDist * headDist) / 0.002) * 0.85;
}
float tailWeight = mix(1.0, smoothstep(0.0, 0.82, vProgress), clamp(uTailFade, 0.0, 1.0));
vec3 rgb = mix(uGlowColor, uColor, clamp(core * 0.92, 0.0, 1.0)) + uGlowColor * (pulse * 0.72 + launchFlare);
float alpha = clamp((core * 0.96 + halo * 0.58 + pulse * 0.44 + launchFlare * 0.55) * uOpacity * tailWeight * revealEdge, 0.0, 1.0);
if (uUnderlayOpacity > 0.001) {
float underlayBand = (1.0 - smoothstep(0.20, 0.62, d)) * uUnderlayOpacity * tailWeight * revealEdge;
float outAlpha = clamp(alpha + underlayBand * (1.0 - alpha), 0.0, 1.0);
if (outAlpha < 0.004) discard;
vec3 outRgb = (rgb * alpha + uUnderlayColor * underlayBand * (1.0 - alpha)) / max(outAlpha, 0.001);
gl_FragColor = vec4(outRgb, outAlpha);
} else {
if (alpha < 0.004) discard;
gl_FragColor = vec4(rgb, alpha);
}
#include <colorspace_fragment>
}
`;
function normalizePolylineList(polylines) {
if (!Array.isArray(polylines) || polylines.length === 0) return [];
const first = polylines[0];
if (first && (Array.isArray(first) || (first.length !== undefined && typeof first[0] === "object"))) {
return polylines.filter(p => Array.isArray(p) && p.length >= 2);
}
return polylines.length >= 2 ? [polylines] : [];
}
/**
* Build an indexed screen-space ribbon BufferGeometry from one polyline or an array of polylines.
*/
export function createSurfaceRibbonGeometry(polylines) {
const lines = normalizePolylineList(polylines);
const geometry = new THREE.BufferGeometry();
if (lines.length === 0) {
geometry.setAttribute("position", new THREE.Float32BufferAttribute([], 3));
geometry.setAttribute("aPrev", new THREE.Float32BufferAttribute([], 3));
geometry.setAttribute("aNext", new THREE.Float32BufferAttribute([], 3));
geometry.setAttribute("aSide", new THREE.Float32BufferAttribute([], 1));
geometry.setAttribute("aProgress", new THREE.Float32BufferAttribute([], 1));
return geometry;
}
let totalVertices = 0;
let totalIndices = 0;
const lineInfos = [];
for (const rawPoints of lines) {
const clean = [];
for (const pt of rawPoints) {
if (!pt || !Number.isFinite(pt.x) || !Number.isFinite(pt.y) || !Number.isFinite(pt.z)) continue;
if (clean.length > 0 && clean[clean.length - 1].distanceToSquared(pt) < 1e-10) continue;
clean.push(new THREE.Vector3(pt.x, pt.y, pt.z));
}
if (clean.length < 2) continue;
const cumLen = new Float32Array(clean.length);
let totalLen = 0;
for (let i = 1; i < clean.length; i += 1) {
totalLen += clean[i].distanceTo(clean[i - 1]);
cumLen[i] = totalLen;
}
const denom = totalLen > 1e-6 ? totalLen : 1;
lineInfos.push({ clean, cumLen, denom });
totalVertices += clean.length * 2;
totalIndices += (clean.length - 1) * 6;
}
if (lineInfos.length === 0) {
geometry.setAttribute("position", new THREE.Float32BufferAttribute([], 3));
geometry.setAttribute("aPrev", new THREE.Float32BufferAttribute([], 3));
geometry.setAttribute("aNext", new THREE.Float32BufferAttribute([], 3));
geometry.setAttribute("aSide", new THREE.Float32BufferAttribute([], 1));
geometry.setAttribute("aProgress", new THREE.Float32BufferAttribute([], 1));
return geometry;
}
const positions = new Float32Array(totalVertices * 3);
const prevs = new Float32Array(totalVertices * 3);
const nexts = new Float32Array(totalVertices * 3);
const sides = new Float32Array(totalVertices);
const progresses = new Float32Array(totalVertices);
const indices = totalVertices > 65535
? new Uint32Array(totalIndices)
: new Uint16Array(totalIndices);
let vCursor = 0;
let iCursor = 0;
for (const { clean, cumLen, denom } of lineInfos) {
const baseVertex = vCursor;
for (let i = 0; i < clean.length; i += 1) {
const curr = clean[i];
const prev = clean[Math.max(0, i - 1)];
const next = clean[Math.min(clean.length - 1, i + 1)];
const progress = cumLen[i] / denom;
for (const side of [-1, 1]) {
const pIdx = vCursor * 3;
positions[pIdx] = curr.x;
positions[pIdx + 1] = curr.y;
positions[pIdx + 2] = curr.z;
prevs[pIdx] = prev.x;
prevs[pIdx + 1] = prev.y;
prevs[pIdx + 2] = prev.z;
nexts[pIdx] = next.x;
nexts[pIdx + 1] = next.y;
nexts[pIdx + 2] = next.z;
sides[vCursor] = side;
progresses[vCursor] = progress;
vCursor += 1;
}
if (i < clean.length - 1) {
const a = baseVertex + i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
indices[iCursor++] = a;
indices[iCursor++] = b;
indices[iCursor++] = c;
indices[iCursor++] = b;
indices[iCursor++] = d;
indices[iCursor++] = c;
}
}
}
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("aPrev", new THREE.BufferAttribute(prevs, 3));
geometry.setAttribute("aNext", new THREE.BufferAttribute(nexts, 3));
geometry.setAttribute("aSide", new THREE.BufferAttribute(sides, 1));
geometry.setAttribute("aProgress", new THREE.BufferAttribute(progresses, 1));
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
geometry.computeBoundingSphere();
return geometry;
}
/**
* Create a GLSL ES 1.00 screen-space width glowing ribbon ShaderMaterial.
*/
export function createSurfaceRibbonMaterial({
color = 0x38bdf8,
glowColor = null,
underlayColor = 0x060c18,
underlayOpacity = 0.0,
halfWidthPx = 4.0,
opacity = 0.9,
pulseSpeed = 0.55,
pulseFreq = 2.0,
pulseIntensity = 0.45,
reveal = 1.0,
tailFade = 0.0,
additive = true,
depthTest = true,
depthWrite = false,
resolution = DEFAULT_RESOLUTION,
} = {}) {
const baseColor = color instanceof THREE.Color ? color.clone() : new THREE.Color(color);
const rimColor = glowColor
? (glowColor instanceof THREE.Color ? glowColor.clone() : new THREE.Color(glowColor))
: baseColor.clone().lerp(new THREE.Color(0xffffff), 0.42);
const darkUnderlayColor = underlayColor instanceof THREE.Color
? underlayColor.clone()
: new THREE.Color(underlayColor);
const material = new THREE.ShaderMaterial({
uniforms: {
uResolution: { value: new THREE.Vector2(resolution[0] || 1280, resolution[1] || 720) },
uHalfWidthPx: { value: Number(halfWidthPx) || 4.0 },
uColor: { value: baseColor },
uGlowColor: { value: rimColor },
uUnderlayColor: { value: darkUnderlayColor },
uUnderlayOpacity: { value: Number.isFinite(underlayOpacity) ? underlayOpacity : 0.0 },
uOpacity: { value: Number.isFinite(opacity) ? opacity : 0.9 },
uTime: { value: 0.0 },
uPulseSpeed: { value: Number(pulseSpeed) || 0.0 },
uPulseFreq: { value: Number(pulseFreq) || 1.0 },
uPulseIntensity: { value: Number(pulseIntensity) || 0.0 },
uReveal: { value: Number.isFinite(reveal) ? reveal : 1.0 },
uTailFade: { value: Number(tailFade) || 0.0 },
},
vertexShader: SURFACE_RIBBON_VERTEX_SHADER,
fragmentShader: SURFACE_RIBBON_FRAGMENT_SHADER,
transparent: true,
depthTest,
depthWrite,
side: THREE.DoubleSide,
blending: additive ? THREE.AdditiveBlending : THREE.NormalBlending,
toneMapped: false,
});
return registerRibbonMaterial(material);
}
@@ -0,0 +1,55 @@
import { describe, expect, it } from "bun:test";
import * as THREE from "three";
import {
createSurfaceRibbonGeometry,
createSurfaceRibbonMaterial,
getActiveRibbonMaterialCount,
updateAllRibbonResolutions,
} from "./surface-ribbon.js";
describe("surface-ribbon GLSL ES 1.00 geometry & material", () => {
it("builds extruded single and multi-polyline ribbon geometry with normalized arc progress", () => {
const single = createSurfaceRibbonGeometry([
new THREE.Vector3(100, 0, 0),
new THREE.Vector3(100, 1, 0),
new THREE.Vector3(100, 4, 0),
]);
expect(single.attributes.position.count).toBe(6);
expect(single.attributes.aSide.array).toEqual(new Float32Array([-1, 1, -1, 1, -1, 1]));
expect(single.attributes.aProgress.array[0]).toBeCloseTo(0);
expect(single.attributes.aProgress.array[2]).toBeCloseTo(0.25);
expect(single.attributes.aProgress.array[4]).toBeCloseTo(1);
expect(single.index.count).toBe(12);
single.dispose();
const multi = createSurfaceRibbonGeometry([
[new THREE.Vector3(10, 0, 0), new THREE.Vector3(12, 0, 0)],
[new THREE.Vector3(0, 10, 0), new THREE.Vector3(0, 13, 0)],
]);
expect(multi.attributes.position.count).toBe(8);
expect(multi.index.count).toBe(12);
multi.dispose();
});
it("tracks active ribbon materials across resolution updates and cleans up on dispose", () => {
const before = getActiveRibbonMaterialCount();
const mat = createSurfaceRibbonMaterial({
color: 0x38bdf8,
halfWidthPx: 5.5,
pulseSpeed: 0.8,
tailFade: 1.0,
});
expect(mat.transparent).toBe(true);
expect(mat.depthWrite).toBe(false);
expect(mat.vertexShader).toContain("max(abs(clip.w), 0.001)");
expect(getActiveRibbonMaterialCount()).toBe(before + 1);
updateAllRibbonResolutions(1920, 1080);
expect(mat.uniforms.uResolution.value.x).toBe(1920);
expect(mat.uniforms.uResolution.value.y).toBe(1080);
mat.dispose();
expect(getActiveRibbonMaterialCount()).toBe(before);
});
});
+15 -6
View File
@@ -4,6 +4,7 @@ import * as THREE from "three";
import { CONFIG, PATHS, VESSEL_CONFIG } from "./constants.js"; import { CONFIG, PATHS, VESSEL_CONFIG } from "./constants.js";
import { createInteractableLayer } from "./interactable.js"; import { createInteractableLayer } from "./interactable.js";
import { latLonToVector3 } from "./utils.js"; import { latLonToVector3 } from "./utils.js";
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
let showVessels = false; let showVessels = false;
let activeTrackLine = null; let activeTrackLine = null;
@@ -474,15 +475,19 @@ export async function showVesselTrack(marker, earth) {
appendCurrentMarkerTrackPoint(points, marker); appendCurrentMarkerTrackPoint(points, marker);
if (points.length < 2) return null; if (points.length < 2) return null;
const geometry = new THREE.BufferGeometry().setFromPoints(points); const geometry = createSurfaceRibbonGeometry(points);
const material = new THREE.LineBasicMaterial({ const material = createSurfaceRibbonMaterial({
color: VESSEL_CONFIG.track.color, color: VESSEL_CONFIG.track.color,
transparent: true, halfWidthPx: 4.2,
opacity: VESSEL_CONFIG.track.opacity, opacity: Math.min(0.95, (VESSEL_CONFIG.track.opacity || 0.7) * 1.15),
depthWrite: false, pulseSpeed: 0.55,
pulseFreq: 2.0,
pulseIntensity: 0.5,
tailFade: 1.0,
}); });
activeTrackLine = new THREE.Line(geometry, material); activeTrackLine = new THREE.Mesh(geometry, material);
activeTrackLine.renderOrder = VESSEL_RENDER_ORDER - 0.1; activeTrackLine.renderOrder = VESSEL_RENDER_ORDER - 0.1;
activeTrackLine.raycast = () => {};
earth.add(activeTrackLine); earth.add(activeTrackLine);
return activeTrackLine; return activeTrackLine;
} }
@@ -500,6 +505,10 @@ export function getVesselLegendItems() {
} }
export function updateVesselVisualState(lockedObjectType, lockedObject, camera) { export function updateVesselVisualState(lockedObjectType, lockedObject, camera) {
if (activeTrackLine?.material?.uniforms?.uTime) {
activeTrackLine.material.uniforms.uTime.value =
(typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001;
}
vesselIconLayer.updateVisualState(lockedObjectType, lockedObject, camera); vesselIconLayer.updateVisualState(lockedObjectType, lockedObject, camera);
} }
+14 -1
View File
@@ -274,6 +274,18 @@ export function closeWorkflowActionPicker() {
} }
} }
export function ensureEarthBottomDock() {
if (typeof document === "undefined" || !document.body) return null;
let dock = document.getElementById("earth-bottom-dock");
if (!dock) {
dock = document.createElement("div");
dock.id = "earth-bottom-dock";
dock.className = "earth-bottom-dock";
document.body.appendChild(dock);
}
return dock;
}
function renderCompareTray() { function renderCompareTray() {
if ( if (
typeof window === "undefined" typeof window === "undefined"
@@ -293,7 +305,8 @@ function renderCompareTray() {
trayEl.id = "earth-target-tray"; trayEl.id = "earth-target-tray";
trayEl.className = "hud-panel earth-target-tray"; trayEl.className = "hud-panel earth-target-tray";
trayEl.setAttribute("aria-label", translateText("多物件联合分析对比栏")); trayEl.setAttribute("aria-label", translateText("多物件联合分析对比栏"));
document.body.appendChild(trayEl); const dock = ensureEarthBottomDock() || document.body;
dock.appendChild(trayEl);
trayEl.addEventListener?.("click", (event) => { trayEl.addEventListener?.("click", (event) => {
event.stopPropagation(); event.stopPropagation();
const target = event.target instanceof Element ? event.target : null; const target = event.target instanceof Element ? event.target : null;
+17 -1
View File
@@ -16,12 +16,16 @@ export function earthRuntimePlugin(root) {
const earth = join(root, 'public/earth') const earth = join(root, 'public/earth')
const require = createRequire(join(root, 'package.json')) const require = createRequire(join(root, 'package.json'))
const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json')) const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json'))
const threeModulePath = join(dirname(require.resolve('three')), 'three.module.js')
let outDir = 'dist' let outDir = 'dist'
let compilation = null let compilation = null
async function compile() { async function compile() {
if (compilation) return compilation if (compilation) return compilation
compilation = compileEarthRuntime({ earthDir: earth }).catch((error) => { compilation = compileEarthRuntime({
earthDir: earth,
importMapOverrides: { three: './vendor/three.module.js' },
}).catch((error) => {
compilation = null compilation = null
throw error throw error
}) })
@@ -41,6 +45,13 @@ export function earthRuntimePlugin(root) {
}) })
server.middlewares.use(async (req, res, next) => { server.middlewares.use(async (req, res, next) => {
const url = (req.url || '').split('?')[0] const url = (req.url || '').split('?')[0]
if (url === '/earth/vendor/three.module.js') {
if (!existsSync(threeModulePath)) return next()
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Content-Type', 'text/javascript; charset=utf-8')
res.end(readFileSync(threeModulePath))
return
}
if (url === '/earth/vendor/mediapipe/vision_bundle.mjs') { if (url === '/earth/vendor/mediapipe/vision_bundle.mjs') {
const filePath = join(mediaPipePkgDir, 'vision_bundle.mjs') const filePath = join(mediaPipePkgDir, 'vision_bundle.mjs')
if (!existsSync(filePath)) return next() if (!existsSync(filePath)) return next()
@@ -93,6 +104,11 @@ export function earthRuntimePlugin(root) {
this.emitFile({ type: 'asset', fileName: 'earth/index.html', source: html }) this.emitFile({ type: 'asset', fileName: 'earth/index.html', source: html })
}, },
closeBundle() { closeBundle() {
const targetThreeDir = resolve(root, outDir, 'earth/vendor')
mkdirSync(targetThreeDir, { recursive: true })
if (existsSync(threeModulePath)) {
cpSync(threeModulePath, join(targetThreeDir, 'three.module.js'))
}
const targetMediaPipeDir = resolve(root, outDir, 'earth/vendor/mediapipe') const targetMediaPipeDir = resolve(root, outDir, 'earth/vendor/mediapipe')
mkdirSync(targetMediaPipeDir, { recursive: true }) mkdirSync(targetMediaPipeDir, { recursive: true })
const bundleSrc = join(mediaPipePkgDir, 'vision_bundle.mjs') const bundleSrc = join(mediaPipePkgDir, 'vision_bundle.mjs')
@@ -155,6 +155,7 @@ interface WorkflowRecord {
published_graph: WorkflowGraphDef published_graph: WorkflowGraphDef
draft_graph: WorkflowGraphDef | null draft_graph: WorkflowGraphDef | null
bindings?: WorkflowBindingsDef bindings?: WorkflowBindingsDef
draft_bindings?: WorkflowBindingsDef | null
} }
interface RevisionRecord { interface RevisionRecord {
@@ -747,7 +748,8 @@ export default function AdvisorWorkflows() {
setEarthSurfaces(Array.isArray(data.earth_surfaces) ? data.earth_surfaces : []) setEarthSurfaces(Array.isArray(data.earth_surfaces) ? data.earth_surfaces : [])
setBindingsState({ setBindingsState({
...EMPTY_BINDINGS, ...EMPTY_BINDINGS,
...(wf.bindings || {}), // Draft bindings ship with the draft graph; the live entry keeps `bindings` until publish.
...((wf.has_draft && wf.draft_bindings) || wf.bindings || {}),
}) })
setWorkflowMeta({ setWorkflowMeta({
name: wf.name || '', name: wf.name || '',
+49 -110
View File
@@ -56,6 +56,16 @@ import { DetailPanel, EmptyState, PageFrame, Panel, StatCell, StatusText, Summar
import { ComputeComparisonSettings } from './ComputeComparisonSettings' import { ComputeComparisonSettings } from './ComputeComparisonSettings'
import { CardImageSettings } from './CardImageSettings' import { CardImageSettings } from './CardImageSettings'
import { ApiKeySettings } from './ApiKeySettings' import { ApiKeySettings } from './ApiKeySettings'
import {
DATASOURCE_SECRET_KEYS as datasourceSecretKeys,
isMaskedSecretDraft,
mapConfigsAllRow,
normalizeDatasourceConfigPayload,
parsePositiveConfigId,
recordContainsSecrets,
redactRawJsonText,
shouldHideDatasourceConfigObjectField,
} from './datasourceConfigHelpers'
import { import {
COLLECTION_QUEUE_ACTIVE_STATUSES, isStaleTaskUpdate, patchCollectionTask, upsertCollectionTask, COLLECTION_QUEUE_ACTIVE_STATUSES, isStaleTaskUpdate, patchCollectionTask, upsertCollectionTask,
type CollectionQueueItem, type CollectionQueueStatus, type CollectionQueueItem, type CollectionQueueStatus,
@@ -1199,59 +1209,6 @@ function targetSchemaRows(payload: unknown) {
})) }))
} }
const datasourceSecretKeys = new Set(['api_key', 'client_secret', 'password', 'token', 'access_token', 'bearer_token'])
const datasourceCredentialObjectKeys = new Set(['auth_config', 'auth_configured'])
function normalizeDatasourceConfigPayload(payload: AnyRecord) {
const next = { ...payload }
const authConfig = isObjectRecord(next.auth_config) ? { ...next.auth_config } : {}
const apiKey = text(next.api_key, '').trim()
const apiKeyName = text(next.api_key_name, '').trim()
const apiKeyLocation = text(next.api_key_location, '').trim()
const clientId = text(next.client_id, '').trim()
const clientSecret = text(next.client_secret, '').trim()
const username = text(next.username, '').trim()
const password = text(next.password, '').trim()
const sourceName = text(next.name || next.source, '').trim()
if (apiKey && !isMaskedSecretDraft(apiKey)) {
authConfig.api_key = apiKey
}
if (clientId) authConfig.client_id = clientId
if (clientSecret && !isMaskedSecretDraft(clientSecret)) authConfig.client_secret = clientSecret
if (username) authConfig.username = username
if (password && !isMaskedSecretDraft(password)) authConfig.password = password
if (apiKeyName) {
authConfig.key_name = apiKeyName
authConfig.param_name = apiKeyName
}
if (apiKeyLocation) authConfig.location = apiKeyLocation
delete next.api_key
delete next.api_key_name
delete next.api_key_location
delete next.client_id
delete next.client_secret
delete next.username
delete next.password
if (sourceName === 'barentswatch_vessels') next.auth_type = 'oauth_client'
if (sourceName === 'spacetrack_tle') next.auth_type = 'basic'
next.auth_config = authConfig
return next
}
function datasourceConfigCredentialKind(record: AnyRecord) {
const provider = text(record.credential_provider, '').toLowerCase()
const name = text(record.name || record.source, '').toLowerCase()
if (provider === 'barentswatch' || name === 'barentswatch_vessels') return 'oauth_client'
if (provider === 'aisstream' || name === 'aisstream_vessels') return 'api_key'
if (provider === 'spacetrack' || name === 'spacetrack_tle') return 'basic'
if (record.requires_credentials || record.api_key !== undefined) return 'api_key'
return ''
}
function shouldHideDatasourceConfigObjectField(record: AnyRecord, endpoint: string, key: string) {
return endpoint === 'configsAll' && datasourceCredentialObjectKeys.has(key) && Boolean(datasourceConfigCredentialKind(record))
}
function credentialGuideProvider(record: AnyRecord) { function credentialGuideProvider(record: AnyRecord) {
const provider = text(record.credential_provider || record.provider, '').trim().toLowerCase() const provider = text(record.credential_provider || record.provider, '').trim().toLowerCase()
if (['barentswatch', 'aisstream'].includes(provider)) return provider if (['barentswatch', 'aisstream'].includes(provider)) return provider
@@ -1259,6 +1216,7 @@ function credentialGuideProvider(record: AnyRecord) {
const name = text(record.source || record.source_id || record.name, '').trim().toLowerCase() const name = text(record.source || record.source_id || record.name, '').trim().toLowerCase()
if (name.includes('barentswatch')) return 'barentswatch' if (name.includes('barentswatch')) return 'barentswatch'
if (name.includes('aisstream')) return 'aisstream' if (name.includes('aisstream')) return 'aisstream'
if (name.includes('spacetrack')) return 'spacetrack'
return name.replace(/\s+/g, '_') return name.replace(/\s+/g, '_')
} }
@@ -2251,15 +2209,6 @@ function isSecretDraftUnchanged(nextSecret: unknown, savedPreview?: unknown, rev
) )
} }
function isMaskedSecretDraft(value: string) {
const draft = value.trim()
if (!draft) return false
if (draft.startsWith('••••') || draft.startsWith('****')) return true
const hyphenIndex = draft.indexOf('-')
const secretPart = hyphenIndex > 0 ? draft.slice(hyphenIndex + 1) : draft
return Boolean(secretPart) && Array.from(secretPart).every((char) => char === '*' || char === '•' || /\s/.test(char))
}
function sanitizeSecretDrafts(payload: AnyRecord, baseline: AnyRecord, keys: string[], revealed: AnyRecord = {}) { function sanitizeSecretDrafts(payload: AnyRecord, baseline: AnyRecord, keys: string[], revealed: AnyRecord = {}) {
const next = { ...payload } const next = { ...payload }
keys.forEach((key) => { keys.forEach((key) => {
@@ -4271,12 +4220,15 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
} }
const fetchCustomSample = async (record: TableRecord) => { const fetchCustomSample = async (record: TableRecord) => {
const id = pick(record, ['config_id', 'id', 'source_id', 'key', 'name'], '') const configId = parsePositiveConfigId(pick(record, ['config_id', 'id'], ''))
if (!id) return if (!configId) {
toast({ title: '请先保存自定义数据源配置', description: '内置采集器或未保存草稿不支持自定义映射采样。', tone: 'error' })
return
}
setActionLoading(true) setActionLoading(true)
try { try {
const response = await axios.post(apiPath('/datasources/configs/custom/sample'), { const response = await axios.post(apiPath('/datasources/custom/sample'), {
datasource_config_id: Number(id), datasource_config_id: configId,
}) })
replaceSelectedWithPayload('custom-sample', '采样数据', [{ replaceSelectedWithPayload('custom-sample', '采样数据', [{
...response.data, ...response.data,
@@ -6436,10 +6388,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
{config === configs.collection && activeSection.key === 'collector_credentials' && activeSourceEndpoint === 'configsAll' && activeTableRecord && !activeGroup?.record.__isDraft ? ( {config === configs.collection && activeSection.key === 'collector_credentials' && activeSourceEndpoint === 'configsAll' && activeTableRecord && !activeGroup?.record.__isDraft ? (
<> <>
<Button size="icon" variant="subtle" icon="connect" title="连接测试" aria-label="连接测试" onClick={() => void testDatasourceConfigDraft(record, { builtin: true })} loading={actionLoading} /> <Button size="icon" variant="subtle" icon="connect" title="连接测试" aria-label="连接测试" onClick={() => void testDatasourceConfigDraft(record, { builtin: true })} loading={actionLoading} />
<Button size="icon" variant="subtle" title="采样" aria-label="采样" onClick={() => void fetchCustomSample(activeTableRecord)} loading={actionLoading}><Search size={15} /></Button>
<Button size="icon" variant="subtle" icon="start" title="运行" aria-label="运行" onClick={() => void requestAction('启动采集', 'post', `/datasources/${encodeURIComponent(pick(activeGroup?.record || {}, ['config_id', 'id', 'source_id', 'key', 'name'], ''))}/run-mapped`, undefined, { refresh: false, successDescription: '采集任务已提交,当前配置未保存。' })} loading={actionLoading} />
<Button size="icon" variant="danger" icon="stop" title="停止" aria-label="停止" onClick={() => void requestAction('停止采集', 'post', `/datasources/${encodeURIComponent(pick(activeGroup?.record || {}, ['config_id', 'id', 'source_id', 'key', 'name'], ''))}/stop-mapped`, undefined, { refresh: false, successDescription: '停止请求已提交,当前配置未保存。' })} loading={actionLoading} />
<Button size="icon" variant="subtle" title="运行状态" aria-label="运行状态" onClick={() => void loadStreamStatus(activeTableRecord)} loading={actionLoading}><RefreshCw size={15} /></Button>
</> </>
) : null} ) : null}
{config === configs.collection && ((activeSection.key === 'mappings') || (activeSection.key === 'collector_credentials' && activeSourceEndpoint === 'mappings')) && !activeGroup?.record.__isDraft ? ( {config === configs.collection && ((activeSection.key === 'mappings') || (activeSection.key === 'collector_credentials' && activeSourceEndpoint === 'mappings')) && !activeGroup?.record.__isDraft ? (
@@ -6702,12 +6650,21 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
) : ( ) : (
<FieldGrid record={activeGroup.record} draft={hierarchyDraft} onDraftChange={setHierarchyDraft} fields={editableFields} searchGroupKey={activeGroup.key} /> <FieldGrid record={activeGroup.record} draft={hierarchyDraft} onDraftChange={setHierarchyDraft} fields={editableFields} searchGroupKey={activeGroup.key} />
)} )}
{config === configs.collection && activeSection.key === 'collection_history' ? null : ( {config === configs.collection && activeSection.key === 'collection_history' ? null : (() => {
<details className="an-advanced-editor"> const rawSensitive = isObjectRecord(activeGroup.record) && recordContainsSecrets(activeGroup.record)
<summary>元数据 / 原始字段</summary> const rawValue = hierarchyDraft || formatRaw(activeGroup.record)
<Textarea value={hierarchyDraft || formatRaw(activeGroup.record)} onChange={(event) => setHierarchyDraft(event.target.value)} spellCheck={false} /> return (
</details> <details className="an-advanced-editor">
)} <summary>元数据 / 原始字段</summary>
<Textarea
value={rawSensitive ? redactRawJsonText(rawValue, activeGroup.record) : rawValue}
readOnly={rawSensitive}
onChange={rawSensitive ? undefined : (event) => setHierarchyDraft(event.target.value)}
spellCheck={false}
/>
</details>
)
})()}
</div> </div>
) : <EmptyState title={isPlaceholderSection(activeSection.key) ? localizeAdminText('暂未接入数据', locale) : localizeAdminText('暂无分组', locale)} description={isPlaceholderSection(activeSection.key) ? localizeAdminText('该功能模块尚未提供配置接口。', locale) : localizeAdminText('当前分区没有可配置项。', locale)} />} ) : <EmptyState title={isPlaceholderSection(activeSection.key) ? localizeAdminText('暂未接入数据', locale) : localizeAdminText('暂无分组', locale)} description={isPlaceholderSection(activeSection.key) ? localizeAdminText('该功能模块尚未提供配置接口。', locale) : localizeAdminText('当前分区没有可配置项。', locale)} />}
</Scrollbar> </Scrollbar>
@@ -6792,18 +6749,22 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
actions.push( actions.push(
<Button key="save-config" variant="primary" onClick={saveAdvancedJson} loading={actionLoading}><Save size={15} />保存</Button>, <Button key="save-config" variant="primary" onClick={saveAdvancedJson} loading={actionLoading}><Save size={15} />保存</Button>,
<Button key="test-config" size="icon" variant="subtle" icon="connect" onClick={() => void testDatasourceConfigDraft(cleanRecord(selected), { builtin: useBuiltinConnectivity })} loading={actionLoading} title="连接测试" aria-label="连接测试" />, <Button key="test-config" size="icon" variant="subtle" icon="connect" onClick={() => void testDatasourceConfigDraft(cleanRecord(selected), { builtin: useBuiltinConnectivity })} loading={actionLoading} title="连接测试" aria-label="连接测试" />,
<Button key="sample-config" size="icon" variant="subtle" icon="sample" onClick={() => void fetchCustomSample(selected)} loading={actionLoading} title="采样" aria-label="采样" />,
<Button key="run-config" size="icon" variant="subtle" icon="start" onClick={() => void requestAction('启动采集', 'post', `/datasources/${encodeURIComponent(id)}/run-mapped`, undefined, { refresh: false, successDescription: '采集任务已提交,当前配置未保存。' })} loading={actionLoading} title="运行" aria-label="运行" />,
<Button key="stop-config" size="icon" variant="danger" icon="stop" onClick={() => void requestAction('停止采集', 'post', `/datasources/${encodeURIComponent(id)}/stop-mapped`, undefined, { refresh: false, successDescription: '停止请求已提交,当前配置未保存。' })} loading={actionLoading} title="停止" aria-label="停止" />,
<Button key="stream-status" size="icon" variant="subtle" icon="status" onClick={() => void loadStreamStatus(selected)} loading={actionLoading} title="状态" aria-label="状态" />,
<Button key="delete-config" variant="danger" onClick={() => setConfirmAction({
title: '删除采集配置',
description: `确认删除 ${recordTitle(selected)}?`,
danger: true,
confirmLabel: '删除',
run: () => requestAction('删除采集配置', 'delete', `/datasources/configs/${encodeURIComponent(id)}`),
})} loading={actionLoading}><Trash2 size={15} />删除</Button>,
) )
if (!useBuiltinConnectivity) {
actions.push(
<Button key="sample-config" size="icon" variant="subtle" icon="sample" onClick={() => void fetchCustomSample(selected)} loading={actionLoading} title="采样" aria-label="采样" />,
<Button key="run-config" size="icon" variant="subtle" icon="start" onClick={() => void requestAction('启动采集', 'post', `/datasources/${encodeURIComponent(id)}/run-mapped`, undefined, { refresh: false, successDescription: '采集任务已提交,当前配置未保存。' })} loading={actionLoading} title="运行" aria-label="运行" />,
<Button key="stop-config" size="icon" variant="danger" icon="stop" onClick={() => void requestAction('停止采集', 'post', `/datasources/${encodeURIComponent(id)}/stop-mapped`, undefined, { refresh: false, successDescription: '停止请求已提交,当前配置未保存。' })} loading={actionLoading} title="停止" aria-label="停止" />,
<Button key="stream-status" size="icon" variant="subtle" icon="status" onClick={() => void loadStreamStatus(selected)} loading={actionLoading} title="状态" aria-label="状态" />,
<Button key="delete-config" variant="danger" onClick={() => setConfirmAction({
title: '删除采集配置',
description: `确认删除 ${recordTitle(selected)}?`,
danger: true,
confirmLabel: '删除',
run: () => requestAction('删除采集配置', 'delete', `/datasources/configs/${encodeURIComponent(id)}`),
})} loading={actionLoading}><Trash2 size={15} />删除</Button>,
)
}
} }
if (config === configs.collection && endpointKey === 'mappings' && id) { if (config === configs.collection && endpointKey === 'mappings' && id) {
@@ -7867,29 +7828,7 @@ const configs = {
label: '采集器', label: '采集器',
map: (payload) => dataArray(payload), map: (payload) => dataArray(payload),
endpoints: [ endpoints: [
{ key: 'configsAll', label: '采集器配置', url: '/datasources/configs/all', map: (payload) => dataArray(payload).map((row) => ({ { key: 'configsAll', label: '采集器配置', url: '/datasources/configs/all', map: (payload) => dataArray(payload).map((row) => mapConfigsAllRow(row)) },
...row,
...(datasourceConfigCredentialKind(row) === 'oauth_client' ? {
client_id: text(objectAt(row, 'auth_config').client_id, ''),
client_secret: Boolean(objectAt(row, 'auth_configured').client_secret) ? '••••••••' : '',
} : datasourceConfigCredentialKind(row) === 'basic' ? {
username: text(objectAt(row, 'auth_config').username, ''),
password: Boolean(objectAt(row, 'auth_configured').password) ? '••••••••' : '',
} : {
api_key: Boolean(objectAt(row, 'auth_configured').api_key) ? '••••••••' : '',
api_key_name: text(objectAt(row, 'auth_config').key_name || objectAt(row, 'auth_config').param_name, 'X-API-Key'),
api_key_location: text(objectAt(row, 'auth_config').location || objectAt(row, 'auth_config').in, 'header'),
}),
auth_type: row.name === 'barentswatch_vessels' ? 'oauth_client' : row.name === 'spacetrack_tle' ? 'basic' : row.auth_type,
__module: '采集器配置',
__status: row.requires_credentials && datasourceConfigCredentialKind(row) === 'oauth_client' && (!objectAt(row, 'auth_config').client_id || !objectAt(row, 'auth_configured').client_secret)
? '未配置'
: row.requires_credentials && datasourceConfigCredentialKind(row) === 'basic' && (!objectAt(row, 'auth_config').username || !objectAt(row, 'auth_configured').password)
? '未配置'
: row.requires_credentials && datasourceConfigCredentialKind(row) === 'api_key' && !objectAt(row, 'auth_configured').api_key
? '未配置'
: row.is_active ? '已配置' : '未启用',
})) },
{ key: 'mappings', label: '映射模板', url: '/datasources/mappings', map: mappingRows }, { key: 'mappings', label: '映射模板', url: '/datasources/mappings', map: mappingRows },
{ key: 'targetSchemas', label: '目标 Schema', url: '/datasources/target-schemas', map: targetSchemaRows }, { key: 'targetSchemas', label: '目标 Schema', url: '/datasources/target-schemas', map: targetSchemaRows },
], ],
@@ -0,0 +1,179 @@
type AnyRecord = Record<string, unknown>
export const DATASOURCE_SECRET_KEYS = new Set([
'api_key',
'client_secret',
'password',
'token',
'access_token',
'bearer_token',
])
const RAW_REDACT_SECRET_KEYS = new Set([
...DATASOURCE_SECRET_KEYS,
'service_token',
])
const DATASOURCE_CREDENTIAL_OBJECT_KEYS = new Set(['auth_config', 'auth_configured'])
function asRecord(value: unknown): AnyRecord {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as AnyRecord) : {}
}
function asText(value: unknown, fallback = ''): string {
if (typeof value === 'string') return value
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
return fallback
}
export function isMaskedSecretDraft(value: string): boolean {
const draft = value.trim()
if (!draft) return false
if (draft.startsWith('••••') || draft.startsWith('****')) return true
const hyphenIndex = draft.indexOf('-')
const secretPart = hyphenIndex > 0 ? draft.slice(hyphenIndex + 1) : draft
return Boolean(secretPart) && Array.from(secretPart).every((char) => char === '*' || char === '•' || /\s/.test(char))
}
export function datasourceConfigCredentialKind(record: AnyRecord): 'oauth_client' | 'api_key' | 'basic' | '' {
const provider = asText(record.credential_provider, '').toLowerCase()
const name = asText(record.name || record.source, '').toLowerCase()
if (provider === 'barentswatch' || name === 'barentswatch_vessels') return 'oauth_client'
if (provider === 'aisstream' || name === 'aisstream_vessels') return 'api_key'
if (provider === 'spacetrack' || name === 'spacetrack_tle') return 'basic'
if (record.requires_credentials || record.api_key !== undefined) return 'api_key'
return ''
}
export function shouldHideDatasourceConfigObjectField(record: AnyRecord, endpoint: string, key: string): boolean {
return endpoint === 'configsAll' && DATASOURCE_CREDENTIAL_OBJECT_KEYS.has(key) && Boolean(datasourceConfigCredentialKind(record))
}
export function normalizeDatasourceConfigPayload(payload: AnyRecord): AnyRecord {
const next: AnyRecord = { ...payload }
const authConfig = { ...asRecord(next.auth_config) }
const apiKey = asText(next.api_key, '').trim()
const apiKeyName = asText(next.api_key_name, '').trim()
const apiKeyLocation = asText(next.api_key_location, '').trim()
const clientId = asText(next.client_id, '').trim()
const clientSecret = asText(next.client_secret, '').trim()
const username = asText(next.username, '').trim()
const password = asText(next.password, '').trim()
const sourceName = asText(next.name || next.source, '').trim()
if (apiKey && !isMaskedSecretDraft(apiKey)) {
authConfig.api_key = apiKey
}
if (clientId) authConfig.client_id = clientId
if (clientSecret && !isMaskedSecretDraft(clientSecret)) authConfig.client_secret = clientSecret
if (username) authConfig.username = username
if (password && !isMaskedSecretDraft(password)) authConfig.password = password
if (apiKeyName) {
authConfig.key_name = apiKeyName
authConfig.param_name = apiKeyName
}
if (apiKeyLocation) authConfig.location = apiKeyLocation
delete next.api_key
delete next.api_key_name
delete next.api_key_location
delete next.client_id
delete next.client_secret
delete next.username
delete next.password
if (sourceName === 'barentswatch_vessels') next.auth_type = 'oauth_client'
if (sourceName === 'spacetrack_tle') next.auth_type = 'basic'
if (sourceName === 'aisstream_vessels') next.auth_type = 'api_key'
next.auth_config = authConfig
return next
}
export function mapConfigsAllRow(row: AnyRecord): AnyRecord {
const kind = datasourceConfigCredentialKind(row)
const authConfig = asRecord(row.auth_config)
const authConfigured = asRecord(row.auth_configured)
const credentialFields: AnyRecord = kind === 'oauth_client'
? {
client_id: asText(authConfig.client_id, ''),
client_secret: authConfigured.client_secret ? '••••••••' : '',
}
: kind === 'basic'
? {
username: asText(authConfig.username, ''),
password: authConfigured.password ? '••••••••' : '',
}
: kind === 'api_key'
? {
api_key: authConfigured.api_key ? '••••••••' : '',
api_key_name: asText(authConfig.key_name || authConfig.param_name, 'X-API-Key'),
api_key_location: asText(authConfig.location || authConfig.in, 'header'),
}
: {}
const authType = row.name === 'barentswatch_vessels'
? 'oauth_client'
: row.name === 'spacetrack_tle'
? 'basic'
: row.name === 'aisstream_vessels'
? 'api_key'
: row.auth_type
const missingCreds = Boolean(row.requires_credentials) && (
(kind === 'oauth_client' && (!authConfig.client_id || !authConfigured.client_secret))
|| (kind === 'basic' && (!authConfig.username || !authConfigured.password))
|| (kind === 'api_key' && !authConfigured.api_key)
)
return {
...row,
...credentialFields,
auth_type: authType,
__module: '采集器配置',
__status: missingCreds ? '未配置' : row.is_active ? '已配置' : '未启用',
}
}
export function recordContainsSecrets(value: unknown, parentKey = ''): boolean {
if (!value || typeof value !== 'object') return false
if (Array.isArray(value)) return value.some((item) => recordContainsSecrets(item, parentKey))
if (parentKey === 'auth_configured') return false
return Object.entries(value as AnyRecord).some(([key, entryVal]) => {
if (RAW_REDACT_SECRET_KEYS.has(key)) return true
if (entryVal && typeof entryVal === 'object') return recordContainsSecrets(entryVal, key)
return false
})
}
export function redactRecordSecrets(value: unknown, parentKey = ''): unknown {
if (Array.isArray(value)) {
return value.map((item) => redactRecordSecrets(item, parentKey))
}
if (!value || typeof value !== 'object') return value
if (parentKey === 'auth_configured') return { ...(value as AnyRecord) }
const out: AnyRecord = {}
for (const [key, entryVal] of Object.entries(value as AnyRecord)) {
if (RAW_REDACT_SECRET_KEYS.has(key)) {
out[key] = typeof entryVal === 'string' && entryVal.trim() ? '••••••••' : ''
} else if (entryVal && typeof entryVal === 'object') {
out[key] = redactRecordSecrets(entryVal, key)
} else {
out[key] = entryVal
}
}
return out
}
export function redactRawJsonText(rawText: string, fallbackRecord: AnyRecord): string {
try {
const parsed = JSON.parse(rawText) as unknown
if (parsed && typeof parsed === 'object') {
return JSON.stringify(redactRecordSecrets(parsed), null, 2)
}
} catch {
// Fall back to redacting the baseline record when draft JSON is temporarily unparseable.
}
return JSON.stringify(redactRecordSecrets(fallbackRecord), null, 2)
}
export function parsePositiveConfigId(rawId: unknown): number | null {
const num = Number(rawId)
return Number.isInteger(num) && num > 0 ? num : null
}
@@ -0,0 +1,65 @@
import { describe, expect, test } from 'bun:test'
import {
datasourceConfigCredentialKind,
mapConfigsAllRow,
normalizeDatasourceConfigPayload,
parsePositiveConfigId,
recordContainsSecrets,
redactRawJsonText,
} from '../src/admin/pages/datasourceConfigHelpers'
describe('datasourceConfigHelpers', () => {
test('sets auth_type=oauth_client and omits masked secrets for barentswatch_vessels', () => {
const normalized = normalizeDatasourceConfigPayload({
name: 'barentswatch_vessels',
source_type: 'api',
endpoint: 'https://live.ais.barentswatch.no/v1/latest/combined',
client_id: 'user@example.com:client',
client_secret: '••••••••',
auth_type: 'none',
})
expect(normalized.auth_type).toBe('oauth_client')
expect(normalized.client_id).toBeUndefined()
expect(normalized.client_secret).toBeUndefined()
expect(normalized.auth_config).toEqual({ client_id: 'user@example.com:client' })
})
test('free built-in collectors do not receive bogus api_key fields', () => {
const mapped = mapConfigsAllRow({
name: 'bgpstream_bgp',
requires_credentials: false,
credential_provider: null,
endpoint: 'https://broker.bgpstream.caida.org/v2',
auth_type: 'none',
is_active: true,
auth_config: {},
auth_configured: {},
})
expect(mapped.api_key).toBeUndefined()
expect(mapped.api_key_name).toBeUndefined()
expect(mapped.api_key_location).toBeUndefined()
expect(datasourceConfigCredentialKind(mapped)).toBe('')
})
test('redacts plaintext secrets from raw metadata text while preserving boolean flags', () => {
const draftRecord = {
name: 'barentswatch_vessels',
requires_credentials: true,
client_id: 'qklovehs@hotmail.com:planet-collector',
client_secret: 'super-secret-value',
auth_configured: { client_id: true, client_secret: false },
}
expect(recordContainsSecrets(draftRecord)).toBe(true)
const redacted = JSON.parse(redactRawJsonText(JSON.stringify(draftRecord), draftRecord))
expect(redacted.client_secret).toBe('••••••••')
expect(redacted.client_id).toBe('qklovehs@hotmail.com:planet-collector')
expect(redacted.auth_configured.client_secret).toBe(false)
})
test('validates saved config IDs before custom sample POST', () => {
expect(parsePositiveConfigId(12)).toBe(12)
expect(parsePositiveConfigId('7')).toBe(7)
expect(parsePositiveConfigId('bgpstream_bgp')).toBeNull()
expect(parsePositiveConfigId(null)).toBeNull()
})
})
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "planet" name = "planet"
version = "0.82.0" version = "0.83.0"
description = "智能星球计划 - 态势感知系统" description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14" requires-python = ">=3.14"
dependencies = [ dependencies = [
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]] [[package]]
name = "planet" name = "planet"
version = "0.82.0" version = "0.83.0"
source = { virtual = "." } source = { virtual = "." }
dependencies = [ dependencies = [
{ name = "aiofiles" }, { name = "aiofiles" },