Compare commits

..
5 Commits
Author SHA1 Message Date
linkong 41059ca42a release: bump version to 0.80.0
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-26 10:50:38 +08:00
linkong b7772f664c release: bump version to 0.79.2
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-25 19:38:13 +08:00
linkong 352b34e7c6 release: bump version to 0.79.1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-24 21:00:42 +08:00
linkong 1e9508f2f1 ci: deploy published Planet releases by image digest
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-24 17:27:54 +08:00
linkong e53c3af355 release: bump version to 0.79.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release / images (push) Canceled after 0s
release / client_release (push) Canceled after 0s
2026-11-24 15:40:10 +08:00
120 changed files with 14332 additions and 931 deletions

No files matched your search

+12 -5
View File
@@ -179,12 +179,19 @@ Push to remote:
### Step 9 — Publish and verify the Gitea Release ### Step 9 — Publish and verify the Gitea Release
When remote publication is requested, verify the remote tag points to the When remote publication is requested, verify the remote tag points to the
release commit. Check the tag's Gitea Actions run and its release job. A queued release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
run without an online runner does not publish anything. using the command below. The publisher builds the three production images and
the desktop packages from the tag. A published stable release triggers the
server's two-minute Compose deployment check. The workstation can go offline
after publication. Check the live update manifest and the running image digests
before reporting production deployment complete.
If the job cannot start or finish, use the packaged client artifacts for the ```bash
exact tag. Reuse verified artifacts when available, or build with Bun from the python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
tag in a clean checkout. Use an asset directory that contains only this release. ```
When verified desktop artifacts for the exact tag already exist, pass their
directory explicitly. A queued Gitea Actions run does not block local publication.
```bash ```bash
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run
+14 -20
View File
@@ -4,8 +4,7 @@ on:
push: push:
branches: branches:
- main - main
tags: # Tagged production releases are published on demand from the workstation.
- "v*"
workflow_dispatch: workflow_dispatch:
env: env:
@@ -17,18 +16,18 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Resolve image tags
id: meta
run: |
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
else
echo "release_tag=" >> "$GITHUB_OUTPUT"
fi
- name: Login to registry - name: Login to registry
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin env:
- name: Build and push images REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
- name: Publish immutable production images
if: startsWith(github.ref, 'refs/tags/v')
run: |
export PLANET_RELEASE_DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
python3 scripts/production_release.py "$GITHUB_REF_NAME"
- name: Build and push staging images
if: "!startsWith(github.ref, 'refs/tags/v')"
run: | run: |
for service in frontend admin backend aiprovider; do for service in frontend admin backend aiprovider; do
extra_build_args="" extra_build_args=""
@@ -52,18 +51,13 @@ jobs:
;; ;;
esac esac
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}" image="$REGISTRY/$IMAGE_NAMESPACE/$service:$GITHUB_SHA"
docker build $extra_build_args -t "$image" -f "$dockerfile" "$context" docker build $extra_build_args -t "$image" -f "$dockerfile" "$context"
docker push "$image" docker push "$image"
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
docker tag "$image" "$release_image"
docker push "$release_image"
fi
done done
client_release: client_release:
needs: images
if: startsWith(github.ref, 'refs/tags/v') if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
+1 -1
View File
@@ -1 +1 @@
0.78.0 0.80.0
+34
View File
@@ -1,8 +1,10 @@
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
import hmac import hmac
import json
from uuid import uuid4 from uuid import uuid4
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status
from fastapi.responses import StreamingResponse
from aiprovider.config import settings from aiprovider.config import settings
from aiprovider.provider_service import ProviderService from aiprovider.provider_service import ProviderService
@@ -124,3 +126,35 @@ async def analyze(
): ):
response.headers["X-Request-ID"] = request.state.request_id response.headers["X-Request-ID"] = request.state.request_id
return await provider_service.analyze(payload) return await provider_service.analyze(payload)
@app.post(
"/v1/analyze/stream",
dependencies=[Depends(verify_service_token)],
)
async def analyze_stream(
payload: SituationalAnalysisRequest,
request: Request,
provider_service: ProviderService = Depends(get_provider_service),
):
request_id = request.state.request_id
async def event_generator():
try:
async for item in provider_service.stream_analyze(payload):
event_name = str(item.get("event") or "message")
yield f"event: {event_name}\ndata: {json.dumps(item, ensure_ascii=False)}\n\n"
except Exception as exc:
detail = exc.detail if isinstance(exc, HTTPException) else exc
err_payload = {"event": "error", "detail": str(detail)}
yield f"event: error\ndata: {json.dumps(err_payload, ensure_ascii=False)}\n\n"
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"X-Request-ID": request_id,
},
)
+471 -40
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from collections.abc import AsyncIterator
import json import json
from typing import Any from typing import Any
from uuid import NAMESPACE_URL, uuid4, uuid5 from uuid import NAMESPACE_URL, uuid4, uuid5
@@ -97,17 +98,22 @@ class ProviderService:
) )
prompt = self._build_prompt(payload) prompt = self._build_prompt(payload)
conversation_messages = self._build_conversation_messages(payload, prompt)
if payload.context.get("session_id") is not None: if payload.context.get("session_id") is not None:
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}")) self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
provider_api = self._resolve_model_provider_api(model) provider_api = self._resolve_model_provider_api(model)
if provider_api == "openai-completions": if provider_api == "openai-completions":
data = await self._request_openai_compatible(model, prompt, payload.system_prompt) data = await self._request_openai_compatible(
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
)
content = self._extract_openai_content(data) content = self._extract_openai_content(data)
content_blocks = self._extract_openai_blocks(data) content_blocks = self._extract_openai_blocks(data)
elif provider_api == "openai-responses": elif provider_api == "openai-responses":
data = await self._request_openai_responses(model, prompt, payload.system_prompt) data = await self._request_openai_responses(
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
)
content_blocks = self._extract_responses_blocks(data) content_blocks = self._extract_responses_blocks(data)
content = "".join(block.text for block in content_blocks if block.text) content = "".join(block.text for block in content_blocks if block.text)
elif provider_api == "anthropic-messages": elif provider_api == "anthropic-messages":
@@ -116,11 +122,14 @@ class ProviderService:
prompt, prompt,
payload.thinking, payload.thinking,
payload.system_prompt, payload.system_prompt,
conversation_messages=conversation_messages,
) )
content = self._extract_anthropic_content(data) content = self._extract_anthropic_content(data)
content_blocks = self._extract_anthropic_blocks(data) content_blocks = self._extract_anthropic_blocks(data)
elif provider_api == "ollama-generate": elif provider_api == "ollama-generate":
data = await self._request_ollama(model, prompt, payload.system_prompt) data = await self._request_ollama(
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
)
content = self._extract_ollama_content(data) content = self._extract_ollama_content(data)
content_blocks = self._extract_ollama_blocks(data) content_blocks = self._extract_ollama_blocks(data)
else: else:
@@ -142,6 +151,394 @@ class ProviderService:
raw_response=data, raw_response=data,
) )
async def stream_analyze(
self,
payload: SituationalAnalysisRequest,
) -> AsyncIterator[dict[str, Any]]:
if self.provider == "disabled":
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="AI provider is disabled. Configure AI_PROVIDER in .env to enable analysis.",
)
model = payload.preferred_model or self.default_model
has_credentials = bool(self.api_key) if self._requires_api_key() else True
if not self.base_url or not has_credentials or not model:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="AI provider is not fully configured. Check AI_BASE_URL, AI_API_KEY, and AI_MODEL.",
)
prompt = self._build_prompt(payload)
conversation_messages = self._build_conversation_messages(payload, prompt)
if payload.context.get("session_id") is not None:
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
provider_api = self._resolve_model_provider_api(model)
yield {"event": "start", "provider": self.provider, "model": model}
if provider_api == "anthropic-messages":
async for item in self._stream_anthropic_messages(
model,
prompt,
payload.thinking,
payload.system_prompt,
conversation_messages=conversation_messages,
):
yield item
return
if provider_api == "openai-completions":
async for item in self._stream_openai_compatible(
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
):
yield item
return
if provider_api == "openai-responses":
async for item in self._stream_openai_responses(
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
):
yield item
return
if provider_api == "ollama-generate":
async for item in self._stream_ollama(
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
):
yield item
return
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Unsupported AI provider API: {self.provider_api}",
)
def _outbound_headers(self, headers: dict[str, str]) -> dict[str, str]:
merged = {"User-Agent": "Planet/1.0", **headers}
if self.provider == "opencode-go":
merged["x-opencode-session"] = self.session_id
return merged
async def _iter_sse_events(
self,
response: httpx.Response,
) -> AsyncIterator[tuple[str, str]]:
event_name = ""
data_lines: list[str] = []
async for raw_line in response.aiter_lines():
line = raw_line.rstrip("\r")
if line == "":
if data_lines:
yield event_name, "\n".join(data_lines)
event_name = ""
data_lines = []
continue
if line.startswith(":"):
continue
if line.startswith("event:"):
event_name = line[6:].strip()
elif line.startswith("data:"):
data_lines.append(line[5:].lstrip())
if data_lines:
yield event_name, "\n".join(data_lines)
def _build_anthropic_request(
self,
model: str,
prompt: str,
thinking: dict[str, Any] | None = None,
system_prompt: str | None = None,
*,
stream: bool = False,
conversation_messages: list[dict[str, str]] | None = None,
) -> tuple[str, dict[str, str], dict[str, Any]]:
if conversation_messages and len(conversation_messages) > 1:
anthropic_messages = [
{"role": m["role"], "content": [{"type": "text", "text": m["content"]}]}
for m in conversation_messages
]
else:
anthropic_messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(thinking, model)
thinking_active = bool(
resolved_thinking
and str(resolved_thinking.get("type") or "").lower() in {"enabled", "adaptive"}
)
max_tokens = self.max_tokens
if resolved_thinking and isinstance(resolved_thinking.get("budget_tokens"), (int, float)):
budget_tokens = int(resolved_thinking["budget_tokens"])
if budget_tokens >= max_tokens:
max_tokens = budget_tokens + 1024
request_body: dict[str, Any] = {
"model": model,
"messages": anthropic_messages,
"max_tokens": max_tokens,
}
if not thinking_active:
request_body["temperature"] = 0.2
if stream:
request_body["stream"] = True
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
if resolved_system_prompt:
request_body["system"] = resolved_system_prompt
if resolved_thinking:
request_body["thinking"] = resolved_thinking
if resolved_output_config:
request_body["output_config"] = resolved_output_config
path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages"
headers = {
"x-api-key": self.api_key,
"anthropic-version": self.anthropic_version,
"Content-Type": "application/json",
}
return path, headers, request_body
async def _stream_anthropic_messages(
self,
model: str,
prompt: str,
thinking: dict[str, Any] | None = None,
system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> AsyncIterator[dict[str, Any]]:
path, headers, request_body = self._build_anthropic_request(
model,
prompt,
thinking,
system_prompt,
stream=True,
conversation_messages=conversation_messages,
)
resolved_model = model
usage: dict[str, Any] = {}
async with httpx.AsyncClient(timeout=self.timeout) as client:
async with client.stream(
"POST",
f"{self.base_url}{path}",
headers=self._outbound_headers(headers),
json=request_body,
) as response:
if response.status_code >= 400:
detail = (await response.aread()).decode("utf-8", errors="replace")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"AI provider request failed: {detail or response.status_code}",
)
async for event_name, data_str in self._iter_sse_events(response):
if data_str == "[DONE]":
continue
try:
chunk = json.loads(data_str)
except json.JSONDecodeError:
continue
if not isinstance(chunk, dict):
continue
msg_type = str(chunk.get("type") or event_name or "")
if msg_type == "error":
err = chunk.get("error") if isinstance(chunk.get("error"), dict) else {}
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=str(err.get("message") or chunk.get("message") or "Upstream stream error"),
)
if msg_type == "message_start":
message = chunk.get("message") if isinstance(chunk.get("message"), dict) else {}
if isinstance(message.get("model"), str) and message["model"]:
resolved_model = message["model"]
if isinstance(message.get("usage"), dict):
usage.update(message["usage"])
elif msg_type == "message_delta":
if isinstance(chunk.get("usage"), dict):
usage.update(chunk["usage"])
elif msg_type == "content_block_start":
block = chunk.get("content_block") if isinstance(chunk.get("content_block"), dict) else {}
if block.get("type") == "thinking" and isinstance(block.get("thinking"), str) and block["thinking"]:
yield {"event": "reasoning", "delta": block["thinking"]}
elif block.get("type") == "text" and isinstance(block.get("text"), str) and block["text"]:
yield {"event": "text", "delta": block["text"]}
elif msg_type == "content_block_delta":
delta = chunk.get("delta") if isinstance(chunk.get("delta"), dict) else {}
delta_type = str(delta.get("type") or "")
if delta_type == "thinking_delta" and isinstance(delta.get("thinking"), str) and delta["thinking"]:
yield {"event": "reasoning", "delta": delta["thinking"]}
elif delta_type == "text_delta" and isinstance(delta.get("text"), str) and delta["text"]:
yield {"event": "text", "delta": delta["text"]}
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
async def _stream_openai_compatible(
self,
model: str,
prompt: str,
system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> AsyncIterator[dict[str, Any]]:
messages = []
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
if resolved_system_prompt:
messages.append({"role": "system", "content": resolved_system_prompt})
if conversation_messages and len(conversation_messages) > 1:
messages.extend(conversation_messages)
else:
messages.append({"role": "user", "content": prompt})
request_body = {
"model": model,
"messages": messages,
"temperature": 0.2,
"max_tokens": self.max_tokens,
"stream": True,
"stream_options": {"include_usage": True},
}
resolved_model = model
usage: dict[str, Any] = {}
async with httpx.AsyncClient(timeout=self.timeout) as client:
async with client.stream(
"POST",
f"{self.base_url}/chat/completions",
headers=self._outbound_headers(
{"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
),
json=request_body,
) as response:
if response.status_code >= 400:
detail = (await response.aread()).decode("utf-8", errors="replace")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"AI provider request failed: {detail or response.status_code}",
)
async for _, data_str in self._iter_sse_events(response):
if data_str == "[DONE]":
break
try:
chunk = json.loads(data_str)
except json.JSONDecodeError:
continue
if not isinstance(chunk, dict):
continue
if isinstance(chunk.get("model"), str) and chunk["model"]:
resolved_model = chunk["model"]
if isinstance(chunk.get("usage"), dict):
usage.update(chunk["usage"])
choices = chunk.get("choices") or []
if not choices or not isinstance(choices[0], dict):
continue
delta = choices[0].get("delta") if isinstance(choices[0].get("delta"), dict) else {}
for r_key in ("reasoning_content", "reasoning", "thinking"):
r_val = delta.get(r_key)
if isinstance(r_val, str) and r_val:
yield {"event": "reasoning", "delta": r_val}
break
text_val = delta.get("content")
if isinstance(text_val, str) and text_val:
yield {"event": "text", "delta": text_val}
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
async def _stream_openai_responses(
self,
model: str,
prompt: str,
system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> AsyncIterator[dict[str, Any]]:
responses_input: Any = (
[{"role": m["role"], "content": m["content"]} for m in conversation_messages]
if (conversation_messages and len(conversation_messages) > 1)
else prompt
)
request_body: dict[str, Any] = {
"model": model,
"input": responses_input,
"max_output_tokens": self.max_tokens,
"store": False,
"stream": True,
}
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
if resolved_system_prompt:
request_body["instructions"] = resolved_system_prompt
resolved_model = model
usage: dict[str, Any] = {}
async with httpx.AsyncClient(timeout=self.timeout) as client:
async with client.stream(
"POST",
f"{self.base_url}/responses",
headers=self._outbound_headers(
{"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
),
json=request_body,
) as response:
if response.status_code >= 400:
detail = (await response.aread()).decode("utf-8", errors="replace")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"AI provider request failed: {detail or response.status_code}",
)
async for event_name, data_str in self._iter_sse_events(response):
if data_str == "[DONE]":
break
try:
chunk = json.loads(data_str)
except json.JSONDecodeError:
continue
if not isinstance(chunk, dict):
continue
ev_type = str(chunk.get("type") or event_name or "")
if ev_type == "response.output_text.delta" and isinstance(chunk.get("delta"), str) and chunk["delta"]:
yield {"event": "text", "delta": chunk["delta"]}
elif ("reasoning" in ev_type or "thinking" in ev_type) and isinstance(chunk.get("delta"), str) and chunk["delta"]:
yield {"event": "reasoning", "delta": chunk["delta"]}
elif ev_type == "response.completed":
resp_obj = chunk.get("response") if isinstance(chunk.get("response"), dict) else {}
if isinstance(resp_obj.get("model"), str) and resp_obj["model"]:
resolved_model = resp_obj["model"]
if isinstance(resp_obj.get("usage"), dict):
usage.update(resp_obj["usage"])
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
async def _stream_ollama(
self,
model: str,
prompt: str,
system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> AsyncIterator[dict[str, Any]]:
ollama_prompt = self._format_ollama_prompt(prompt, conversation_messages)
request_body: dict[str, Any] = {
"model": model,
"stream": True,
"prompt": ollama_prompt,
"options": {"temperature": 0.2, "num_predict": self.max_tokens},
}
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
if resolved_system_prompt:
request_body["system"] = resolved_system_prompt
usage: dict[str, Any] = {}
async with httpx.AsyncClient(timeout=self.timeout) as client:
async with client.stream(
"POST",
f"{self.base_url}/api/generate",
headers=self._outbound_headers({"Content-Type": "application/json"}),
json=request_body,
) as response:
if response.status_code >= 400:
detail = (await response.aread()).decode("utf-8", errors="replace")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"AI provider request failed: {detail or response.status_code}",
)
async for line in response.aiter_lines():
if not line.strip():
continue
try:
chunk = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(chunk.get("thinking"), str) and chunk["thinking"]:
yield {"event": "reasoning", "delta": chunk["thinking"]}
if isinstance(chunk.get("response"), str) and chunk["response"]:
yield {"event": "text", "delta": chunk["response"]}
yield {"event": "done", "provider": self.provider, "model": model, "usage": usage}
def _requires_api_key(self) -> bool: def _requires_api_key(self) -> bool:
return self.provider_api != "ollama-generate" return self.provider_api != "ollama-generate"
@@ -165,6 +562,44 @@ class ProviderService:
if model and provider_api if model and provider_api
} }
def _build_conversation_messages(
self,
payload: SituationalAnalysisRequest,
final_prompt: str,
) -> list[dict[str, str]]:
"""Normalize multi-turn history + current prompt into alternating user/assistant messages."""
normalized: list[dict[str, str]] = []
for item in getattr(payload, "messages", None) or []:
role = str(getattr(item, "role", None) or (item.get("role") if isinstance(item, dict) else "")).strip().lower()
content = str(getattr(item, "content", None) or (item.get("content") if isinstance(item, dict) else "")).strip()
if role not in {"user", "assistant"} or not content:
continue
if not normalized and role == "assistant":
continue
if normalized and normalized[-1]["role"] == role:
normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{content}"
else:
normalized.append({"role": role, "content": content})
if normalized and normalized[-1]["role"] == "user":
normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{final_prompt}"
else:
normalized.append({"role": "user", "content": final_prompt})
return normalized
@staticmethod
def _format_ollama_prompt(
prompt: str,
conversation_messages: list[dict[str, str]] | None,
) -> str:
if not conversation_messages or len(conversation_messages) <= 1:
return prompt
history_lines = []
for m in conversation_messages[:-1]:
prefix = "用户" if m["role"] == "user" else "助手"
history_lines.append(f"{prefix}: {m['content']}")
return "历史对话:\n" + "\n".join(history_lines) + f"\n\n当前任务:\n{conversation_messages[-1]['content']}"
def _build_prompt(self, payload: SituationalAnalysisRequest) -> str: def _build_prompt(self, payload: SituationalAnalysisRequest) -> str:
sections = [ sections = [
f"任务标题:\n{payload.title}", f"任务标题:\n{payload.title}",
@@ -187,11 +622,16 @@ class ProviderService:
model: str, model: str,
prompt: str, prompt: str,
system_prompt: str | None = None, system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
messages = [] messages = []
resolved_system_prompt = self._resolve_system_prompt(system_prompt) resolved_system_prompt = self._resolve_system_prompt(system_prompt)
if resolved_system_prompt: if resolved_system_prompt:
messages.append({"role": "system", "content": resolved_system_prompt}) messages.append({"role": "system", "content": resolved_system_prompt})
if conversation_messages and len(conversation_messages) > 1:
messages.extend(conversation_messages)
else:
messages.append({"role": "user", "content": prompt}) messages.append({"role": "user", "content": prompt})
request_body = { request_body = {
"model": model, "model": model,
@@ -209,10 +649,23 @@ class ProviderService:
) )
async def _request_openai_responses( async def _request_openai_responses(
self, model: str, prompt: str, system_prompt: str | None = None, self,
model: str,
prompt: str,
system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
responses_input: Any = (
[{"role": m["role"], "content": m["content"]} for m in conversation_messages]
if (conversation_messages and len(conversation_messages) > 1)
else prompt
)
request_body: dict[str, Any] = { request_body: dict[str, Any] = {
"model": model, "input": prompt, "max_output_tokens": self.max_tokens, "store": False, "model": model,
"input": responses_input,
"max_output_tokens": self.max_tokens,
"store": False,
} }
resolved_system_prompt = self._resolve_system_prompt(system_prompt) resolved_system_prompt = self._resolve_system_prompt(system_prompt)
if resolved_system_prompt: if resolved_system_prompt:
@@ -247,44 +700,20 @@ class ProviderService:
prompt: str, prompt: str,
thinking: dict[str, Any] | None = None, thinking: dict[str, Any] | None = None,
system_prompt: str | None = None, system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
request_body = { path, headers, request_body = self._build_anthropic_request(
"model": model, model,
"messages": [ prompt,
{ thinking,
"role": "user", system_prompt,
"content": [ stream=False,
{ conversation_messages=conversation_messages,
"type": "text",
"text": prompt,
}
],
}
],
"max_tokens": self.max_tokens,
"temperature": 0.2,
}
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
if resolved_system_prompt:
request_body["system"] = resolved_system_prompt
resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(
thinking, model
) )
if resolved_thinking:
request_body["thinking"] = resolved_thinking
if resolved_output_config:
request_body["output_config"] = resolved_output_config
if self.provider == "minimax" and self.base_url.endswith("/anthropic"):
path = "/v1/messages"
else:
path = "/messages"
return await self._post( return await self._post(
path=path, path=path,
headers={ headers=headers,
"x-api-key": self.api_key,
"anthropic-version": self.anthropic_version,
"Content-Type": "application/json",
},
request_body=request_body, request_body=request_body,
) )
@@ -332,11 +761,13 @@ class ProviderService:
model: str, model: str,
prompt: str, prompt: str,
system_prompt: str | None = None, system_prompt: str | None = None,
*,
conversation_messages: list[dict[str, str]] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
request_body = { request_body = {
"model": model, "model": model,
"stream": False, "stream": False,
"prompt": prompt, "prompt": self._format_ollama_prompt(prompt, conversation_messages),
"options": { "options": {
"temperature": 0.2, "temperature": 0.2,
"num_predict": self.max_tokens, "num_predict": self.max_tokens,
+7 -1
View File
@@ -1,8 +1,13 @@
from typing import Any from typing import Any, Literal
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
class ChatMessage(BaseModel):
role: Literal["user", "assistant"]
content: str = Field(..., min_length=1, max_length=12000)
class AIContentBlock(BaseModel): class AIContentBlock(BaseModel):
type: str type: str
text: str | None = None text: str | None = None
@@ -20,6 +25,7 @@ class SituationalAnalysisRequest(BaseModel):
system_prompt: str | None = Field(default=None, max_length=8000) system_prompt: str | None = Field(default=None, max_length=8000)
preferred_model: str | None = Field(default=None, max_length=200) preferred_model: str | None = Field(default=None, max_length=200)
thinking: dict[str, Any] | None = None thinking: dict[str, Any] | None = None
messages: list[ChatMessage] = Field(default_factory=list, max_length=32)
class SituationalAnalysisResponse(BaseModel): class SituationalAnalysisResponse(BaseModel):
+2
View File
@@ -8,6 +8,7 @@ from app.api.v1 import (
datasources, datasources,
docs, docs,
earth, earth,
client_updates,
tasks, tasks,
dashboard, dashboard,
alerts, alerts,
@@ -40,6 +41,7 @@ api_router.include_router(datasources.router, prefix="/datasources", tags=["data
api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"]) api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"])
api_router.include_router(docs.router, prefix="/docs", tags=["docs"]) api_router.include_router(docs.router, prefix="/docs", tags=["docs"])
api_router.include_router(earth.router, prefix="/earth", tags=["earth"]) api_router.include_router(earth.router, prefix="/earth", tags=["earth"])
api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"])
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"]) api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboard"]) api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboard"])
api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"]) api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"])
+317
View File
@@ -0,0 +1,317 @@
"""Client L1 Earth hot-update manifest and bundle hosting endpoints."""
from __future__ import annotations
import hashlib
import hmac
import io
import json
import os
import re
import tarfile
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from uuid import uuid4
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status
from fastapi.responses import FileResponse, JSONResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.logging import get_logger
from app.core.security import get_current_user
from app.db.session import get_db
router = APIRouter()
logger = get_logger(__name__, service="api")
bearer_optional = HTTPBearer(auto_error=False)
DEFAULT_CLIENT_UPDATES_DIR = Path(__file__).resolve().parents[3] / "data" / "client-updates"
MAX_HOTFIX_BUNDLE_BYTES = 32 * 1024 * 1024
MAX_HOTFIX_FILES = 2000
MAX_HOTFIX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
SEMVER_PATTERN = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$")
SAFE_BUNDLE_FILENAME_PATTERN = re.compile(r"^planet-earth-bundle-[0-9A-Za-z._-]+\.tar\.gz$")
def get_client_updates_dir() -> Path:
configured = str(settings.CLIENT_UPDATES_DIR or "").strip()
if configured:
return Path(configured)
return DEFAULT_CLIENT_UPDATES_DIR
def _manifest_path(updates_dir: Path) -> Path:
return updates_dir / "manifest.json"
def _atomic_write_bytes(target: Path, content: bytes) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
tmp_path = target.with_name(f".{target.name}.{os.getpid()}.{uuid4().hex}.tmp")
try:
tmp_path.write_bytes(content)
os.replace(tmp_path, target)
except Exception:
tmp_path.unlink(missing_ok=True)
raise
def _validate_hotfix_tar_gz(content: bytes) -> dict[str, int]:
if not content:
raise HTTPException(status_code=400, detail="Hotfix bundle archive is empty")
file_count = 0
total_size = 0
has_index_html = False
try:
with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as archive:
for member in archive.getmembers():
raw_name = member.name or ""
if "\\" in raw_name or "\0" in raw_name:
raise HTTPException(status_code=400, detail=f"Unsafe archive entry path: {raw_name!r}")
if member.issym() or member.islnk() or member.isdev() or member.ischr() or member.isblk() or member.isfifo():
raise HTTPException(status_code=400, detail=f"Unsupported special archive entry: {raw_name!r}")
stripped = raw_name.lstrip("./") if raw_name.startswith("./") else raw_name
while stripped.startswith("./"):
stripped = stripped[2:]
stripped = stripped.rstrip("/")
if raw_name.startswith("/"):
raise HTTPException(status_code=400, detail=f"Absolute archive entry path is forbidden: {raw_name!r}")
if stripped in ("", "."):
if member.isdir():
continue
raise HTTPException(status_code=400, detail="Empty archive file path")
segments = stripped.split("/")
if any(seg in ("", ".", "..") for seg in segments):
raise HTTPException(status_code=400, detail=f"Path traversal forbidden in archive: {raw_name!r}")
if member.isdir():
continue
if not member.isreg():
raise HTTPException(status_code=400, detail=f"Unsupported archive entry type: {raw_name!r}")
file_count += 1
if file_count > MAX_HOTFIX_FILES:
raise HTTPException(status_code=400, detail="Archive exceeds maximum allowed file count")
total_size += max(0, int(member.size))
if total_size > MAX_HOTFIX_UNCOMPRESSED_BYTES:
raise HTTPException(status_code=400, detail="Archive exceeds maximum uncompressed size limit")
if stripped == "index.html":
has_index_html = True
except HTTPException:
raise
except (tarfile.TarError, EOFError, OSError, ValueError) as exc:
raise HTTPException(status_code=400, detail=f"Invalid gzip tar archive: {exc}") from exc
if not has_index_html:
raise HTTPException(status_code=400, detail="Hotfix bundle must include index.html at root")
return {"filesCount": file_count, "uncompressedBytes": total_size}
def _default_manifest() -> dict[str, Any]:
return {
"shell": {
"version": settings.VERSION,
"minRequired": settings.CLIENT_MIN_SHELL_VERSION,
"downloadUrl": settings.CLIENT_RELEASE_PAGE_URL,
"releaseNotes": "",
},
"bundle": None,
}
def _read_manifest(updates_dir: Path) -> dict[str, Any]:
manifest_file = _manifest_path(updates_dir)
if not manifest_file.is_file():
return _default_manifest()
try:
payload = json.loads(manifest_file.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
return _default_manifest()
return payload
except (OSError, json.JSONDecodeError):
return _default_manifest()
async def _require_update_publisher(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_optional),
db: AsyncSession = Depends(get_db),
) -> str:
publish_token = request.headers.get("X-Client-Update-Token")
if publish_token is not None:
expected = str(settings.CLIENT_UPDATE_PUBLISH_TOKEN or "").strip()
if not expected or not hmac.compare_digest(publish_token.strip(), expected):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid client update publish token",
)
return "ci-token"
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
)
user = await get_current_user(credentials=credentials, db=db)
if getattr(user, "role", None) != "admin":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin privileges required",
)
return f"admin:{user.username}"
def _validate_semver(value: str, field_name: str) -> str:
cleaned = str(value or "").strip().lstrip("vV")
if not SEMVER_PATTERN.match(cleaned):
raise HTTPException(
status_code=400,
detail=f"Invalid semantic version for {field_name}: {value!r}",
)
return cleaned
@router.get("/update-manifest")
async def get_client_update_manifest(
platform: str = "",
arch: str = "",
shell: str = "",
bundle: str = "",
):
updates_dir = get_client_updates_dir()
manifest = _read_manifest(updates_dir)
bundle_info = manifest.get("bundle")
if isinstance(bundle_info, dict):
filename = Path(str(bundle_info.get("url") or "")).name
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename) or not (updates_dir / filename).is_file():
manifest = {**manifest, "bundle": None}
logger.debug_event(
"Served client update manifest",
event="client_updates.manifest.read",
context={
"platform": platform or None,
"arch": arch or None,
"shell": shell or None,
"bundle": bundle or None,
"has_bundle": bool(manifest.get("bundle")),
},
)
return JSONResponse(content=manifest, headers={"Cache-Control": "no-store"})
@router.get("/updates/files/{filename}")
async def download_client_hotfix_bundle(filename: str):
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename):
raise HTTPException(status_code=400, detail="Invalid client hotfix bundle filename")
updates_dir = get_client_updates_dir().resolve()
target = (updates_dir / filename).resolve()
if target.parent != updates_dir or not target.is_file():
raise HTTPException(status_code=404, detail="Client hotfix bundle not found")
return FileResponse(
path=target,
media_type="application/gzip",
filename=filename,
headers={"Cache-Control": "public, max-age=31536000, immutable"},
)
@router.post("/updates/bundle")
async def publish_client_hotfix_bundle(
file: UploadFile = File(...),
version: str = Form(...),
min_shell_version: str = Form(""),
release_notes: str = Form(""),
shell_version: str = Form(""),
shell_min_required: str = Form(""),
shell_download_url: str = Form(""),
publisher: str = Depends(_require_update_publisher),
):
normalized_version = _validate_semver(version, "version")
normalized_min_shell = _validate_semver(
min_shell_version or settings.CLIENT_MIN_SHELL_VERSION or normalized_version,
"min_shell_version",
)
content = await file.read(MAX_HOTFIX_BUNDLE_BYTES + 1)
if len(content) > MAX_HOTFIX_BUNDLE_BYTES:
raise HTTPException(status_code=400, detail="Hotfix bundle exceeds 32 MiB limit")
archive_meta = _validate_hotfix_tar_gz(content)
sha256_hex = hashlib.sha256(content).hexdigest()
bundle_filename = f"planet-earth-bundle-{normalized_version}.tar.gz"
updates_dir = get_client_updates_dir()
_atomic_write_bytes(updates_dir / bundle_filename, content)
existing_manifest = _read_manifest(updates_dir)
existing_shell = existing_manifest.get("shell") if isinstance(existing_manifest.get("shell"), dict) else {}
resolved_shell_version = (
_validate_semver(shell_version, "shell_version")
if str(shell_version or "").strip()
else str(existing_shell.get("version") or settings.VERSION)
)
resolved_shell_min = (
_validate_semver(shell_min_required, "shell_min_required")
if str(shell_min_required or "").strip()
else str(existing_shell.get("minRequired") or settings.CLIENT_MIN_SHELL_VERSION)
)
resolved_shell_url = str(shell_download_url or "").strip() or str(
existing_shell.get("downloadUrl") or settings.CLIENT_RELEASE_PAGE_URL
)
if not resolved_shell_url.startswith(("https://", "http://")):
raise HTTPException(status_code=400, detail="shell_download_url must start with http:// or https://")
cleaned_notes = str(release_notes or "").strip()[:4000]
manifest: dict[str, Any] = {
"shell": {
"version": resolved_shell_version,
"minRequired": resolved_shell_min,
"downloadUrl": resolved_shell_url,
"releaseNotes": cleaned_notes or str(existing_shell.get("releaseNotes") or ""),
},
"bundle": {
"version": normalized_version,
"minShellVersion": normalized_min_shell,
"url": f"/api/v1/client/updates/files/{bundle_filename}",
"sha256": sha256_hex,
"size": len(content),
"releaseNotes": cleaned_notes,
"publishedAt": datetime.now(UTC).isoformat(),
**archive_meta,
},
}
_atomic_write_bytes(
_manifest_path(updates_dir),
(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
)
logger.info_event(
"Published client L1 hotfix bundle",
event="client_updates.bundle_published",
context={
"publisher": publisher,
"version": normalized_version,
"min_shell_version": normalized_min_shell,
"bytes": len(content),
"sha256": sha256_hex,
"files_count": archive_meta["filesCount"],
},
)
return {"status": "published", "manifest": manifest}
+86 -6
View File
@@ -66,7 +66,12 @@ from app.services.llm_provider_catalog import (
list_fallback_llm_provider_presets, list_fallback_llm_provider_presets,
refresh_llm_provider_preset, refresh_llm_provider_preset,
) )
from app.services.llm_model_catalog import catalog_error_message, fetch_model_catalog from app.services.llm_model_catalog import (
LLMProviderCatalogConfigError,
catalog_error_message,
catalog_requires_api_key,
fetch_model_catalog,
)
from app.services.scheduler import sync_datasource_job from app.services.scheduler import sync_datasource_job
from app.services.tv_streams import DEFAULT_TV_SETTINGS, get_tv_settings_payload, normalize_tv_settings from app.services.tv_streams import DEFAULT_TV_SETTINGS, get_tv_settings_payload, normalize_tv_settings
from app.services.persistent_logs import record_audit_log from app.services.persistent_logs import record_audit_log
@@ -840,7 +845,7 @@ async def _check_ai_provider_lightweight(llm_config: dict, timeout_seconds: int)
} }
if not base_url or not model: if not base_url or not model:
return {**result, "message": "当前 provider/base_url/model 未完整配置。"} return {**result, "message": "当前 provider/base_url/model 未完整配置。"}
if provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key: if provider != "ollama" and provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key:
return {**result, "message": "当前 provider 未配置 API Key。"} return {**result, "message": "当前 provider 未配置 API Key。"}
try: try:
catalog = await fetch_model_catalog( catalog = await fetch_model_catalog(
@@ -2145,6 +2150,74 @@ async def get_ai_provider_presets(
} }
async def refresh_public_llm_provider_presets(db: AsyncSession) -> dict:
current_payload = await get_setting_payload(db, "external_integrations")
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
results: list[dict] = []
for preset in list_fallback_llm_provider_presets():
provider_id = preset["provider"]
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
base_url = str(provider_config.get("base_url") or preset["base_url"] or "")
provider_api = str(provider_config.get("provider_api") or preset["provider_api"] or "")
if catalog_requires_api_key(provider_id, base_url, provider_api):
continue
try:
refreshed = await refresh_llm_provider_preset(
provider_id,
api_key="",
base_url=base_url,
provider_api=provider_api,
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
)
except Exception as exc:
logger.warning(
"LLM provider catalog refresh failed",
extra={
"event": "settings.ai_provider.catalog.failed",
"context": {
"provider": provider_id,
"error_type": type(exc).__name__,
},
},
)
results.append(
{
"provider": provider_id,
"status": "failed",
"error": f"{catalog_error_message(exc)} 已保留上次模型列表。",
}
)
continue
refreshed["refreshed_at"] = to_iso8601_utc(datetime.now(UTC))
await save_setting_payload(
db, f"{LLM_PROVIDER_PRESET_CATEGORY_PREFIX}{provider_id}", refreshed
)
results.append(
{
"provider": provider_id,
"status": "refreshed",
"models_count": len(refreshed["models"]),
"refreshed_at": refreshed["refreshed_at"],
"source": refreshed["source"],
}
)
return {
"data": results,
"refreshed": [item["provider"] for item in results if item["status"] == "refreshed"],
"failed": [item["provider"] for item in results if item["status"] == "failed"],
}
@router.post("/integrations/ai-provider/presets/refresh-public")
async def refresh_public_ai_provider_presets(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can refresh AI provider presets")
return await refresh_public_llm_provider_presets(db)
@router.post("/integrations/ai-provider/presets/{provider}/refresh") @router.post("/integrations/ai-provider/presets/{provider}/refresh")
async def refresh_ai_provider_preset( async def refresh_ai_provider_preset(
provider: str, provider: str,
@@ -2152,9 +2225,10 @@ async def refresh_ai_provider_preset(
db: AsyncSession = Depends(get_db), db: AsyncSession = Depends(get_db),
payload: AIProviderIntegrationUpdate | None = None, payload: AIProviderIntegrationUpdate | None = None,
): ):
_require_admin(current_user, "Only administrators can refresh AI provider presets")
try: try:
provider_id = _normalize_provider_id(provider) provider_id = _normalize_provider_id(provider)
get_fallback_llm_provider_preset(provider_id) fallback = get_fallback_llm_provider_preset(provider_id)
except ValueError as exc: except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc raise HTTPException(status_code=404, detail=str(exc)) from exc
@@ -2166,17 +2240,23 @@ async def refresh_ai_provider_preset(
else: else:
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {}) ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id) provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
resolved_base_url = str(provider_config.get("base_url") or fallback["base_url"] or "")
resolved_api = str(provider_config.get("provider_api") or fallback["provider_api"] or "")
api_key, _api_key_source = _resolve_provider_api_key(provider_id, provider_config) api_key, _api_key_source = _resolve_provider_api_key(provider_id, provider_config)
if not api_key and provider_id not in {"ollama", "opencode-go", "openrouter"}: if not api_key and catalog_requires_api_key(provider_id, resolved_base_url, resolved_api):
raise HTTPException( raise HTTPException(
status_code=400, detail="请先配置当前供应商的 API Key,再刷新模型列表。", status_code=400, detail="请先配置当前供应商的 API Key,再刷新模型列表。",
) )
try: try:
refreshed = await refresh_llm_provider_preset( refreshed = await refresh_llm_provider_preset(
provider_id, api_key=api_key, base_url=provider_config.get("base_url"), provider_id,
provider_api=provider_config.get("provider_api"), api_key=api_key,
base_url=resolved_base_url,
provider_api=resolved_api,
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01", anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
) )
except LLMProviderCatalogConfigError as exc:
raise HTTPException(status_code=400, detail=catalog_error_message(exc)) from exc
except Exception as exc: except Exception as exc:
logger.warning( logger.warning(
"LLM provider catalog refresh failed", "LLM provider catalog refresh failed",
+77 -1
View File
@@ -7,7 +7,8 @@ from datetime import UTC, datetime
import uuid import uuid
from typing import Any, Literal from typing import Any, Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Response from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import desc, select from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
@@ -53,6 +54,7 @@ from app.services.ai.workflow_runtime import (
get_active_run_handle, get_active_run_handle,
read_frozen_result_revision, read_frozen_result_revision,
) )
from app.services.ai.stream_turn import stream_session_turn
from app.services.ai_client import AIProviderClient, get_ai_provider_client from app.services.ai_client import AIProviderClient, get_ai_provider_client
from app.services.compute_history import ComputeSeriesMode from app.services.compute_history import ComputeSeriesMode
@@ -79,6 +81,13 @@ class SessionPinUpdateRequest(BaseModel):
pinned_items: list[dict[str, Any]] = Field(default_factory=list, max_length=12) pinned_items: list[dict[str, Any]] = Field(default_factory=list, max_length=12)
class HistoryMessageItem(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
role: Literal["user", "assistant"]
content: str = Field(min_length=1, max_length=6000)
class SessionTurnRequest(BaseModel): class SessionTurnRequest(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
@@ -95,6 +104,11 @@ class SessionTurnRequest(BaseModel):
preset: ViewPreset | None = None preset: ViewPreset | None = None
prefer_llm: bool | Literal["auto"] = False prefer_llm: bool | Literal["auto"] = False
external_urls: list[str] = Field(default_factory=list, max_length=3) external_urls: list[str] = Field(default_factory=list, max_length=3)
news_context: dict[str, Any] | None = None
history: list[HistoryMessageItem] = Field(default_factory=list, max_length=40)
conversation_summary: str | None = Field(default=None, max_length=2400)
memory_notes: list[str] = Field(default_factory=list, max_length=12)
pinned_summaries: list[str] = Field(default_factory=list, max_length=8)
run_id: str | None = Field(default=None, min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$") run_id: str | None = Field(default=None, min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
@@ -340,6 +354,68 @@ async def create_session_turn(
return turn_result return turn_result
@router.post("/sessions/{session_id}/turns/stream")
async def stream_investigation_session_turn(
session_id: str,
payload: SessionTurnRequest,
request: Request,
response: Response,
access: AccessContext = Depends(resolve_access_context),
db: AsyncSession = Depends(get_db),
ai_client: AIProviderClient = Depends(get_ai_provider_client),
) -> StreamingResponse:
"""Adaptive SSE endpoint streaming LLM reasoning & answer when configured, else grounded baseline."""
session_row: InvestigationSession | None = None
effective_access = access
issued_token: str | None = None
if session_id == "stateless":
owner_key, issued_token = ensure_session_owner_identity(access, response)
effective_access = replace(access, actor_key=owner_key, has_session_credential=True)
else:
session_row = await _load_owned_session_or_fail(session_id, access, db)
codes = (
selected_countries(",".join(payload.selected_codes))
if payload.selected_codes
else None
)
overrides = {
"domain": payload.domain,
"selected_codes": codes,
"mode": payload.mode,
"focus_year": payload.focus_year,
"entity_id": payload.entity_id,
"visible_layers": payload.visible_layers,
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"include_drill": payload.include_drill,
}
headers = {
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
}
return StreamingResponse(
stream_session_turn(
db,
request=request,
session=session_row,
question=payload.question,
context_override=overrides,
news_context=payload.news_context,
history=[item.model_dump() for item in payload.history],
conversation_summary=payload.conversation_summary,
memory_notes=payload.memory_notes,
pinned_summaries=payload.pinned_summaries,
access=effective_access,
ai_client=ai_client,
client_run_id=payload.run_id,
issued_session_token=issued_token,
),
media_type="text/event-stream",
headers=headers,
)
# ============================================================================ # ============================================================================
# Group 3: WorkflowRun Inspection & Explicit Cancellation # Group 3: WorkflowRun Inspection & Explicit Cancellation
# ============================================================================ # ============================================================================
+120 -14
View File
@@ -7,11 +7,12 @@ Returns GeoJSON format compatible with Three.js, CesiumJS, and Unreal Cesium.
import asyncio import asyncio
import base64 import base64
from collections import OrderedDict from collections import OrderedDict
from contextlib import aclosing
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
import math import math
import re import re
import httpx import httpx
from fastapi import APIRouter, HTTPException, Depends, Query, Response from fastapi import APIRouter, HTTPException, Depends, Query, Request, Response
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func from sqlalchemy import select, func
@@ -63,6 +64,7 @@ from app.services.earth_layer_cache import (
earth_layer_cache, earth_layer_cache,
format_bbox_key, format_bbox_key,
get_or_build_layer_payload, get_or_build_layer_payload,
get_or_build_layer_response,
quantize_bbox, quantize_bbox,
) )
from app.core.logging import get_logger from app.core.logging import get_logger
@@ -278,16 +280,11 @@ def convert_landing_point_to_geojson(records: List[CollectedData], city_to_cable
return {"type": "FeatureCollection", "features": features} return {"type": "FeatureCollection", "features": features}
def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]: def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], Any, Optional[str], Optional[str], Optional[str], str] | None:
"""Convert satellite TLE records to GeoJSON"""
features = []
for record in records:
metadata = record.extra_data or {} metadata = record.extra_data or {}
norad_id = metadata.get("norad_cat_id") norad_id = metadata.get("norad_cat_id")
if not norad_id: if not norad_id:
continue return None
tle_line1 = metadata.get("tle_line1") tle_line1 = metadata.get("tle_line1")
tle_line2 = metadata.get("tle_line2") tle_line2 = metadata.get("tle_line2")
@@ -308,6 +305,18 @@ def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]
record.name, record.name,
) )
footprint_policy = _get_satellite_footprint_policy(constellation_group) footprint_policy = _get_satellite_footprint_policy(constellation_group)
return metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy
def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]:
"""Convert satellite TLE records to GeoJSON"""
features = []
for record in records:
extracted = _extract_satellite_record(record)
if extracted is None:
continue
metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy = extracted
features.append( features.append(
{ {
@@ -340,6 +349,43 @@ def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]
return {"type": "FeatureCollection", "features": features} return {"type": "FeatureCollection", "features": features}
def convert_satellite_to_compact_rows(records: List[CollectedData]) -> List[List[Any]]:
"""Convert satellite TLE records into compact array rows while keeping full catalog fidelity."""
rows: List[List[Any]] = []
for record in records:
extracted = _extract_satellite_record(record)
if extracted is None:
continue
metadata, norad_id, tle_line1, tle_line2, constellation_group, _footprint_policy = extracted
row: List[Any] = [
record.id,
norad_id,
record.name,
constellation_group,
tle_line1,
tle_line2,
]
if not tle_line1 or not tle_line2:
row.append(
[
metadata.get("inclination"),
metadata.get("raan"),
metadata.get("eccentricity"),
metadata.get("arg_of_perigee"),
metadata.get("mean_anomaly"),
metadata.get("mean_motion"),
metadata.get("epoch"),
metadata.get("international_designator"),
metadata.get("classification_type"),
metadata.get("bstar"),
]
)
rows.append(row)
return rows
def _get_satellite_footprint_policy(constellation_group: Optional[str]) -> str: def _get_satellite_footprint_policy(constellation_group: Optional[str]) -> str:
if constellation_group == "starlink": if constellation_group == "starlink":
@@ -1836,32 +1882,55 @@ async def get_all_geojson(db: AsyncSession = Depends(get_db)):
@router.get("/geo/satellites") @router.get("/geo/satellites")
async def get_satellites_geojson( async def get_satellites_geojson(
request: Request = None,
limit: Optional[int] = Query( limit: Optional[int] = Query(
None, None,
ge=1, ge=1,
description="Maximum number of satellites to return. Omit for no limit.", description="Maximum number of satellites to return. Omit for no limit.",
), ),
format: Optional[str] = Query(
None,
pattern="^(geojson|compact)$",
description="Response payload format: default GeoJSON or compact full-catalog rows.",
),
db: AsyncSession = Depends(get_db), db: AsyncSession = Depends(get_db),
response: Response = None, response: Response = None,
): ):
"""获取卫星 TLE GeoJSON 数据""" """获取卫星 TLE 数据(支持完整 GeoJSON 与全量紧凑数组格式)"""
compact = format == "compact"
cache_key = (
earth_layer_cache.key("satellites", format="compact", limit=limit or "all")
if compact
else earth_layer_cache.key("satellites", limit=limit or "all")
)
async def build_payload() -> dict[str, Any]: async def build_payload() -> dict[str, Any]:
if compact:
return await _build_satellites_compact(limit=limit, db=db)
return await _build_satellites_geojson(limit=limit, db=db) return await _build_satellites_geojson(limit=limit, db=db)
if request is None:
return await get_or_build_layer_payload( return await get_or_build_layer_payload(
key=earth_layer_cache.key("satellites", limit=limit or "all"), key=cache_key,
policy=SATELLITE_CACHE_POLICY, policy=SATELLITE_CACHE_POLICY,
builder=build_payload, builder=build_payload,
response=response, response=response,
) )
return await get_or_build_layer_response(
key=cache_key,
policy=SATELLITE_CACHE_POLICY,
builder=build_payload,
request=request,
response=response,
)
async def _build_satellites_geojson(
async def _stream_satellite_batches(
*, *,
limit: int | None, limit: int | None,
db: AsyncSession, db: AsyncSession,
) -> dict[str, Any]: ):
features: list[dict[str, Any]] = []
source = "celestrak_tle" source = "celestrak_tle"
for current_only in (True, False): for current_only in (True, False):
if current_only: if current_only:
@@ -1887,15 +1956,52 @@ async def _build_satellites_geojson(
try: try:
async for batch in records.partitions(SATELLITE_QUERY_BATCH_SIZE): async for batch in records.partitions(SATELLITE_QUERY_BATCH_SIZE):
found_records = True found_records = True
features.extend(convert_satellite_to_geojson(batch)["features"]) yield batch
finally: finally:
await records.close() await records.close()
if found_records: if found_records:
break break
async def _build_satellites_geojson(
*,
limit: int | None,
db: AsyncSession,
) -> dict[str, Any]:
features: list[dict[str, Any]] = []
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
async for batch in batches:
features.extend(convert_satellite_to_geojson(batch)["features"])
return {"type": "FeatureCollection", "features": features, "count": len(features)} return {"type": "FeatureCollection", "features": features, "count": len(features)}
async def _build_satellites_compact(
*,
limit: int | None,
db: AsyncSession,
) -> dict[str, Any]:
rows: list[list[Any]] = []
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
async for batch in batches:
rows.extend(convert_satellite_to_compact_rows(batch))
return {
"format": "satellite_compact_v1",
"count": len(rows),
"fields": [
"id",
"norad_cat_id",
"name",
"constellation_group",
"tle_line1",
"tle_line2",
"fallback_elements",
],
"satellites": rows,
}
@router.get("/geo/supercomputers") @router.get("/geo/supercomputers")
async def get_supercomputers_geojson( async def get_supercomputers_geojson(
limit: int = 500, limit: int = 500,
+5
View File
@@ -87,6 +87,11 @@ class Settings(BaseSettings):
AI_PROVIDER_RETRY_ATTEMPTS: int = 2 AI_PROVIDER_RETRY_ATTEMPTS: int = 2
OBSERVABILITY_INGEST_TOKEN: str = "" OBSERVABILITY_INGEST_TOKEN: str = ""
CLIENT_UPDATES_DIR: str = ""
CLIENT_UPDATE_PUBLISH_TOKEN: str = ""
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
@property @property
def is_production(self) -> bool: def is_production(self) -> bool:
return str(self.APP_ENV or "").strip().lower() == "production" return str(self.APP_ENV or "").strip().lower() == "production"
+21
View File
@@ -5,6 +5,7 @@ from uuid import uuid4
from fastapi import Depends, FastAPI from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from sqlalchemy import text from sqlalchemy import text
@@ -185,6 +186,26 @@ app = FastAPI(
openapi_url="/openapi.json", openapi_url="/openapi.json",
) )
class NonStreamingGZipMiddleware:
"""Apply GZip compression while skipping SSE streaming responses so events flush immediately."""
def __init__(self, app, minimum_size: int = 1024) -> None:
self.app = app
self.gzip_app = GZipMiddleware(app, minimum_size=minimum_size)
async def __call__(self, scope, receive, send) -> None:
if scope.get("type") == "http":
path = str(scope.get("path") or "")
headers = dict(scope.get("headers") or [])
accept = headers.get(b"accept", b"").lower()
if path.endswith("/stream") or b"text/event-stream" in accept:
await self.app(scope, receive, send)
return
await self.gzip_app(scope, receive, send)
app.add_middleware(NonStreamingGZipMiddleware, minimum_size=1024)
configured_origins = list(settings.CORS_ORIGINS or []) configured_origins = list(settings.CORS_ORIGINS or [])
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
+8 -1
View File
@@ -1,9 +1,15 @@
from typing import Any from typing import Any, Literal
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from app.core.enums import PlaygroundMessageKind, PlaygroundMessageRole, PlaygroundMessageStatus from app.core.enums import PlaygroundMessageKind, PlaygroundMessageRole, PlaygroundMessageStatus
class ChatMessage(BaseModel):
role: Literal["user", "assistant"]
content: str = Field(..., min_length=1, max_length=12000)
class AIContentBlock(BaseModel): class AIContentBlock(BaseModel):
type: str type: str
text: str | None = None text: str | None = None
@@ -21,6 +27,7 @@ class SituationalAnalysisRequest(BaseModel):
system_prompt: str | None = Field(default=None, max_length=8000) system_prompt: str | None = Field(default=None, max_length=8000)
preferred_model: str | None = Field(default=None, max_length=200) preferred_model: str | None = Field(default=None, max_length=200)
thinking: dict[str, Any] | None = None thinking: dict[str, Any] | None = None
messages: list[ChatMessage] = Field(default_factory=list, max_length=32)
class BGPBriefRequest(BaseModel): class BGPBriefRequest(BaseModel):
@@ -0,0 +1,209 @@
"""Multi-turn conversation sanitization, rolling compaction, and lightweight memory formatting."""
from __future__ import annotations
import asyncio
from typing import Any
from app.core.logging import get_logger
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
from app.services.ai_client import AIProviderClient
logger = get_logger(__name__, service="ai_memory")
RECENT_WINDOW_TURNS = 4
COMPACT_TRIGGER_CHARS = 7500
MAX_MESSAGE_CHARS = 1800
MAX_SUMMARY_CHARS = 1600
MAX_MEMORY_NOTES = 12
MAX_PINNED_SUMMARIES = 8
def _truncate_text(text: str, limit: int) -> str:
cleaned = str(text or "").strip()
if len(cleaned) <= limit:
return cleaned
return f"{cleaned[: max(0, limit - 1)].rstrip()}…"
def sanitize_history_messages(raw_messages: list[Any] | None) -> list[dict[str, str]]:
"""Strip inline thinking blocks, truncate extremes, and normalize alternating user/assistant turns."""
normalized: list[dict[str, str]] = []
for item in raw_messages or []:
if isinstance(item, dict):
role = str(item.get("role") or "").strip().lower()
raw_content = item.get("content")
else:
role = str(getattr(item, "role", "") or "").strip().lower()
raw_content = getattr(item, "content", "")
if role not in {"user", "assistant"}:
continue
content = str(raw_content or "").strip()
if not content:
continue
if role == "assistant":
clean_content, _ = strip_thinking_text(content)
content = clean_content or content
content = _truncate_text(content, MAX_MESSAGE_CHARS)
if not content:
continue
if not normalized and role == "assistant":
continue
if normalized and normalized[-1]["role"] == role:
merged = f"{normalized[-1]['content']}\n\n{content}"
normalized[-1]["content"] = _truncate_text(merged, MAX_MESSAGE_CHARS)
else:
normalized.append({"role": role, "content": content})
return normalized
def _sanitize_short_list(items: list[Any] | None, *, max_items: int, max_chars: int = 200) -> list[str]:
result: list[str] = []
seen: set[str] = set()
for raw in items or []:
text = _truncate_text(str(raw or "").replace("\r", " ").replace("\n", " "), max_chars)
if not text or text in seen:
continue
seen.add(text)
result.append(text)
if len(result) >= max_items:
break
return result
def sanitize_memory_notes(notes: list[Any] | None) -> list[str]:
"""Return deduplicated short user memory notes within configured cap."""
return _sanitize_short_list(notes, max_items=MAX_MEMORY_NOTES)
def sanitize_pinned_summaries(items: list[Any] | None) -> list[str]:
"""Return deduplicated short pinned comparison summaries within configured cap."""
return _sanitize_short_list(items, max_items=MAX_PINNED_SUMMARIES)
def build_deterministic_compaction_summary(
existing_summary: str,
dropped_messages: list[dict[str, str]],
) -> str:
"""Build a bounded structured summary when older turns overflow the active window."""
lines: list[str] = []
prior = str(existing_summary or "").strip()
if prior:
lines.append(prior)
pair_lines: list[str] = []
idx = 0
while idx < len(dropped_messages):
msg = dropped_messages[idx]
if msg["role"] == "user":
q = _truncate_text(msg["content"].replace("\n", " "), 120)
a = ""
if idx + 1 < len(dropped_messages) and dropped_messages[idx + 1]["role"] == "assistant":
a = _truncate_text(dropped_messages[idx + 1]["content"].replace("\n", " "), 180)
idx += 2
else:
idx += 1
pair_lines.append(f"- 问:{q}" + (f" → 结:{a}" if a else ""))
else:
a = _truncate_text(msg["content"].replace("\n", " "), 160)
pair_lines.append(f"- 历史结论:{a}")
idx += 1
if pair_lines:
block = "\n".join(pair_lines)
if prior and not prior.startswith("### 前序对话摘要"):
lines = [f"### 前序对话摘要\n{prior}", block]
elif prior:
lines = [prior, block]
else:
lines = [f"### 前序对话摘要\n{block}"]
combined = "\n".join(lines).strip()
if len(combined) > MAX_SUMMARY_CHARS:
head = "### 前序对话摘要\n"
tail_budget = MAX_SUMMARY_CHARS - len(head) - 2
combined = f"{head}…{combined[-tail_budget:].lstrip()}"
return combined
async def compact_conversation_history(
raw_messages: list[Any] | None,
existing_summary: str = "",
*,
ai_client: AIProviderClient | None = None,
ai_ready: bool = False,
recent_window_turns: int = RECENT_WINDOW_TURNS,
char_budget: int = COMPACT_TRIGGER_CHARS,
) -> dict[str, Any]:
"""Keep recent window verbatim and compact overflow turns into a rolling summary."""
sanitized = sanitize_history_messages(raw_messages)
summary = _truncate_text(existing_summary or "", MAX_SUMMARY_CHARS)
keep_limit = max(2, recent_window_turns * 2)
split_idx = max(0, len(sanitized) - keep_limit)
if split_idx < len(sanitized) and sanitized[split_idx]["role"] == "assistant":
split_idx += 1
older = sanitized[:split_idx]
recent = sanitized[split_idx:]
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
while not older and total_chars > char_budget and len(recent) > 2:
move_count = 2 if (len(recent) >= 4 and recent[0]["role"] == "user" and recent[1]["role"] == "assistant") else 1
older.extend(recent[:move_count])
recent = recent[move_count:]
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
if not older:
return {
"summary": summary,
"recent_messages": recent,
"compacted": False,
"compacted_count": 0,
}
next_summary = ""
if ai_ready and ai_client is not None:
try:
effective_client = ai_client
if type(ai_client) is AIProviderClient and ai_client.llm_config:
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=900)
transcript = "\n".join(
f"{'用户' if m['role'] == 'user' else 'AI 参谋'}: {m['content']}" for m in older
)
compact_req = SituationalAnalysisRequest(
title="Planet 多轮对话上下文压缩摘要",
objective=(
"请将以下较早的多轮对话与既有摘要压缩为简明中文备忘(不超过 280 字),"
"保留:1) 用户聚焦的图层/国家/新闻实体与口径边界;2) 已核验关键数据结论;"
"3) 尚未完结的追问线索。严禁保留客套或编造数值。"
),
system_prompt="你是精准的对话上下文压缩器,只输出精炼中文要点摘要。",
context={
"existing_summary": summary or None,
"archived_dialogue": transcript,
},
thinking=None,
)
resp = await asyncio.wait_for(effective_client.analyze(compact_req), timeout=12.0)
clean_resp, _ = strip_thinking_text(str(getattr(resp, "content", "") or ""))
next_summary = _truncate_text(clean_resp, MAX_SUMMARY_CHARS)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning_event(
"LLM conversation compaction fell back to deterministic summary",
event="ai_memory.compaction.fallback",
context={"error": str(exc), "older_count": len(older)},
)
if not next_summary:
next_summary = build_deterministic_compaction_summary(summary, older)
return {
"summary": next_summary,
"recent_messages": recent,
"compacted": True,
"compacted_count": len(older),
}
+5 -2
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Literal from typing import Literal
WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel"] WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel", "news"]
SpatialDomain = Literal["global", "cable", "satellite", "vessel"] SpatialDomain = Literal["global", "cable", "satellite", "vessel"]
ReportSubjectType = Literal[ ReportSubjectType = Literal[
"global_posture", "global_posture",
@@ -13,11 +13,12 @@ ReportSubjectType = Literal[
"cable_posture", "cable_posture",
"satellite_posture", "satellite_posture",
"vessel_posture", "vessel_posture",
"news_brief",
] ]
SPATIAL_POSTURE_DOMAINS: frozenset[str] = frozenset({"global", "cable", "satellite", "vessel"}) SPATIAL_POSTURE_DOMAINS: frozenset[str] = frozenset({"global", "cable", "satellite", "vessel"})
SUPPORTED_WORKBENCH_DOMAINS: frozenset[str] = frozenset( SUPPORTED_WORKBENCH_DOMAINS: frozenset[str] = frozenset(
{"global", "compute", "bgp", "cable", "satellite", "vessel"} {"global", "compute", "bgp", "cable", "satellite", "vessel", "news"}
) )
DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = { DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
@@ -27,6 +28,7 @@ DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
"cable": "cable_posture", "cable": "cable_posture",
"satellite": "satellite_posture", "satellite": "satellite_posture",
"vessel": "vessel_posture", "vessel": "vessel_posture",
"news": "news_brief",
} }
SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = { SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
@@ -36,6 +38,7 @@ SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
"cable_posture": "cable", "cable_posture": "cable",
"satellite_posture": "satellite", "satellite_posture": "satellite",
"vessel_posture": "vessel", "vessel_posture": "vessel",
"news_brief": "news",
} }
@@ -520,7 +520,7 @@ async def investigate_spatial_domain(
timeout=35.0, timeout=35.0,
) )
_raise_if_cancelled(cancel_event) _raise_if_cancelled(cancel_event)
raw_text = (llm_resp.answer or "").strip() raw_text = (llm_resp.content or "").strip()
assert_no_thinking_leak(raw_text) assert_no_thinking_leak(raw_text)
parsed = extract_json_object(raw_text) parsed = extract_json_object(raw_text)
if not isinstance(parsed, dict): if not isinstance(parsed, dict):
+613
View File
@@ -0,0 +1,613 @@
"""Adaptive SSE streaming turn orchestrator with thinking process, model attribution, and news context."""
from __future__ import annotations
import asyncio
from collections import defaultdict, deque
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
import json
import os
from typing import Any
import uuid
from fastapi import HTTPException, Request, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.situational_assessment import InvestigationSession
from app.schemas.ai import ChatMessage, SituationalAnalysisRequest
from app.services.ai.access_policy import AccessContext
from app.services.ai.conversation_memory import (
compact_conversation_history,
sanitize_memory_notes,
sanitize_pinned_summaries,
)
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
from app.services.ai.tool_registry import (
TimeBasis,
query_global_situational_tool,
query_recent_earth_news_tool,
)
from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn
from app.services.ai_client import AIProviderClient
logger = get_logger(__name__, service="ai_stream")
_STREAM_QUOTA_WINDOW: dict[str, deque[datetime]] = defaultdict(deque)
_GEOPOLITICAL_OR_NEWS_KEYWORDS = (
"国际局势",
"全球局势",
"地缘",
"新闻",
"报道",
"外交",
"冲突",
"制裁",
"关税",
"战争",
"和平",
"热点",
"geopolit",
"headline",
"news",
"international situation",
"world situation",
)
def reset_stream_quota_ledger() -> None:
"""Reset in-memory public stream rate limiter state (for deterministic tests)."""
_STREAM_QUOTA_WINDOW.clear()
def check_stream_quota(access: AccessContext) -> None:
"""Enforce bounded hourly quota on adaptive streaming AI turns across all access tiers."""
default_public_cap = int(os.getenv("PLANET_PUBLIC_AI_STREAM_HOURLY_QUOTA", "60"))
limit = access.hourly_paid_quota if access.hourly_paid_quota > 0 else default_public_cap
if limit <= 0:
return
now = datetime.now(UTC)
window_start = now - timedelta(hours=1)
dq = _STREAM_QUOTA_WINDOW[access.actor_key]
while dq and dq[0] < window_start:
dq.popleft()
if len(dq) >= limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"Hourly AI stream quota ({limit}) exceeded.",
)
dq.append(now)
def build_streaming_thinking_config(ai_client: AIProviderClient) -> dict[str, Any] | None:
"""Enable streamed reasoning tokens for MiniMax/Anthropic providers when streaming turns."""
llm_cfg = getattr(ai_client, "llm_config", None) or {}
provider = str(llm_cfg.get("provider") or "").strip().lower()
provider_api = str(llm_cfg.get("provider_api") or "").strip().lower()
model = str(llm_cfg.get("model") or "").strip().lower()
if "minimax-m3" in model:
return {"type": "adaptive", "effort": "medium"}
if provider == "minimax" or provider_api == "anthropic-messages" or "anthropic" in provider or "claude" in model:
return {"type": "enabled", "budget_tokens": 2048}
return None
def _is_geopolitical_or_news_question(
question: str,
*,
domain: str,
news_context: dict[str, Any] | None,
) -> bool:
if domain == "news" or news_context:
return True
q = (question or "").strip().lower()
return any(kw in q for kw in _GEOPOLITICAL_OR_NEWS_KEYWORDS)
def _format_sse(event: str, payload: dict[str, Any]) -> str:
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
def _build_news_fallback_markdown(
*,
question: str,
news_context: dict[str, Any] | None,
recent_news: dict[str, Any],
ai_configured: bool,
fallback_reason: str | None = None,
) -> str:
lines: list[str] = []
if news_context:
title = str(news_context.get("title") or "新闻速递").strip()
source = str(news_context.get("source") or "").strip()
region = str(news_context.get("region") or news_context.get("region_key") or "").strip()
published_at = str(news_context.get("published_at") or "").strip()
summary = str(news_context.get("summary") or "").strip()
lines.append(f"### 新闻焦点:{title}")
meta_parts = [p for p in (source, region, published_at) if p]
if meta_parts:
lines.append(f"- **来源与时间**:{' · '.join(meta_parts)}")
if summary:
lines.append(f"- **报道摘要**:{summary}")
else:
lines.append("### 全球局势与新闻态势速览")
if question:
lines.append(f"- **当前问题**:{question}")
items = list(recent_news.get("items") or [])
if items:
lines.append("")
lines.append("#### 近期关联动态")
for item in items[:5]:
item_title = str(item.get("title") or "").strip()
item_src = str(item.get("source") or "").strip()
item_reg = str(item.get("region") or "").strip()
if item_title:
meta = f"({item_src}{' · ' + item_reg if item_reg else ''})" if item_src else ""
lines.append(f"- {item_title}{meta}")
if not ai_configured:
lines.append("")
lines.append("> 当前后台尚未接入可用 AI 大模型,以上为内置新闻与遥测结构化汇总。")
elif fallback_reason:
lines.append("")
lines.append(f"> AI 流式生成暂时不可用({fallback_reason}),已自动回退为内置结构化汇总。")
return "\n".join(lines).strip()
def _build_news_analysis_request(
*,
question: str,
news_context: dict[str, Any] | None,
recent_news: dict[str, Any],
global_snapshot: dict[str, Any],
thinking_cfg: dict[str, Any] | None,
conversation_messages: list[ChatMessage] | None = None,
conversation_summary: str = "",
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
) -> SituationalAnalysisRequest:
context: dict[str, Any] = {
"focused_news": news_context or None,
"recent_news_headlines": (recent_news.get("items") or [])[:10],
"global_infrastructure_summary": global_snapshot.get("domain_summaries") or [],
}
if conversation_summary:
context["conversation_summary"] = conversation_summary
if memory_notes:
context["user_memory_notes"] = memory_notes
if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries
return SituationalAnalysisRequest(
title="Planet 全球新闻与国际局势研判",
objective=(
f"用户提问:{question}\n\n"
"请结合多轮对话延续性与记忆备忘,直接使用中文(若用户用英文提问则用英文)输出结构清晰的 Markdown 深度分析,包括:\n"
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
"3. **后续重点观察信号与不确定边界**。\n"
"请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。"
),
system_prompt=(
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
"如有前序对话与用户备忘录,请保持指代与口径延续。"
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。"
),
context=context,
constraints=[
"Output clean user-facing Markdown directly (not JSON).",
"Distinguish reported facts from analytical outlook.",
],
thinking=thinking_cfg,
messages=conversation_messages or [],
)
def _build_telemetry_stream_request(
*,
domain: str,
question: str,
base_answer_md: str,
evidence: dict[str, Any],
view_spec: dict[str, Any] | None,
recent_news: dict[str, Any] | None,
thinking_cfg: dict[str, Any] | None,
conversation_messages: list[ChatMessage] | None = None,
conversation_summary: str = "",
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
) -> SituationalAnalysisRequest:
context: dict[str, Any] = {
"domain": domain,
"verified_baseline_summary": base_answer_md,
"evidence": evidence,
"view_headline": (view_spec or {}).get("headline"),
}
if recent_news and recent_news.get("items"):
context["recent_news_headlines"] = (recent_news.get("items") or [])[:10]
if conversation_summary:
context["conversation_summary"] = conversation_summary
if memory_notes:
context["user_memory_notes"] = memory_notes
if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries
return SituationalAnalysisRequest(
title=f"Planet 态势参谋分析({domain})",
objective=(
f"用户问题:{question}\n\n"
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。"
),
system_prompt=(
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。"
),
context=context,
constraints=[
"Output clean Markdown directly (not JSON).",
"Do not invent telemetry counts or unverified outages outside context.",
],
thinking=thinking_cfg,
messages=conversation_messages or [],
)
async def stream_session_turn(
db: AsyncSession,
*,
request: Request | None,
session: InvestigationSession | None,
question: str,
context_override: dict[str, Any] | None,
news_context: dict[str, Any] | None,
access: AccessContext,
ai_client: AIProviderClient | None,
client_run_id: str | None = None,
issued_session_token: str | None = None,
history: list[dict[str, Any]] | None = None,
conversation_summary: str | None = None,
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
) -> AsyncIterator[str]:
"""Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline."""
check_stream_quota(access)
session_id_val = str(session.id) if session is not None else "stateless"
run_id = client_run_id or f"run-{uuid.uuid4().hex[:12]}"
merged_ctx: dict[str, Any] = {}
if session is not None and isinstance(session.context_state, dict):
merged_ctx.update(session.context_state)
if context_override:
for k, v in context_override.items():
if v is not None:
merged_ctx[k] = v
raw_history = history if history else merged_ctx.get("recent_messages")
existing_summary = str(
conversation_summary
if conversation_summary is not None
else merged_ctx.get("conversation_summary") or ""
)
clean_memory_notes = sanitize_memory_notes(memory_notes)
clean_pinned_summaries = sanitize_pinned_summaries(
pinned_summaries
if pinned_summaries is not None
else [
f"{p.get('pin_id', 'PIN')}: {p.get('title', '')}"
for p in ((getattr(session, "pinned_items", None) or []) if session is not None else [])
if isinstance(p, dict) and p.get("title")
]
)
routed = classify_turn_intent(question, merged_ctx)
explicit_domain = str((context_override or {}).get("domain") or "").strip().lower()
domain = "news" if news_context or explicit_domain == "news" else str(routed.get("domain") or "global")
is_pure_view = bool(routed.get("is_pure_projection") or routed.get("auto_play_presentation"))
geo_or_news_query = _is_geopolitical_or_news_question(
question,
domain=domain,
news_context=news_context,
)
time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective"
cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at")
codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"])
visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {})
ai_ready = False
provider_name = ""
model_name = ""
if ai_client is not None:
ai_ready, provider_name, model_name = await ai_client.is_ready()
compaction = await compact_conversation_history(
raw_history,
existing_summary,
ai_client=ai_client,
ai_ready=ai_ready,
)
compacted_summary = str(compaction.get("summary") or "")
recent_history = list(compaction.get("recent_messages") or [])
compacted_flag = bool(compaction.get("compacted"))
memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries)
view_spec: dict[str, Any] | None = None
scene_spec: dict[str, Any] | None = None
evidence: dict[str, Any] = {}
subject_key = "global"
revision = 1
base_answer_md = ""
context_state: dict[str, Any] = {**merged_ctx, "domain": domain}
recent_news: dict[str, Any] = {"items": [], "evidence": {}}
if news_context or domain == "news":
news_region = str((news_context or {}).get("region_key") or "").strip() or None
recent_news = await query_recent_earth_news_tool(db, region=news_region, limit=10)
global_snap = await query_global_situational_tool(
db,
selected_codes=codes,
visible_layers=visible_layers,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
evidence = {**(recent_news.get("evidence") or {}), **(global_snap.get("evidence") or {})}
if news_context and news_context.get("url"):
evidence["ev-news-focus"] = {
"id": "ev-news-focus",
"title": str(news_context.get("title") or "聚焦新闻"),
"publisher": str(news_context.get("source") or "Planet News"),
"url": str(news_context.get("url") or ""),
"published_at": str(news_context.get("published_at") or ""),
"locator": str(news_context.get("region") or news_context.get("region_key") or "news"),
}
subject_key = f"news:{(news_context or {}).get('id') or news_region or 'global'}"
base_answer_md = _build_news_fallback_markdown(
question=question,
news_context=news_context,
recent_news=recent_news,
ai_configured=ai_ready,
)
else:
base_turn = await execute_session_turn(
db,
session=session,
question=question,
context_override=context_override,
prefer_llm=False,
access=access,
ai_client=None,
client_run_id=None,
)
view_spec = base_turn.get("view_spec")
scene_spec = base_turn.get("scene_spec")
evidence = base_turn.get("evidence") or {}
subject_key = str(base_turn.get("subject_key") or domain)
revision = int(base_turn.get("revision") or 1)
base_answer_md = str((base_turn.get("reply") or {}).get("answer_markdown") or "")
if isinstance(base_turn.get("context_state"), dict):
context_state = base_turn["context_state"]
if domain == "global" and (geo_or_news_query or ai_ready):
recent_news = await query_recent_earth_news_tool(db, limit=10)
evidence = {**evidence, **(recent_news.get("evidence") or {})}
if geo_or_news_query and not is_pure_view:
# Conversational international/news questions should focus on the narrative, not a static bar chart.
view_spec = None
scene_spec = None
if not ai_ready:
base_answer_md = _build_news_fallback_markdown(
question=question,
news_context=None,
recent_news=recent_news,
ai_configured=False,
)
meta_payload: dict[str, Any] = {
"session_id": session_id_val,
"run_id": run_id,
"domain": domain,
"subject_key": subject_key,
"revision": revision,
"ai_enabled": ai_ready and not is_pure_view,
"provider": provider_name if (ai_ready and not is_pure_view) else None,
"model": model_name if (ai_ready and not is_pure_view) else None,
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"view_spec": view_spec,
"scene_spec": scene_spec,
"evidence": evidence,
"context_state": context_state,
}
if issued_session_token:
meta_payload["session_token"] = issued_session_token
yield _format_sse("meta", meta_payload)
def _persist_session_memory(answer_text: str) -> None:
if session is None or not isinstance(session.context_state, dict):
return
updated_recent = [*recent_history, {"role": "user", "content": question}]
if answer_text:
updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
session.context_state = {
**session.context_state,
"conversation_summary": compacted_summary,
"recent_messages": updated_recent[-8:],
}
if not ai_ready or is_pure_view or ai_client is None:
_persist_session_memory(base_answer_md)
if base_answer_md:
yield _format_sse("text", {"delta": base_answer_md})
yield _format_sse(
"done",
{
"status": "completed",
"generation_mode": "deterministic_baseline",
"zero_token": True,
"provider": None,
"model": None,
"usage": {},
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"answer_markdown": base_answer_md,
"reasoning_markdown": "",
},
)
return
conversation_messages = [
ChatMessage(role=m["role"], content=m["content"]) for m in recent_history
]
thinking_cfg = build_streaming_thinking_config(ai_client)
effective_client = ai_client
current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0)
if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200:
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
analysis_req = (
_build_news_analysis_request(
question=question,
news_context=news_context,
recent_news=recent_news,
global_snapshot=await query_global_situational_tool(
db,
selected_codes=codes,
visible_layers=visible_layers,
time_basis=time_basis,
cutoff_at=cutoff_at,
),
thinking_cfg=thinking_cfg,
conversation_messages=conversation_messages,
conversation_summary=compacted_summary,
memory_notes=clean_memory_notes,
pinned_summaries=clean_pinned_summaries,
)
if (news_context or domain == "news")
else _build_telemetry_stream_request(
domain=domain,
question=question,
base_answer_md=base_answer_md,
evidence=evidence,
view_spec=view_spec,
recent_news=recent_news if domain == "global" else None,
thinking_cfg=thinking_cfg,
conversation_messages=conversation_messages,
conversation_summary=compacted_summary,
memory_notes=clean_memory_notes,
pinned_summaries=clean_pinned_summaries,
)
)
text_chunks: list[str] = []
reasoning_chunks: list[str] = []
resolved_provider = provider_name
resolved_model = model_name
final_usage: dict[str, Any] = {}
try:
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
if request is not None and await request.is_disconnected():
return
ev_type = str(ev.get("event") or "")
if ev_type == "start":
if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"]
if isinstance(ev.get("model"), str) and ev["model"]:
resolved_model = ev["model"]
elif ev_type == "reasoning":
delta = ev.get("delta")
if isinstance(delta, str) and delta:
reasoning_chunks.append(delta)
yield _format_sse("reasoning", {"delta": delta})
elif ev_type == "text":
delta = ev.get("delta")
if isinstance(delta, str) and delta:
text_chunks.append(delta)
yield _format_sse("text", {"delta": delta})
elif ev_type == "done":
if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"]
if isinstance(ev.get("model"), str) and ev["model"]:
resolved_model = ev["model"]
if isinstance(ev.get("usage"), dict):
final_usage = ev["usage"]
elif ev_type == "error":
raise RuntimeError(str(ev.get("detail") or "AI stream error"))
combined_text = "".join(text_chunks).strip()
if not combined_text:
raise RuntimeError("AI provider stream returned empty response")
clean_text, inline_thoughts = strip_thinking_text(combined_text)
combined_reasoning = "".join(reasoning_chunks).strip()
if inline_thoughts:
extra_thought = "\n\n".join(inline_thoughts)
combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
final_answer_md = clean_text or combined_text
_persist_session_memory(final_answer_md)
if hasattr(db, "commit"):
try:
await db.commit()
except Exception:
pass
yield _format_sse(
"done",
{
"status": "completed",
"generation_mode": "llm_verified",
"zero_token": False,
"provider": resolved_provider,
"model": resolved_model,
"usage": final_usage,
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"answer_markdown": final_answer_md,
"reasoning_markdown": combined_reasoning,
},
)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning_event(
"AI stream turn failed",
event="ai_stream.llm.fallback",
context={"domain": domain, "emitted_text": bool(text_chunks), "error": str(exc)},
)
if text_chunks:
yield _format_sse("error", {"detail": str(exc), "partial": True})
return
fallback_md = (
_build_news_fallback_markdown(
question=question,
news_context=news_context,
recent_news=recent_news,
ai_configured=True,
fallback_reason=str(exc),
)
if (news_context or domain == "news" or geo_or_news_query)
else f"{base_answer_md}\n\n> AI 流式研判暂时回退:{exc}".strip()
)
if fallback_md:
yield _format_sse("text", {"delta": fallback_md})
yield _format_sse(
"done",
{
"status": "completed",
"generation_mode": "deterministic_fallback",
"zero_token": True,
"provider": None,
"model": None,
"usage": {},
"answer_markdown": fallback_md,
"reasoning_markdown": "".join(reasoning_chunks).strip(),
"fallback_reason": str(exc),
},
)
+93 -5
View File
@@ -11,11 +11,13 @@ from urllib.parse import urljoin, urlparse
import httpx import httpx
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from sqlalchemy import select from sqlalchemy import desc, func, select
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger from app.core.logging import get_logger
from app.models.bgp_incident import BGPIncident from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.earth_news import EarthNewsItem
from app.schemas.compute_configuration import ComputeConfiguration from app.schemas.compute_configuration import ComputeConfiguration
from app.services.ai_tools.schemas import FetchedEvidence from app.services.ai_tools.schemas import FetchedEvidence
from app.services.compute_configuration import read_configuration from app.services.compute_configuration import read_configuration
@@ -610,7 +612,20 @@ async def query_satellite_posture_tool(
safe_limit = max(50, min(int(limit or 1200), 3000)) safe_limit = max(50, min(int(limit or 1200), 3000))
features: list[dict[str, Any]] = [] features: list[dict[str, Any]] = []
catalog_total: int | None = None
limitations: list[str] = [] limitations: list[str] = []
try:
count_stmt = select(func.count(CollectedData.id)).where(
CollectedData.source == "celestrak_tle",
CollectedData.is_current.is_(True),
CollectedData.name != "Unknown",
)
counted = (await db.execute(count_stmt)).scalar_one_or_none()
if isinstance(counted, int) and counted > 0:
catalog_total = counted
except Exception:
catalog_total = None
try: try:
sat_fc = await _build_satellites_geojson(limit=safe_limit, db=db) sat_fc = await _build_satellites_geojson(limit=safe_limit, db=db)
features = list(sat_fc.get("features") or []) features = list(sat_fc.get("features") or [])
@@ -622,6 +637,8 @@ async def query_satellite_posture_tool(
) )
limitations.append("内置卫星 TLE 查询受限") limitations.append("内置卫星 TLE 查询受限")
effective_total = catalog_total if catalog_total is not None and catalog_total >= len(features) else len(features)
by_constellation: dict[str, int] = {} by_constellation: dict[str, int] = {}
by_orbit_regime: dict[str, int] = {} by_orbit_regime: dict[str, int] = {}
sample_satellites: list[dict[str, Any]] = [] sample_satellites: list[dict[str, Any]] = []
@@ -657,15 +674,18 @@ async def query_satellite_posture_tool(
sorted_constellations = dict( sorted_constellations = dict(
sorted(by_constellation.items(), key=lambda kv: kv[1], reverse=True)[:10] sorted(by_constellation.items(), key=lambda kv: kv[1], reverse=True)[:10]
) )
if len(features) >= safe_limit: if effective_total > len(features):
limitations.append(f"本次卫星样本按性能上限截取前 {safe_limit} 颗轨道目标,不代表全库总编目。") limitations.append(
f"在轨卫星全库共 {effective_total} 颗;星座/轨道分布基于最新 {len(features)} 颗样本统计。"
)
if time_basis == "as_known_then": if time_basis == "as_known_then":
limitations.append("在轨星历基于最新同步批次(celestrak_tle),未按历史截点回卷旧 TLE。") limitations.append("在轨星历基于最新同步批次(celestrak_tle),未按历史截点回卷旧 TLE。")
return { return {
"domain": "satellite", "domain": "satellite",
"available": len(features) > 0, "available": effective_total > 0,
"satellites_total": len(features), "satellites_total": effective_total,
"sampled_count": len(features),
"sample_limit": safe_limit, "sample_limit": safe_limit,
"by_constellation": sorted_constellations, "by_constellation": sorted_constellations,
"by_orbit_regime": by_orbit_regime, "by_orbit_regime": by_orbit_regime,
@@ -678,6 +698,74 @@ async def query_satellite_posture_tool(
} }
async def query_recent_earth_news_tool(
db: AsyncSession,
*,
region: str | None = None,
limit: int = 12,
) -> dict[str, Any]:
"""Read-only built-in snapshot of recent global/regional Earth news items for geopolitical & news copilot turns."""
base_ev_id = "ev-news-1"
evidence = {
base_ev_id: {
"id": base_ev_id,
"title": "Planet 全球态势新闻聚合快照(earth_news_items)",
"publisher": "Planet Global News Monitor",
"url": "/api/v1/earth/news",
"published_at": datetime.now(UTC).date().isoformat(),
"locator": f"builtin:earth_news:{region or 'global'}:limit={limit}",
}
}
if not hasattr(db, "execute"):
return {"domain": "news", "available": False, "items": [], "evidence": evidence}
safe_limit = max(1, min(int(limit or 12), 25))
items: list[dict[str, Any]] = []
try:
stmt = (
select(EarthNewsItem)
.where(EarthNewsItem.resolved_at.is_(None))
.order_by(desc(EarthNewsItem.published_at), desc(EarthNewsItem.last_seen_at))
.limit(safe_limit)
)
if region:
stmt = stmt.where(EarthNewsItem.region == region)
rows = (await db.execute(stmt)).scalars().all()
for row in rows:
loc_meta = dict(row.location_meta or {})
news_meta = loc_meta.get("news_meta") if isinstance(loc_meta.get("news_meta"), dict) else {}
localizations = row.localizations if isinstance(row.localizations, dict) else {}
zh_loc = localizations.get("zh-CN") if isinstance(localizations.get("zh-CN"), dict) else {}
items.append(
{
"id": row.id,
"title": zh_loc.get("title") or row.title,
"summary": (zh_loc.get("summary") or row.summary or "")[:400],
"source": row.source or row.feed_name,
"region": row.region,
"location_label": row.location_label,
"category": news_meta.get("category") or "other",
"breaking_level": news_meta.get("breaking_level") or "none",
"published_at": row.published_at.isoformat() if row.published_at else None,
"url": row.url,
}
)
except Exception as exc:
logger.warning_event(
"Recent earth news query degraded",
event="ai_tool.earth_news.degraded",
context={"error": str(exc)},
)
return {
"domain": "news",
"available": len(items) > 0,
"count": len(items),
"items": items,
"evidence": evidence,
}
async def query_vessel_posture_tool( async def query_vessel_posture_tool(
db: AsyncSession, db: AsyncSession,
*, *,
+77
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from collections.abc import AsyncIterator
import json import json
from time import perf_counter from time import perf_counter
@@ -45,6 +46,82 @@ class AIProviderClient:
) )
self.llm_config = llm_config or {} self.llm_config = llm_config or {}
async def is_ready(self) -> tuple[bool, str, str]:
"""Return `(configured_and_enabled, provider, model)` without calling LLM inference."""
if not self.service_url:
return False, "unconfigured", ""
if isinstance(self.llm_config, dict) and self.llm_config:
provider = str(self.llm_config.get("provider") or "").strip().lower()
provider_api = str(self.llm_config.get("provider_api") or "").strip().lower()
base_url = str(self.llm_config.get("base_url") or "").strip()
model = str(self.llm_config.get("model") or "").strip()
api_key = str(self.llm_config.get("api_key") or "").strip()
if not provider or provider == "disabled":
return False, provider or "disabled", model
needs_key = provider != "ollama" and provider_api != "ollama-generate"
configured = bool(base_url and model and (api_key or not needs_key))
return configured, provider, model
try:
status_resp = await self.get_status()
return (
bool(status_resp.enabled and status_resp.configured),
str(status_resp.provider or ""),
str(status_resp.model or ""),
)
except Exception:
return False, "unavailable", ""
async def stream_analyze(
self,
payload: SituationalAnalysisRequest,
request_id: str | None = None,
) -> AsyncIterator[dict]:
"""Stream structured SSE events (`start`, `reasoning`, `text`, `done`, `error`) from aiprovider."""
if not self.service_url:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="AI provider service URL is not configured.",
)
async with httpx.AsyncClient(timeout=self.timeout) as client:
async with client.stream(
"POST",
f"{self.service_url}/v1/analyze/stream",
headers=self._headers(request_id),
json=payload.model_dump(),
) as response:
if response.status_code >= 400:
detail = (await response.aread()).decode("utf-8", errors="replace")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"AI provider service request failed: {detail or response.status_code}",
)
event_name = ""
data_lines: list[str] = []
async for raw_line in response.aiter_lines():
line = raw_line.rstrip("\r")
if line == "":
if data_lines:
raw_json = "\n".join(data_lines)
event_name_cur = event_name
event_name = ""
data_lines = []
parsed = json.loads(raw_json)
if isinstance(parsed, dict):
parsed.setdefault("event", event_name_cur or "message")
yield parsed
continue
if line.startswith(":"):
continue
if line.startswith("event:"):
event_name = line[6:].strip()
elif line.startswith("data:"):
data_lines.append(line[5:].lstrip())
if data_lines:
parsed = json.loads("\n".join(data_lines))
if isinstance(parsed, dict):
parsed.setdefault("event", event_name or "message")
yield parsed
def _headers(self, request_id: str | None = None) -> dict[str, str]: def _headers(self, request_id: str | None = None) -> dict[str, str]:
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
if self.service_token: if self.service_token:
+182 -13
View File
@@ -1,16 +1,18 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from collections import OrderedDict
from collections.abc import Awaitable, Callable from collections.abc import Awaitable, Callable
from contextlib import suppress from contextlib import suppress
from dataclasses import dataclass, replace from dataclasses import dataclass, replace
import gzip
import hashlib import hashlib
import json import json
import time import time
from typing import Any from typing import Any
from uuid import uuid4 from uuid import uuid4
from fastapi import HTTPException, Response from fastapi import HTTPException, Request, Response
from app.core.cache import _RedisClient from app.core.cache import _RedisClient
from app.core.config import settings from app.core.config import settings
@@ -27,6 +29,8 @@ DEFAULT_MAX_FEATURES = 5000
DEFAULT_MAX_BYTES = 5 * 1024 * 1024 DEFAULT_MAX_BYTES = 5 * 1024 * 1024
DEFAULT_BBOX_PRECISION_DEGREES = 0.1 DEFAULT_BBOX_PRECISION_DEGREES = 0.1
DEV_CACHE_KEY_HEADER = {"development", "dev", "test", "testing", "local"} DEV_CACHE_KEY_HEADER = {"development", "dev", "test", "testing", "local"}
ENCODED_ARTIFACT_CACHE_MAX_ENTRIES = 8
GZIP_COMPRESS_LEVEL = 5
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -49,6 +53,25 @@ class EarthLayerCacheResult:
bytes: int bytes: int
@dataclass(frozen=True)
class _EncodedLayerArtifact:
raw_bytes: bytes
gzip_bytes: bytes
etag: str
features: int
byte_length: int
@dataclass(frozen=True)
class EarthLayerEncodedResult:
artifact: _EncodedLayerArtifact
state: str
key: str
_ENCODED_ARTIFACT_CACHE: OrderedDict[tuple[str, str], _EncodedLayerArtifact] = OrderedDict()
class EarthLayerCache: class EarthLayerCache:
def __init__(self) -> None: def __init__(self) -> None:
self._client = None self._client = None
@@ -81,6 +104,16 @@ class EarthLayerCache:
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:32] digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:32]
return f"{EARTH_LAYER_LOCK_PREFIX}:{digest}" return f"{EARTH_LAYER_LOCK_PREFIX}:{digest}"
def get_raw(self, key: str) -> bytes | None:
raw = self.client.get(key)
if not raw:
return None
if isinstance(raw, bytes):
return raw
if isinstance(raw, str):
return raw.encode("utf-8")
return None
def get_json(self, key: str) -> dict[str, Any] | None: def get_json(self, key: str) -> dict[str, Any] | None:
raw = self.client.get(key) raw = self.client.get(key)
if not raw: if not raw:
@@ -191,15 +224,143 @@ def format_bbox_key(bbox: tuple[float, float, float, float]) -> str:
return ",".join(f"{value:.1f}" for value in bbox) return ",".join(f"{value:.1f}" for value in bbox)
def apply_cache_headers(response: Response | None, result: EarthLayerCacheResult) -> None: def _cache_headers(
if response is None: result: EarthLayerCacheResult | EarthLayerEncodedResult,
return ) -> dict[str, str]:
response.headers["X-Planet-Cache"] = result.state if isinstance(result, EarthLayerEncodedResult):
response.headers["X-Planet-Cache-Features"] = str(result.features) features, byte_length = result.artifact.features, result.artifact.byte_length
response.headers["X-Planet-Cache-Bytes"] = str(result.bytes) else:
features, byte_length = result.features, result.bytes
headers = {
"X-Planet-Cache": result.state,
"X-Planet-Cache-Features": str(features),
"X-Planet-Cache-Bytes": str(byte_length),
}
env_name = str(getattr(settings, "ENVIRONMENT", "") or "development").lower() env_name = str(getattr(settings, "ENVIRONMENT", "") or "development").lower()
if env_name in DEV_CACHE_KEY_HEADER: if env_name in DEV_CACHE_KEY_HEADER:
response.headers["X-Planet-Cache-Key"] = result.key headers["X-Planet-Cache-Key"] = result.key
return headers
def apply_cache_headers(
response: Response | None,
result: EarthLayerCacheResult | EarthLayerEncodedResult,
) -> None:
if response is not None:
response.headers.update(_cache_headers(result))
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
if not if_none_match:
return False
normalized_target = etag.strip()
if normalized_target.startswith("W/"):
normalized_target = normalized_target[2:].strip()
for candidate in if_none_match.split(","):
token = candidate.strip()
if token == "*":
return True
if token.startswith("W/"):
token = token[2:].strip()
if token == normalized_target:
return True
return False
def _encode_layer_bytes(
key: str,
raw_bytes: bytes,
*,
features: int | None = None,
) -> _EncodedLayerArtifact:
etag = f'"{hashlib.sha256(raw_bytes).hexdigest()[:24]}"'
cache_key = (key, etag)
cached = _ENCODED_ARTIFACT_CACHE.get(cache_key)
if cached is not None:
_ENCODED_ARTIFACT_CACHE.move_to_end(cache_key)
return cached
resolved_features = features
if resolved_features is None:
parsed = json.loads(raw_bytes)
if not isinstance(parsed, dict):
raise ValueError("Earth layer cache payload must be a JSON object")
resolved_features = _feature_count(parsed)
gzip_bytes = gzip.compress(raw_bytes, compresslevel=GZIP_COMPRESS_LEVEL)
artifact = _EncodedLayerArtifact(
raw_bytes=raw_bytes,
gzip_bytes=gzip_bytes,
etag=etag,
features=resolved_features,
byte_length=len(raw_bytes),
)
_ENCODED_ARTIFACT_CACHE[cache_key] = artifact
while len(_ENCODED_ARTIFACT_CACHE) > ENCODED_ARTIFACT_CACHE_MAX_ENTRIES:
_ENCODED_ARTIFACT_CACHE.popitem(last=False)
return artifact
async def resolve_layer_encoded_payload(
*,
key: str,
policy: EarthLayerCachePolicy,
builder: Callable[[], Awaitable[dict[str, Any]]],
) -> EarthLayerEncodedResult:
flight_key = (asyncio.get_running_loop(), key)
if flight_key not in earth_layer_cache._inflight:
cached_raw = None
with suppress(Exception):
cached_raw = earth_layer_cache.get_raw(key)
if cached_raw is not None:
try:
artifact = _encode_layer_bytes(key, cached_raw)
return EarthLayerEncodedResult(artifact=artifact, state="hit", key=key)
except Exception as exc:
logger.warning_event(
"Invalid raw earth layer cache payload; falling back to standard resolver",
event="earth_layer_cache.raw_decode_failed",
context={"key": key, "error": str(exc)},
)
result = await resolve_layer_payload(key=key, policy=policy, builder=builder)
raw_bytes = json.dumps(result.payload, ensure_ascii=False, default=str).encode("utf-8")
artifact = _encode_layer_bytes(key, raw_bytes, features=result.features)
return EarthLayerEncodedResult(artifact=artifact, state=result.state, key=result.key)
async def get_or_build_layer_response(
*,
key: str,
policy: EarthLayerCachePolicy,
builder: Callable[[], Awaitable[dict[str, Any]]],
request: Request,
response: Response | None = None,
) -> Response:
result = await resolve_layer_encoded_payload(key=key, policy=policy, builder=builder)
headers = _cache_headers(result)
if response is not None:
response.headers.update(headers)
headers.update({
"ETag": result.artifact.etag,
"Cache-Control": "private, no-cache",
"Vary": "Accept-Encoding",
})
if _etag_matches(request.headers.get("if-none-match"), result.artifact.etag):
return Response(status_code=304, headers=headers)
accept_encoding = (request.headers.get("accept-encoding") or "").lower()
if "gzip" in accept_encoding:
return Response(
content=result.artifact.gzip_bytes,
media_type="application/json",
headers={**headers, "Content-Encoding": "gzip"},
)
return Response(
content=result.artifact.raw_bytes,
media_type="application/json",
headers=headers,
)
async def get_or_build_layer_payload( async def get_or_build_layer_payload(
@@ -262,9 +423,11 @@ async def _resolve_layer_payload(
try: try:
async with asyncio.timeout(policy.build_wait_seconds): async with asyncio.timeout(policy.build_wait_seconds):
while True: while True:
cached = earth_layer_cache.get_json(key) cached_raw = earth_layer_cache.get_raw(key)
if cached is not None: if cached_raw is not None:
return _result(cached, state="hit", key=key) cached = json.loads(cached_raw)
if isinstance(cached, dict):
return _result(cached, state="hit", key=key, byte_length=len(cached_raw))
token = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds) token = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds)
if token is not None: if token is not None:
break break
@@ -454,13 +617,19 @@ def _with_budget_diagnostics(
return {**payload, "diagnostics": diagnostics} return {**payload, "diagnostics": diagnostics}
def _result(payload: dict[str, Any], *, state: str, key: str) -> EarthLayerCacheResult: def _result(
payload: dict[str, Any],
*,
state: str,
key: str,
byte_length: int | None = None,
) -> EarthLayerCacheResult:
return EarthLayerCacheResult( return EarthLayerCacheResult(
payload=payload, payload=payload,
state=state, state=state,
key=key, key=key,
features=_feature_count(payload), features=_feature_count(payload),
bytes=_payload_size(payload), bytes=_payload_size(payload) if byte_length is None else byte_length,
) )
+33 -10
View File
@@ -20,26 +20,47 @@ SUPPORTED_PROVIDER_APIS = {
"anthropic-messages", "anthropic-messages",
"ollama-generate", "ollama-generate",
} }
OFFICIAL_PUBLIC_CATALOG_HOSTS: dict[str, frozenset[str]] = {
"openrouter": frozenset({"openrouter.ai"}),
"opencode-go": frozenset({"opencode.ai"}),
}
class LLMProviderCatalogError(RuntimeError): class LLMProviderCatalogError(RuntimeError):
"""A safe, user-facing catalog failure with no upstream response or credentials.""" """A safe, user-facing catalog failure with no upstream response or credentials."""
class LLMProviderCatalogConfigError(LLMProviderCatalogError):
"""Invalid local catalog configuration or missing required credentials."""
@dataclass(frozen=True) @dataclass(frozen=True)
class ModelCatalog: class ModelCatalog:
url: str url: str
models: list[str] models: list[str]
def is_official_public_catalog(provider: str, base_url: str) -> bool:
provider_key = provider.strip().lower()
host = (urlsplit(base_url.strip()).hostname or "").lower()
return host in OFFICIAL_PUBLIC_CATALOG_HOSTS.get(provider_key, frozenset())
def catalog_requires_api_key(provider: str, base_url: str, provider_api: str) -> bool:
provider_key = provider.strip().lower()
if provider_key == "ollama" or provider_api == "ollama-generate":
return False
return not is_official_public_catalog(provider_key, base_url)
def model_catalog_url(provider: str, base_url: str, provider_api: str) -> str: def model_catalog_url(provider: str, base_url: str, provider_api: str) -> str:
parts = urlsplit(base_url.strip()) parts = urlsplit(base_url.strip())
if parts.scheme not in {"http", "https"} or not parts.hostname: if parts.scheme not in {"http", "https"} or not parts.hostname:
raise LLMProviderCatalogError("请填写有效的 HTTP(S) 模型基础地址。") raise LLMProviderCatalogConfigError("请填写有效的 HTTP(S) 模型基础地址。")
if parts.username or parts.password or parts.query or parts.fragment: if parts.username or parts.password or parts.query or parts.fragment:
raise LLMProviderCatalogError("模型基础地址不能包含账号、密码、查询参数或片段。") raise LLMProviderCatalogConfigError("模型基础地址不能包含账号、密码、查询参数或片段。")
if provider_api not in SUPPORTED_PROVIDER_APIS: if provider_api not in SUPPORTED_PROVIDER_APIS:
raise LLMProviderCatalogError("当前接口协议不支持模型目录查询。") raise LLMProviderCatalogConfigError("当前接口协议不支持模型目录查询。")
path = parts.path.rstrip("/") path = parts.path.rstrip("/")
if provider_api == "ollama-generate": if provider_api == "ollama-generate":
path = path.removesuffix("/api").removesuffix("/v1") + "/api/tags" path = path.removesuffix("/api").removesuffix("/v1") + "/api/tags"
@@ -132,12 +153,14 @@ async def fetch_model_catalog(
api_key: str = "", api_key: str = "",
anthropic_version: str = "2023-06-01", anthropic_version: str = "2023-06-01",
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS, timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
*,
include_auth: bool = True,
) -> ModelCatalog: ) -> ModelCatalog:
url = model_catalog_url(provider, base_url, provider_api) url = model_catalog_url(provider, base_url, provider_api)
public_catalog = provider in {"opencode-go", "openrouter"} if not api_key and catalog_requires_api_key(provider, base_url, provider_api):
if not api_key and provider_api != "ollama-generate" and not public_catalog: raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
raise LLMProviderCatalogError("请先配置当前供应商的 API Key,再刷新模型列表。")
headers = {"User-Agent": "Planet/1.0", "Accept": "application/json"} headers = {"User-Agent": "Planet/1.0", "Accept": "application/json"}
if include_auth and api_key:
if provider_api == "anthropic-messages" and provider not in { if provider_api == "anthropic-messages" and provider not in {
"opencode-go", "opencode-go",
"openrouter", "openrouter",
@@ -145,7 +168,7 @@ async def fetch_model_catalog(
"moonshotai", "moonshotai",
}: }:
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version}) headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
elif api_key: else:
headers["Authorization"] = f"Bearer {api_key}" headers["Authorization"] = f"Bearer {api_key}"
native_dashscope = provider == "alibaba" and urlsplit(url).hostname.endswith(".aliyuncs.com") native_dashscope = provider == "alibaba" and urlsplit(url).hostname.endswith(".aliyuncs.com")
params: dict[str, str | int] = {} params: dict[str, str | int] = {}
@@ -179,8 +202,8 @@ async def fetch_model_catalog(
) )
# An empty Ollama catalog is valid: no models have been installed yet. # An empty Ollama catalog is valid: no models have been installed yet.
if not models and provider_api != "ollama-generate": if not models and provider_api != "ollama-generate":
raise LLMProviderCatalogError("供应商返回了空模型目录,已保留上次模型列表。") raise LLMProviderCatalogError("供应商返回了空模型目录。")
return ModelCatalog(url=url, models=models) return ModelCatalog(url=url, models=models)
if len(rows_by_id) == previous_count: if len(rows_by_id) == previous_count:
raise LLMProviderCatalogError("供应商模型目录分页没有进展,已保留上次模型列表。") raise LLMProviderCatalogError("供应商模型目录分页没有进展。")
raise LLMProviderCatalogError("供应商模型目录分页超过限制,已保留上次模型列表。") raise LLMProviderCatalogError("供应商模型目录分页超过限制。")
+34 -19
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
from typing import Any from typing import Any
from urllib.parse import urlsplit from urllib.parse import urlsplit
from app.services.llm_model_catalog import fetch_model_catalog from app.services.llm_model_catalog import fetch_model_catalog, is_official_public_catalog
OPENCODE_GO_MODEL_PROVIDER_APIS = { OPENCODE_GO_MODEL_PROVIDER_APIS = {
"minimax-m3": "anthropic-messages", "minimax-m3": "anthropic-messages",
@@ -22,23 +22,31 @@ OPENCODE_GO_MODEL_PROVIDER_APIS = {
"minimax-m2.5": "anthropic-messages", "minimax-m2.5": "anthropic-messages",
} }
OPENCODE_GO_FALLBACK_MODELS = [ OPENCODE_GO_FALLBACK_MODELS = [
"minimax-m3",
"kimi-k3",
"glm-5.3", "glm-5.3",
"qwen3.8-max", "glm-5.3-flash",
"gpt-5.6-luna", "deepseek-v4.1-flash",
"minimax-m2.7",
"minimax-m2.5",
"kimi-k2.6",
"kimi-k2.5",
"glm-5.1",
"glm-5",
"deepseek-v4-pro", "deepseek-v4-pro",
"deepseek-v4-flash", "kimi-k3.1-pro",
"qwen3.6-plus", "kimi-k3",
"qwen3.5-plus", "kimi-k2.7-code",
"mimo-v2.5-pro", "minimax-m3",
"mimo-v2.5", "minimax-m3.1-flash",
"qwen4-max",
"qwen3.8-max",
"qwen3.8-flash",
"qwen3.7-plus",
"gpt-6-luna",
"gpt-5.6-luna",
"grok-4.7",
"claude-haiku-5-5",
"gemini-4-argon",
"mimo-v2.6-pro",
"mimo-v2.6-flash",
"hy4",
"hy4-flash-free",
"step-5-preview",
"muse-spark-1.3-contributor",
"muse-spark-1.2-contributor",
] ]
@@ -131,8 +139,14 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
"label": "OpenRouter", "label": "OpenRouter",
"provider_api": "openai-completions", "provider_api": "openai-completions",
"base_url": "https://openrouter.ai/api/v1", "base_url": "https://openrouter.ai/api/v1",
"model": "openai/gpt-5.1", "model": "openai/gpt-6.2-astra",
"models": ["openai/gpt-5.1", "anthropic/claude-sonnet-4.5", "qwen/qwen3-max"], "models": [
"openai/gpt-6.2-astra",
"openai/gpt-6.2-sol",
"google/gemini-4-neon",
"qwen/qwen4-max",
"anthropic/claude-sonnet-4.5",
],
"api_key_env": "OPENROUTER_API_KEY", "api_key_env": "OPENROUTER_API_KEY",
"source": "fallback", "source": "fallback",
}, },
@@ -141,7 +155,7 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
"label": "OpenCode Go", "label": "OpenCode Go",
"provider_api": "openai-completions", "provider_api": "openai-completions",
"base_url": "https://opencode.ai/zen/go/v1", "base_url": "https://opencode.ai/zen/go/v1",
"model": "glm-5.1", "model": "glm-5.3",
"models": OPENCODE_GO_FALLBACK_MODELS, "models": OPENCODE_GO_FALLBACK_MODELS,
"model_provider_apis": OPENCODE_GO_MODEL_PROVIDER_APIS, "model_provider_apis": OPENCODE_GO_MODEL_PROVIDER_APIS,
"api_key_env": "OPENCODE_GO_API_KEY", "api_key_env": "OPENCODE_GO_API_KEY",
@@ -195,6 +209,7 @@ async def refresh_llm_provider_preset(
resolved_api, resolved_api,
api_key or "", api_key or "",
anthropic_version, anthropic_version,
include_auth=not is_official_public_catalog(fallback["provider"], resolved_base_url),
) )
model_provider_apis = ( model_provider_apis = (
_opencode_go_model_provider_apis(catalog.models) _opencode_go_model_provider_apis(catalog.models)
+279
View File
@@ -0,0 +1,279 @@
from __future__ import annotations
import json
import httpx
import pytest
from fastapi import FastAPI
from app.api.v1 import situational_awareness
from app.schemas.ai import SituationalAnalysisResponse
from app.services.ai import spatial_domain_agent
from app.services.ai.stream_turn import reset_stream_quota_ledger
from app.services.ai_client import AIProviderClient, get_ai_provider_client
def _parse_sse_text(raw: str) -> list[tuple[str, dict]]:
events: list[tuple[str, dict]] = []
for block in raw.replace("\r\n", "\n").split("\n\n"):
if not block.strip():
continue
ev_name = "message"
data_lines: list[str] = []
for line in block.split("\n"):
if line.startswith("event:"):
ev_name = line[6:].strip()
elif line.startswith("data:"):
data_lines.append(line[5:].lstrip())
if data_lines:
events.append((ev_name, json.loads("\n".join(data_lines))))
return events
class _StubDb:
pass
@pytest.mark.asyncio
async def test_spatial_domain_agent_reads_content_attribute(monkeypatch):
class _FakeClient:
service_url = "http://aiprovider.test"
llm_config = {"provider": "minimax", "model": "MiniMax-M2.7"}
async def analyze(self, _req):
return SituationalAnalysisResponse(
provider="minimax",
model="MiniMax-M2.7",
content=json.dumps(
{
"domain": "global",
"subject_key": "global:test",
"title": "全球多图层态势",
"executive_assertion": "已成功读取大模型合成内容。",
"confirmed_facts": [{"statement": "全网多图层数据在线。", "evidence_ids": ["ev-global-1"]}],
"analytical_notes": [{"statement": "LLM 输出字段匹配成功。", "evidence_ids": ["ev-global-1"]}],
"open_gaps": ["示例口径边界。"],
"evidence_ids": ["ev-global-1"],
},
ensure_ascii=False,
),
)
async def fake_global_tool(*_args, **_kwargs):
return {
"domain": "global",
"available": True,
"domain_summaries": [],
"bgp_summary": {"active_count": 0},
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Snapshot"}},
"limitations": [],
}
monkeypatch.setattr(spatial_domain_agent, "query_global_situational_tool", fake_global_tool)
result = await spatial_domain_agent.investigate_spatial_domain(
_StubDb(),
domain="global",
question="分析全球态势",
persist=False,
ai_client=_FakeClient(),
)
assert result["generation_mode"] == "llm_verified"
assert result["payload"]["executive_assertion"] == "已成功读取大模型合成内容。"
@pytest.mark.asyncio
async def test_stream_turn_adapts_between_configured_minimax_and_disabled_ai(monkeypatch):
reset_stream_quota_ledger()
async def fake_recent_news(*_args, **_kwargs):
return {
"domain": "news",
"available": True,
"count": 1,
"items": [{"id": "n1", "title": "全球海缆路由测试头条", "source": "Reuters", "region": "global"}],
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Planet News"}},
}
async def fake_global_tool(*_args, **_kwargs):
return {
"domain": "global",
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
}
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
class _ConfiguredClient(AIProviderClient):
def __init__(self):
super().__init__(
service_url="http://aiprovider.test",
llm_config={
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "secret-key",
"model": "MiniMax-M2.7",
},
)
async def stream_analyze(self, payload, request_id=None):
assert payload.thinking == {"type": "enabled", "budget_tokens": 2048}
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
yield {"event": "reasoning", "delta": "先梳理新闻核心矛盾。"}
yield {"event": "text", "delta": "### 新闻深度分析\n\n- **要点**:供应链与光缆关注升温。"}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 42}}
class _DisabledClient(AIProviderClient):
def __init__(self):
super().__init__(
service_url="http://aiprovider.test",
llm_config={"provider": "disabled"},
)
app = FastAPI()
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
app.dependency_overrides[get_ai_provider_client] = lambda: _ConfiguredClient()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
# 1. Anonymous Earth/desktop caller uses MiniMax automatically when configured
res_ai = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
"domain": "news",
"news_context": {
"id": "n1",
"title": "全球海缆路由测试头条",
"summary": "测试新闻摘要",
"source": "Reuters",
"region": "全球",
},
},
)
assert res_ai.status_code == 200
assert "text/event-stream" in res_ai.headers["content-type"]
ai_events = _parse_sse_text(res_ai.text)
ai_names = [name for name, _ in ai_events]
assert ai_names == ["meta", "reasoning", "text", "done"]
assert ai_events[0][1]["ai_enabled"] is True
assert ai_events[0][1]["model"] == "MiniMax-M2.7"
assert ai_events[1][1]["delta"] == "先梳理新闻核心矛盾。"
assert "新闻深度分析" in ai_events[2][1]["delta"]
assert ai_events[3][1]["zero_token"] is False
assert ai_events[3][1]["generation_mode"] == "llm_verified"
assert ai_events[3][1]["model"] == "MiniMax-M2.7"
# 2. Switching provider to disabled adapts seamlessly back to deterministic baseline
app.dependency_overrides[get_ai_provider_client] = lambda: _DisabledClient()
res_no_ai = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
"domain": "news",
"news_context": {"id": "n1", "title": "全球海缆路由测试头条", "summary": "测试新闻摘要"},
},
)
assert res_no_ai.status_code == 200
no_ai_events = _parse_sse_text(res_no_ai.text)
assert no_ai_events[0][1]["ai_enabled"] is False
assert no_ai_events[0][1]["model"] is None
assert no_ai_events[-1][0] == "done"
assert no_ai_events[-1][1]["zero_token"] is True
assert no_ai_events[-1][1]["model"] is None
assert no_ai_events[-1][1]["generation_mode"] == "deterministic_baseline"
@pytest.mark.asyncio
async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
reset_stream_quota_ledger()
async def fake_global_tool(*_args, **_kwargs):
return {
"domain": "global",
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
}
async def fake_recent_news(*_args, **_kwargs):
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
captured_analyze_reqs = []
captured_stream_reqs = []
class _CompactingClient(AIProviderClient):
def __init__(self):
super().__init__(
service_url="http://aiprovider.test",
llm_config={
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "secret-key",
"model": "MiniMax-M2.7",
},
)
async def analyze(self, payload, request_id=None):
captured_analyze_reqs.append(payload)
return SituationalAnalysisResponse(
provider="minimax",
model="MiniMax-M2.7",
content="<think>internal</think>前序关注中美算力与亚太海缆冗余,已核验 343 条骨干海缆。",
)
async def stream_analyze(self, payload, request_id=None):
captured_stream_reqs.append(payload)
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
yield {"event": "text", "delta": "结合前文 343 条海缆与您的亚太聚焦偏好,补充说明如下。"}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 55}}
app = FastAPI()
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
app.dependency_overrides[get_ai_provider_client] = lambda: _CompactingClient()
long_history = []
for idx in range(1, 7):
long_history.append({"role": "user", "content": f"第 {idx} 轮提问"})
long_history.append({"role": "assistant", "content": f"<think>thought-{idx}</think>第 {idx} 轮结论"})
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
res = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "基于前面总结继续追问亚太海缆脆弱点",
"domain": "global",
"history": long_history,
"memory_notes": ["优先给出亚太海缆冗余与算力口径边界"],
"pinned_summaries": ["GLOBAL · Rev.1: 全球综合态势"],
},
)
assert res.status_code == 200
events = _parse_sse_text(res.text)
meta_ev = events[0][1]
done_ev = events[-1][1]
assert meta_ev["compacted"] is True
assert "343 条骨干海缆" in meta_ev["conversation_summary"]
assert "<think>" not in meta_ev["conversation_summary"]
assert meta_ev["memory_used"] is True
assert done_ev["compacted"] is True
assert done_ev["conversation_summary"] == meta_ev["conversation_summary"]
assert len(captured_analyze_reqs) == 1
assert len(captured_stream_reqs) == 1
sent_payload = captured_stream_reqs[0]
# Recent window preserves latest 4 turns (8 messages), with <think> stripped
assert len(sent_payload.messages) == 8
assert sent_payload.messages[0].content == "第 3 轮提问"
assert sent_payload.messages[1].content == "第 3 轮结论"
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
+174
View File
@@ -0,0 +1,174 @@
"""Tests for client L1 hot-update manifest and bundle hosting APIs."""
import hashlib
import io
import tarfile
import pytest
from httpx import ASGITransport, AsyncClient
from app.core.config import settings
from app.core.security import create_access_token
from app.db.session import get_db
from app.main import app
from app.models.user import User
class _DummyDbSession:
pass
class _ScalarResult:
def __init__(self, user: User):
self._user = user
def scalar_one_or_none(self):
return self._user
class _UserLookupSession:
def __init__(self, user: User):
self._user = user
async def execute(self, _stmt):
return _ScalarResult(self._user)
def _make_tar_gz(entries: dict[str, bytes], *, prefix: str = "") -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for name, data in entries.items():
info = tarfile.TarInfo(name=f"{prefix}{name}")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
return buf.getvalue()
@pytest.fixture(autouse=True)
def _isolate_client_updates_dir(tmp_path, monkeypatch):
monkeypatch.setattr(settings, "CLIENT_UPDATES_DIR", str(tmp_path))
monkeypatch.setattr(settings, "CLIENT_UPDATE_PUBLISH_TOKEN", "ci-publish-secret-token")
monkeypatch.setattr("app.core.security.redis_client", type("NoRedis", (), {"sismember": staticmethod(lambda *_a, **_k: False)})())
yield
app.dependency_overrides.clear()
@pytest.mark.asyncio
async def test_default_manifest_before_any_hotfix_published():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
res = await client.get("/api/v1/client/update-manifest?shell=0.78.0&bundle=0.78.0")
assert res.status_code == 200
assert res.headers["cache-control"] == "no-store"
data = res.json()
assert data["shell"]["version"] == settings.VERSION
assert data["bundle"] is None
@pytest.mark.asyncio
async def test_publish_bundle_auth_validation_and_download():
valid_tar = _make_tar_gz(
{
"index.html": b"<!doctype html><html><body>updated</body></html>",
"js/main.js": b"console.log('hotfix');",
}
)
expected_sha = hashlib.sha256(valid_tar).hexdigest()
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
# Unauthenticated rejected
unauth = await client.post(
"/api/v1/client/updates/bundle",
data={"version": "0.78.1"},
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
)
assert unauth.status_code == 401
# Wrong CI publish token rejected
bad_token = await client.post(
"/api/v1/client/updates/bundle",
headers={"X-Client-Update-Token": "wrong-token"},
data={"version": "0.78.1"},
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
)
assert bad_token.status_code == 401
# Non-admin JWT rejected
async def _non_admin_db():
yield _UserLookupSession(User(id=2, username="viewer", email="v@example.com", role="viewer", is_active=True))
app.dependency_overrides[get_db] = _non_admin_db
viewer_jwt = create_access_token({"sub": "2", "username": "viewer"})
forbidden = await client.post(
"/api/v1/client/updates/bundle",
headers={"Authorization": f"Bearer {viewer_jwt}"},
data={"version": "0.78.1"},
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
)
assert forbidden.status_code == 403
app.dependency_overrides.clear()
# Malicious path traversal archive rejected
evil_tar = _make_tar_gz({"../evil.js": b"alert(1)", "index.html": b"ok"})
evil_res = await client.post(
"/api/v1/client/updates/bundle",
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
data={"version": "0.78.1"},
files={"file": ("evil.tar.gz", evil_tar, "application/gzip")},
)
assert evil_res.status_code == 400
# Valid publish via CI token succeeds and updates manifest
pub = await client.post(
"/api/v1/client/updates/bundle",
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
data={
"version": "0.78.1",
"min_shell_version": "0.78.0",
"release_notes": "Fix WebGL recovery",
"shell_version": "0.78.1",
"shell_min_required": "0.78.0",
"shell_download_url": "https://gitea.rclaw.top/linkong/planet/releases/tag/v0.78.1",
},
files={"file": ("planet-earth-bundle-0.78.1.tar.gz", valid_tar, "application/gzip")},
)
assert pub.status_code == 200
pub_data = pub.json()
assert pub_data["status"] == "published"
assert pub_data["manifest"]["bundle"]["version"] == "0.78.1"
assert pub_data["manifest"]["bundle"]["sha256"] == expected_sha
assert pub_data["manifest"]["bundle"]["size"] == len(valid_tar)
assert pub_data["manifest"]["bundle"]["filesCount"] == 2
# Manifest reflects published bundle
manifest_res = await client.get("/api/v1/client/update-manifest")
assert manifest_res.status_code == 200
bundle = manifest_res.json()["bundle"]
assert bundle["version"] == "0.78.1"
assert bundle["url"] == "/api/v1/client/updates/files/planet-earth-bundle-0.78.1.tar.gz"
# Download serves exact archive bytes
dl = await client.get(bundle["url"])
assert dl.status_code == 200
assert dl.content == valid_tar
# Admin JWT publish also works cleanly
missing_index_tar = _make_tar_gz({"js/main.js": b"console.log(1)"})
async def _admin_db():
yield _UserLookupSession(User(id=1, username="admin", email="a@example.com", role="admin", is_active=True))
app.dependency_overrides[get_db] = _admin_db
admin_jwt = create_access_token({"sub": "1", "username": "admin"})
no_idx = await client.post(
"/api/v1/client/updates/bundle",
headers={"Authorization": f"Bearer {admin_jwt}"},
data={"version": "0.78.2"},
files={"file": ("no-index.tar.gz", missing_index_tar, "application/gzip")},
)
assert no_idx.status_code == 400
# Invalid download filename rejected
bad_dl = await client.get("/api/v1/client/updates/files/not-allowed.txt")
assert bad_dl.status_code == 400
+100
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import gzip
import json import json
import httpx import httpx
@@ -9,6 +10,7 @@ from fastapi import FastAPI, HTTPException, Response
from app.api.v1 import visualization from app.api.v1 import visualization
from app.services.earth_layer_cache import ( from app.services.earth_layer_cache import (
_ENCODED_ARTIFACT_CACHE,
EarthLayerCachePolicy, EarthLayerCachePolicy,
apply_payload_budget, apply_payload_budget,
earth_layer_cache, earth_layer_cache,
@@ -81,9 +83,11 @@ def fake_cache_client():
previous = earth_layer_cache._client previous = earth_layer_cache._client
fake = FakeRedis() fake = FakeRedis()
earth_layer_cache._client = fake earth_layer_cache._client = fake
_ENCODED_ARTIFACT_CACHE.clear()
try: try:
yield fake yield fake
finally: finally:
_ENCODED_ARTIFACT_CACHE.clear()
earth_layer_cache._client = previous earth_layer_cache._client = previous
@@ -566,3 +570,99 @@ def test_invalidate_earth_layer_cache_for_source_degrades_gracefully_on_redis_fa
assert invalidate_earth_layer_cache_for_source("ris_live_bgp") == 0 assert invalidate_earth_layer_cache_for_source("ris_live_bgp") == 0
finally: finally:
earth_layer_cache._client = previous earth_layer_cache._client = previous
@pytest.mark.asyncio
async def test_satellites_endpoint_supports_compact_gzip_and_etag_304(
fake_cache_client,
monkeypatch,
):
geojson_calls = 0
compact_calls = 0
async def fake_build_satellites_geojson(*, limit, db):
nonlocal geojson_calls
geojson_calls += 1
return {
"type": "FeatureCollection",
"features": [{"type": "Feature", "id": 25544, "properties": {"id": 1}}],
"count": 1,
}
async def fake_build_satellites_compact(*, limit, db):
nonlocal compact_calls
compact_calls += 1
return {
"format": "satellite_compact_v1",
"count": 1,
"fields": [
"id",
"norad_cat_id",
"name",
"constellation_group",
"tle_line1",
"tle_line2",
"fallback_elements",
],
"satellites": [[1, 25544, "ISS (ZARYA)", "leo", "1 25544U ...", "2 25544 ..."]],
}
monkeypatch.setattr(visualization, "_build_satellites_geojson", fake_build_satellites_geojson)
monkeypatch.setattr(visualization, "_build_satellites_compact", fake_build_satellites_compact)
app = FastAPI()
app.include_router(visualization.router, prefix="/api/v1/visualization")
app.dependency_overrides[visualization.get_db] = lambda: object()
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://test",
) as client:
first_compact = await client.get(
"/api/v1/visualization/geo/satellites?format=compact",
headers={"Accept-Encoding": "gzip"},
)
assert first_compact.status_code == 200
assert first_compact.headers["X-Planet-Cache"] == "refresh"
assert first_compact.headers["X-Planet-Cache-Features"] == "1"
assert first_compact.headers["Content-Encoding"] == "gzip"
etag = first_compact.headers["ETag"]
assert etag
assert first_compact.json()["format"] == "satellite_compact_v1"
assert first_compact.json()["satellites"][0][1] == 25544
second_compact = await client.get(
"/api/v1/visualization/geo/satellites?format=compact",
headers={"Accept-Encoding": "gzip"},
)
assert second_compact.status_code == 200
assert second_compact.headers["X-Planet-Cache"] == "hit"
assert second_compact.headers["ETag"] == etag
assert second_compact.headers["Content-Encoding"] == "gzip"
not_modified = await client.get(
"/api/v1/visualization/geo/satellites?format=compact",
headers={"If-None-Match": etag, "Accept-Encoding": "gzip"},
)
assert not_modified.status_code == 304
assert not_modified.content == b""
assert not_modified.headers["ETag"] == etag
plain_geo = await client.get(
"/api/v1/visualization/geo/satellites",
headers={"Accept-Encoding": "identity"},
)
assert plain_geo.status_code == 200
assert "content-encoding" not in {k.lower() for k in plain_geo.headers.keys()}
assert plain_geo.json()["type"] == "FeatureCollection"
assert geojson_calls == 1
assert compact_calls == 1
# Verify raw bytes cached cleanly match uncompressed response and encoded artifact gzip round-trips
raw_cached = fake_cache_client.store[
earth_layer_cache.key("satellites", format="compact", limit="all")
]
assert json.loads(raw_cached)["count"] == 1
assert second_compact.json()["count"] == 1
artifact = next(iter(_ENCODED_ARTIFACT_CACHE.values()))
assert gzip.decompress(artifact.gzip_bytes) == artifact.raw_bytes
+80 -3
View File
@@ -26,8 +26,8 @@ def mock_http(monkeypatch, handler):
("deepseek", "/v1/models", "authorization"), ("deepseek", "/v1/models", "authorization"),
("alibaba", "/api/v1/models", "authorization"), ("alibaba", "/api/v1/models", "authorization"),
("moonshotai", "/v1/models", "authorization"), ("moonshotai", "/v1/models", "authorization"),
("openrouter", "/api/v1/models", "authorization"), ("openrouter", "/api/v1/models", None),
("opencode-go", "/zen/go/v1/models", "authorization"), ("opencode-go", "/zen/go/v1/models", None),
("ollama", "/api/tags", "authorization"), ("ollama", "/api/tags", "authorization"),
], ],
) )
@@ -37,7 +37,13 @@ async def test_official_catalog_requests(monkeypatch, provider, path, auth):
def handle(request): def handle(request):
assert request.url.path == path assert request.url.path == path
assert request.url.host == httpx.URL(preset["base_url"]).host assert request.url.host == httpx.URL(preset["base_url"]).host
assert request.headers[auth] == ("test-key" if auth == "x-api-key" else "Bearer test-key") if auth is None:
assert "authorization" not in request.headers
assert "x-api-key" not in request.headers
else:
assert request.headers[auth] == (
"test-key" if auth == "x-api-key" else "Bearer test-key"
)
if provider == "alibaba": if provider == "alibaba":
assert request.url.params["capabilities"] == "TG" assert request.url.params["capabilities"] == "TG"
return httpx.Response( return httpx.Response(
@@ -217,3 +223,74 @@ async def test_retry_transient_error_only(monkeypatch):
await catalog.refresh_llm_provider_preset("minimax", "test-key") await catalog.refresh_llm_provider_preset("minimax", "test-key")
assert len(calls) == 1 assert len(calls) == 1
assert "secret-upstream-text" not in discovery.catalog_error_message(error.value) assert "secret-upstream-text" not in discovery.catalog_error_message(error.value)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"provider,custom_base",
[
("openrouter", "https://proxy.test/api/v1"),
("opencode-go", "https://proxy.test/zen/go/v1"),
],
)
async def test_custom_gateway_for_public_provider_requires_and_sends_key(
monkeypatch, provider, custom_base
):
with pytest.raises(discovery.LLMProviderCatalogConfigError):
await catalog.refresh_llm_provider_preset(provider, base_url=custom_base)
def handle(request):
assert request.url.host == "proxy.test"
assert request.headers["authorization"] == "Bearer custom-key"
return httpx.Response(200, json={"data": [{"id": "proxy-model"}]})
mock_http(monkeypatch, handle)
result = await catalog.refresh_llm_provider_preset(
provider, api_key="custom-key", base_url=custom_base
)
assert result["models"] == ["proxy-model"]
@pytest.mark.asyncio
async def test_fetch_model_catalog_include_auth_for_connectivity_check(monkeypatch):
def handle(request):
assert request.headers["authorization"] == "Bearer check-key"
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}]})
mock_http(monkeypatch, handle)
result = await discovery.fetch_model_catalog(
"opencode-go",
"https://opencode.ai/zen/go/v1",
"openai-completions",
api_key="check-key",
include_auth=True,
)
assert result.models == ["glm-5.3"]
@pytest.mark.asyncio
async def test_ollama_openai_completions_refreshes_without_key(monkeypatch):
def handle(request):
assert request.url.path == "/v1/models"
assert "authorization" not in request.headers
return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]})
mock_http(monkeypatch, handle)
result = await catalog.refresh_llm_provider_preset(
"ollama", provider_api="openai-completions"
)
assert result["models"] == ["qwen2.5:7b"]
@pytest.mark.asyncio
async def test_config_error_type_and_clean_upstream_error_messages(monkeypatch):
with pytest.raises(discovery.LLMProviderCatalogConfigError):
discovery.model_catalog_url("openai", "not-a-url", "openai-responses")
with pytest.raises(discovery.LLMProviderCatalogConfigError):
discovery.model_catalog_url("openai", "https://api.openai.com/v1", "unsupported-api")
mock_http(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
with pytest.raises(discovery.LLMProviderCatalogError) as exc:
await catalog.refresh_llm_provider_preset("openai", "test-key")
assert not isinstance(exc.value, discovery.LLMProviderCatalogConfigError)
assert "已保留上次模型列表" not in str(exc.value)
+164 -3
View File
@@ -13,6 +13,8 @@ from app.services import llm_model_catalog as discovery
from app.services.llm_provider_catalog import list_fallback_llm_provider_presets from app.services.llm_provider_catalog import list_fallback_llm_provider_presets
REAL_CLIENT = httpx.AsyncClient REAL_CLIENT = httpx.AsyncClient
ADMIN_USER = SimpleNamespace(role="admin")
VIEWER_USER = SimpleNamespace(role="viewer")
@pytest.fixture @pytest.fixture
@@ -82,7 +84,7 @@ async def test_refresh_commits_reloads_and_preserves_runtime_and_draft(settings_
api_key="draft-secret", api_key="draft-secret",
service_token="unsaved-service-token", service_token="unsaved-service-token",
) )
refreshed = await api.refresh_ai_provider_preset("minimax", None, settings_db, draft) refreshed = await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db, draft)
result = await api.get_ai_provider_presets(None, settings_db) result = await api.get_ai_provider_presets(None, settings_db)
preset = next(row for row in result["data"] if row["provider"] == "minimax") preset = next(row for row in result["data"] if row["provider"] == "minimax")
assert len(seen) == 1 assert len(seen) == 1
@@ -108,7 +110,7 @@ async def test_failed_refresh_preserves_stored_catalog_and_sanitizes_errors(
use_upstream(monkeypatch, lambda request: httpx.Response(401, text="private-upstream-secret")) use_upstream(monkeypatch, lambda request: httpx.Response(401, text="private-upstream-secret"))
commits = settings_db.commit.await_count commits = settings_db.commit.await_count
with pytest.raises(api.HTTPException) as error: with pytest.raises(api.HTTPException) as error:
await api.refresh_ai_provider_preset("openrouter", None, settings_db) await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db)
assert error.value.status_code == 502 assert error.value.status_code == 502
assert "private-upstream-secret" not in error.value.detail assert "private-upstream-secret" not in error.value.detail
assert settings_db.commit.await_count == commits assert settings_db.commit.await_count == commits
@@ -124,11 +126,170 @@ async def test_missing_key_is_actionable_and_does_not_request_upstream(settings_
use_upstream(monkeypatch, fail_request) use_upstream(monkeypatch, fail_request)
with pytest.raises(api.HTTPException) as error: with pytest.raises(api.HTTPException) as error:
await api.refresh_ai_provider_preset("minimax", None, settings_db) await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db)
assert error.value.status_code == 400 assert error.value.status_code == 400
assert "API Key" in error.value.detail assert "API Key" in error.value.detail
@pytest.mark.asyncio
async def test_refresh_requires_admin_role(settings_db):
with pytest.raises(api.HTTPException) as single_err:
await api.refresh_ai_provider_preset("openrouter", VIEWER_USER, settings_db)
assert single_err.value.status_code == 403
with pytest.raises(api.HTTPException) as bulk_err:
await api.refresh_public_ai_provider_presets(VIEWER_USER, settings_db)
assert bulk_err.value.status_code == 403
@pytest.mark.asyncio
async def test_opencode_go_refreshes_ignoring_invalid_saved_and_draft_keys(
settings_db, monkeypatch
):
await api.save_setting_payload(
settings_db,
"external_integrations",
{
"ai_provider": {
"default_provider": "opencode-go",
"providers": {
"opencode-go": {
"base_url": "https://opencode.ai/zen/go/v1",
"model": "glm-5.3",
"api_key": "stale-invalid-key",
}
},
}
},
)
def handle(request):
assert "authorization" not in request.headers
assert "x-api-key" not in request.headers
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "deepseek-v4.1-flash"}]})
use_upstream(monkeypatch, handle)
draft = api.AIProviderIntegrationUpdate(
provider="opencode-go",
base_url="https://opencode.ai/zen/go/v1",
model="glm-5.3",
api_key="bad-draft-key",
)
refreshed = await api.refresh_ai_provider_preset("opencode-go", ADMIN_USER, settings_db, draft)
assert refreshed["data"]["models"] == ["glm-5.3", "deepseek-v4.1-flash"]
stored = await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go")
assert stored["models"] == ["glm-5.3", "deepseek-v4.1-flash"]
@pytest.mark.asyncio
async def test_ollama_openai_completions_works_without_key(settings_db, monkeypatch):
def handle(request):
assert request.url.path == "/v1/models"
assert "authorization" not in request.headers
return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]})
use_upstream(monkeypatch, handle)
draft = api.AIProviderIntegrationUpdate(
provider="ollama",
provider_api="openai-completions",
base_url="http://127.0.0.1:11434/v1",
model="qwen2.5:7b",
)
refreshed = await api.refresh_ai_provider_preset("ollama", ADMIN_USER, settings_db, draft)
assert refreshed["data"]["models"] == ["qwen2.5:7b"]
check = await api._check_ai_provider_lightweight(
{
"provider": "ollama",
"provider_api": "openai-completions",
"base_url": "http://127.0.0.1:11434/v1",
"model": "qwen2.5:7b",
"api_key": "",
},
5,
)
assert check["success"] is True
assert check["connected"] is True
@pytest.mark.asyncio
async def test_invalid_draft_base_url_returns_400_without_calling_upstream(
settings_db, monkeypatch
):
use_upstream(
monkeypatch,
lambda request: pytest.fail("must not query upstream when draft base_url is invalid"),
)
draft = api.AIProviderIntegrationUpdate(
provider="openrouter",
base_url="not-a-valid-url",
model="openai/gpt-6.2-astra",
)
with pytest.raises(api.HTTPException) as error:
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db, draft)
assert error.value.status_code == 400
@pytest.mark.asyncio
async def test_empty_catalog_error_does_not_duplicate_retention_suffix(settings_db, monkeypatch):
use_upstream(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
with pytest.raises(api.HTTPException) as error:
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db)
assert error.value.status_code == 502
assert error.value.detail.count("已保留上次模型列表") == 1
@pytest.mark.asyncio
async def test_refresh_public_presets_updates_credential_free_and_isolates_failures(
settings_db, monkeypatch
):
await api.save_setting_payload(
settings_db,
"external_integrations",
{
"ai_provider": {
"default_provider": "openrouter",
"providers": {
"openrouter": {
"base_url": "https://proxy.test/api/v1",
"model": "custom-model",
"api_key": "",
},
"opencode-go": {
"base_url": "https://opencode.ai/zen/go/v1",
"model": "glm-5.3",
"api_key": "stale-key",
},
},
}
},
)
await api.save_setting_payload(
settings_db, "llm_provider_preset:ollama", {"models": ["kept-local-model"]}
)
seen_hosts = []
def handle(request):
seen_hosts.append(request.url.host)
assert "authorization" not in request.headers
if request.url.host == "opencode.ai":
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "qwen4-max"}]})
raise httpx.ConnectError("local ollama offline", request=request)
use_upstream(monkeypatch, handle)
summary = await api.refresh_public_ai_provider_presets(ADMIN_USER, settings_db)
assert seen_hosts == ["opencode.ai", "127.0.0.1", "127.0.0.1"]
assert summary["refreshed"] == ["opencode-go"]
assert summary["failed"] == ["ollama"]
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go"))[
"models"
] == ["glm-5.3", "qwen4-max"]
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:ollama"))[
"models"
] == ["kept-local-model"]
@pytest.mark.asyncio @pytest.mark.asyncio
@pytest.mark.parametrize( @pytest.mark.parametrize(
"preset", list_fallback_llm_provider_presets(), ids=lambda p: p["provider"] "preset", list_fallback_llm_provider_presets(), ids=lambda p: p["provider"]
+171
View File
@@ -1,3 +1,4 @@
import json
from pathlib import Path from pathlib import Path
import sys import sys
from unittest.mock import patch from unittest.mock import patch
@@ -175,3 +176,173 @@ async def test_minimax_m31_flash_forces_adaptive_thinking_and_effort(monkeypatch
assert payloads[0]["output_config"] == {"effort": "low"} assert payloads[0]["output_config"] == {"effort": "low"}
assert payloads[1]["thinking"] == {"type": "adaptive"} assert payloads[1]["thinking"] == {"type": "adaptive"}
assert payloads[1]["output_config"] == {"effort": "medium"} assert payloads[1]["output_config"] == {"effort": "medium"}
@pytest.mark.asyncio
async def test_stream_analyze_anthropic_emits_thinking_text_and_done(monkeypatch):
client_type = httpx.AsyncClient
sse_bytes = (
b'event: message_start\n'
b'data: {"type":"message_start","message":{"model":"MiniMax-M2.7","usage":{"input_tokens":12}}}\n\n'
b'event: content_block_delta\n'
b'data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"step-1 "}}\n\n'
b'event: content_block_delta\n'
b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hello "}}\n\n'
b'event: message_delta\n'
b'data: {"type":"message_delta","usage":{"output_tokens":7}}\n\n'
b'event: message_stop\n'
b'data: {"type":"message_stop"}\n\n'
)
def handle(_request):
return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"})
transport = httpx.MockTransport(handle)
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
service = ProviderService(
{
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "test-key",
"model": "MiniMax-M2.7",
}
)
events = []
async for ev in service.stream_analyze(
SituationalAnalysisRequest(title="news", objective="analyze", thinking={"type": "enabled", "budget_tokens": 1024})
):
events.append(ev)
assert events[0] == {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
assert {"event": "reasoning", "delta": "step-1 "} in events
assert {"event": "text", "delta": "hello "} in events
assert events[-1]["event"] == "done"
assert events[-1]["model"] == "MiniMax-M2.7"
assert events[-1]["usage"]["output_tokens"] == 7
@pytest.mark.asyncio
async def test_stream_analyze_openai_emits_reasoning_and_text(monkeypatch):
client_type = httpx.AsyncClient
sse_bytes = (
b'data: {"model":"gpt-5.6","choices":[{"delta":{"reasoning_content":"check cables"}}]}\n\n'
b'data: {"model":"gpt-5.6","choices":[{"delta":{"content":"summary ok"}}],"usage":{"total_tokens":20}}\n\n'
b'data: [DONE]\n\n'
)
def handle(_request):
return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"})
transport = httpx.MockTransport(handle)
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
service = ProviderService(
{
"provider": "openai",
"provider_api": "openai-completions",
"base_url": "https://api.openai.test/v1",
"api_key": "test-key",
"model": "gpt-5.6",
}
)
events = []
async for ev in service.stream_analyze(SituationalAnalysisRequest(title="global", objective="analyze")):
events.append(ev)
assert {"event": "reasoning", "delta": "check cables"} in events
assert {"event": "text", "delta": "summary ok"} in events
assert events[-1]["event"] == "done"
assert events[-1]["usage"]["total_tokens"] == 20
@pytest.mark.asyncio
async def test_stream_analyze_forwards_normalized_multi_turn_messages(monkeypatch):
client_type = httpx.AsyncClient
captured_bodies = []
def handle(request):
captured_bodies.append(json.loads(request.content.decode("utf-8")))
sse = (
b'event: content_block_delta\n'
b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"multi-turn ok"}}\n\n'
b'event: message_stop\n'
b'data: {"type":"message_stop"}\n\n'
)
return httpx.Response(200, content=sse, headers={"content-type": "text/event-stream"})
transport = httpx.MockTransport(handle)
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
service = ProviderService(
{
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "test-key",
"model": "MiniMax-M2.7",
}
)
events = []
async for ev in service.stream_analyze(
SituationalAnalysisRequest(
title="follow-up",
objective="继续追问第二点",
messages=[
{"role": "assistant", "content": "leading assistant ignored"},
{"role": "user", "content": "第一轮问题"},
{"role": "assistant", "content": "第一轮回答"},
],
)
):
events.append(ev)
assert len(captured_bodies) == 1
sent_msgs = captured_bodies[0]["messages"]
assert [m["role"] for m in sent_msgs] == ["user", "assistant", "user"]
assert sent_msgs[0]["content"][0]["text"] == "第一轮问题"
assert sent_msgs[1]["content"][0]["text"] == "第一轮回答"
assert "继续追问第二点" in sent_msgs[2]["content"][0]["text"]
assert {"event": "text", "delta": "multi-turn ok"} in events
def test_anthropic_request_omits_temperature_and_bumps_max_tokens_when_thinking_enabled():
service = ProviderService(
{
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "test-key",
"model": "MiniMax-M2.7",
"max_tokens": 1200,
}
)
_, _, enabled_body = service._build_anthropic_request(
"MiniMax-M2.7",
"analyze",
thinking={"type": "enabled", "budget_tokens": 2048},
stream=True,
)
assert "temperature" not in enabled_body
assert enabled_body["max_tokens"] == 3072
assert enabled_body["thinking"] == {"type": "enabled", "budget_tokens": 2048}
_, _, adaptive_body = service._build_anthropic_request(
"MiniMax-M3.1",
"analyze",
thinking=None,
stream=True,
)
assert "temperature" not in adaptive_body
assert adaptive_body["thinking"] == {"type": "adaptive"}
_, _, disabled_body = service._build_anthropic_request(
"MiniMax-M2.7",
"analyze",
thinking=None,
stream=False,
)
assert disabled_body["temperature"] == 0.2
assert disabled_body["thinking"] == {"type": "disabled"}
+3 -3
View File
@@ -108,9 +108,9 @@ def test_opencode_go_provider_preset_is_openai_compatible():
assert preset["label"] == "OpenCode Go" assert preset["label"] == "OpenCode Go"
assert preset["provider_api"] == "openai-completions" assert preset["provider_api"] == "openai-completions"
assert preset["base_url"] == "https://opencode.ai/zen/go/v1" assert preset["base_url"] == "https://opencode.ai/zen/go/v1"
assert preset["model"] == "glm-5.1" assert preset["model"] == "glm-5.3"
assert "glm-5.1" in preset["models"] assert "glm-5.3" in preset["models"]
assert "deepseek-v4-flash" in preset["models"] assert "deepseek-v4.1-flash" in preset["models"]
assert preset["model_provider_apis"]["minimax-m2.7"] == "anthropic-messages" assert preset["model_provider_apis"]["minimax-m2.7"] == "anthropic-messages"
assert preset["api_key_env"] == "OPENCODE_GO_API_KEY" assert preset["api_key_env"] == "OPENCODE_GO_API_KEY"
@@ -154,3 +154,50 @@ async def test_satellite_cursor_closes_if_conversion_fails(
await visualization._build_satellites_geojson(limit=None, db=satellite_db) await visualization._build_satellites_geojson(limit=None, db=satellite_db)
assert satellite_db.streams[0].closed assert satellite_db.streams[0].closed
@pytest.mark.asyncio
async def test_compact_satellite_builder_emits_compact_rows_and_fallback_elements(
satellite_db: SatelliteSession,
) -> None:
with_tle = satellite(10)
without_tle = CollectedData(
id=11,
source="celestrak_tle",
source_id="11",
data_type="satellite_tle",
name="NO-TLE-SAT",
is_current=True,
task_id=1,
collected_at=datetime(2026, 1, 1, tzinfo=UTC),
extra_data={
"norad_cat_id": 51000,
"inclination": 53.2,
"raan": 120.5,
"eccentricity": 0.00012,
"arg_of_perigee": 90.0,
"mean_anomaly": 45.0,
"mean_motion": 15.1,
"international_designator": "24001A",
"classification_type": "U",
"bstar": 0.0001,
},
)
starlink = satellite(12, name="STARLINK-1234")
satellite_db.session.add_all([with_tle, without_tle, starlink])
satellite_db.session.commit()
payload = await visualization._build_satellites_compact(limit=None, db=satellite_db)
assert payload["format"] == "satellite_compact_v1"
assert payload["count"] == 3
rows_by_id = {row[0]: row for row in payload["satellites"]}
assert len(rows_by_id[10]) == 6
assert rows_by_id[10][:4] == [10, 40010, "SAT-10", None]
assert rows_by_id[10][4:6] == ["line-1-10", "line-2-10"]
assert rows_by_id[12][:4] == [12, 40012, "STARLINK-1234", "starlink"]
assert len(rows_by_id[11]) == 7
assert rows_by_id[11][4] is None
assert isinstance(rows_by_id[11][5], str) and rows_by_id[11][5].startswith("2 51000 ")
assert rows_by_id[11][6][:2] == [53.2, 120.5]
assert all(stream.closed for stream in satellite_db.streams)
+2
View File
@@ -56,6 +56,8 @@ linux:
mac: mac:
icon: resources/icon.png icon: resources/icon.png
category: public.app-category.utilities category: public.app-category.utilities
extendInfo:
NSCameraUsageDescription: Planet Earth uses your camera locally for motion gesture control.
target: target:
- target: dmg - target: dmg
arch: arch:
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "planet-client", "name": "planet-client",
"version": "0.78.0", "version": "0.80.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",
+58 -6
View File
@@ -1,9 +1,11 @@
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' import { createHash } from 'node:crypto'
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module' import { createRequire } from 'node:module'
import { dirname, join } from 'node:path' import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs' import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs'
import { createTarGz } from '../src/main/tar-gz.ts'
const __dirname = dirname(fileURLToPath(import.meta.url)) const __dirname = dirname(fileURLToPath(import.meta.url))
const desktopRoot = join(__dirname, '..') const desktopRoot = join(__dirname, '..')
@@ -88,15 +90,65 @@ if (existsSync(zjuEmblemSrc)) {
const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json')) const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json'))
const mediaPipeOutDir = join(bundleEarthDir, 'vendor/mediapipe') const mediaPipeOutDir = join(bundleEarthDir, 'vendor/mediapipe')
mkdirSync(mediaPipeOutDir, { recursive: true }) mkdirSync(mediaPipeOutDir, { recursive: true })
for (const candidate of ['vision_bundle.mjs', 'vision_bundle.cjs']) { const mediaPipeBundleSrc = join(mediaPipePkgDir, 'vision_bundle.mjs')
const srcFile = join(mediaPipePkgDir, candidate) if (existsSync(mediaPipeBundleSrc)) {
if (existsSync(srcFile)) { cpSync(mediaPipeBundleSrc, join(mediaPipeOutDir, 'vision_bundle.mjs'))
cpSync(srcFile, join(mediaPipeOutDir, candidate))
}
} }
const mediaPipeWasmDir = join(mediaPipePkgDir, 'wasm') const mediaPipeWasmDir = join(mediaPipePkgDir, 'wasm')
if (existsSync(mediaPipeWasmDir)) { if (existsSync(mediaPipeWasmDir)) {
cpSync(mediaPipeWasmDir, join(mediaPipeOutDir, 'wasm'), { recursive: true }) cpSync(mediaPipeWasmDir, join(mediaPipeOutDir, 'wasm'), { recursive: true })
} }
const poseModelSrc = join(earthSourceDir, 'vendor/mediapipe/pose_landmarker_lite.task')
if (!existsSync(poseModelSrc)) {
throw new Error(`Missing bundled MediaPipe pose model: ${poseModelSrc}`)
}
cpSync(poseModelSrc, join(mediaPipeOutDir, 'pose_landmarker_lite.task'))
console.log(`Built offline Earth bundle at ${bundleEarthDir}`) console.log(`Built offline Earth bundle at ${bundleEarthDir}`)
const clientPkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
const bundleVersion = String(clientPkg.version || '0.0.0').trim()
const metaPayload = {
version: bundleVersion,
shellVersion: bundleVersion,
builtAt: new Date().toISOString(),
}
writeFileSync(join(bundleEarthDir, 'bundle-meta.json'), `${JSON.stringify(metaPayload, null, 2)}\n`, 'utf8')
function collectHotfixEntries(rootDir) {
const entries = []
for (const topFile of ['index.html', 'bundle-meta.json']) {
const filePath = join(rootDir, topFile)
if (existsSync(filePath)) {
entries.push({ path: topFile, data: readFileSync(filePath) })
}
}
const walk = (relDir) => {
const absDir = join(rootDir, relDir)
if (!existsSync(absDir)) return
for (const dirent of readdirSync(absDir, { withFileTypes: true })) {
const relPath = `${relDir}/${dirent.name}`
if (dirent.isDirectory()) {
walk(relPath)
} else if (dirent.isFile()) {
entries.push({ path: relPath, data: readFileSync(join(rootDir, relPath)) })
}
}
}
walk('js')
walk('css')
return entries
}
const hotfixEntries = collectHotfixEntries(bundleEarthDir)
const hotfixArchive = createTarGz(hotfixEntries)
const hotfixSha256 = createHash('sha256').update(hotfixArchive).digest('hex')
const releaseOutDir = join(desktopRoot, 'release')
mkdirSync(releaseOutDir, { recursive: true })
const hotfixName = `planet-earth-bundle-${bundleVersion}.tar.gz`
const hotfixPath = join(releaseOutDir, hotfixName)
writeFileSync(hotfixPath, hotfixArchive)
writeFileSync(join(releaseOutDir, `${hotfixName}.sha256`), `${hotfixSha256} ${hotfixName}\n`, 'utf8')
console.log(
`Built L1 hotfix bundle ${hotfixPath} (${(hotfixArchive.byteLength / 1024).toFixed(1)} KiB, sha256=${hotfixSha256})`,
)
+144 -17
View File
@@ -1,7 +1,8 @@
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off' export type SplashTheme = 'singularity' | 'off'
export type GpuRenderMode = 'auto' | 'high-performance' | 'low-power' | 'software'
export interface ServerEndpoints { export interface ServerEndpoints {
backendUrl: string backendUrl: string
@@ -11,6 +12,23 @@ export interface ServerEndpoints {
export interface PersistedUserConfig extends Partial<ServerEndpoints> { export interface PersistedUserConfig extends Partial<ServerEndpoints> {
splashTheme?: SplashTheme splashTheme?: SplashTheme
gpuMode?: GpuRenderMode
}
export type GpuHandoffTarget = 'default' | 'high-performance' | 'low-power' | 'software'
export function normalizeGpuHandoffTarget(raw: unknown): GpuHandoffTarget | undefined {
if (typeof raw !== 'string') return undefined
const normalized = raw.trim().toLowerCase()
if (
normalized === 'default' ||
normalized === 'high-performance' ||
normalized === 'low-power' ||
normalized === 'software'
) {
return normalized
}
return undefined
} }
export interface DesktopLaunchFlags { export interface DesktopLaunchFlags {
@@ -22,18 +40,23 @@ export interface DesktopLaunchFlags {
smokeOutputPath: string | null smokeOutputPath: string | null
deepLinkUrl: string | null deepLinkUrl: string | null
splashThemeOverride?: SplashTheme splashThemeOverride?: SplashTheme
gpuModeOverride?: GpuRenderMode
gpuHandoff: boolean
gpuHandoffTarget?: GpuHandoffTarget
} }
export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags { export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags {
wsUrl: string wsUrl: string
splashTheme: SplashTheme splashTheme: SplashTheme
gpuMode: GpuRenderMode
} }
const VALID_SPLASH_THEMES: ReadonlySet<SplashTheme> = new Set([ const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
'singularity', 'singularity',
'constellation', 'constellation',
'horizon', 'horizon',
'off', 'on',
'default',
]) ])
export function normalizeSplashTheme( export function normalizeSplashTheme(
@@ -41,8 +64,38 @@ export function normalizeSplashTheme(
fallback: SplashTheme = 'singularity', fallback: SplashTheme = 'singularity',
): SplashTheme { ): SplashTheme {
if (typeof raw !== 'string') return fallback if (typeof raw !== 'string') return fallback
const normalized = raw.trim().toLowerCase() as SplashTheme const normalized = raw.trim().toLowerCase()
return VALID_SPLASH_THEMES.has(normalized) ? normalized : fallback if (normalized === 'off') return 'off'
return LEGACY_ACTIVE_THEMES.has(normalized) ? 'singularity' : fallback
}
export function normalizeGpuMode(
raw: unknown,
fallback: GpuRenderMode = 'auto',
): GpuRenderMode {
if (typeof raw !== 'string') return fallback
const normalized = raw.trim().toLowerCase()
if (normalized === 'auto') return 'auto'
if (
normalized === 'high-performance' ||
normalized === 'high' ||
normalized === 'discrete' ||
normalized === 'dgpu'
) {
return 'high-performance'
}
if (
normalized === 'low-power' ||
normalized === 'low' ||
normalized === 'integrated' ||
normalized === 'igpu'
) {
return 'low-power'
}
if (normalized === 'software' || normalized === 'cpu' || normalized === 'swiftshader') {
return 'software'
}
return fallback
} }
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = { export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
@@ -113,6 +166,7 @@ export function parseLaunchArgs(argv: string[]): {
headlessSmoke: false, headlessSmoke: false,
smokeOutputPath: null, smokeOutputPath: null,
deepLinkUrl: null, deepLinkUrl: null,
gpuHandoff: false,
} }
for (let i = 0; i < argv.length; i += 1) { for (let i = 0; i < argv.length; i += 1) {
@@ -134,6 +188,22 @@ export function parseLaunchArgs(argv: string[]): {
flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length)) flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length))
} else if (arg === '--splash-theme' && argv[i + 1]) { } else if (arg === '--splash-theme' && argv[i + 1]) {
flags.splashThemeOverride = normalizeSplashTheme(argv[++i]) flags.splashThemeOverride = normalizeSplashTheme(argv[++i])
} else if (arg.startsWith('--gpu-mode=')) {
flags.gpuModeOverride = normalizeGpuMode(arg.slice('--gpu-mode='.length))
} else if (arg === '--gpu-mode' && argv[i + 1]) {
flags.gpuModeOverride = normalizeGpuMode(argv[++i])
} else if (arg === '--software-gl') {
flags.gpuModeOverride = 'software'
} else if (arg === '--low-power-gpu') {
flags.gpuModeOverride = 'low-power'
} else if (arg === '--high-performance-gpu') {
flags.gpuModeOverride = 'high-performance'
} else if (arg === '--gpu-handoff') {
flags.gpuHandoff = true
} else if (arg.startsWith('--gpu-handoff-target=')) {
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(arg.slice('--gpu-handoff-target='.length))
} else if (arg === '--gpu-handoff-target' && argv[i + 1]) {
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(argv[++i])
} else if (arg === '--fullscreen') { } else if (arg === '--fullscreen') {
flags.fullscreen = true flags.fullscreen = true
} else if (arg === '--kiosk') { } else if (arg === '--kiosk') {
@@ -155,6 +225,55 @@ export function parseLaunchArgs(argv: string[]): {
return { endpoints, flags } return { endpoints, flags }
} }
function getPortableConfigPaths(exeDir: string, resourcesDir?: string): string[] {
const candidates: string[] = []
if (exeDir) {
candidates.push(path.join(exeDir, 'planet-earth.json'))
}
if (resourcesDir) {
candidates.push(path.join(resourcesDir, 'planet-earth.json'))
}
return candidates
}
function readFirstPortableConfig(paths: string[]): PersistedUserConfig {
for (const candidate of paths) {
const data = readJsonFileSafe(candidate)
if (Object.keys(data).length > 0) {
return data
}
}
return {}
}
export function readPreReadyGpuMode(options: {
userDataDir: string
exeDir: string
resourcesDir?: string
argv: string[]
env?: NodeJS.ProcessEnv
}): GpuRenderMode {
const env = options.env ?? process.env
const { flags } = parseLaunchArgs(options.argv)
const portable = readFirstPortableConfig(getPortableConfigPaths(options.exeDir, options.resourcesDir))
const userSaved = options.userDataDir ? readJsonFileSafe(path.join(options.userDataDir, 'config.json')) : {}
return normalizeGpuMode(
flags.gpuModeOverride ?? env.PLANET_GPU_MODE ?? portable.gpuMode ?? userSaved.gpuMode,
'auto',
)
}
export function readPreReadyGpuHandoff(argv: string[]): {
gpuHandoff: boolean
gpuHandoffTarget?: GpuHandoffTarget
} {
const { flags } = parseLaunchArgs(argv)
return {
gpuHandoff: flags.gpuHandoff,
gpuHandoffTarget: flags.gpuHandoffTarget,
}
}
export class DesktopConfigStore { export class DesktopConfigStore {
private readonly userConfigPath: string private readonly userConfigPath: string
private readonly portableConfigPaths: string[] private readonly portableConfigPaths: string[]
@@ -170,10 +289,7 @@ export class DesktopConfigStore {
env?: NodeJS.ProcessEnv env?: NodeJS.ProcessEnv
}) { }) {
this.userConfigPath = path.join(options.userDataDir, 'config.json') this.userConfigPath = path.join(options.userDataDir, 'config.json')
this.portableConfigPaths = [ this.portableConfigPaths = getPortableConfigPaths(options.exeDir, options.resourcesDir)
path.join(options.exeDir, 'planet-earth.json'),
...(options.resourcesDir ? [path.join(options.resourcesDir, 'planet-earth.json')] : []),
]
const parsed = parseLaunchArgs(options.argv) const parsed = parseLaunchArgs(options.argv)
this.cliEndpoints = parsed.endpoints this.cliEndpoints = parsed.endpoints
this.launchFlags = parsed.flags this.launchFlags = parsed.flags
@@ -182,14 +298,7 @@ export class DesktopConfigStore {
private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig { private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig {
const userSaved = readJsonFileSafe(this.userConfigPath) const userSaved = readJsonFileSafe(this.userConfigPath)
let portable: PersistedUserConfig = {} const portable = readFirstPortableConfig(this.portableConfigPaths)
for (const candidate of this.portableConfigPaths) {
const data = readJsonFileSafe(candidate)
if (Object.keys(data).length > 0) {
portable = data
break
}
}
const backendUrl = normalizeHttpUrl( const backendUrl = normalizeHttpUrl(
this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl, this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl,
@@ -210,6 +319,13 @@ export class DesktopConfigStore {
userSaved.splashTheme, userSaved.splashTheme,
'singularity', 'singularity',
) )
const gpuMode = normalizeGpuMode(
this.launchFlags.gpuModeOverride ??
env.PLANET_GPU_MODE ??
portable.gpuMode ??
userSaved.gpuMode,
'auto',
)
return { return {
backendUrl, backendUrl,
@@ -217,6 +333,7 @@ export class DesktopConfigStore {
motionWsUrl, motionWsUrl,
wsUrl: deriveBackendWsUrl(backendUrl), wsUrl: deriveBackendWsUrl(backendUrl),
splashTheme, splashTheme,
gpuMode,
...this.launchFlags, ...this.launchFlags,
} }
} }
@@ -258,4 +375,14 @@ export class DesktopConfigStore {
} }
return this.get() return this.get()
} }
updateGpuMode(rawMode: unknown): DesktopRuntimeConfig {
const nextMode = normalizeGpuMode(rawMode, this.current.gpuMode)
this.writeUserConfig({ gpuMode: nextMode })
this.current = {
...this.current,
gpuMode: nextMode,
}
return this.get()
}
} }
+321
View File
@@ -0,0 +1,321 @@
import { execFile, execFileSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { promisify } from 'node:util'
import type { BrowserWindow } from 'electron'
import type { GpuRenderMode } from './config'
import {
canAutoSwitchGpu,
createVramHysteresisTracker,
detectIntegratedGpuFromRegistryOutput,
parseNvidiaSmiCsv,
VRAM_LOW_THRESHOLD_MIB,
VRAM_MONITOR_INTERVAL_MS,
type DiscreteVramSample,
type ResolvedGpuTarget,
type StartupGpuDecision,
type StartupGpuDecisionReason,
} from './gpu-policy'
const execFileAsync = promisify(execFile)
const HANDOFF_RECORD_MAX_AGE_MS = 30_000
const HANDOFF_RECORD_FILE = 'gpu-handoff.json'
const NVIDIA_SMI_ARGS = [
'--query-gpu=name,memory.used,memory.free,memory.total',
'--format=csv,noheader,nounits',
]
const DISPLAY_CLASS_REG_ARGS = [
'query',
'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}',
'/s',
'/v',
'DriverDesc',
]
export interface GpuHandoffRecord {
lastSwitchAt: number
target: ResolvedGpuTarget
reason: 'low-fps-low-vram' | 'vram-recovered' | 'manual'
freeMiB?: number
avgFps?: number
}
export interface GpuRuntimeSummary {
requestedMode: GpuRenderMode
activeTarget: ResolvedGpuTarget
reason: StartupGpuDecisionReason
hasIntegratedGpu: boolean
latestVramSample: DiscreteVramSample | null
}
export interface AdaptiveGpuMonitor {
start(): void
stop(): void
handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void>
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null
getRuntimeSummary(): GpuRuntimeSummary
}
export function readGpuHandoffRecord(userDataDir: string): GpuHandoffRecord | null {
if (!userDataDir) return null
try {
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
if (!fs.existsSync(filePath)) return null
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<GpuHandoffRecord>
if (
!parsed ||
typeof parsed.lastSwitchAt !== 'number' ||
!Number.isFinite(parsed.lastSwitchAt) ||
typeof parsed.target !== 'string' ||
typeof parsed.reason !== 'string'
) {
return null
}
return parsed as GpuHandoffRecord
} catch {
return null
}
}
export function writeGpuHandoffRecord(userDataDir: string, record: GpuHandoffRecord): void {
if (!userDataDir) return
try {
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
fs.mkdirSync(path.dirname(filePath), { recursive: true })
fs.writeFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
} catch {
// Ignore non-critical handoff state write failures.
}
}
export function probeWindowsGpuEnvironmentSync(): {
vramSample: DiscreteVramSample | null
hasIntegratedGpu: boolean
} {
if (process.platform !== 'win32') {
return { vramSample: null, hasIntegratedGpu: false }
}
let vramSample: DiscreteVramSample | null = null
try {
const out = execFileSync('nvidia-smi', NVIDIA_SMI_ARGS, {
encoding: 'utf8',
timeout: 800,
windowsHide: true,
stdio: ['ignore', 'pipe', 'ignore'],
})
vramSample = parseNvidiaSmiCsv(out)
} catch {
vramSample = null
}
let hasIntegratedGpu = false
try {
const out = execFileSync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
encoding: 'utf8',
timeout: 800,
windowsHide: true,
stdio: ['ignore', 'pipe', 'ignore'],
})
hasIntegratedGpu = detectIntegratedGpuFromRegistryOutput(out)
} catch {
hasIntegratedGpu = false
}
return { vramSample, hasIntegratedGpu }
}
export async function probeDiscreteVramAsync(): Promise<DiscreteVramSample | null> {
if (process.platform !== 'win32') {
return null
}
try {
const { stdout } = await execFileAsync('nvidia-smi', NVIDIA_SMI_ARGS, {
encoding: 'utf8',
timeout: 2000,
windowsHide: true,
})
return parseNvidiaSmiCsv(stdout)
} catch {
return null
}
}
export async function probeIntegratedGpuAsync(): Promise<boolean> {
if (process.platform !== 'win32') {
return false
}
try {
const { stdout } = await execFileAsync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
encoding: 'utf8',
timeout: 2000,
windowsHide: true,
})
return detectIntegratedGpuFromRegistryOutput(stdout)
} catch {
return false
}
}
export function createAdaptiveGpuMonitor(options: {
userDataDir: string
startupDecision: StartupGpuDecision
getConfiguredMode: () => GpuRenderMode
getMainWindow: () => BrowserWindow | null
onAutoSwitch: (target: ResolvedGpuTarget, record: GpuHandoffRecord) => void
onStatusUpdated?: () => void
}): AdaptiveGpuMonitor {
let latestVramSample: DiscreteVramSample | null = options.startupDecision.vramSample
let switching = false
let toastConsumed = false
let intervalTimer: ReturnType<typeof setInterval> | null = null
const lastSwitchAt = readGpuHandoffRecord(options.userDataDir)?.lastSwitchAt ?? null
const activeTarget = options.startupDecision.target
const isDiscrete = activeTarget === 'default' || activeTarget === 'high-performance'
const isOffloaded = activeTarget === 'low-power' || activeTarget === 'software'
const tracker = createVramHysteresisTracker({
activeTarget,
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
})
const triggerAutoSwitch = (target: ResolvedGpuTarget, record: GpuHandoffRecord) => {
if (switching) return
switching = true
if (intervalTimer) {
clearInterval(intervalTimer)
intervalTimer = null
}
writeGpuHandoffRecord(options.userDataDir, record)
options.onAutoSwitch(target, record)
}
const tickOffloadedRecovery = async () => {
if (switching || !isOffloaded || options.getConfiguredMode() !== 'auto') return
if (!canAutoSwitchGpu(lastSwitchAt, Date.now())) return
const win = options.getMainWindow()
if (!win || win.isDestroyed() || win.isMinimized()) return
const sample = await probeDiscreteVramAsync()
latestVramSample = sample
options.onStatusUpdated?.()
if (switching || options.getConfiguredMode() !== 'auto') return
const action = tracker.observe(sample)
if (!action || action.kind !== 'switch-to-discrete') return
const now = Date.now()
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
console.info(
`[planet-client] Discrete GPU VRAM recovered (freeMiB=${action.sample.freeMiB}); auto-switching back to discrete GPU`,
)
triggerAutoSwitch('default', {
lastSwitchAt: now,
target: 'default',
reason: 'vram-recovered',
freeMiB: action.sample.freeMiB,
})
}
return {
start() {
if (process.platform !== 'win32' || options.startupDecision.reason === 'headless-smoke') {
return
}
if (!isOffloaded || intervalTimer) return
intervalTimer = setInterval(() => {
void tickOffloadedRecovery()
}, VRAM_MONITOR_INTERVAL_MS)
},
stop() {
if (intervalTimer) {
clearInterval(intervalTimer)
intervalTimer = null
}
},
async handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void> {
if (
process.platform !== 'win32' ||
options.startupDecision.reason === 'headless-smoke' ||
switching ||
!isDiscrete ||
options.getConfiguredMode() !== 'auto'
) {
return
}
const now = Date.now()
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
const sample = await probeDiscreteVramAsync()
latestVramSample = sample
options.onStatusUpdated?.()
if (
switching ||
options.getConfiguredMode() !== 'auto' ||
!sample ||
sample.freeMiB >= VRAM_LOW_THRESHOLD_MIB
) {
return
}
const hasIgpu = options.startupDecision.hasIntegratedGpu || (await probeIntegratedGpuAsync())
const nextTarget: ResolvedGpuTarget = hasIgpu ? 'low-power' : 'software'
const switchNow = Date.now()
if (!canAutoSwitchGpu(lastSwitchAt, switchNow)) return
console.info(
`[planet-client] Sustained low FPS (${report.avgFps} fps for ${report.sustainedMs}ms) with low discrete VRAM (freeMiB=${sample.freeMiB}); auto-switching to ${nextTarget}`,
)
triggerAutoSwitch(nextTarget, {
lastSwitchAt: switchNow,
target: nextTarget,
reason: 'low-fps-low-vram',
freeMiB: sample.freeMiB,
avgFps: report.avgFps,
})
},
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null {
if (toastConsumed || options.startupDecision.reason !== 'gpu-handoff') {
return null
}
toastConsumed = true
const record = readGpuHandoffRecord(options.userDataDir)
if (!record || Date.now() - record.lastSwitchAt >= HANDOFF_RECORD_MAX_AGE_MS) {
return null
}
if (record.reason === 'low-fps-low-vram') {
return record.target === 'software'
? { message: '独显显存不足且帧率偏低,已自动切换至 CPU 软渲染', type: 'info' }
: {
message: '独显显存不足且帧率偏低,已自动切换至集成核显渲染(保留全部特效)',
type: 'info',
}
}
if (record.reason === 'vram-recovered') {
return { message: '独显显存已充足,已自动切回独立显卡渲染', type: 'success' }
}
return null
},
getRuntimeSummary(): GpuRuntimeSummary {
return {
requestedMode: options.getConfiguredMode(),
activeTarget: options.startupDecision.target,
reason: options.startupDecision.reason,
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
latestVramSample,
}
},
}
}
+347
View File
@@ -0,0 +1,347 @@
import type { GpuRenderMode } from './config'
export const VRAM_LOW_THRESHOLD_MIB = 2048
export const VRAM_RECOVER_THRESHOLD_MIB = 3584
export const VRAM_MONITOR_INTERVAL_MS = 5_000
export const VRAM_SWITCH_CONSECUTIVE_REQUIRED = 2
export const LOW_FPS_THRESHOLD = 20
export const LOW_FPS_SUSTAINED_MS = 5_000
export const FPS_STARTUP_WARMUP_MS = 6_000
export const FPS_REPORT_COOLDOWN_MS = 15_000
export const AUTO_SWITCH_COOLDOWN_MS = 45_000
export interface ChromiumSwitch {
name: string
value?: string
}
export type ResolvedGpuTarget = 'default' | 'high-performance' | 'low-power' | 'software'
export interface DiscreteVramSample {
gpuName: string
usedMiB: number
freeMiB: number
totalMiB: number
}
export type StartupGpuDecisionReason =
| 'headless-smoke'
| 'gpu-handoff'
| 'user-software'
| 'user-low-power'
| 'user-high-performance'
| 'low-vram-igpu'
| 'low-vram-software'
| 'normal-gpu'
export interface StartupGpuDecision {
target: ResolvedGpuTarget
requestedMode: GpuRenderMode
reason: StartupGpuDecisionReason
vramSample: DiscreteVramSample | null
hasIntegratedGpu: boolean
}
export interface VramMonitorAction {
kind: 'switch-to-discrete' | 'switch-to-low-power' | 'switch-to-software'
sample: DiscreteVramSample
}
export interface GpuPolicyInput {
platform: NodeJS.Platform
headlessSmoke: boolean
softwareGl?: boolean
target?: ResolvedGpuTarget
}
const VIRTUAL_DISPLAY_ADAPTER_RE = /microsoft basic|remote display|parsec|virtual|indirect|mirage/i
const INTEL_ADAPTER_RE = /\bintel\b/i
const INTEL_DISCRETE_ARC_RE = /\barc\b.*\b[ab]\d{3}\b/i
const AMD_INTEGRATED_RE = /\bamd\s+radeon(?:\(tm\))?\s+(?:graphics|\d+m\b|vega\s+\d+\s+graphics)/i
function parseMiBField(raw: string | undefined): number | null {
if (!raw) return null
const trimmed = raw.trim()
if (!trimmed || /n\/a/i.test(trimmed)) return null
const cleaned = trimmed.replace(/\s*mib$/i, '')
if (!/^\d+(?:\.\d+)?$/.test(cleaned)) return null
const num = Number(cleaned)
return Number.isFinite(num) ? num : null
}
export function parseNvidiaSmiCsv(stdout: string): DiscreteVramSample | null {
if (!stdout) return null
for (const rawLine of stdout.split(/\r?\n/)) {
const line = rawLine.trim()
if (!line) continue
const parts = line.split(',')
if (parts.length < 4) continue
const gpuName = parts.slice(0, -3).join(',').trim()
const usedMiB = parseMiBField(parts[parts.length - 3])
const freeMiB = parseMiBField(parts[parts.length - 2])
const totalMiB = parseMiBField(parts[parts.length - 1])
if (
!gpuName ||
usedMiB === null ||
freeMiB === null ||
totalMiB === null ||
usedMiB < 0 ||
freeMiB < 0 ||
totalMiB <= 0
) {
continue
}
return { gpuName, usedMiB, freeMiB, totalMiB }
}
return null
}
export function detectIntegratedGpuFromRegistryOutput(stdout: string): boolean {
if (!stdout) return false
for (const rawLine of stdout.split(/\r?\n/)) {
const match = /^\s*DriverDesc\s+REG_SZ\s+(.+?)\s*$/i.exec(rawLine)
if (!match) continue
const desc = match[1].trim()
if (!desc || VIRTUAL_DISPLAY_ADAPTER_RE.test(desc)) continue
if (INTEL_ADAPTER_RE.test(desc) && !INTEL_DISCRETE_ARC_RE.test(desc)) {
return true
}
if (AMD_INTEGRATED_RE.test(desc)) {
return true
}
}
return false
}
export function chooseStartupGpuTarget(input: {
platform: NodeJS.Platform
headlessSmoke: boolean
requestedMode: GpuRenderMode
handoffTarget?: ResolvedGpuTarget
vramSample: DiscreteVramSample | null
hasIntegratedGpu: boolean
}): StartupGpuDecision {
const base = {
requestedMode: input.requestedMode,
vramSample: input.vramSample,
hasIntegratedGpu: input.hasIntegratedGpu,
}
if (input.headlessSmoke) {
return { ...base, target: 'software', reason: 'headless-smoke' }
}
if (input.requestedMode === 'software') {
return { ...base, target: 'software', reason: 'user-software' }
}
if (input.requestedMode === 'low-power') {
return { ...base, target: 'low-power', reason: 'user-low-power' }
}
if (input.requestedMode === 'high-performance') {
return { ...base, target: 'high-performance', reason: 'user-high-performance' }
}
if (input.handoffTarget) {
return { ...base, target: input.handoffTarget, reason: 'gpu-handoff' }
}
if (
input.platform === 'win32' &&
input.vramSample &&
input.vramSample.freeMiB < VRAM_LOW_THRESHOLD_MIB
) {
return input.hasIntegratedGpu
? { ...base, target: 'low-power', reason: 'low-vram-igpu' }
: { ...base, target: 'software', reason: 'low-vram-software' }
}
return { ...base, target: 'default', reason: 'normal-gpu' }
}
export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitch[] {
const effectiveTarget: ResolvedGpuTarget =
input.headlessSmoke || input.softwareGl || input.target === 'software'
? 'software'
: (input.target ?? 'default')
if (effectiveTarget === 'software') {
return [
{ name: 'disable-gpu' },
{ name: 'use-gl', value: 'angle' },
{ name: 'use-angle', value: 'swiftshader' },
{ name: 'enable-unsafe-swiftshader' },
]
}
// Avoid forcing enable-zero-copy / enable-gpu-rasterization:
// on Windows dual-GPU setups with high baseline VRAM usage they can provoke driver TDRs.
const switches: ChromiumSwitch[] = []
if (effectiveTarget === 'low-power') {
switches.push({ name: 'force_low_power_gpu' })
} else if (effectiveTarget === 'high-performance') {
switches.push({ name: 'force_high_performance_gpu' })
}
switches.push({ name: 'disable-renderer-backgrounding' })
if (input.platform === 'linux') {
switches.push({ name: 'ozone-platform-hint', value: 'auto' })
}
return switches
}
export function createVramHysteresisTracker(options: {
activeTarget: ResolvedGpuTarget
hasIntegratedGpu: boolean
lowThresholdMiB?: number
recoverThresholdMiB?: number
requiredConsecutive?: number
}) {
const lowThresholdMiB = options.lowThresholdMiB ?? VRAM_LOW_THRESHOLD_MIB
const recoverThresholdMiB = options.recoverThresholdMiB ?? VRAM_RECOVER_THRESHOLD_MIB
const requiredConsecutive = Math.max(1, options.requiredConsecutive ?? VRAM_SWITCH_CONSECUTIVE_REQUIRED)
let streak = 0
return {
observe(sample: DiscreteVramSample | null): VramMonitorAction | null {
if (!sample) {
streak = 0
return null
}
if (options.activeTarget === 'low-power' || options.activeTarget === 'software') {
if (sample.freeMiB >= recoverThresholdMiB) {
streak += 1
if (streak >= requiredConsecutive) {
return { kind: 'switch-to-discrete', sample }
}
} else {
streak = 0
}
return null
}
if (sample.freeMiB < lowThresholdMiB) {
streak += 1
if (streak >= requiredConsecutive) {
return {
kind: options.hasIntegratedGpu ? 'switch-to-low-power' : 'switch-to-software',
sample,
}
}
} else {
streak = 0
}
return null
},
reset(): void {
streak = 0
},
}
}
export function createSustainedLowFpsTracker(
options: {
thresholdFps?: number
sustainedMs?: number
sampleWindowMs?: number
reportCooldownMs?: number
} = {},
) {
const thresholdFps = options.thresholdFps ?? LOW_FPS_THRESHOLD
const sustainedMs = options.sustainedMs ?? LOW_FPS_SUSTAINED_MS
const sampleWindowMs = options.sampleWindowMs ?? 1000
const reportCooldownMs = options.reportCooldownMs ?? FPS_REPORT_COOLDOWN_MS
let bucketStartMs: number | null = null
let bucketFrames = 0
let lowDurationMs = 0
let lowFrames = 0
let lastReportedAt = -Infinity
return {
onFrame(nowMs: number): { avgFps: number; sustainedMs: number } | null {
if (!Number.isFinite(nowMs)) return null
if (bucketStartMs === null) {
bucketStartMs = nowMs
bucketFrames = 0
return null
}
bucketFrames += 1
const elapsedMs = nowMs - bucketStartMs
if (elapsedMs < sampleWindowMs) {
return null
}
const fps = (bucketFrames * 1000) / elapsedMs
bucketStartMs = nowMs
if (fps < thresholdFps) {
lowDurationMs += elapsedMs
lowFrames += bucketFrames
bucketFrames = 0
if (lowDurationMs >= sustainedMs && nowMs - lastReportedAt >= reportCooldownMs) {
const avgFps = Math.round(((lowFrames * 1000) / lowDurationMs) * 10) / 10
const reportedDuration = Math.round(lowDurationMs)
lastReportedAt = nowMs
lowDurationMs = 0
lowFrames = 0
return { avgFps, sustainedMs: reportedDuration }
}
return null
}
bucketFrames = 0
lowDurationMs = 0
lowFrames = 0
return null
},
reset(): void {
bucketStartMs = null
bucketFrames = 0
lowDurationMs = 0
lowFrames = 0
},
}
}
export function canAutoSwitchGpu(
lastSwitchAt: number | null | undefined,
nowMs: number,
cooldownMs = AUTO_SWITCH_COOLDOWN_MS,
): boolean {
return !lastSwitchAt || !Number.isFinite(lastSwitchAt) || nowMs - lastSwitchAt >= cooldownMs
}
export function stripGpuOverrideArgs(argv: string[]): string[] {
const stripped: string[] = []
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
if (
arg === '--software-gl' ||
arg === '--low-power-gpu' ||
arg === '--high-performance-gpu' ||
arg === '--gpu-handoff' ||
arg.startsWith('--gpu-mode=') ||
arg.startsWith('--gpu-handoff-target=')
) {
continue
}
if (arg === '--gpu-mode' || arg === '--gpu-handoff-target') {
i += 1
continue
}
stripped.push(arg)
}
return stripped
}
export function buildGpuHandoffArgs(argv: string[], target?: ResolvedGpuTarget): string[] {
return [
...stripGpuOverrideArgs(argv),
'--gpu-handoff',
...(target ? [`--gpu-handoff-target=${target}`] : []),
]
}
export function isGpuProcessCrash(
details: { type?: string; reason?: string } | null | undefined,
): boolean {
return Boolean(details && details.type === 'GPU' && details.reason !== 'clean-exit')
}
+504
View File
@@ -0,0 +1,504 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { extractTarGzSafely } from './tar-gz'
export interface ClientShellUpdateInfo {
version: string
minRequired?: string | null
downloadUrl: string
releaseNotes?: string | null
}
export interface ClientBundleUpdateInfo {
version: string
minShellVersion: string
url: string
sha256: string
size?: number
releaseNotes?: string | null
}
export interface ClientUpdateManifest {
shell?: ClientShellUpdateInfo | null
bundle?: ClientBundleUpdateInfo | null
}
export interface HotfixState {
activeVersion: string | null
previousVerifiedVersion: string | null
status: 'verified' | 'pending'
pendingAttempts: number
blacklistedVersions: string[]
installedAt?: string
}
export interface ActiveOverlayResolution {
overlayRoot: string | null
activeBundleVersion: string
pendingVerification: boolean
rolledBackFrom: string | null
}
export type UpdateDecision =
| { kind: 'up-to-date' }
| { kind: 'hotfix-update'; bundle: ClientBundleUpdateInfo }
| { kind: 'shell-update'; shell: ClientShellUpdateInfo; mandatory: boolean }
const SEMVER_PATTERN = /^[vV]?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
const STRICT_VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/
const SHA256_PATTERN = /^[0-9a-f]{64}$/i
const MAX_PENDING_ATTEMPTS = 2
interface ParsedSemver {
major: number
minor: number
patch: number
prerelease: string[]
}
function parseSemver(raw: string): ParsedSemver | null {
const match = SEMVER_PATTERN.exec(String(raw || '').trim())
if (!match) return null
return {
major: Number(match[1] ?? 0),
minor: Number(match[2] ?? 0),
patch: Number(match[3] ?? 0),
prerelease: match[4] ? match[4].split('.') : [],
}
}
export function compareSemver(a: string, b: string): number {
const pa = parseSemver(a)
const pb = parseSemver(b)
if (!pa || !pb) {
return String(a).localeCompare(String(b))
}
for (const [va, vb] of [
[pa.major, pb.major],
[pa.minor, pb.minor],
[pa.patch, pb.patch],
]) {
if (va !== vb) return va > vb ? 1 : -1
}
if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0
if (pa.prerelease.length === 0) return 1
if (pb.prerelease.length === 0) return -1
const maxLen = Math.max(pa.prerelease.length, pb.prerelease.length)
for (let i = 0; i < maxLen; i += 1) {
const ia = pa.prerelease[i]
const ib = pb.prerelease[i]
if (ia === undefined) return -1
if (ib === undefined) return 1
const na = /^\d+$/.test(ia) ? Number(ia) : null
const nb = /^\d+$/.test(ib) ? Number(ib) : null
if (na !== null && nb !== null) {
if (na !== nb) return na > nb ? 1 : -1
} else if (na !== null) {
return -1
} else if (nb !== null) {
return 1
} else if (ia !== ib) {
return ia > ib ? 1 : -1
}
}
return 0
}
export function getHotfixRootDir(userDataDir: string): string {
return path.join(userDataDir, 'earth-hotfix')
}
export function getHotfixBundlesDir(userDataDir: string): string {
return path.join(getHotfixRootDir(userDataDir), 'bundles')
}
export function getHotfixBundleDir(userDataDir: string, version: string): string {
return path.join(getHotfixBundlesDir(userDataDir), version)
}
function getHotfixStatePath(userDataDir: string): string {
return path.join(getHotfixRootDir(userDataDir), 'state.json')
}
function defaultHotfixState(): HotfixState {
return {
activeVersion: null,
previousVerifiedVersion: null,
status: 'verified',
pendingAttempts: 0,
blacklistedVersions: [],
}
}
export function readHotfixState(userDataDir: string): HotfixState {
const statePath = getHotfixStatePath(userDataDir)
try {
if (!fs.existsSync(statePath)) return defaultHotfixState()
const raw = JSON.parse(fs.readFileSync(statePath, 'utf8')) as Partial<HotfixState>
return {
activeVersion: typeof raw.activeVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.activeVersion)
? raw.activeVersion
: null,
previousVerifiedVersion: typeof raw.previousVerifiedVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.previousVerifiedVersion)
? raw.previousVerifiedVersion
: null,
status: raw.status === 'pending' ? 'pending' : 'verified',
pendingAttempts: Number.isInteger(raw.pendingAttempts) && Number(raw.pendingAttempts) >= 0
? Number(raw.pendingAttempts)
: 0,
blacklistedVersions: Array.isArray(raw.blacklistedVersions)
? raw.blacklistedVersions.filter((item): item is string => typeof item === 'string' && STRICT_VERSION_PATTERN.test(item))
: [],
installedAt: typeof raw.installedAt === 'string' ? raw.installedAt : undefined,
}
} catch {
return defaultHotfixState()
}
}
export function writeHotfixStateAtomic(userDataDir: string, state: HotfixState): void {
const rootDir = getHotfixRootDir(userDataDir)
const statePath = getHotfixStatePath(userDataDir)
const tmpPath = `${statePath}.${process.pid}.tmp`
fs.mkdirSync(rootDir, { recursive: true })
fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, 'utf8')
fs.renameSync(tmpPath, statePath)
}
function hasValidBundleIndex(bundleDir: string): boolean {
try {
return fs.statSync(path.join(bundleDir, 'index.html')).isFile()
} catch {
return false
}
}
function resolveFallbackVersion(state: HotfixState, shellVersion: string, userDataDir: string): string | null {
const candidate = state.previousVerifiedVersion
if (!candidate) return null
if (candidate === state.activeVersion) return null
if (state.blacklistedVersions.includes(candidate)) return null
if (compareSemver(candidate, shellVersion) <= 0) return null
if (!hasValidBundleIndex(getHotfixBundleDir(userDataDir, candidate))) return null
return candidate
}
function pruneObsoleteBundles(userDataDir: string, keepVersions: Set<string>): void {
const bundlesDir = getHotfixBundlesDir(userDataDir)
try {
if (!fs.existsSync(bundlesDir)) return
for (const entry of fs.readdirSync(bundlesDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue
if (keepVersions.has(entry.name)) continue
fs.rmSync(path.join(bundlesDir, entry.name), { recursive: true, force: true })
}
} catch {
// Non-fatal cleanup best-effort.
}
}
export function resolveActiveEarthOverlay(options: {
userDataDir: string
shellVersion: string
}): ActiveOverlayResolution {
const { userDataDir, shellVersion } = options
const state = readHotfixState(userDataDir)
if (!state.activeVersion || compareSemver(state.activeVersion, shellVersion) <= 0) {
return {
overlayRoot: null,
activeBundleVersion: shellVersion,
pendingVerification: false,
rolledBackFrom: null,
}
}
const activeDir = getHotfixBundleDir(userDataDir, state.activeVersion)
const activeUsable =
!state.blacklistedVersions.includes(state.activeVersion) && hasValidBundleIndex(activeDir)
if (!activeUsable) {
const badVersion = state.activeVersion
const fallbackVer = resolveFallbackVersion(state, shellVersion, userDataDir)
const nextState: HotfixState = {
...state,
activeVersion: fallbackVer,
previousVerifiedVersion: fallbackVer,
status: 'verified',
pendingAttempts: 0,
}
writeHotfixStateAtomic(userDataDir, nextState)
return {
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
activeBundleVersion: fallbackVer ?? shellVersion,
pendingVerification: false,
rolledBackFrom: badVersion,
}
}
if (state.status === 'pending') {
if (state.pendingAttempts >= MAX_PENDING_ATTEMPTS) {
const rolledBackFrom = state.activeVersion
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
? state.blacklistedVersions
: [...state.blacklistedVersions, rolledBackFrom]
const fallbackVer = resolveFallbackVersion(
{ ...state, blacklistedVersions: blacklist },
shellVersion,
userDataDir,
)
const nextState: HotfixState = {
activeVersion: fallbackVer,
previousVerifiedVersion: fallbackVer,
status: 'verified',
pendingAttempts: 0,
blacklistedVersions: blacklist,
}
writeHotfixStateAtomic(userDataDir, nextState)
fs.rmSync(activeDir, { recursive: true, force: true })
return {
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
activeBundleVersion: fallbackVer ?? shellVersion,
pendingVerification: false,
rolledBackFrom,
}
}
const nextState: HotfixState = {
...state,
pendingAttempts: state.pendingAttempts + 1,
}
writeHotfixStateAtomic(userDataDir, nextState)
return {
overlayRoot: activeDir,
activeBundleVersion: state.activeVersion,
pendingVerification: true,
rolledBackFrom: null,
}
}
return {
overlayRoot: activeDir,
activeBundleVersion: state.activeVersion,
pendingVerification: false,
rolledBackFrom: null,
}
}
export function markHotfixVerified(userDataDir: string): HotfixState {
const state = readHotfixState(userDataDir)
if (!state.activeVersion) {
return state
}
const nextState: HotfixState = {
...state,
previousVerifiedVersion: state.activeVersion,
status: 'verified',
pendingAttempts: 0,
}
writeHotfixStateAtomic(userDataDir, nextState)
const keep = new Set<string>([state.activeVersion])
if (nextState.previousVerifiedVersion) {
keep.add(nextState.previousVerifiedVersion)
}
pruneObsoleteBundles(userDataDir, keep)
return nextState
}
export function rollbackPendingHotfix(userDataDir: string, shellVersion: string): {
rolledBackFrom: string | null
overlayRoot: string | null
activeBundleVersion: string
} {
const state = readHotfixState(userDataDir)
if (!state.activeVersion || state.status !== 'pending') {
const activeDir = state.activeVersion ? getHotfixBundleDir(userDataDir, state.activeVersion) : null
const valid = Boolean(
activeDir &&
state.activeVersion &&
compareSemver(state.activeVersion, shellVersion) > 0 &&
hasValidBundleIndex(activeDir),
)
return {
rolledBackFrom: null,
overlayRoot: valid ? activeDir : null,
activeBundleVersion: valid && state.activeVersion ? state.activeVersion : shellVersion,
}
}
const rolledBackFrom = state.activeVersion
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
? state.blacklistedVersions
: [...state.blacklistedVersions, rolledBackFrom]
const fallbackVer = resolveFallbackVersion(
{ ...state, blacklistedVersions: blacklist },
shellVersion,
userDataDir,
)
const nextState: HotfixState = {
activeVersion: fallbackVer,
previousVerifiedVersion: fallbackVer,
status: 'verified',
pendingAttempts: 0,
blacklistedVersions: blacklist,
}
writeHotfixStateAtomic(userDataDir, nextState)
fs.rmSync(getHotfixBundleDir(userDataDir, rolledBackFrom), { recursive: true, force: true })
return {
rolledBackFrom,
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
activeBundleVersion: fallbackVer ?? shellVersion,
}
}
export function evaluateUpdateDecision(input: {
shellVersion: string
activeBundleVersion: string
blacklistedVersions: string[]
manifest: ClientUpdateManifest | null | undefined
}): UpdateDecision {
const manifest = input.manifest
if (!manifest || typeof manifest !== 'object') {
return { kind: 'up-to-date' }
}
const shell = manifest.shell
const hasShellDownload = Boolean(shell?.downloadUrl && typeof shell.downloadUrl === 'string')
const shellMandatory = Boolean(
hasShellDownload && shell?.minRequired && compareSemver(shell.minRequired, input.shellVersion) > 0,
)
const shellNewer = Boolean(
hasShellDownload && shell?.version && compareSemver(shell.version, input.shellVersion) > 0,
)
if (shell && shellMandatory) {
return { kind: 'shell-update', shell, mandatory: true }
}
const bundle = manifest.bundle
if (
bundle &&
typeof bundle.version === 'string' &&
STRICT_VERSION_PATTERN.test(bundle.version) &&
typeof bundle.url === 'string' &&
bundle.url.trim().length > 0 &&
typeof bundle.sha256 === 'string' &&
SHA256_PATTERN.test(bundle.sha256.trim()) &&
compareSemver(bundle.version, input.activeBundleVersion) > 0 &&
compareSemver(input.shellVersion, bundle.minShellVersion || '0.0.0') >= 0 &&
!input.blacklistedVersions.includes(bundle.version)
) {
return { kind: 'hotfix-update', bundle }
}
if (shell && shellNewer) {
return { kind: 'shell-update', shell, mandatory: false }
}
return { kind: 'up-to-date' }
}
export const PERIODIC_UPDATE_CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000
export function getUpdatePromptKey(decision: UpdateDecision): string | null {
if (decision.kind === 'hotfix-update') {
return `hotfix:${decision.bundle.version}`
}
if (decision.kind === 'shell-update') {
return `shell:${decision.shell.version}`
}
return null
}
export function shouldSuppressUpdatePrompt(
decision: UpdateDecision,
options: { manual: boolean; dismissedKeys: ReadonlySet<string> },
): boolean {
if (options.manual || decision.kind === 'up-to-date') {
return false
}
const key = getUpdatePromptKey(decision)
return Boolean(key && options.dismissedKeys.has(key))
}
export function resolveUpdateAssetUrl(rawUrl: string, backendUrl: string): string {
const trimmed = String(rawUrl || '').trim()
if (!trimmed) {
throw new Error('Empty update asset URL')
}
if (trimmed.startsWith('/')) {
const base = new URL(backendUrl)
return new URL(trimmed, `${base.origin}`).toString()
}
const parsed = new URL(trimmed)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new Error(`Unsupported update asset URL protocol: ${parsed.protocol}`)
}
return parsed.toString()
}
export function installHotfixArchive(input: {
userDataDir: string
version: string
archiveBuffer: Buffer
expectedSha256: string
}): { overlayRoot: string; filesCount: number } {
const version = String(input.version || '').trim()
if (!STRICT_VERSION_PATTERN.test(version)) {
throw new Error(`Invalid hotfix bundle version: ${version}`)
}
const expected = String(input.expectedSha256 || '').trim().toLowerCase()
if (!SHA256_PATTERN.test(expected)) {
throw new Error('Invalid expected SHA-256 checksum')
}
const actual = crypto.createHash('sha256').update(input.archiveBuffer).digest('hex').toLowerCase()
if (actual !== expected) {
throw new Error(`Hotfix SHA-256 mismatch (expected ${expected}, got ${actual})`)
}
const rootDir = getHotfixRootDir(input.userDataDir)
const bundlesDir = getHotfixBundlesDir(input.userDataDir)
const targetDir = getHotfixBundleDir(input.userDataDir, version)
const stagingDir = path.join(rootDir, `staging-${version}-${Date.now()}`)
try {
const extracted = extractTarGzSafely(input.archiveBuffer, stagingDir)
if (!hasValidBundleIndex(stagingDir)) {
throw new Error('Hotfix archive is missing required index.html entry')
}
fs.mkdirSync(bundlesDir, { recursive: true })
fs.rmSync(targetDir, { recursive: true, force: true })
fs.renameSync(stagingDir, targetDir)
const previousState = readHotfixState(input.userDataDir)
const preservedVerified =
previousState.status === 'verified' && previousState.activeVersion && previousState.activeVersion !== version
? previousState.activeVersion
: previousState.previousVerifiedVersion && previousState.previousVerifiedVersion !== version
? previousState.previousVerifiedVersion
: null
const nextState: HotfixState = {
activeVersion: version,
previousVerifiedVersion: preservedVerified,
status: 'pending',
pendingAttempts: 0,
blacklistedVersions: previousState.blacklistedVersions.filter((item) => item !== version),
installedAt: new Date().toISOString(),
}
writeHotfixStateAtomic(input.userDataDir, nextState)
return {
overlayRoot: targetDir,
filesCount: extracted.files.length,
}
} catch (error) {
fs.rmSync(stagingDir, { recursive: true, force: true })
throw error
}
}
+313
View File
@@ -0,0 +1,313 @@
import { dialog, net, shell, type BrowserWindow, type MessageBoxOptions } from 'electron'
import {
evaluateUpdateDecision,
getUpdatePromptKey,
installHotfixArchive,
markHotfixVerified,
readHotfixState,
resolveActiveEarthOverlay,
resolveUpdateAssetUrl,
rollbackPendingHotfix,
shouldSuppressUpdatePrompt,
type ClientUpdateManifest,
} from './hot-update-core'
export interface HotUpdateVersionInfo {
shellVersion: string
activeBundleVersion: string
usingHotfix: boolean
pendingVerification: boolean
}
export interface HotUpdateController {
getOverlayRoot(): string | null
getVersionInfo(): HotUpdateVersionInfo
markStartupReady(): void
handleRendererCrash(): void
startStartupWatchdog(): void
stopStartupWatchdog(): void
checkForUpdates(options?: { manual?: boolean }): Promise<void>
}
const MANIFEST_TIMEOUT_MS = 10_000
const DOWNLOAD_TIMEOUT_MS = 60_000
const STARTUP_VERIFY_TIMEOUT_MS = 15_000
async function fetchWithTimeout(
fetchImpl: typeof fetch,
url: string,
timeoutMs: number,
init: RequestInit = {},
): Promise<Response> {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs)
try {
return await fetchImpl(url, { ...init, signal: controller.signal })
} finally {
clearTimeout(timer)
}
}
export function createHotUpdateController(options: {
userDataDir: string
shellVersion: string
getBackendUrl: () => string
getMainWindow: () => BrowserWindow | null
onOverlayChanged: (nextOverlayRoot: string | null, nextBundleVersion: string) => void
fetchImpl?: typeof fetch
}): HotUpdateController {
const fetchImpl = options.fetchImpl ?? ((input, init) => net.fetch(input as string, init))
const initial = resolveActiveEarthOverlay({
userDataDir: options.userDataDir,
shellVersion: options.shellVersion,
})
if (initial.rolledBackFrom) {
console.warn(
`[planet-client] Rolled back unverified hotfix v${initial.rolledBackFrom} -> v${initial.activeBundleVersion}`,
)
}
let overlayRoot = initial.overlayRoot
let activeBundleVersion = initial.activeBundleVersion
let pendingVerification = initial.pendingVerification
let watchdogTimer: ReturnType<typeof setTimeout> | null = null
let inFlightCheck: Promise<void> | null = null
const dismissedPromptKeys = new Set<string>()
const notifyStatus = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
const win = options.getMainWindow()
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
win.webContents.send('planet:update-status', { message, type })
}
}
const showBox = (boxOptions: MessageBoxOptions) => {
const win = options.getMainWindow()
if (win && !win.isDestroyed()) {
return dialog.showMessageBox(win, boxOptions)
}
return dialog.showMessageBox(boxOptions)
}
const stopStartupWatchdog = () => {
if (watchdogTimer) {
clearTimeout(watchdogTimer)
watchdogTimer = null
}
}
const performRollbackAndReload = (reason: string) => {
stopStartupWatchdog()
const result = rollbackPendingHotfix(options.userDataDir, options.shellVersion)
if (!result.rolledBackFrom) return
console.warn(`[planet-client] ${reason}; rolled back v${result.rolledBackFrom} -> v${result.activeBundleVersion}`)
overlayRoot = result.overlayRoot
activeBundleVersion = result.activeBundleVersion
pendingVerification = false
options.onOverlayChanged(overlayRoot, activeBundleVersion)
const win = options.getMainWindow()
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
win.webContents.reloadIgnoringCache()
}
}
const startStartupWatchdog = () => {
stopStartupWatchdog()
if (!pendingVerification) return
watchdogTimer = setTimeout(() => {
watchdogTimer = null
if (!pendingVerification) return
performRollbackAndReload('Hotfix startup verification timed out')
}, STARTUP_VERIFY_TIMEOUT_MS)
}
const markStartupReady = () => {
stopStartupWatchdog()
if (!pendingVerification) return
pendingVerification = false
markHotfixVerified(options.userDataDir)
options.onOverlayChanged(overlayRoot, activeBundleVersion)
notifyStatus(`热更新已生效 / Hotfix v${activeBundleVersion} active`, 'success')
}
const handleRendererCrash = () => {
if (!pendingVerification) return
performRendererCrashRecovery()
}
const performRendererCrashRecovery = () => {
performRendererSafeRollback()
}
const performRendererSafeRollback = () => {
performRollbackAndReload('Renderer exited unexpectedly under pending hotfix')
}
const applyHotfixBundle = async (bundleUrl: string, version: string, expectedSha256: string) => {
notifyStatus(`正在下载热更新 v${version}… / Downloading hotfix v${version}…`, 'info')
const response = await fetchWithTimeout(fetchImpl, bundleUrl, DOWNLOAD_TIMEOUT_MS, {
cache: 'no-store',
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const arrayBuf = await response.arrayBuffer()
const archiveBuffer = Buffer.from(arrayBuf)
const installed = installHotfixArchive({
userDataDir: options.userDataDir,
version,
archiveBuffer,
expectedSha256,
})
overlayRoot = installed.overlayRoot
activeBundleVersion = version
pendingVerification = true
options.onOverlayChanged(overlayRoot, activeBundleVersion)
startStartupWatchdog()
const win = options.getMainWindow()
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
win.webContents.reloadIgnoringCache()
}
}
const runCheck = async (manual: boolean): Promise<void> => {
const backendUrl = options.getBackendUrl().replace(/\/+$/, '')
const manifestUrl = new URL(`${backendUrl}/api/v1/client/update-manifest`)
manifestUrl.searchParams.set('platform', process.platform)
manifestUrl.searchParams.set('arch', process.arch)
manifestUrl.searchParams.set('shell', options.shellVersion)
manifestUrl.searchParams.set('bundle', activeBundleVersion)
let manifest: ClientUpdateManifest
try {
const response = await fetchWithTimeout(fetchImpl, manifestUrl.toString(), MANIFEST_TIMEOUT_MS, {
cache: 'no-store',
headers: { Accept: 'application/json' },
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
manifest = (await response.json()) as ClientUpdateManifest
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
if (manual) {
await showBox({
type: 'warning',
title: '检查更新失败 / Update Check Failed',
message: '无法获取版本清单,请确认服务端连接正常。',
detail,
buttons: ['确定 / OK'],
})
} else {
console.warn('[planet-client] Startup update check skipped:', detail)
}
return
}
const state = readHotfixState(options.userDataDir)
const decision = evaluateUpdateDecision({
shellVersion: options.shellVersion,
activeBundleVersion,
blacklistedVersions: state.blacklistedVersions,
manifest,
})
if (decision.kind === 'up-to-date') {
if (manual) {
await showBox({
type: 'info',
title: '当前已是最新版本 / Up to Date',
message: 'Planet Earth 客户端已是最新版本。',
detail: `外壳版本 / Shell: v${options.shellVersion}\n地球业务包 / Earth Bundle: v${activeBundleVersion}`,
buttons: ['确定 / OK'],
})
}
return
}
if (shouldSuppressUpdatePrompt(decision, { manual, dismissedKeys: dismissedPromptKeys })) {
return
}
const promptKey = getUpdatePromptKey(decision)
if (decision.kind === 'hotfix-update') {
const { bundle } = decision
const notes = bundle.releaseNotes?.trim() ? `\n\n更新内容:\n${bundle.releaseNotes.trim()}` : ''
const { response } = await showBox({
type: 'info',
title: '发现新版本 / Update Available',
message: `发现 Planet Earth 增量热更新 v${bundle.version}`,
detail: `当前地球版本 v${activeBundleVersion} → 最新版本 v${bundle.version}\n更新方式:轻量热更新(无需重新安装,应用后自动生效)${notes}`,
buttons: ['立即更新 / Update Now', '稍后提醒 / Later'],
defaultId: 0,
cancelId: 1,
})
if (response !== 0) {
if (promptKey) dismissedPromptKeys.add(promptKey)
return
}
try {
const assetUrl = resolveUpdateAssetUrl(bundle.url, backendUrl)
await applyHotfixBundle(assetUrl, bundle.version, bundle.sha256)
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
console.error('[planet-client] Hotfix installation failed:', detail)
await showBox({
type: 'error',
title: '热更新失败 / Hotfix Failed',
message: `热更新包 v${bundle.version} 下载或校验失败,已保留当前版本运行。`,
detail,
buttons: ['确定 / OK'],
})
}
return
}
const { shell: shellInfo, mandatory } = decision
const notes = shellInfo.releaseNotes?.trim() ? `\n\n更新说明:\n${shellInfo.releaseNotes.trim()}` : ''
const { response } = await showBox({
type: mandatory ? 'warning' : 'info',
title: '发现客户端大版本更新 / Major Client Update',
message: mandatory
? `当前客户端版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}`
: `发现客户端新版本 v${shellInfo.version}`,
detail: `当前客户端外壳:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n该版本包含底层架构或原生壳变更,需下载安装包覆盖更新。${notes}`,
buttons: ['前往下载 / Download', '稍后提醒 / Later'],
defaultId: 0,
cancelId: 1,
})
if (response === 0) {
await shell.openExternal(shellInfo.downloadUrl)
} else if (promptKey) {
dismissedPromptKeys.add(promptKey)
}
}
return {
getOverlayRoot: () => overlayRoot,
getVersionInfo: () => ({
shellVersion: options.shellVersion,
activeBundleVersion,
usingHotfix: Boolean(overlayRoot),
pendingVerification,
}),
markStartupReady,
handleRendererCrash,
startStartupWatchdog,
stopStartupWatchdog,
checkForUpdates(checkOpts = {}) {
if (inFlightCheck) return inFlightCheck
inFlightCheck = runCheck(Boolean(checkOpts.manual)).finally(() => {
inFlightCheck = null
})
return inFlightCheck
},
}
}
+230 -26
View File
@@ -1,30 +1,73 @@
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron' import { app, BrowserWindow, dialog, ipcMain, Menu, session, shell } from 'electron'
import { DesktopConfigStore, normalizeSplashTheme, type ServerEndpoints } from './config' import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config'
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link' import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy'
import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core'
import { createHotUpdateController } from './hot-updater'
import { buildApplicationMenu } from './menu' import { buildApplicationMenu } from './menu'
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol' import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation } from './window' import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
registerEarthScheme() registerEarthScheme()
const isHeadlessSmoke = process.argv.includes('--headless-smoke') const isHeadlessSmoke = process.argv.includes('--headless-smoke')
if (isHeadlessSmoke) { let preReadyUserDataDir = ''
app.commandLine.appendSwitch('disable-gpu') let preReadyExeDir = process.cwd()
app.commandLine.appendSwitch('use-gl', 'angle') try {
app.commandLine.appendSwitch('use-angle', 'swiftshader') preReadyUserDataDir = app.getPath('userData')
app.commandLine.appendSwitch('enable-unsafe-swiftshader') } catch {
} else { preReadyUserDataDir = ''
// Prioritize discrete/high-performance GPU and avoid throttling visible secondary-screen renders. }
app.commandLine.appendSwitch('force_high_performance_gpu') try {
app.commandLine.appendSwitch('enable-gpu-rasterization') preReadyExeDir = path.dirname(app.getPath('exe'))
app.commandLine.appendSwitch('enable-zero-copy') } catch {
app.commandLine.appendSwitch('disable-renderer-backgrounding') preReadyExeDir = process.cwd()
if (process.platform === 'linux') { }
app.commandLine.appendSwitch('ozone-platform-hint', 'auto')
const requestedGpuMode = readPreReadyGpuMode({
userDataDir: preReadyUserDataDir,
exeDir: preReadyExeDir,
resourcesDir: process.resourcesPath,
argv: process.argv,
})
const preReadyHandoff = readPreReadyGpuHandoff(process.argv)
const preReadyGpuEnv =
!isHeadlessSmoke &&
!preReadyHandoff.gpuHandoffTarget &&
requestedGpuMode === 'auto' &&
process.platform === 'win32'
? probeWindowsGpuEnvironmentSync()
: { vramSample: null, hasIntegratedGpu: false }
const startupGpuDecision = chooseStartupGpuTarget({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
requestedMode: requestedGpuMode,
handoffTarget: preReadyHandoff.gpuHandoffTarget,
vramSample: preReadyGpuEnv.vramSample,
hasIntegratedGpu: preReadyGpuEnv.hasIntegratedGpu,
})
if (startupGpuDecision.reason === 'low-vram-igpu' || startupGpuDecision.reason === 'low-vram-software') {
console.info(
`[planet-client] Adaptive GPU selected ${startupGpuDecision.target} (reason=${startupGpuDecision.reason}, freeMiB=${startupGpuDecision.vramSample?.freeMiB ?? 'unknown'})`,
)
}
for (const sw of resolveChromiumGpuSwitches({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
target: startupGpuDecision.target,
})) {
if (sw.value !== undefined) {
app.commandLine.appendSwitch(sw.name, sw.value)
} else {
app.commandLine.appendSwitch(sw.name)
} }
} }
@@ -93,6 +136,20 @@ if (!singleInstanceLock) {
} }
}) })
app.on('child-process-gone', (_event, details) => {
if (!isGpuProcessCrash(details)) return
console.warn('[planet-client] GPU process exited unexpectedly', {
reason: details.reason,
exitCode: details.exitCode,
})
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {
mainWindow.webContents.send('planet:gpu-process-gone', {
reason: details.reason,
exitCode: details.exitCode,
})
}
})
void app.whenReady().then(async () => { void app.whenReady().then(async () => {
if (!isHeadlessSmoke) { if (!isHeadlessSmoke) {
void registerDesktopLink().catch(error => console.warn('Planet Earth protocol registration failed', error)) void registerDesktopLink().catch(error => console.warn('Planet Earth protocol registration failed', error))
@@ -105,11 +162,120 @@ if (!singleInstanceLock) {
}) })
const earthBundleRoot = resolveEarthBundleRoot() const earthBundleRoot = resolveEarthBundleRoot()
const relaunchDesktopApp = (relaunchOptions?: {
gpuHandoff?: boolean
gpuHandoffTarget?: ResolvedGpuTarget
}) => {
flushWindowState(mainWindow)
if (singleInstanceLock) {
app.releaseSingleInstanceLock()
}
const rawArgs = process.argv.slice(1)
const args = relaunchOptions?.gpuHandoff
? buildGpuHandoffArgs(rawArgs, relaunchOptions.gpuHandoffTarget)
: stripGpuOverrideArgs(rawArgs)
app.relaunch({ args })
app.exit(0)
}
const hotUpdater = createHotUpdateController({
userDataDir: app.getPath('userData'),
shellVersion: app.getVersion(),
getBackendUrl: () => configStore.get().backendUrl,
getMainWindow: () => mainWindow,
onOverlayChanged: () => {
refreshApplicationMenu()
},
})
const gpuMonitor = createAdaptiveGpuMonitor({
userDataDir: app.getPath('userData'),
startupDecision: startupGpuDecision,
getConfiguredMode: () => configStore.get().gpuMode,
getMainWindow: () => mainWindow,
onAutoSwitch: (nextTarget) => {
relaunchDesktopApp({ gpuHandoff: true, gpuHandoffTarget: nextTarget })
},
onStatusUpdated: () => {
refreshApplicationMenu()
},
})
const sendPendingHandoffToast = () => {
if (isHeadlessSmoke || !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
return
}
const toast = gpuMonitor.consumePendingHandoffToast()
if (toast) {
mainWindow.webContents.send('planet:update-status', toast)
}
}
const refreshApplicationMenu = () => {
if (!mainWindow || mainWindow.isDestroyed()) return
Menu.setApplicationMenu(
buildApplicationMenu({
mainWindow,
configStore,
getVersionInfo: () => hotUpdater.getVersionInfo(),
onCheckForUpdates: () => {
void hotUpdater.checkForUpdates({ manual: true })
},
getGpuStatus: () => gpuMonitor.getRuntimeSummary(),
onSelectGpuMode: async (nextMode: GpuRenderMode) => {
configStore.updateGpuMode(nextMode)
refreshApplicationMenu()
const targetWin = mainWindow && !mainWindow.isDestroyed() ? mainWindow : undefined
const boxOptions = {
type: 'info' as const,
title: '渲染设备设置 / GPU Mode',
message: '渲染设备模式已更新,需重启客户端生效',
detail: '是否立即重启 Planet Earth?(重启约需 1-2 秒,将保留全部视觉特效)',
buttons: ['立即重启 / Restart Now', '稍后手动重启 / Later'],
defaultId: 0,
cancelId: 1,
}
const { response } = targetWin
? await dialog.showMessageBox(targetWin, boxOptions)
: await dialog.showMessageBox(boxOptions)
if (response === 0) {
relaunchDesktopApp({ gpuHandoff: true })
}
},
}),
)
}
installEarthSessionHandlers(session.defaultSession, { installEarthSessionHandlers(session.defaultSession, {
earthBundleRoot, earthBundleRoot,
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
getBackendUrl: () => configStore.get().backendUrl, getBackendUrl: () => configStore.get().backendUrl,
}) })
ipcMain.on('planet:earth-startup-ready', () => {
if (!isHeadlessSmoke) {
hotUpdater.markStartupReady()
sendPendingHandoffToast()
}
})
ipcMain.on('planet:low-fps-report', (_event, payload: unknown) => {
if (isHeadlessSmoke || !payload || typeof payload !== 'object') return
const candidate = payload as { avgFps?: unknown; sustainedMs?: unknown }
const avgFps = Number(candidate.avgFps)
const sustainedMs = Number(candidate.sustainedMs)
if (!Number.isFinite(avgFps) || avgFps <= 0 || !Number.isFinite(sustainedMs) || sustainedMs <= 0) {
return
}
void gpuMonitor.handleLowFpsReport({ avgFps, sustainedMs })
})
ipcMain.handle('planet:check-for-updates', async () => {
await hotUpdater.checkForUpdates({ manual: true })
})
ipcMain.handle('planet:get-version-info', () => hotUpdater.getVersionInfo())
ipcMain.on('planet:get-runtime-config', (event) => { ipcMain.on('planet:get-runtime-config', (event) => {
const cfg = configStore.get() const cfg = configStore.get()
event.returnValue = { event.returnValue = {
@@ -119,10 +285,14 @@ if (!singleInstanceLock) {
wsUrl: cfg.wsUrl, wsUrl: cfg.wsUrl,
forceShowFps: cfg.forceShowFps, forceShowFps: cfg.forceShowFps,
splashTheme: cfg.splashTheme, splashTheme: cfg.splashTheme,
gpuMode: cfg.gpuMode,
gpuTarget: startupGpuDecision.target,
gpuHandoff: cfg.gpuHandoff,
headlessSmoke: cfg.headlessSmoke, headlessSmoke: cfg.headlessSmoke,
isElectron: true, isElectron: true,
platform: process.platform, platform: process.platform,
localMediaPipeBaseUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe`, localMediaPipeBaseUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe`,
localPoseModelUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe/pose_landmarker_lite.task`,
} }
}) })
@@ -178,9 +348,7 @@ if (!singleInstanceLock) {
ipcMain.handle('planet:set-splash-theme', (_event, rawTheme: unknown) => { ipcMain.handle('planet:set-splash-theme', (_event, rawTheme: unknown) => {
const next = configStore.updateSplashTheme(normalizeSplashTheme(rawTheme, configStore.get().splashTheme)) const next = configStore.updateSplashTheme(normalizeSplashTheme(rawTheme, configStore.get().splashTheme))
if (mainWindow && !mainWindow.isDestroyed()) { refreshApplicationMenu()
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
}
return next.splashTheme return next.splashTheme
}) })
@@ -197,11 +365,48 @@ if (!singleInstanceLock) {
configStore, configStore,
}) })
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore })) refreshApplicationMenu()
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
mainWindow.setMenuBarVisibility(false) mainWindow.setMenuBarVisibility(false)
} }
if (!isHeadlessSmoke) {
let autoUpdateTimer: ReturnType<typeof setTimeout> | null = null
let periodicUpdateTimer: ReturnType<typeof setInterval> | null = null
mainWindow.webContents.on('render-process-gone', () => {
hotUpdater.handleRendererCrash()
})
hotUpdater.startStartupWatchdog()
mainWindow.webContents.once('did-finish-load', () => {
gpuMonitor.start()
autoUpdateTimer = setTimeout(() => {
autoUpdateTimer = null
if (mainWindow && !mainWindow.isDestroyed()) {
void hotUpdater.checkForUpdates({ manual: false })
}
}, 4000)
if (!periodicUpdateTimer) {
periodicUpdateTimer = setInterval(() => {
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.isMinimized()) {
void hotUpdater.checkForUpdates({ manual: false })
}
}, PERIODIC_UPDATE_CHECK_INTERVAL_MS)
}
})
mainWindow.once('closed', () => {
gpuMonitor.stop()
if (autoUpdateTimer) {
clearTimeout(autoUpdateTimer)
autoUpdateTimer = null
}
if (periodicUpdateTimer) {
clearInterval(periodicUpdateTimer)
periodicUpdateTimer = null
}
hotUpdater.stopStartupWatchdog()
})
}
if (isHeadlessSmoke) { if (isHeadlessSmoke) {
const smokeTimeout = setTimeout(() => { const smokeTimeout = setTimeout(() => {
app.exit(1) app.exit(1)
@@ -267,19 +472,18 @@ if (!singleInstanceLock) {
const img = sr?.querySelector('.splash-zju-emblem'); const img = sr?.querySelector('.splash-zju-emblem');
const copy = sr?.querySelector('.splash-presenter-copy')?.textContent || ''; const copy = sr?.querySelector('.splash-presenter-copy')?.textContent || '';
const finishCheck = () => { const finishCheck = () => {
window.planetDesktop.replaySplash('constellation'); const activeTheme = host?.dataset.splashTheme || '';
const firstSwitch = host?.dataset.splashTheme || ''; const hasNoThemeSwitcher = !sr?.querySelector('.splash-switcher');
window.planetDesktop.replaySplash('horizon');
const secondSwitch = host?.dataset.splashTheme || '';
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
resolve({ resolve({
mounted: Boolean(host && sr), mounted: Boolean(host && sr),
hasPresentedBy: copy.includes('PRESENTED BY'), hasPresentedBy: copy.includes('PRESENTED BY'),
hasPresenterZh: copy.includes('临空智能媒体研究院'), hasPresenterZh: copy.includes('临空智能媒体研究院'),
hasPresenterEn: copy.includes('Institute of Intelligent Media'), hasPresenterEn: copy.includes('Intelligent Media Institute'),
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0), emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
emblemWidth: img ? img.naturalWidth : 0, emblemWidth: img ? img.naturalWidth : 0,
switchedThemes: [firstSwitch, secondSwitch], activeTheme,
hasNoThemeSwitcher,
}); });
}; };
if (!img || img.complete) { if (!img || img.complete) {
+93 -24
View File
@@ -1,11 +1,33 @@
import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } from 'electron' import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } from 'electron'
import type { DesktopConfigStore, SplashTheme } from './config' import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config'
import type { GpuRuntimeSummary } from './gpu-monitor'
import type { HotUpdateVersionInfo } from './hot-updater'
import { openServerSettingsDialog, toggleWindowOrientation } from './window' import { openServerSettingsDialog, toggleWindowOrientation } from './window'
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
const targetLabel =
summary.activeTarget === 'low-power'
? '集成核显'
: summary.activeTarget === 'software'
? 'CPU 软渲染'
: summary.activeTarget === 'high-performance' || summary.latestVramSample
? '独立显卡'
: '硬件 GPU'
const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动'
const vramTag = summary.latestVramSample
? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`
: ''
return `当前生效: ${targetLabel} (${modeTag}${vramTag})`
}
export function buildApplicationMenu(options: { export function buildApplicationMenu(options: {
mainWindow: BrowserWindow mainWindow: BrowserWindow
configStore: DesktopConfigStore configStore: DesktopConfigStore
getVersionInfo?: () => HotUpdateVersionInfo
onCheckForUpdates?: () => void
getGpuStatus?: () => GpuRuntimeSummary
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
}): Menu { }): Menu {
const sendAction = (action: string) => { const sendAction = (action: string) => {
if (!options.mainWindow.isDestroyed()) { if (!options.mainWindow.isDestroyed()) {
@@ -19,6 +41,8 @@ export function buildApplicationMenu(options: {
} }
const currentSplashTheme = options.configStore.get().splashTheme const currentSplashTheme = options.configStore.get().splashTheme
const currentGpuMode = options.configStore.get().gpuMode
const gpuSummary = options.getGpuStatus?.()
const selectSplashTheme = (theme: SplashTheme) => { const selectSplashTheme = (theme: SplashTheme) => {
options.configStore.updateSplashTheme(theme) options.configStore.updateSplashTheme(theme)
@@ -72,31 +96,13 @@ export function buildApplicationMenu(options: {
}, },
}, },
{ {
label: '启动画面方案 / Splash Screen', label: '启动画面 / Splash Screen',
submenu: [ submenu: [
{ {
label: '方案 1:星核奇点展开 / Singularity Burst', label: '启用启动画面 / Enable Splash Screen',
type: 'radio', type: 'checkbox',
checked: currentSplashTheme === 'singularity', checked: currentSplashTheme !== 'off',
click: () => selectSplashTheme('singularity'), click: () => selectSplashTheme(currentSplashTheme === 'off' ? 'singularity' : 'off'),
},
{
label: '方案 2:轨道星座校准 / Orbital Astrolabe',
type: 'radio',
checked: currentSplashTheme === 'constellation',
click: () => selectSplashTheme('constellation'),
},
{
label: '方案 3:晨昏日冕破晓 / Eclipse Horizon',
type: 'radio',
checked: currentSplashTheme === 'horizon',
click: () => selectSplashTheme('horizon'),
},
{
label: '关闭启动画面 / Off',
type: 'radio',
checked: currentSplashTheme === 'off',
click: () => selectSplashTheme('off'),
}, },
{ type: 'separator' }, { type: 'separator' },
{ {
@@ -106,6 +112,52 @@ export function buildApplicationMenu(options: {
}, },
], ],
}, },
{
label: '渲染设备 / GPU Mode',
submenu: [
...(gpuSummary
? [
{
label: formatGpuSummaryLabel(gpuSummary),
enabled: false,
},
{ type: 'separator' as const },
]
: []),
{
label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto',
type: 'radio',
checked: currentGpuMode === 'auto',
click: () => {
void options.onSelectGpuMode?.('auto')
},
},
{
label: '独立显卡(高性能) / Discrete GPU',
type: 'radio',
checked: currentGpuMode === 'high-performance',
click: () => {
void options.onSelectGpuMode?.('high-performance')
},
},
{
label: '集成核显(不占独显显存) / Integrated GPU',
type: 'radio',
checked: currentGpuMode === 'low-power',
click: () => {
void options.onSelectGpuMode?.('low-power')
},
},
{
label: '纯 CPU 软渲染 / Software GL',
type: 'radio',
checked: currentGpuMode === 'software',
click: () => {
void options.onSelectGpuMode?.('software')
},
},
],
},
{ type: 'separator' }, { type: 'separator' },
{ {
label: '打开运维控制台 / Open Admin Console', label: '打开运维控制台 / Open Admin Console',
@@ -116,6 +168,23 @@ export function buildApplicationMenu(options: {
click: () => openAdminPath('/docs/manual'), click: () => openAdminPath('/docs/manual'),
}, },
{ type: 'separator' }, { type: 'separator' },
{
label: '检查更新 / Check for Updates...',
click: () => options.onCheckForUpdates?.(),
},
...(options.getVersionInfo
? [
(() => {
const info = options.getVersionInfo!()
const suffix = info.usingHotfix ? ' (热更 / Hotfix)' : ''
return {
label: `当前版本: Shell v${info.shellVersion} · Earth v${info.activeBundleVersion}${suffix}`,
enabled: false,
}
})(),
]
: []),
{ type: 'separator' },
{ role: 'quit', label: '退出 / Quit' }, { role: 'quit', label: '退出 / Quit' },
], ],
}, },
+41
View File
@@ -101,3 +101,44 @@ export function computeLandscapeBounds(params: {
const targetPos = pos ?? centerOnAnchor(anchorBounds, width, height) const targetPos = pos ?? centerOnAnchor(anchorBounds, width, height)
return clampBoundsToWorkArea({ x: targetPos.x, y: targetPos.y, width, height }, workArea) return clampBoundsToWorkArea({ x: targetPos.x, y: targetPos.y, width, height }, workArea)
} }
export function resolveInitialWindowBounds(params: {
saved: {
x?: number
y?: number
width: number
height: number
isMaximized?: boolean
isFullScreen?: boolean
}
launchFullScreen: boolean
headlessSmoke: boolean
displayWorkArea: Rect
displayBounds: Rect
}): {
initialBounds: { x?: number; y?: number; width: number; height: number }
shouldRestoreNormalBoundsOnUnmaximize: boolean
} {
const { saved, launchFullScreen, headlessSmoke, displayWorkArea, displayBounds } = params
if (!headlessSmoke && (launchFullScreen || saved.isFullScreen)) {
return {
initialBounds: { ...displayBounds },
shouldRestoreNormalBoundsOnUnmaximize: Boolean(saved.isMaximized),
}
}
if (!headlessSmoke && saved.isMaximized) {
return {
initialBounds: { ...displayWorkArea },
shouldRestoreNormalBoundsOnUnmaximize: true,
}
}
return {
initialBounds: {
x: saved.x,
y: saved.y,
width: saved.width,
height: saved.height,
},
shouldRestoreNormalBoundsOnUnmaximize: false,
}
}
+27 -1
View File
@@ -156,6 +156,7 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade
export function createEarthProtocolHandler(options: { export function createEarthProtocolHandler(options: {
earthBundleRoot: string earthBundleRoot: string
getEarthOverlayRoot?: () => string | null
getBackendUrl: () => string getBackendUrl: () => string
fetchImpl?: typeof fetch fetchImpl?: typeof fetch
}): (request: Request) => Promise<Response> { }): (request: Request) => Promise<Response> {
@@ -172,6 +173,9 @@ export function createEarthProtocolHandler(options: {
const forwardHeaders = new Headers(request.headers) const forwardHeaders = new Headers(request.headers)
forwardHeaders.delete('host') forwardHeaders.delete('host')
forwardHeaders.delete('content-length') forwardHeaders.delete('content-length')
if (!forwardHeaders.has('accept-encoding')) {
forwardHeaders.set('accept-encoding', 'gzip, deflate, br')
}
const method = request.method.toUpperCase() const method = request.method.toUpperCase()
const hasBody = method !== 'GET' && method !== 'HEAD' const hasBody = method !== 'GET' && method !== 'HEAD'
@@ -180,6 +184,9 @@ export function createEarthProtocolHandler(options: {
method, method,
headers: forwardHeaders, headers: forwardHeaders,
} }
if (request.signal) {
init.signal = request.signal
}
if (hasBody && request.body) { if (hasBody && request.body) {
init.body = request.body init.body = request.body
init.duplex = 'half' init.duplex = 'half'
@@ -188,12 +195,16 @@ export function createEarthProtocolHandler(options: {
const responseHeaders = new Headers(upstream.headers) const responseHeaders = new Headers(upstream.headers)
responseHeaders.delete('content-encoding') responseHeaders.delete('content-encoding')
responseHeaders.delete('content-length') responseHeaders.delete('content-length')
return new Response(upstream.body, { const isNullBodyStatus = upstream.status === 204 || upstream.status === 205 || upstream.status === 304
return new Response(isNullBodyStatus ? null : upstream.body, {
status: upstream.status, status: upstream.status,
statusText: upstream.statusText, statusText: upstream.statusText,
headers: responseHeaders, headers: responseHeaders,
}) })
} catch (error) { } catch (error) {
if (request.signal?.aborted) {
throw error
}
return Response.json( return Response.json(
{ {
detail: 'Backend service unavailable', detail: 'Backend service unavailable',
@@ -209,6 +220,21 @@ export function createEarthProtocolHandler(options: {
if (!staticPath) { if (!staticPath) {
return new Response('Forbidden', { status: 403 }) return new Response('Forbidden', { status: 403 })
} }
const overlayRoot = options.getEarthOverlayRoot?.()
if (overlayRoot) {
const overlayPath = resolveEarthStaticPath(overlayRoot, parsedUrl.pathname)
if (overlayPath) {
try {
if (fs.statSync(overlayPath).isFile()) {
return createStaticFileResponse(overlayPath, request.headers)
}
} catch {
// Fall back to the built-in shell bundle for non-overlaid static assets.
}
}
}
return createStaticFileResponse(staticPath, request.headers) return createStaticFileResponse(staticPath, request.headers)
} }
} }
+33 -5
View File
@@ -1,10 +1,14 @@
import { net, protocol, type Session } from 'electron' import { net, protocol, systemPreferences, type Session } from 'electron'
import { createEarthProtocolHandler } from './protocol-core' import { createEarthProtocolHandler } from './protocol-core'
export const EARTH_ORIGIN = 'planet://earth' export const EARTH_ORIGIN = 'planet://earth'
export const EARTH_ENTRY_URL = `${EARTH_ORIGIN}/earth/index.html` export const EARTH_ENTRY_URL = `${EARTH_ORIGIN}/earth/index.html`
function isEarthUrl(url: string): boolean {
return url === EARTH_ORIGIN || url.startsWith(`${EARTH_ORIGIN}/`)
}
export function registerEarthScheme(): void { export function registerEarthScheme(): void {
protocol.registerSchemesAsPrivileged([ protocol.registerSchemesAsPrivileged([
{ {
@@ -25,11 +29,13 @@ export function installEarthSessionHandlers(
targetSession: Session, targetSession: Session,
options: { options: {
earthBundleRoot: string earthBundleRoot: string
getEarthOverlayRoot?: () => string | null
getBackendUrl: () => string getBackendUrl: () => string
}, },
): void { ): void {
const handler = createEarthProtocolHandler({ const handler = createEarthProtocolHandler({
earthBundleRoot: options.earthBundleRoot, earthBundleRoot: options.earthBundleRoot,
getEarthOverlayRoot: options.getEarthOverlayRoot,
getBackendUrl: options.getBackendUrl, getBackendUrl: options.getBackendUrl,
fetchImpl: (input, init) => net.fetch(input as string, init), fetchImpl: (input, init) => net.fetch(input as string, init),
}) })
@@ -49,13 +55,35 @@ export function installEarthSessionHandlers(
}, },
) )
targetSession.setPermissionRequestHandler((webContents, permission, callback) => { targetSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
const pageUrl = webContents.getURL() if (permission === 'fullscreen') {
const isEarthOrigin = pageUrl.startsWith(EARTH_ORIGIN) callback(isEarthUrl(webContents.getURL()))
if (isEarthOrigin && (permission === 'media' || permission === 'fullscreen')) { return
}
if (permission === 'media' && details.isMainFrame && isEarthUrl(details.requestingUrl)) {
if ('mediaTypes' in details && details.mediaTypes?.includes('audio')) {
callback(false)
return
}
if (process.platform === 'darwin') {
void systemPreferences.askForMediaAccess('camera').then(
(granted) => callback(granted),
() => callback(false),
)
return
}
callback(true) callback(true)
return return
} }
callback(false) callback(false)
}) })
targetSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'fullscreen') return isEarthUrl(webContents?.getURL() || '')
if (permission !== 'media' || details.mediaType === 'audio' || !details.isMainFrame) return false
return (
isEarthUrl(details.requestingUrl || requestingOrigin) &&
(process.platform !== 'darwin' || systemPreferences.getMediaAccessStatus('camera') === 'granted')
)
})
} }
+233
View File
@@ -0,0 +1,233 @@
import fs from 'node:fs'
import path from 'node:path'
import zlib from 'node:zlib'
export interface TarEntryInput {
path: string
data: Uint8Array
}
export interface ExtractTarGzOptions {
maxFiles?: number
maxTotalBytes?: number
}
export interface ExtractTarGzResult {
files: string[]
totalBytes: number
}
const TAR_BLOCK_SIZE = 512
const DEFAULT_MAX_FILES = 2000
const DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024
export function normalizeArchiveEntryPath(rawPath: string): string {
if (!rawPath || rawPath.includes('\0') || rawPath.includes('\\')) {
throw new Error(`Invalid archive entry path: ${JSON.stringify(rawPath)}`)
}
let stripped = rawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
if (!stripped || stripped.startsWith('/')) {
throw new Error(`Unsafe archive entry path: ${JSON.stringify(rawPath)}`)
}
const segments = stripped.split('/')
if (segments.some((seg) => !seg || seg === '.' || seg === '..')) {
throw new Error(`Path traversal not allowed in archive entry: ${JSON.stringify(rawPath)}`)
}
stripped = segments.join('/')
if (/^[A-Za-z]:/.test(stripped)) {
throw new Error(`Drive-prefixed archive entry path not allowed: ${JSON.stringify(rawPath)}`)
}
return stripped
}
function splitUstarPath(entryPath: string): { name: string; prefix: string } {
const bytesLen = Buffer.byteLength(entryPath, 'utf8')
if (bytesLen <= 100) {
return { name: entryPath, prefix: '' }
}
if (bytesLen > 256) {
throw new Error(`Archive entry path exceeds POSIX USTAR 256-byte limit: ${entryPath}`)
}
for (let idx = entryPath.indexOf('/', Math.max(0, entryPath.length - 101)); idx !== -1; idx = entryPath.indexOf('/', idx + 1)) {
const prefix = entryPath.slice(0, idx)
const name = entryPath.slice(idx + 1)
if (name && Buffer.byteLength(name, 'utf8') <= 100 && Buffer.byteLength(prefix, 'utf8') <= 155) {
return { name, prefix }
}
}
throw new Error(`Cannot split archive entry path into USTAR prefix/name: ${entryPath}`)
}
function writeOctalField(buf: Buffer, offset: number, length: number, value: number): void {
const digits = length - 1
const octal = Math.max(0, Math.floor(value)).toString(8)
if (octal.length > digits) {
throw new Error(`Tar numeric value overflows ${digits}-digit octal field: ${value}`)
}
buf.write(`${octal.padStart(digits, '0')}\0`, offset, length, 'ascii')
}
export function createTarGz(entries: TarEntryInput[]): Buffer {
const normalizedEntries = [...entries]
.map((entry) => ({
path: normalizeArchiveEntryPath(entry.path),
data: entry.data instanceof Buffer ? entry.data : Buffer.from(entry.data),
}))
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
const chunks: Buffer[] = []
for (const entry of normalizedEntries) {
const { name, prefix } = splitUstarPath(entry.path)
const header = Buffer.alloc(TAR_BLOCK_SIZE, 0)
header.write(name, 0, 100, 'utf8')
writeOctalField(header, 100, 8, 0o644)
writeOctalField(header, 108, 8, 0)
writeOctalField(header, 116, 8, 0)
writeOctalField(header, 124, 12, entry.data.byteLength)
writeOctalField(header, 136, 12, 0)
header.fill(0x20, 148, 156)
header.write('0', 156, 1, 'ascii')
header.write('ustar\0', 257, 6, 'ascii')
header.write('00', 263, 2, 'ascii')
if (prefix) {
header.write(prefix, 345, 155, 'utf8')
}
let checksum = 0
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
checksum += header[i]
}
const chksumStr = `${checksum.toString(8).padStart(6, '0')}\0 `
header.write(chksumStr, 148, 8, 'ascii')
chunks.push(header)
if (entry.data.byteLength > 0) {
chunks.push(entry.data)
const remainder = entry.data.byteLength % TAR_BLOCK_SIZE
if (remainder !== 0) {
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE - remainder, 0))
}
}
}
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE * 2, 0))
const tarBuffer = Buffer.concat(chunks)
return zlib.gzipSync(tarBuffer, { level: 9 })
}
function readCString(buf: Buffer, start: number, length: number): string {
const slice = buf.subarray(start, start + length)
const nulIdx = slice.indexOf(0)
return slice.subarray(0, nulIdx === -1 ? length : nulIdx).toString('utf8')
}
function parseOctalField(buf: Buffer, start: number, length: number): number {
const raw = readCString(buf, start, length).trim()
if (!raw) return 0
if (!/^[0-7]+$/.test(raw)) {
throw new Error(`Invalid tar octal field: ${JSON.stringify(raw)}`)
}
return Number.parseInt(raw, 8)
}
function isZeroBlock(block: Buffer): boolean {
for (let i = 0; i < block.length; i += 1) {
if (block[i] !== 0) return false
}
return true
}
function verifyHeaderChecksum(header: Buffer): void {
const stored = parseOctalField(header, 148, 8)
let unsignedSum = 0
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
unsignedSum += i >= 148 && i < 156 ? 0x20 : header[i]
}
if (stored !== unsignedSum) {
throw new Error(`Invalid tar header checksum (expected ${unsignedSum}, got ${stored})`)
}
}
export function extractTarGzSafely(
archiveBuffer: Buffer,
destDir: string,
options: ExtractTarGzOptions = {},
): ExtractTarGzResult {
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES
const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES
const tarBuffer = zlib.gunzipSync(archiveBuffer, {
maxOutputLength: maxTotalBytes + 2 * 1024 * 1024,
})
if (tarBuffer.byteLength % TAR_BLOCK_SIZE !== 0) {
throw new Error('Corrupt tar archive: unaligned block length')
}
const resolvedDest = path.resolve(destDir)
fs.mkdirSync(resolvedDest, { recursive: true })
const extractedFiles: string[] = []
let totalBytes = 0
let offset = 0
while (offset + TAR_BLOCK_SIZE <= tarBuffer.byteLength) {
const header = tarBuffer.subarray(offset, offset + TAR_BLOCK_SIZE)
offset += TAR_BLOCK_SIZE
if (isZeroBlock(header)) {
break
}
verifyHeaderChecksum(header)
const rawName = readCString(header, 0, 100)
const rawPrefix = readCString(header, 345, 155)
const fullRawPath = rawPrefix ? `${rawPrefix}/${rawName}` : rawName
const size = parseOctalField(header, 124, 12)
const typeFlagByte = header[156]
const typeFlag = typeFlagByte === 0 ? '0' : String.fromCharCode(typeFlagByte)
if (offset + size > tarBuffer.byteLength) {
throw new Error(`Truncated tar entry data for ${fullRawPath}`)
}
const data = tarBuffer.subarray(offset, offset + size)
const paddedSize = Math.ceil(size / TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE
offset += paddedSize
if (typeFlag === '5') {
const normalizedDir = fullRawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
if (normalizedDir && normalizedDir !== '.') {
const safeDir = normalizeArchiveEntryPath(normalizedDir)
const targetDir = path.resolve(resolvedDest, safeDir)
if (targetDir !== resolvedDest && !targetDir.startsWith(`${resolvedDest}${path.sep}`)) {
throw new Error(`Directory escapes extraction root: ${safeDir}`)
}
fs.mkdirSync(targetDir, { recursive: true })
}
continue
}
if (typeFlag !== '0') {
throw new Error(`Unsupported or unsafe tar entry type ${JSON.stringify(typeFlag)} for ${fullRawPath}`)
}
const safeRelPath = normalizeArchiveEntryPath(fullRawPath)
if (extractedFiles.length + 1 > maxFiles) {
throw new Error(`Archive exceeds maximum file count limit (${maxFiles})`)
}
totalBytes += size
if (totalBytes > maxTotalBytes) {
throw new Error(`Archive exceeds maximum uncompressed byte limit (${maxTotalBytes})`)
}
const targetPath = path.resolve(resolvedDest, safeRelPath)
if (!targetPath.startsWith(`${resolvedDest}${path.sep}`)) {
throw new Error(`File escapes extraction root: ${safeRelPath}`)
}
fs.mkdirSync(path.dirname(targetPath), { recursive: true })
fs.writeFileSync(targetPath, data)
extractedFiles.push(safeRelPath)
}
return {
files: extractedFiles,
totalBytes,
}
}
+63 -8
View File
@@ -8,6 +8,7 @@ import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig }
import { resolveExternalTargetUrl } from './external-links' import { resolveExternalTargetUrl } from './external-links'
import { createWindowShowGate } from './show-gate' import { createWindowShowGate } from './show-gate'
import { import {
clampBoundsToWorkArea,
computeLandscapeBounds, computeLandscapeBounds,
computePortraitBounds, computePortraitBounds,
DEFAULT_LANDSCAPE_HEIGHT, DEFAULT_LANDSCAPE_HEIGHT,
@@ -15,12 +16,20 @@ import {
detectWindowOrientation, detectWindowOrientation,
MIN_WINDOW_HEIGHT, MIN_WINDOW_HEIGHT,
MIN_WINDOW_WIDTH, MIN_WINDOW_WIDTH,
resolveInitialWindowBounds,
type Rect, type Rect,
type WindowOrientation, type WindowOrientation,
} from './orientation' } from './orientation'
import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol' import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol'
const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>() const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>()
const windowStateFlushers = new WeakMap<BrowserWindow, () => void>()
const cancelInitialUnmaximizeRestore = new WeakMap<BrowserWindow, () => void>()
export function flushWindowState(win: BrowserWindow | null): void {
if (!win || win.isDestroyed()) return
windowStateFlushers.get(win)?.()
}
interface OrientationWindowState { interface OrientationWindowState {
lastLandscapeBounds: Rect | null lastLandscapeBounds: Rect | null
@@ -68,6 +77,7 @@ export function toggleWindowOrientation(win: BrowserWindow): WindowOrientation {
win.setFullScreen(false) win.setFullScreen(false)
} }
if (wasMaximized) { if (wasMaximized) {
cancelInitialUnmaximizeRestore.get(win)?.()
win.unmaximize() win.unmaximize()
} }
const portraitBounds = computePortraitBounds({ const portraitBounds = computePortraitBounds({
@@ -176,12 +186,23 @@ export function createMainWindow(options: {
const statePath = path.join(options.userDataDir, 'window-state.json') const statePath = path.join(options.userDataDir, 'window-state.json')
const runtimeConfig: DesktopRuntimeConfig = options.configStore.get() const runtimeConfig: DesktopRuntimeConfig = options.configStore.get()
const saved = loadWindowState(statePath, runtimeConfig.headlessSmoke) const saved = loadWindowState(statePath, runtimeConfig.headlessSmoke)
const targetDisplay =
saved.x !== undefined && saved.y !== undefined
? screen.getDisplayMatching({ x: saved.x, y: saved.y, width: saved.width, height: saved.height })
: screen.getPrimaryDisplay()
const { initialBounds, shouldRestoreNormalBoundsOnUnmaximize } = resolveInitialWindowBounds({
saved,
launchFullScreen: Boolean(runtimeConfig.fullscreen || runtimeConfig.kiosk),
headlessSmoke: runtimeConfig.headlessSmoke,
displayWorkArea: targetDisplay.workArea,
displayBounds: targetDisplay.bounds,
})
const win = new BrowserWindow({ const win = new BrowserWindow({
x: saved.x, x: initialBounds.x,
y: saved.y, y: initialBounds.y,
width: saved.width, width: initialBounds.width,
height: saved.height, height: initialBounds.height,
minWidth: MIN_WINDOW_WIDTH, minWidth: MIN_WINDOW_WIDTH,
minHeight: MIN_WINDOW_HEIGHT, minHeight: MIN_WINDOW_HEIGHT,
show: false, show: false,
@@ -282,7 +303,17 @@ export function createMainWindow(options: {
restoreFullScreenOnLandscape: Boolean(saved.isFullScreen), restoreFullScreenOnLandscape: Boolean(saved.isFullScreen),
}) })
let pendingInitialReveal =
!runtimeConfig.headlessSmoke &&
Boolean(saved.isMaximized || saved.isFullScreen || runtimeConfig.fullscreen || runtimeConfig.kiosk)
let restoreNormalBoundsOnUnmaximize = shouldRestoreNormalBoundsOnUnmaximize
cancelInitialUnmaximizeRestore.set(win, () => {
restoreNormalBoundsOnUnmaximize = false
})
const captureNormalBounds = () => { const captureNormalBounds = () => {
if (pendingInitialReveal) return
if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized() && !win.isFullScreen()) { if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized() && !win.isFullScreen()) {
lastNormalBounds = win.getBounds() lastNormalBounds = win.getBounds()
const orientState = windowOrientationStates.get(win) const orientState = windowOrientationStates.get(win)
@@ -296,13 +327,28 @@ export function createMainWindow(options: {
} }
} }
win.on('resize', captureNormalBounds) const flushCurrentWindowState = () => {
win.on('move', captureNormalBounds)
win.on('close', () => {
captureNormalBounds() captureNormalBounds()
if (!runtimeConfig.headlessSmoke) { if (!runtimeConfig.headlessSmoke) {
saveWindowState(statePath, win, lastNormalBounds) saveWindowState(statePath, win, lastNormalBounds)
} }
}
windowStateFlushers.set(win, flushCurrentWindowState)
win.on('resize', captureNormalBounds)
win.on('move', captureNormalBounds)
win.on('close', flushCurrentWindowState)
win.on('unmaximize', () => {
if (!restoreNormalBoundsOnUnmaximize) return
restoreNormalBoundsOnUnmaximize = false
if (win.isDestroyed() || win.isFullScreen()) return
if (
lastNormalBounds.width < targetDisplay.workArea.width ||
lastNormalBounds.height < targetDisplay.workArea.height
) {
const workArea = screen.getDisplayMatching(win.getBounds()).workArea
win.setBounds(clampBoundsToWorkArea(lastNormalBounds, workArea))
}
}) })
win.on('minimize', () => { win.on('minimize', () => {
@@ -331,6 +377,7 @@ export function createMainWindow(options: {
const revealMainWindow = () => { const revealMainWindow = () => {
if (win.isDestroyed() || runtimeConfig.headlessSmoke) return if (win.isDestroyed() || runtimeConfig.headlessSmoke) return
try {
if (saved.isMaximized) { if (saved.isMaximized) {
win.maximize() win.maximize()
} }
@@ -343,10 +390,16 @@ export function createMainWindow(options: {
if (runtimeConfig.devtools) { if (runtimeConfig.devtools) {
win.webContents.openDevTools({ mode: 'detach' }) win.webContents.openDevTools({ mode: 'detach' })
} }
} finally {
pendingInitialReveal = false
}
} }
const showGate = createWindowShowGate({ const showGate = createWindowShowGate({
requireSplashFirstPaint: !runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off', requireSplashFirstPaint:
!runtimeConfig.headlessSmoke &&
!runtimeConfig.gpuHandoff &&
runtimeConfig.splashTheme !== 'off',
fallbackDelayMs: 1500, fallbackDelayMs: 1500,
onReveal: revealMainWindow, onReveal: revealMainWindow,
}) })
@@ -359,6 +412,8 @@ export function createMainWindow(options: {
ipcMain.on('planet:splash-first-paint', onSplashFirstPaint) ipcMain.on('planet:splash-first-paint', onSplashFirstPaint)
win.once('closed', () => { win.once('closed', () => {
windowStateFlushers.delete(win)
cancelInitialUnmaximizeRestore.delete(win)
showGate.dispose() showGate.dispose()
ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint) ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint)
}) })
+94
View File
@@ -0,0 +1,94 @@
import {
createSustainedLowFpsTracker,
FPS_STARTUP_WARMUP_MS,
} from '../main/gpu-policy'
export function startDesktopLowFpsWatcher(options: {
onLowFps: (report: { avgFps: number; sustainedMs: number }) => void
}): () => void {
const tracker = createSustainedLowFpsTracker()
let disposed = false
let rafId = 0
let warmupTimer: ReturnType<typeof setTimeout> | null = null
let startupReady = document.documentElement?.dataset?.earthStartupReady === '1'
let warmupDone = false
let desktopMinimized = false
const isActive = () =>
!disposed && startupReady && warmupDone && !desktopMinimized && !document.hidden
const stopLoop = () => {
if (rafId) {
cancelAnimationFrame(rafId)
rafId = 0
}
tracker.reset()
}
const tick = (now: number) => {
if (!isActive()) {
rafId = 0
tracker.reset()
return
}
const report = tracker.onFrame(now)
if (report) {
options.onLowFps(report)
}
rafId = requestAnimationFrame(tick)
}
const syncLoop = () => {
if (!isActive()) {
stopLoop()
return
}
if (!rafId) {
rafId = requestAnimationFrame(tick)
}
}
const beginWarmup = () => {
if (disposed || warmupDone || warmupTimer) return
warmupTimer = setTimeout(() => {
warmupTimer = null
warmupDone = true
syncLoop()
}, FPS_STARTUP_WARMUP_MS)
}
const onStartupReady = () => {
startupReady = true
beginWarmup()
}
const onVisibilityChange = () => {
syncLoop()
}
const onDesktopVisibility = (event: Event) => {
const detail = (event as CustomEvent<{ minimized?: boolean }>).detail
desktopMinimized = Boolean(detail?.minimized)
syncLoop()
}
if (startupReady) {
beginWarmup()
} else {
window.addEventListener('earth:startup-ready', onStartupReady, { once: true })
}
document.addEventListener('visibilitychange', onVisibilityChange)
window.addEventListener('planet-desktop:visibility', onDesktopVisibility)
return () => {
disposed = true
stopLoop()
if (warmupTimer) {
clearTimeout(warmupTimer)
warmupTimer = null
}
window.removeEventListener('earth:startup-ready', onStartupReady)
document.removeEventListener('visibilitychange', onVisibilityChange)
window.removeEventListener('planet-desktop:visibility', onDesktopVisibility)
}
}
+40 -1
View File
@@ -1,5 +1,6 @@
import { contextBridge, ipcRenderer } from 'electron' import { contextBridge, ipcRenderer } from 'electron'
import { startDesktopLowFpsWatcher } from './fps-watcher'
import { createDesktopSplashController, type SplashTheme } from './splash' import { createDesktopSplashController, type SplashTheme } from './splash'
interface PreloadRuntimeConfig { interface PreloadRuntimeConfig {
@@ -9,10 +10,14 @@ interface PreloadRuntimeConfig {
wsUrl: string wsUrl: string
forceShowFps: boolean forceShowFps: boolean
splashTheme: SplashTheme splashTheme: SplashTheme
gpuMode?: string
gpuTarget?: string
gpuHandoff?: boolean
headlessSmoke: boolean headlessSmoke: boolean
isElectron: true isElectron: true
platform: string platform: string
localMediaPipeBaseUrl: string localMediaPipeBaseUrl: string
localPoseModelUrl: string
} }
const runtimeConfig = ipcRenderer.sendSync('planet:get-runtime-config') as PreloadRuntimeConfig const runtimeConfig = ipcRenderer.sendSync('planet:get-runtime-config') as PreloadRuntimeConfig
@@ -27,7 +32,7 @@ const splashController = createDesktopSplashController({
}, },
}) })
if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') { if (!runtimeConfig.headlessSmoke && !runtimeConfig.gpuHandoff && runtimeConfig.splashTheme !== 'off') {
let bootStarted = false let bootStarted = false
const tryStartBoot = () => { const tryStartBoot = () => {
if (bootStarted || !document.documentElement) return false if (bootStarted || !document.documentElement) return false
@@ -54,6 +59,19 @@ if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
} }
} }
if (
!runtimeConfig.headlessSmoke &&
runtimeConfig.platform === 'win32' &&
runtimeConfig.gpuMode === 'auto' &&
(runtimeConfig.gpuTarget === 'default' || runtimeConfig.gpuTarget === 'high-performance')
) {
startDesktopLowFpsWatcher({
onLowFps: (report) => {
ipcRenderer.send('planet:low-fps-report', report)
},
})
}
contextBridge.exposeInMainWorld('__PLANET_RUNTIME_CONFIG__', runtimeConfig) contextBridge.exposeInMainWorld('__PLANET_RUNTIME_CONFIG__', runtimeConfig)
contextBridge.exposeInMainWorld('planetDesktop', { contextBridge.exposeInMainWorld('planetDesktop', {
@@ -75,6 +93,8 @@ contextBridge.exposeInMainWorld('planetDesktop', {
replaySplash: (theme?: SplashTheme) => { replaySplash: (theme?: SplashTheme) => {
splashController.replay(theme) splashController.replay(theme)
}, },
checkForUpdates: () => ipcRenderer.invoke('planet:check-for-updates') as Promise<void>,
getVersionInfo: () => ipcRenderer.invoke('planet:get-version-info'),
}) })
ipcRenderer.on('planet:visibility', (_event, detail) => { ipcRenderer.on('planet:visibility', (_event, detail) => {
@@ -93,6 +113,25 @@ ipcRenderer.on('planet:replay-splash', (_event, detail?: { theme?: SplashTheme }
splashController.replay(detail?.theme) splashController.replay(detail?.theme)
}) })
ipcRenderer.on('planet:gpu-process-gone', (_event, detail) => {
window.dispatchEvent(new CustomEvent('planet-desktop:gpu-process-gone', { detail }))
})
ipcRenderer.on('planet:update-status', (_event, detail) => {
window.dispatchEvent(new CustomEvent('earth:status', { detail }))
})
if (document.documentElement?.dataset?.earthStartupReady === '1') {
ipcRenderer.send('planet:earth-startup-ready')
}
window.addEventListener(
'earth:startup-ready',
() => {
ipcRenderer.send('planet:earth-startup-ready')
},
{ once: true },
)
window.addEventListener( window.addEventListener(
'pointerdown', 'pointerdown',
() => { () => {
+195 -340
View File
@@ -1,7 +1,7 @@
import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from './earth-landmask' import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from './earth-landmask'
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off' export type SplashTheme = 'singularity' | 'off'
export type ActiveSplashTheme = Exclude<SplashTheme, 'off'> export type ActiveSplashTheme = 'singularity'
interface GlobePoint { interface GlobePoint {
lat: number lat: number
@@ -32,10 +32,70 @@ interface ArcDef {
const SPLASH_HOST_ID = 'planet-desktop-splash-host' const SPLASH_HOST_ID = 'planet-desktop-splash-host'
const DEFAULT_HOST_THEME: ActiveSplashTheme = 'singularity' const DEFAULT_HOST_THEME: ActiveSplashTheme = 'singularity'
const REPLAY_DURATION_MS = 2600 const REPLAY_DURATION_MS = 3200
const MIN_BOOT_SHOWCASE_MS = 1800 const MIN_BOOT_SHOWCASE_MS = 2200
const MAX_BOOT_CAP_MS = 20000 const MAX_BOOT_CAP_MS = 20000
export interface SplashCanvasSize {
dpr: number
width: number
height: number
}
export function computeSplashCanvasSize(
width: number,
height: number,
devicePixelRatio: number,
maxPixels = 1920 * 1080,
maxDpr = 1.5,
): SplashCanvasSize {
const safeW = Math.max(1, Number(width) || 1)
const safeH = Math.max(1, Number(height) || 1)
const rawDpr = Math.min(Math.max(Number(devicePixelRatio) || 1, 0.5), maxDpr)
const totalPixels = safeW * safeH * rawDpr * rawDpr
const dpr =
totalPixels > maxPixels
? Math.min(rawDpr, Math.max(0.75, Math.floor(Math.sqrt(maxPixels / (safeW * safeH)) * 100) / 100))
: rawDpr
return {
dpr,
width: Math.max(1, Math.round(safeW * dpr)),
height: Math.max(1, Math.round(safeH * dpr)),
}
}
export interface SplashMorphPhases {
dawnIntensity: number
coreReveal: number
orbitReveal: number
arcReveal: number
burst: number
fade: number
}
function clamp01(value: number): number {
return Math.max(0, Math.min(1, value))
}
function smoothstep(edge0: number, edge1: number, x: number): number {
if (edge1 <= edge0) return x >= edge1 ? 1 : 0
const t = clamp01((x - edge0) / (edge1 - edge0))
return t * t * (3 - 2 * t)
}
export function computeSplashMorphPhases(progress: number, exitRatio: number): SplashMorphPhases {
const p = clamp01(Number.isFinite(progress) ? progress : 0)
const e = clamp01(Number.isFinite(exitRatio) ? exitRatio : 0)
return {
dawnIntensity: (1 - smoothstep(0.36, 0.78, p)) * (1 - smoothstep(0, 0.35, e)),
coreReveal: smoothstep(0.18, 0.68, p),
orbitReveal: smoothstep(0.38, 0.82, p),
arcReveal: smoothstep(0.56, 0.9, p),
burst: e > 0 ? Math.pow(e, 1.38) : 0,
fade: 1 - Math.pow(e, 2.2),
}
}
export interface BootSplashStateInput { export interface BootSplashStateInput {
elapsedMs: number elapsedMs: number
minDurationMs: number minDurationMs: number
@@ -84,7 +144,7 @@ const ARC_DEFINITIONS: readonly ArcDef[] = [
] ]
function isActiveTheme(value: string | undefined | null): value is ActiveSplashTheme { function isActiveTheme(value: string | undefined | null): value is ActiveSplashTheme {
return value === 'singularity' || value === 'constellation' || value === 'horizon' return value === 'singularity'
} }
function getLocaleIsEn(): boolean { function getLocaleIsEn(): boolean {
@@ -205,6 +265,8 @@ const SPLASH_CSS = `
all: initial; all: initial;
position: fixed; position: fixed;
inset: 0; inset: 0;
width: 100%;
height: 100%;
z-index: 2147483000; z-index: 2147483000;
display: block; display: block;
pointer-events: auto; pointer-events: auto;
@@ -225,14 +287,6 @@ const SPLASH_CSS = `
transition: opacity 380ms cubic-bezier(0.22, 1, 0.36, 1); transition: opacity 380ms cubic-bezier(0.22, 1, 0.36, 1);
} }
.splash-root[data-theme="horizon"] {
background: radial-gradient(circle at 50% 41%, #091322 0%, #030710 56%, #010308 100%);
}
.splash-root[data-theme="constellation"] {
background: radial-gradient(circle at 50% 41%, #06182c 0%, #030916 55%, #02040a 100%);
}
.splash-root.is-exiting { .splash-root.is-exiting {
pointer-events: none; pointer-events: none;
} }
@@ -309,48 +363,24 @@ const SPLASH_CSS = `
flex-wrap: wrap; flex-wrap: wrap;
} }
.splash-switcher {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px;
border: 1px solid rgba(173, 210, 255, 0.16);
background: rgba(8, 19, 36, 0.62);
backdrop-filter: blur(10px);
}
.splash-pill,
.splash-skip { .splash-skip {
appearance: none; appearance: none;
border: 1px solid transparent; border: 1px solid rgba(173, 210, 255, 0.16);
background: transparent; background: rgba(8, 19, 36, 0.55);
color: rgba(190, 216, 245, 0.72); backdrop-filter: blur(10px);
color: rgba(190, 216, 245, 0.78);
font-family: inherit; font-family: inherit;
font-size: 11px; font-size: 11px;
font-weight: 500; font-weight: 500;
letter-spacing: 0.04em; letter-spacing: 0.04em;
padding: 4px 9px; padding: 5px 10px;
cursor: pointer; cursor: pointer;
transition: color 160ms ease, background-color 160ms ease, border-color 160ms ease; transition: color 160ms ease, background-color 160ms ease, border-color 160ms ease;
} }
.splash-pill:hover,
.splash-skip:hover { .splash-skip:hover {
color: #f3f9ff; color: #f3f9ff;
background: rgba(132, 192, 255, 0.12); background: rgba(132, 192, 255, 0.14);
}
.splash-pill.is-active {
color: #f5faff;
background: rgba(82, 168, 255, 0.24);
border-color: rgba(136, 206, 255, 0.42);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.16);
}
.splash-skip {
border-color: rgba(173, 210, 255, 0.16);
background: rgba(8, 19, 36, 0.55);
padding: 5px 10px;
} }
.splash-footer { .splash-footer {
@@ -438,21 +468,6 @@ const SPLASH_CSS = `
border: 1px solid rgba(173, 214, 255, 0.12); border: 1px solid rgba(173, 214, 255, 0.12);
} }
.splash-root[data-theme="horizon"] .splash-progress-track {
height: 2px;
border: none;
background: rgba(210, 232, 255, 0.14);
}
.splash-root[data-theme="constellation"] .splash-progress-track {
height: 6px;
background: repeating-linear-gradient(
90deg,
rgba(135, 188, 242, 0.18) 0 12px,
rgba(6, 15, 30, 0.7) 12px 16px
);
}
.splash-progress-fill { .splash-progress-fill {
position: relative; position: relative;
height: 100%; height: 100%;
@@ -461,20 +476,6 @@ const SPLASH_CSS = `
box-shadow: 0 0 14px rgba(105, 198, 255, 0.55); box-shadow: 0 0 14px rgba(105, 198, 255, 0.55);
} }
.splash-root[data-theme="constellation"] .splash-progress-fill {
background: repeating-linear-gradient(
90deg,
#77cfff 0 12px,
transparent 12px 16px
);
box-shadow: 0 0 12px rgba(105, 206, 255, 0.45);
}
.splash-root[data-theme="horizon"] .splash-progress-fill {
background: linear-gradient(90deg, rgba(84, 165, 255, 0.55) 0%, #c4e4ff 70%, #ffffff 100%);
box-shadow: 0 0 16px rgba(196, 228, 255, 0.72);
}
.splash-progress-fill::after { .splash-progress-fill::after {
content: ""; content: "";
position: absolute; position: absolute;
@@ -594,11 +595,11 @@ export function createDesktopSplashController(options: {
let progressFillEl: HTMLDivElement | null = null let progressFillEl: HTMLDivElement | null = null
let stageEl: HTMLSpanElement | null = null let stageEl: HTMLSpanElement | null = null
let percentEl: HTMLSpanElement | null = null let percentEl: HTMLSpanElement | null = null
let switcherButtons: HTMLButtonElement[] = []
let rafId = 0 let rafId = 0
let statusObserver: MutationObserver | null = null let statusObserver: MutationObserver | null = null
let keydownHandler: ((event: KeyboardEvent) => void) | null = null let keydownHandler: ((event: KeyboardEvent) => void) | null = null
let resizeHandler: (() => void) | null = null
let startupProgressHandler: ((event: Event) => void) | null = null let startupProgressHandler: ((event: Event) => void) | null = null
let startupReadyHandler: (() => void) | null = null let startupReadyHandler: (() => void) | null = null
let sessionMode: 'boot' | 'replay' = 'boot' let sessionMode: 'boot' | 'replay' = 'boot'
@@ -657,6 +658,10 @@ export function createDesktopSplashController(options: {
window.removeEventListener('keydown', keydownHandler, true) window.removeEventListener('keydown', keydownHandler, true)
keydownHandler = null keydownHandler = null
} }
if (resizeHandler) {
window.removeEventListener('resize', resizeHandler)
resizeHandler = null
}
if (hostEl && hostEl.parentNode) { if (hostEl && hostEl.parentNode) {
hostEl.parentNode.removeChild(hostEl) hostEl.parentNode.removeChild(hostEl)
} }
@@ -667,7 +672,6 @@ export function createDesktopSplashController(options: {
progressFillEl = null progressFillEl = null
stageEl = null stageEl = null
percentEl = null percentEl = null
switcherButtons = []
exitStartTime = 0 exitStartTime = 0
} }
@@ -685,11 +689,6 @@ export function createDesktopSplashController(options: {
if (hostEl) { if (hostEl) {
hostEl.dataset.splashTheme = nextTheme hostEl.dataset.splashTheme = nextTheme
} }
for (const btn of switcherButtons) {
const match = btn.dataset.splashSwitch === nextTheme
btn.classList.toggle('is-active', match)
btn.setAttribute('aria-pressed', String(match))
}
} }
const notifyFirstPaintOnce = () => { const notifyFirstPaintOnce = () => {
@@ -746,7 +745,7 @@ export function createDesktopSplashController(options: {
hostEl = document.createElement('div') hostEl = document.createElement('div')
hostEl.id = SPLASH_HOST_ID hostEl.id = SPLASH_HOST_ID
hostEl.style.cssText = 'position:fixed;inset:0;z-index:2147483647;pointer-events:auto;' hostEl.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;z-index:2147483647;pointer-events:auto;'
hostEl.dataset.splashTheme = activeTheme hostEl.dataset.splashTheme = activeTheme
shadow = hostEl.attachShadow({ mode: 'open' }) shadow = hostEl.attachShadow({ mode: 'open' })
@@ -764,11 +763,6 @@ export function createDesktopSplashController(options: {
<span>PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL</span> <span>PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL</span>
</div> </div>
<div class="splash-controls"> <div class="splash-controls">
<div class="splash-switcher" role="group" aria-label="启动画面方案">
<button type="button" class="splash-pill" data-splash-switch="singularity">01 星核</button>
<button type="button" class="splash-pill" data-splash-switch="constellation">02 星轨</button>
<button type="button" class="splash-pill" data-splash-switch="horizon">03 破晓</button>
</div>
<button type="button" class="splash-skip" data-splash-skip title="跳过启动动画 (Esc)">ESC 跳过</button> <button type="button" class="splash-skip" data-splash-skip title="跳过启动动画 (Esc)">ESC 跳过</button>
</div> </div>
</header> </header>
@@ -792,7 +786,7 @@ export function createDesktopSplashController(options: {
<div class="splash-presenter-copy"> <div class="splash-presenter-copy">
<span class="splash-presenter-kicker">PRESENTED BY</span> <span class="splash-presenter-kicker">PRESENTED BY</span>
<span class="splash-presenter-zh">临空智能媒体研究院</span> <span class="splash-presenter-zh">临空智能媒体研究院</span>
<span class="splash-presenter-en">Institute of Intelligent Media</span> <span class="splash-presenter-en">Intelligent Media Institute</span>
</div> </div>
</div> </div>
</footer> </footer>
@@ -807,23 +801,6 @@ export function createDesktopSplashController(options: {
progressFillEl = root.querySelector('[data-splash-fill]') progressFillEl = root.querySelector('[data-splash-fill]')
stageEl = root.querySelector('[data-splash-stage]') stageEl = root.querySelector('[data-splash-stage]')
percentEl = root.querySelector('[data-splash-percent]') percentEl = root.querySelector('[data-splash-percent]')
switcherButtons = Array.from(root.querySelectorAll('[data-splash-switch]'))
for (const btn of switcherButtons) {
btn.addEventListener('click', (event) => {
event.stopPropagation()
const picked = btn.dataset.splashSwitch
if (isActiveTheme(picked)) {
preferredTheme = picked
options.onSelectTheme(picked)
if (sessionMode === 'boot' && !startupReady) {
setActiveThemeVisual(picked)
} else {
startSplashSession(picked, 'replay')
}
}
})
}
const skipBtn = root.querySelector('[data-splash-skip]') const skipBtn = root.querySelector('[data-splash-skip]')
skipBtn?.addEventListener('click', (event) => { skipBtn?.addEventListener('click', (event) => {
@@ -840,6 +817,18 @@ export function createDesktopSplashController(options: {
window.addEventListener('keydown', keydownHandler, true) window.addEventListener('keydown', keydownHandler, true)
} }
if (!resizeHandler) {
resizeHandler = () => {
if (!canvasEl || !rootEl) return
const now = performance.now()
const exitDuration = prefersReducedMotion() ? 300 : 940
const clampedProgress = Math.max(0, Math.min(1, displayProgress))
const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0
renderSceneFrame(now, clampedProgress, exitRatio)
}
window.addEventListener('resize', resizeHandler)
}
setActiveThemeVisual(activeTheme) setActiveThemeVisual(activeTheme)
} }
@@ -932,7 +921,7 @@ export function createDesktopSplashController(options: {
cx: number, cx: number,
cy: number, cy: number,
) => { ) => {
const warp = exitRatio > 0 && activeTheme === 'singularity' ? exitRatio * exitRatio : 0 const warp = exitRatio > 0 ? exitRatio * exitRatio : 0
for (const star of stars) { for (const star of stars) {
const sx = star.x * w const sx = star.x * w
const sy = star.y * h const sy = star.y * h
@@ -960,7 +949,7 @@ export function createDesktopSplashController(options: {
} }
} }
const drawSingularityScene = ( const drawDawnToSingularityScene = (
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
w: number, w: number,
h: number, h: number,
@@ -971,57 +960,115 @@ export function createDesktopSplashController(options: {
progress: number, progress: number,
exitRatio: number, exitRatio: number,
) => { ) => {
const burst = exitRatio > 0 ? Math.pow(exitRatio, 1.4) : 0 const { dawnIntensity, coreReveal, orbitReveal, arcReveal, burst, fade } =
const fade = 1 - Math.pow(exitRatio, 2.2) computeSplashMorphPhases(progress, exitRatio)
// Deep holographic ambient halo const perspD = 3.6
const perspK = 3.25
const tiltX = -0.25
const rollZ = -0.11
const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 2.1)
const eclipseR = radius * 0.955
const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45
// Act 1 -> Act 2: Eclipse atmospheric corona cross-dissolves into deep holographic halo
if (dawnIntensity > 0.01) {
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
const coronaAlpha = dawnIntensity * fade
const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 1.4))
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.9 * coronaAlpha).toFixed(3)})`)
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.5 * coronaAlpha).toFixed(3)})`)
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.15 * coronaAlpha).toFixed(3)})`)
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
ctx.fillStyle = corona
ctx.beginPath()
ctx.arc(cx, cy, eclipseR * (1.95 + burst * 1.4), 0, Math.PI * 2)
ctx.fill()
}
if (coreReveal > 0.01) {
const haloAlpha = coreReveal * fade
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4)) const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * fade).toFixed(3)})`) glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`)
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * fade).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 * 1.4), 0, Math.PI * 2)
ctx.fill() ctx.fill()
}
// Tilted orbital rings accelerating cleanly toward phase lock // Act 1 silhouette & luminous dawn limb hugging the sphere edge cleanly without shadowBlur
const yaw = (108 * Math.PI) / 180 + elapsed * (0.42 + progress * 0.48 + burst * 2.2) if (dawnIntensity > 0.01) {
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
const discAlpha = dawnIntensity * fade
const discGrad = ctx.createRadialGradient(lx, ly, eclipseR * 0.55, cx, cy, eclipseR)
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * discAlpha).toFixed(3)})`)
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * discAlpha).toFixed(3)})`)
ctx.fillStyle = discGrad
ctx.beginPath()
ctx.arc(cx, cy, eclipseR * 0.99, 0, Math.PI * 2)
ctx.fill()
const arcStart = coronaOffsetAngle - 0.88
const arcEnd = coronaOffsetAngle + 0.88
ctx.strokeStyle = `rgba(148, 214, 255, ${(0.24 * discAlpha).toFixed(3)})`
ctx.lineWidth = 7
ctx.beginPath()
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
ctx.stroke()
ctx.strokeStyle = `rgba(226, 246, 255, ${(0.92 * discAlpha).toFixed(3)})`
ctx.lineWidth = 2.3
ctx.beginPath()
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
ctx.stroke()
}
// Act 2: Three tilted orbital rings drawing into full orbits, expanding on Act 3 burst
if (orbitReveal > 0.01) {
const ringConfigs = [ 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 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' }, { rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' }, { rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
] ]
for (let i = 0; i < ringConfigs.length; i += 1) { for (let i = 0; i < ringConfigs.length; i += 1) {
const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8)
if (ringReveal <= 0.005) continue
const ring = ringConfigs[i] const ring = ringConfigs[i]
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 * fade).toFixed(3)})` ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * fade).toFixed(3)})`
ctx.lineWidth = 1.15 ctx.lineWidth = 1.15
ctx.beginPath() ctx.beginPath()
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)
} else {
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, a - ringReveal * Math.PI * 2, a)
}
ctx.stroke() ctx.stroke()
// Moving orbital shard beacon along ellipse
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
const sx = Math.cos(a) * ring.rx const 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 * fade).toFixed(3)})` ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * fade).toFixed(3)})`
ctx.beginPath() ctx.beginPath()
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2) ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
ctx.fill() ctx.fill()
ctx.restore() ctx.restore()
} }
}
// 3D Holographic Earth point cloud + burst explosion streaks // Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> radial scatter
const tiltX = -0.26 const oceanReveal = clamp01((coreReveal - 0.25) / 0.75)
const rollZ = -0.14
const perspD = 3.1
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 (burst === 0 && p.nz < -0.22) continue
// On explosion, scatter outward radially & toward camera
const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8) const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8)
const jitterX = Math.cos(pt.shardAngle) * burst * 0.28 const jitterX = Math.cos(pt.shardAngle) * burst * 0.28
const jitterY = Math.sin(pt.shardAngle) * burst * 0.28 const jitterY = Math.sin(pt.shardAngle) * burst * 0.28
@@ -1030,7 +1077,7 @@ export function createDesktopSplashController(options: {
const pz = p.nz + burst * pt.shardSpeed * 1.1 const pz = p.nz + burst * pt.shardSpeed * 1.1
const depth = Math.max(0.25, perspD - pz) const depth = Math.max(0.25, perspD - pz)
const screenScale = (radius * (perspD - 0.6)) / depth const screenScale = (radius * perspK) / depth
const sx = cx + px * screenScale const sx = cx + px * screenScale
const sy = cy + py * 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
@@ -1038,23 +1085,29 @@ export function createDesktopSplashController(options: {
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)
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.36 : 1 const polarFade = Math.abs(pt.lat) > 1.14 ? 0.36 : 1
let color = '84, 146, 232' let color = '84, 146, 232'
let baseAlpha = 0.28 let pointGain = 0
let dotR = 1.1 let dotR = 1.1
if (pt.kind === 2) { if (pt.kind === 2) {
color = '196, 240, 255' color = '196, 240, 255'
baseAlpha = 0.94 const dawnShimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
dotR = 1.75 const dawnWeight = p.nz > 0.06 ? dawnIntensity * 0.58 * p.nz * dawnShimmer : 0
const coreWeight = coreReveal * 0.94 * depthFade
pointGain = Math.max(dawnWeight, coreWeight)
dotR = 1.45 + coreReveal * 0.3
} else if (pt.kind === 1) { } else if (pt.kind === 1) {
color = '106, 188, 255' color = '106, 188, 255'
baseAlpha = 0.56 pointGain = coreReveal * 0.56 * depthFade
dotR = 1.3 dotR = 1.3
} else {
pointGain = oceanReveal * 0.28 * depthFade
} }
const alpha = baseAlpha * depthFade * polarFade * fade
const alpha = pointGain * polarFade * fade
if (alpha <= 0.015) continue if (alpha <= 0.015) continue
if (burst > 0.03) { if (burst > 0.03) {
const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst) const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst)
const prevScale = (radius * (perspD - 0.6)) / Math.max(0.3, perspD - p.nz) const prevScale = (radius * perspK) / Math.max(0.3, perspD - p.nz)
const ox = cx + p.nx * prevBoost * prevScale const ox = cx + p.nx * prevBoost * prevScale
const oy = cy + p.ny * prevBoost * prevScale const oy = cy + p.ny * prevBoost * prevScale
ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})` ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})`
@@ -1071,8 +1124,9 @@ export function createDesktopSplashController(options: {
} }
} }
// Great-circle telemetry arcs across front hemisphere // Intercontinental telemetry arcs across front hemisphere
if (burst < 0.55) { if (arcReveal > 0.01 && burst < 0.55) {
const arcAlpha = arcReveal * fade * Math.max(0, 1 - burst * 1.6)
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)
@@ -1088,7 +1142,7 @@ export function createDesktopSplashController(options: {
const cpx = cx + mx * radius * lift const cpx = cx + mx * radius * lift
const cpy = cy + my * radius * lift const cpy = cy + my * radius * lift
ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * fade).toFixed(3)})` ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * arcAlpha).toFixed(3)})`
ctx.lineWidth = 1.25 ctx.lineWidth = 1.25
ctx.beginPath() ctx.beginPath()
ctx.moveTo(x1, y1) ctx.moveTo(x1, y1)
@@ -1099,14 +1153,14 @@ export function createDesktopSplashController(options: {
const inv = 1 - u const inv = 1 - u
const px = inv * inv * x1 + 2 * inv * u * cpx + u * u * x2 const px = inv * inv * x1 + 2 * inv * u * cpx + u * u * x2
const py = inv * inv * y1 + 2 * inv * u * cpy + u * u * y2 const py = inv * inv * y1 + 2 * inv * u * cpy + u * u * y2
ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * fade).toFixed(3)})` ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * arcAlpha).toFixed(3)})`
ctx.beginPath() ctx.beginPath()
ctx.arc(px, py, 2.2, 0, Math.PI * 2) ctx.arc(px, py, 2.2, 0, Math.PI * 2)
ctx.fill() ctx.fill()
} }
} }
// Shockwave ring on climax burst // Act 3: Climax shockwave ring on scatter burst
if (burst > 0.005) { if (burst > 0.005) {
const shockR = radius * (0.88 + exitRatio * 5.2) const shockR = radius * (0.88 + exitRatio * 5.2)
ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})` ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})`
@@ -1117,203 +1171,16 @@ export function createDesktopSplashController(options: {
} }
} }
const drawConstellationScene = (
ctx: CanvasRenderingContext2D,
_w: number,
_h: number,
cx: number,
cy: number,
radius: number,
elapsed: number,
progress: number,
exitRatio: number,
) => {
const irisScale = 1 + Math.pow(exitRatio, 1.55) * 2.1
const fade = 1 - Math.pow(exitRatio, 1.8)
const yaw = (108 * Math.PI) / 180 + elapsed * 0.34
// Outer calibrated compass reticle rings
ctx.save()
ctx.translate(cx, cy)
ctx.scale(irisScale, irisScale)
const outerR = radius * 1.42
const midR = radius * 1.2
ctx.strokeStyle = `rgba(130, 198, 255, ${(0.22 * fade).toFixed(3)})`
ctx.lineWidth = 1
ctx.beginPath()
ctx.arc(0, 0, outerR, 0, Math.PI * 2)
ctx.stroke()
ctx.strokeStyle = `rgba(154, 214, 255, ${(0.36 * fade).toFixed(3)})`
ctx.setLineDash([4, 6])
ctx.beginPath()
ctx.arc(0, 0, midR, -elapsed * 0.25, -elapsed * 0.25 + Math.PI * 1.65)
ctx.stroke()
ctx.setLineDash([])
// Progress calibration arc
const sweepAngle = Math.max(0.08, progress * Math.PI * 2)
ctx.strokeStyle = `rgba(126, 222, 255, ${(0.88 * fade).toFixed(3)})`
ctx.lineWidth = 2.1
ctx.beginPath()
ctx.arc(0, 0, radius * 1.29, -Math.PI / 2, -Math.PI / 2 + sweepAngle)
ctx.stroke()
// 72 degree graduation ticks
for (let deg = 0; deg < 360; deg += 5) {
const rad = (deg * Math.PI) / 180 + elapsed * 0.05
const major = deg % 30 === 0
const len = major ? 9 : 4
ctx.strokeStyle = `rgba(170, 216, 255, ${((major ? 0.55 : 0.22) * fade).toFixed(3)})`
ctx.lineWidth = major ? 1.3 : 0.85
ctx.beginPath()
ctx.moveTo(Math.cos(rad) * (outerR - len), Math.sin(rad) * (outerR - len))
ctx.lineTo(Math.cos(rad) * outerR, Math.sin(rad) * outerR)
ctx.stroke()
}
// Precision meridian & equator CAD wireframe + continental points
ctx.strokeStyle = `rgba(104, 178, 245, ${(0.22 * fade).toFixed(3)})`
ctx.lineWidth = 0.9
ctx.beginPath()
ctx.arc(0, 0, radius, 0, Math.PI * 2)
ctx.stroke()
for (const tilt of [-0.55, 0, 0.55]) {
ctx.beginPath()
ctx.ellipse(0, 0, radius * Math.abs(Math.cos(tilt)), radius, 0, 0, Math.PI * 2)
ctx.stroke()
}
for (const pt of globePoints) {
if (pt.kind === 0) continue
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, 0)
if (p.nz < 0) continue
const sx = p.nx * radius
const sy = p.ny * radius
const isCoast = pt.kind === 2
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
ctx.fillStyle = isCoast
? `rgba(216, 246, 255, ${(0.92 * polarFade * fade).toFixed(3)})`
: `rgba(106, 186, 255, ${(0.42 * polarFade * fade).toFixed(3)})`
ctx.fillRect(sx - (isCoast ? 1 : 0.7), sy - (isCoast ? 1 : 0.7), isCoast ? 2 : 1.4, isCoast ? 2 : 1.4)
}
// Hangzhou target crosshair lock when front-facing
const hz = projectSpherePoint((30.27 * Math.PI) / 180, (120.15 * Math.PI) / 180, yaw, -0.24, 0)
if (hz.nz > 0.1) {
const hx = hz.nx * radius
const hy = hz.ny * radius
ctx.strokeStyle = `rgba(255, 255, 255, ${(0.88 * fade).toFixed(3)})`
ctx.lineWidth = 1.2
ctx.strokeRect(hx - 6, hy - 6, 12, 12)
ctx.beginPath()
ctx.moveTo(hx - 12, hy)
ctx.lineTo(hx + 12, hy)
ctx.moveTo(hx, hy - 12)
ctx.lineTo(hx, hy + 12)
ctx.stroke()
}
// Keplerian satellites
for (let i = 0; i < 3; i += 1) {
ctx.save()
ctx.rotate(-0.5 + i * 0.55)
const rx = radius * 1.48
const ry = radius * 0.42
ctx.strokeStyle = `rgba(136, 206, 255, ${(0.24 * fade).toFixed(3)})`
ctx.lineWidth = 0.9
ctx.beginPath()
ctx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2)
ctx.stroke()
const theta = elapsed * (0.9 + i * 0.35) + i * 1.9
const sx = Math.cos(theta) * rx
const sy = Math.sin(theta) * ry
ctx.fillStyle = `rgba(232, 249, 255, ${(0.95 * fade).toFixed(3)})`
ctx.beginPath()
ctx.arc(sx, sy, 3, 0, Math.PI * 2)
ctx.fill()
ctx.restore()
}
ctx.restore()
}
const drawHorizonScene = (
ctx: CanvasRenderingContext2D,
_w: number,
_h: number,
cx: number,
cy: number,
radius: number,
elapsed: number,
progress: number,
exitRatio: number,
) => {
const fade = 1 - Math.pow(exitRatio, 2.0)
const bloom = 1 + exitRatio * 0.55
const yaw = (108 * Math.PI) / 180 + elapsed * 0.24
const r = radius * 1.06 * bloom
// Volumetric atmospheric crescent corona behind dark planet
const coronaOffsetAngle = -Math.PI * 0.65 + progress * Math.PI * 0.38
const lx = cx + Math.cos(coronaOffsetAngle) * r * 0.72
const ly = cy + Math.sin(coronaOffsetAngle) * r * 0.72
const corona = ctx.createRadialGradient(lx, ly, r * 0.15, cx, cy, r * (1.85 + exitRatio * 1.4))
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.92 * fade).toFixed(3)})`)
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.52 * fade).toFixed(3)})`)
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.16 * fade).toFixed(3)})`)
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
ctx.fillStyle = corona
ctx.beginPath()
ctx.arc(cx, cy, r * (1.9 + exitRatio * 1.4), 0, Math.PI * 2)
ctx.fill()
// Planetary shadow disc eclipsing the sun
const discGrad = ctx.createRadialGradient(lx, ly, r * 0.55, cx, cy, r)
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * fade).toFixed(3)})`)
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * fade).toFixed(3)})`)
ctx.fillStyle = discGrad
ctx.beginPath()
ctx.arc(cx, cy, r * 0.99, 0, Math.PI * 2)
ctx.fill()
// Crisp luminous terminator limb sweep following progress
ctx.save()
ctx.strokeStyle = `rgba(222, 245, 255, ${(0.92 * fade).toFixed(3)})`
ctx.lineWidth = 2.4
ctx.shadowColor = 'rgba(148, 214, 255, 0.95)'
ctx.shadowBlur = 18
ctx.beginPath()
ctx.arc(cx, cy, r, coronaOffsetAngle - 0.85, coronaOffsetAngle + 0.85)
ctx.stroke()
ctx.restore()
// Subtle night-side coastline lights glimmering across the shadowed face
for (const pt of globePoints) {
if (pt.kind !== 2) continue
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, -0.08)
if (p.nz < 0.08) continue
const shimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
const alpha = 0.56 * p.nz * shimmer * polarFade * fade
if (alpha <= 0.02) continue
ctx.fillStyle = `rgba(176, 224, 255, ${alpha.toFixed(3)})`
ctx.beginPath()
ctx.arc(cx + p.nx * r * 0.96, cy + p.ny * r * 0.96, 1.4, 0, Math.PI * 2)
ctx.fill()
}
}
const renderSceneFrame = (now: number, clampedProgress: number, exitRatio: number) => { const renderSceneFrame = (now: number, clampedProgress: number, exitRatio: number) => {
if (!canvasEl || !rootEl) return if (!canvasEl || !rootEl) return
const dpr = Math.min(window.devicePixelRatio || 1, 2)
const width = window.innerWidth || 1280 const width = window.innerWidth || 1280
const height = window.innerHeight || 800 const height = window.innerHeight || 800
const targetCanvasW = Math.max(1, Math.round(width * dpr)) const { dpr, width: targetCanvasW, height: targetCanvasH } = computeSplashCanvasSize(
const targetCanvasH = Math.max(1, Math.round(height * dpr)) width,
height,
window.devicePixelRatio || 1,
)
if (canvasEl.width !== targetCanvasW || canvasEl.height !== targetCanvasH) { if (canvasEl.width !== targetCanvasW || canvasEl.height !== targetCanvasH) {
canvasEl.width = targetCanvasW canvasEl.width = targetCanvasW
canvasEl.height = targetCanvasH canvasEl.height = targetCanvasH
@@ -1347,7 +1214,7 @@ export function createDesktopSplashController(options: {
const radius = Math.max(82, Math.min(width * 0.24, height * 0.21, 196)) const radius = Math.max(82, Math.min(width * 0.24, height * 0.21, 196))
if (exitRatio > 0) { if (exitRatio > 0) {
if (reducedMotion || activeTheme === 'horizon') { 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 // Portal cutout expands from center while particle bursts continue radiating over edges
@@ -1365,13 +1232,7 @@ export function createDesktopSplashController(options: {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0) ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
ctx.clearRect(0, 0, width, height) ctx.clearRect(0, 0, width, height)
drawStars(ctx, width, height, elapsedSec, exitRatio, cx, cy) drawStars(ctx, width, height, elapsedSec, exitRatio, cx, cy)
if (activeTheme === 'singularity') { drawDawnToSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
drawSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
} else if (activeTheme === 'constellation') {
drawConstellationScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
} else {
drawHorizonScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
}
} }
} }
@@ -1463,13 +1324,7 @@ export function createDesktopSplashController(options: {
} }
const clampedProgress = Math.max(0, Math.min(1, displayProgress)) const clampedProgress = Math.max(0, Math.min(1, displayProgress))
const exitDuration = reducedMotion const exitDuration = reducedMotion ? 300 : 940
? 300
: activeTheme === 'singularity'
? 920
: activeTheme === 'constellation'
? 860
: 900
const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0 const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0
renderSceneFrame(now, clampedProgress, exitRatio) renderSceneFrame(now, clampedProgress, exitRatio)
+468
View File
@@ -0,0 +1,468 @@
import { mkdtempSync, rmSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
import {
DesktopConfigStore,
normalizeGpuMode,
parseLaunchArgs,
readPreReadyGpuHandoff,
readPreReadyGpuMode,
} from '../src/main/config'
import {
buildGpuHandoffArgs,
canAutoSwitchGpu,
chooseStartupGpuTarget,
createSustainedLowFpsTracker,
createVramHysteresisTracker,
detectIntegratedGpuFromRegistryOutput,
isGpuProcessCrash,
parseNvidiaSmiCsv,
resolveChromiumGpuSwitches,
stripGpuOverrideArgs,
VRAM_LOW_THRESHOLD_MIB,
VRAM_RECOVER_THRESHOLD_MIB,
} from '../src/main/gpu-policy'
import { computeSplashCanvasSize } from '../src/preload/splash'
let tempRoot = ''
beforeAll(() => {
tempRoot = mkdtempSync(path.join(os.tmpdir(), 'planet-gpu-policy-test-'))
})
afterAll(() => {
if (tempRoot) {
rmSync(tempRoot, { recursive: true, force: true })
}
})
describe('chromium GPU switch policy and splash pixel budget', () => {
test('win32 hardware mode avoids risky zero-copy and forced GPU switches by default', () => {
const switches = resolveChromiumGpuSwitches({
platform: 'win32',
headlessSmoke: false,
softwareGl: false,
})
const names = switches.map((entry) => entry.name)
expect(names).not.toContain('enable-zero-copy')
expect(names).not.toContain('enable-gpu-rasterization')
expect(names).not.toContain('force_high_performance_gpu')
expect(names).not.toContain('force_low_power_gpu')
expect(names).toContain('disable-renderer-backgrounding')
expect(names).not.toContain('ozone-platform-hint')
})
test('low-power and high-performance targets emit matching Chromium GPU preference switches without enable-zero-copy', () => {
const igpuSwitches = resolveChromiumGpuSwitches({
platform: 'win32',
headlessSmoke: false,
target: 'low-power',
})
expect(igpuSwitches).toEqual([
{ name: 'force_low_power_gpu' },
{ name: 'disable-renderer-backgrounding' },
])
const dgpuSwitches = resolveChromiumGpuSwitches({
platform: 'win32',
headlessSmoke: false,
target: 'high-performance',
})
expect(dgpuSwitches).toEqual([
{ name: 'force_high_performance_gpu' },
{ name: 'disable-renderer-backgrounding' },
])
})
test('linux hardware mode adds ozone auto hint without enable-zero-copy', () => {
const switches = resolveChromiumGpuSwitches({
platform: 'linux',
headlessSmoke: false,
softwareGl: false,
})
expect(switches).toEqual([
{ name: 'disable-renderer-backgrounding' },
{ name: 'ozone-platform-hint', value: 'auto' },
])
})
test('headless smoke, explicit software-gl, and target=software select SwiftShader safely', () => {
for (const flags of [
{ headlessSmoke: true, softwareGl: false },
{ headlessSmoke: false, softwareGl: true },
{ headlessSmoke: false, target: 'software' as const },
]) {
const switches = resolveChromiumGpuSwitches({ platform: 'win32', ...flags })
expect(switches).toEqual([
{ name: 'disable-gpu' },
{ name: 'use-gl', value: 'angle' },
{ name: 'use-angle', value: 'swiftshader' },
{ name: 'enable-unsafe-swiftshader' },
])
}
})
test('isGpuProcessCrash detects unexpected GPU exits and ignores clean exits', () => {
expect(isGpuProcessCrash({ type: 'GPU', reason: 'crashed' })).toBe(true)
expect(isGpuProcessCrash({ type: 'GPU', reason: 'killed' })).toBe(true)
expect(isGpuProcessCrash({ type: 'GPU', reason: 'clean-exit' })).toBe(false)
expect(isGpuProcessCrash({ type: 'Utility', reason: 'crashed' })).toBe(false)
expect(isGpuProcessCrash(null)).toBe(false)
})
test('computeSplashCanvasSize preserves 1080p clarity while capping 4K splash buffers', () => {
expect(computeSplashCanvasSize(1920, 1080, 1)).toEqual({
dpr: 1,
width: 1920,
height: 1080,
})
const qhdScaled4k = computeSplashCanvasSize(2560, 1440, 1.5)
expect(qhdScaled4k.dpr).toBeLessThan(1.5)
expect(qhdScaled4k.width * qhdScaled4k.height).toBeLessThanOrEqual(1920 * 1080)
const native4k = computeSplashCanvasSize(3840, 2160, 1)
expect(native4k.dpr).toBe(0.75)
expect(native4k.width).toBe(2880)
expect(native4k.height).toBe(1620)
})
})
describe('adaptive VRAM probing, GPU decision, and hysteresis', () => {
test('parseNvidiaSmiCsv parses single and multi-line CSV while skipping invalid rows', () => {
expect(
parseNvidiaSmiCsv('NVIDIA GeForce RTX 5070 Ti, 14651, 1345, 16303\n'),
).toEqual({
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
usedMiB: 14651,
freeMiB: 1345,
totalMiB: 16303,
})
expect(
parseNvidiaSmiCsv(
'\n[N/A], [N/A], [N/A], [N/A]\nNVIDIA GeForce RTX 4090, 4096 MiB, 20480 MiB, 24576 MiB\n',
),
).toEqual({
gpuName: 'NVIDIA GeForce RTX 4090',
usedMiB: 4096,
freeMiB: 20480,
totalMiB: 24576,
})
expect(parseNvidiaSmiCsv('')).toBeNull()
expect(parseNvidiaSmiCsv('Failed to initialize NVML')).toBeNull()
})
test('detectIntegratedGpuFromRegistryOutput distinguishes iGPU from single-GPU and virtual adapters', () => {
expect(
detectIntegratedGpuFromRegistryOutput(`
HKEY_LOCAL_MACHINE\\...\\0000
DriverDesc REG_SZ Intel(R) Graphics
HKEY_LOCAL_MACHINE\\...\\0001
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
`),
).toBe(true)
expect(
detectIntegratedGpuFromRegistryOutput(`
DriverDesc REG_SZ AMD Radeon(TM) Graphics
DriverDesc REG_SZ NVIDIA GeForce RTX 4060 Laptop GPU
`),
).toBe(true)
expect(
detectIntegratedGpuFromRegistryOutput(`
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
DriverDesc REG_SZ Microsoft Basic Display Adapter
DriverDesc REG_SZ Parsec Virtual Display Adapter
`),
).toBe(false)
expect(
detectIntegratedGpuFromRegistryOutput(`
DriverDesc REG_SZ Intel(R) Arc(TM) A770 Graphics
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
`),
).toBe(false)
})
test('chooseStartupGpuTarget handles low VRAM auto offload, recovery, explicit modes, and smoke', () => {
const lowVramSample = {
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
usedMiB: 14651,
freeMiB: 1345,
totalMiB: 16303,
}
const healthyVramSample = {
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
usedMiB: 4000,
freeMiB: 8000,
totalMiB: 16303,
}
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
vramSample: lowVramSample,
hasIntegratedGpu: true,
}),
).toEqual({
target: 'low-power',
requestedMode: 'auto',
reason: 'low-vram-igpu',
vramSample: lowVramSample,
hasIntegratedGpu: true,
})
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
vramSample: lowVramSample,
hasIntegratedGpu: false,
}),
).toEqual({
target: 'software',
requestedMode: 'auto',
reason: 'low-vram-software',
vramSample: lowVramSample,
hasIntegratedGpu: false,
})
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
}),
).toEqual({
target: 'default',
requestedMode: 'auto',
reason: 'normal-gpu',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
})
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'high-performance',
vramSample: lowVramSample,
hasIntegratedGpu: true,
}).reason,
).toBe('user-high-performance')
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'low-power',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
}).target,
).toBe('low-power')
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: true,
requestedMode: 'high-performance',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
}),
).toMatchObject({ target: 'software', reason: 'headless-smoke' })
})
test('createVramHysteresisTracker enforces consecutive readings and deadband', () => {
const lowSample = { gpuName: 'RTX 5070 Ti', usedMiB: 14500, freeMiB: 1500, totalMiB: 16303 }
const midSample = { gpuName: 'RTX 5070 Ti', usedMiB: 13000, freeMiB: 3000, totalMiB: 16303 }
const highSample = { gpuName: 'RTX 5070 Ti', usedMiB: 11000, freeMiB: VRAM_RECOVER_THRESHOLD_MIB, totalMiB: 16303 }
const igpuTracker = createVramHysteresisTracker({
activeTarget: 'low-power',
hasIntegratedGpu: true,
})
expect(igpuTracker.observe(midSample)).toBeNull()
expect(igpuTracker.observe(highSample)).toBeNull()
expect(igpuTracker.observe(midSample)).toBeNull() // streak reset
expect(igpuTracker.observe(highSample)).toBeNull()
expect(igpuTracker.observe(highSample)).toEqual({
kind: 'switch-to-discrete',
sample: highSample,
})
const dgpuWithIgpu = createVramHysteresisTracker({
activeTarget: 'default',
hasIntegratedGpu: true,
})
expect(dgpuWithIgpu.observe(midSample)).toBeNull()
expect(dgpuWithIgpu.observe({ ...lowSample, freeMiB: VRAM_LOW_THRESHOLD_MIB - 1 })).toBeNull()
expect(dgpuWithIgpu.observe(null)).toBeNull() // missing reading resets streak
expect(dgpuWithIgpu.observe(lowSample)).toBeNull()
expect(dgpuWithIgpu.observe(lowSample)).toEqual({
kind: 'switch-to-low-power',
sample: lowSample,
})
const dgpuNoIgpu = createVramHysteresisTracker({
activeTarget: 'high-performance',
hasIntegratedGpu: false,
})
expect(dgpuNoIgpu.observe(lowSample)).toBeNull()
expect(dgpuNoIgpu.observe(lowSample)).toEqual({
kind: 'switch-to-software',
sample: lowSample,
})
})
test('stripGpuOverrideArgs removes CLI GPU override flags cleanly', () => {
expect(
stripGpuOverrideArgs([
'--fullscreen',
'--software-gl',
'--gpu-mode=low-power',
'--gpu-mode',
'high-performance',
'--low-power-gpu',
'--high-performance-gpu',
'planet-earth://open',
]),
).toEqual(['--fullscreen', 'planet-earth://open'])
})
test('gpuMode config normalization, CLI flags, persistence, and readPreReadyGpuMode precedence work', () => {
expect(normalizeGpuMode('AUTO')).toBe('auto')
expect(normalizeGpuMode('igpu')).toBe('low-power')
expect(normalizeGpuMode('discrete')).toBe('high-performance')
expect(normalizeGpuMode('cpu')).toBe('software')
expect(normalizeGpuMode('unknown', 'low-power')).toBe('low-power')
expect(parseLaunchArgs(['--low-power-gpu']).flags.gpuModeOverride).toBe('low-power')
expect(parseLaunchArgs(['--high-performance-gpu']).flags.gpuModeOverride).toBe('high-performance')
expect(parseLaunchArgs(['--software-gl']).flags.gpuModeOverride).toBe('software')
expect(parseLaunchArgs(['--gpu-mode', 'igpu']).flags.gpuModeOverride).toBe('low-power')
const userDataDir = path.join(tempRoot, 'gpu-user-data')
const exeDir = path.join(tempRoot, 'gpu-exe-dir')
const store = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
expect(store.get().gpuMode).toBe('auto')
store.updateEndpoints({ backendUrl: 'https://rclaw.test' })
store.updateGpuMode('low-power')
expect(
readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: {} }),
).toBe('low-power')
expect(
readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: { PLANET_GPU_MODE: 'high-performance' } }),
).toBe('high-performance')
expect(
readPreReadyGpuMode({
userDataDir,
exeDir,
argv: ['--software-gl'],
env: { PLANET_GPU_MODE: 'high-performance' },
}),
).toBe('software')
const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
expect(reloaded.get().gpuMode).toBe('low-power')
expect(reloaded.get().backendUrl).toBe('https://rclaw.test')
})
test('createSustainedLowFpsTracker ignores brief dips and triggers after 5s below 20 FPS with cooldown', () => {
const tracker = createSustainedLowFpsTracker()
let now = 0
expect(tracker.onFrame(now)).toBeNull()
// Simulate 10 FPS (100ms frame delta) for 4 seconds -> not yet 5s sustained
for (let sec = 0; sec < 4; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
expect(tracker.onFrame(now)).toBeNull()
}
}
// Recover above 20 FPS -> resets low streak
for (let f = 0; f < 30; f += 1) {
now += 35
expect(tracker.onFrame(now)).toBeNull()
}
// Now sustain 10 FPS for 5 full seconds -> triggers on 5th second
let trigger: { avgFps: number; sustainedMs: number } | null = null
for (let sec = 0; sec < 5; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
const res = tracker.onFrame(now)
if (res) trigger = res
}
}
expect(trigger).not.toBeNull()
expect(trigger!.avgFps).toBeGreaterThanOrEqual(9.5)
expect(trigger!.avgFps).toBeLessThan(11)
expect(trigger!.sustainedMs).toBeGreaterThanOrEqual(5000)
// Within 15s report cooldown -> suppressed even if slow again
for (let sec = 0; sec < 5; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
expect(tracker.onFrame(now)).toBeNull()
}
}
// Reset clears accumulated low duration cleanly
tracker.reset()
now += 20_000
expect(tracker.onFrame(now)).toBeNull()
for (let sec = 0; sec < 4; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
expect(tracker.onFrame(now)).toBeNull()
}
}
})
test('canAutoSwitchGpu, handoff target decision, and handoff CLI args preserve state across relaunch', () => {
expect(canAutoSwitchGpu(null, 10_000)).toBe(true)
expect(canAutoSwitchGpu(10_000, 40_000)).toBe(false)
expect(canAutoSwitchGpu(10_000, 55_000)).toBe(true)
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
handoffTarget: 'low-power',
vramSample: null,
hasIntegratedGpu: true,
}),
).toMatchObject({ target: 'low-power', reason: 'gpu-handoff' })
const args = buildGpuHandoffArgs(
['--fullscreen', '--gpu-handoff', '--gpu-handoff-target=low-power', 'planet-earth://open'],
'default',
)
expect(args).toEqual([
'--fullscreen',
'planet-earth://open',
'--gpu-handoff',
'--gpu-handoff-target=default',
])
expect(readPreReadyGpuHandoff(args)).toEqual({
gpuHandoff: true,
gpuHandoffTarget: 'default',
})
expect(stripGpuOverrideArgs(args)).toEqual(['--fullscreen', 'planet-earth://open'])
})
})
+303
View File
@@ -0,0 +1,303 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import zlib from 'node:zlib'
import { afterEach, describe, expect, test } from 'bun:test'
import {
PERIODIC_UPDATE_CHECK_INTERVAL_MS,
compareSemver,
evaluateUpdateDecision,
getUpdatePromptKey,
installHotfixArchive,
markHotfixVerified,
readHotfixState,
resolveActiveEarthOverlay,
resolveUpdateAssetUrl,
rollbackPendingHotfix,
shouldSuppressUpdatePrompt,
} from '../src/main/hot-update-core'
import { createEarthProtocolHandler } from '../src/main/protocol-core'
import { createTarGz, extractTarGzSafely } from '../src/main/tar-gz'
const tempRoots: string[] = []
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
tempRoots.push(dir)
return dir
}
function buildMaliciousTarGz(entryName: string, typeFlag = '0'): Buffer {
const header = Buffer.alloc(512, 0)
header.write(entryName, 0, 100, 'utf8')
header.write('0000644\0', 100, 8, 'ascii')
header.write('0000000\0', 108, 8, 'ascii')
header.write('0000000\0', 116, 8, 'ascii')
header.write('00000000000\0', 124, 12, 'ascii')
header.write('00000000000\0', 136, 12, 'ascii')
header.fill(0x20, 148, 156)
header.write(typeFlag, 156, 1, 'ascii')
header.write('ustar\0', 257, 6, 'ascii')
header.write('00', 263, 2, 'ascii')
let checksum = 0
for (let i = 0; i < 512; i += 1) checksum += header[i]
header.write(`${checksum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii')
return zlib.gzipSync(Buffer.concat([header, Buffer.alloc(1024, 0)]))
}
afterEach(() => {
while (tempRoots.length > 0) {
const dir = tempRoots.pop()!
fs.rmSync(dir, { recursive: true, force: true })
}
})
describe('tar-gz archive creation and safe extraction', () => {
test('round-trips files including nested js/css directories and long USTAR paths', () => {
const outDir = makeTempDir('planet-tar-ok-')
const longPath =
'js/submodules/deeply/nested/component/folder/structure/extra-segment/another-segment/runtime-earth-worker-module-bundle.js'
const archive = createTarGz([
{ path: 'index.html', data: Buffer.from('<!doctype html><html><body>ok</body></html>') },
{ path: 'css/theme.css', data: Buffer.from('body { color: #fff; }') },
{ path: longPath, data: Buffer.from('export const ok = true;') },
])
const result = extractTarGzSafely(archive, outDir)
expect(result.files).toEqual(['css/theme.css', 'index.html', longPath])
expect(fs.readFileSync(path.join(outDir, 'index.html'), 'utf8')).toContain('<body>ok</body>')
expect(fs.readFileSync(path.join(outDir, longPath), 'utf8')).toBe('export const ok = true;')
})
test('rejects path traversal, absolute paths, and symlink entries', () => {
const outDir = makeTempDir('planet-tar-bad-')
expect(() => createTarGz([{ path: '../escape.js', data: Buffer.from('x') }])).toThrow()
expect(() => createTarGz([{ path: '/etc/passwd', data: Buffer.from('x') }])).toThrow()
expect(() => extractTarGzSafely(buildMaliciousTarGz('../escape.js', '0'), outDir)).toThrow()
expect(() => extractTarGzSafely(buildMaliciousTarGz('/abs/path.js', '0'), outDir)).toThrow()
expect(() => extractTarGzSafely(buildMaliciousTarGz('js/link.js', '2'), outDir)).toThrow()
})
})
describe('hot-update decision matrix, verification, rollback, and overlay protocol', () => {
test('compareSemver and evaluateUpdateDecision select the exact right update tier', () => {
expect(compareSemver('0.78.0', '0.78.0')).toBe(0)
expect(compareSemver('0.78.1', '0.78.0')).toBe(1)
expect(compareSemver('0.79.0', '0.78.9')).toBe(1)
expect(compareSemver('v0.79.0', '0.79.0-beta.1')).toBe(1)
const validSha = 'a'.repeat(64)
expect(
evaluateUpdateDecision({
shellVersion: '0.78.0',
activeBundleVersion: '0.78.0',
blacklistedVersions: [],
manifest: {
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
bundle: null,
},
}),
).toEqual({ kind: 'up-to-date' })
expect(
evaluateUpdateDecision({
shellVersion: '0.78.0',
activeBundleVersion: '0.78.0',
blacklistedVersions: [],
manifest: {
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
bundle: { version: '0.78.2', minShellVersion: '0.78.0', url: '/api/v1/client/updates/files/b.tar.gz', sha256: validSha },
},
}),
).toMatchObject({ kind: 'hotfix-update', bundle: { version: '0.78.2' } })
expect(
evaluateUpdateDecision({
shellVersion: '0.78.0',
activeBundleVersion: '0.78.2',
blacklistedVersions: ['0.78.3'],
manifest: {
shell: { version: '0.79.0', minRequired: '0.79.0', downloadUrl: 'https://gitea.rclaw.top/r' },
bundle: { version: '0.78.3', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
},
}),
).toEqual({
kind: 'shell-update',
mandatory: true,
shell: { version: '0.79.0', minRequired: '0.79.0', downloadUrl: 'https://gitea.rclaw.top/r' },
})
expect(
evaluateUpdateDecision({
shellVersion: '0.78.0',
activeBundleVersion: '0.78.0',
blacklistedVersions: [],
manifest: {
shell: { version: '0.79.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
bundle: { version: '0.79.1', minShellVersion: '0.79.0', url: '/b.tar.gz', sha256: validSha },
},
}),
).toMatchObject({ kind: 'shell-update', mandatory: false })
expect(resolveUpdateAssetUrl('/api/v1/client/updates/files/a.tar.gz', 'https://rclaw.top/sub')).toBe(
'https://rclaw.top/api/v1/client/updates/files/a.tar.gz',
)
})
test('verifies SHA-256 on install, marks verified on ready, and auto-rolls back failing pending bundles', () => {
const userDataDir = makeTempDir('planet-hotfix-state-')
const goodV1Archive = createTarGz([
{ path: 'index.html', data: Buffer.from('<html>v1</html>') },
{ path: 'js/app.js', data: Buffer.from('console.log("v1")') },
])
const goodV1Sha = crypto.createHash('sha256').update(goodV1Archive).digest('hex')
expect(() =>
installHotfixArchive({
userDataDir,
version: '0.78.1',
archiveBuffer: goodV1Archive,
expectedSha256: '0'.repeat(64),
}),
).toThrow(/SHA-256 mismatch/)
installHotfixArchive({
userDataDir,
version: '0.78.1',
archiveBuffer: goodV1Archive,
expectedSha256: goodV1Sha,
})
const boot1 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
expect(boot1.activeBundleVersion).toBe('0.78.1')
expect(boot1.pendingVerification).toBe(true)
expect(boot1.overlayRoot).toBeTruthy()
const verifiedState = markHotfixVerified(userDataDir)
expect(verifiedState.status).toBe('verified')
expect(verifiedState.previousVerifiedVersion).toBe('0.78.1')
// Install a bad pending v0.78.2 that fails to mark ready across 2 launch attempts.
const badV2Archive = createTarGz([
{ path: 'index.html', data: Buffer.from('<html>broken v2</html>') },
])
const badV2Sha = crypto.createHash('sha256').update(badV2Archive).digest('hex')
installHotfixArchive({
userDataDir,
version: '0.78.2',
archiveBuffer: badV2Archive,
expectedSha256: badV2Sha,
})
const failBoot1 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
expect(failBoot1.activeBundleVersion).toBe('0.78.2')
expect(failBoot1.pendingVerification).toBe(true)
const failBoot2 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
expect(failBoot2.activeBundleVersion).toBe('0.78.2')
expect(failBoot2.pendingVerification).toBe(true)
// 3rd attempt sees 2 failed unverified boots -> automatically rolls back to verified v0.78.1
const rolledBack = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
expect(rolledBack.rolledBackFrom).toBe('0.78.2')
expect(rolledBack.activeBundleVersion).toBe('0.78.1')
expect(rolledBack.pendingVerification).toBe(false)
expect(readHotfixState(userDataDir).blacklistedVersions).toContain('0.78.2')
// Immediate crash rollback also blacklists pending version right away.
installHotfixArchive({
userDataDir,
version: '0.78.3',
archiveBuffer: badV2Archive,
expectedSha256: badV2Sha,
})
const immediateRollback = rollbackPendingHotfix(userDataDir, '0.78.0')
expect(immediateRollback.rolledBackFrom).toBe('0.78.3')
expect(immediateRollback.activeBundleVersion).toBe('0.78.1')
// Installing a newer shell (0.79.0) automatically retires older hotfixes (0.78.1).
const afterShellUpgrade = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.79.0' })
expect(afterShellUpgrade.overlayRoot).toBeNull()
expect(afterShellUpgrade.activeBundleVersion).toBe('0.79.0')
})
test('createEarthProtocolHandler serves overlay files first and falls back to shell assets', async () => {
const shellRoot = makeTempDir('planet-proto-shell-')
const overlayRoot = makeTempDir('planet-proto-overlay-')
fs.mkdirSync(path.join(shellRoot, 'js'), { recursive: true })
fs.mkdirSync(path.join(shellRoot, 'assets'), { recursive: true })
fs.writeFileSync(path.join(shellRoot, 'index.html'), '<html>shell</html>')
fs.writeFileSync(path.join(shellRoot, 'js', 'main.js'), 'shell-js')
fs.writeFileSync(path.join(shellRoot, 'assets', '8k_earth_daymap.jpg'), 'heavy-texture-bytes')
fs.mkdirSync(path.join(overlayRoot, 'js'), { recursive: true })
fs.writeFileSync(path.join(overlayRoot, 'index.html'), '<html>hotfix</html>')
fs.writeFileSync(path.join(overlayRoot, 'js', 'main.js'), 'hotfix-js')
let activeOverlay: string | null = overlayRoot
const handler = createEarthProtocolHandler({
earthBundleRoot: shellRoot,
getEarthOverlayRoot: () => activeOverlay,
getBackendUrl: () => 'https://rclaw.top',
})
const htmlRes = await handler(new Request('planet://earth/earth/index.html'))
expect(await htmlRes.text()).toBe('<html>hotfix</html>')
const jsRes = await handler(new Request('planet://earth/earth/js/main.js'))
expect(await jsRes.text()).toBe('hotfix-js')
const assetRes = await handler(new Request('planet://earth/earth/assets/8k_earth_daymap.jpg'))
expect(await assetRes.text()).toBe('heavy-texture-bytes')
const traversalRes = await handler(new Request('planet://earth/earth/..%2f..%2fsecret.txt'))
expect(traversalRes.status).toBe(403)
activeOverlay = null
const restoredHtmlRes = await handler(new Request('planet://earth/earth/index.html'))
expect(await restoredHtmlRes.text()).toBe('<html>shell</html>')
})
test('periodic 12h polling interval and per-session dismissal guard behave cleanly', () => {
expect(PERIODIC_UPDATE_CHECK_INTERVAL_MS).toBe(12 * 60 * 60 * 1000)
const validSha = 'b'.repeat(64)
const hotfixDecision = evaluateUpdateDecision({
shellVersion: '0.78.0',
activeBundleVersion: '0.78.0',
blacklistedVersions: [],
manifest: {
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
bundle: { version: '0.78.1', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
},
})
const key = getUpdatePromptKey(hotfixDecision)
expect(key).toBe('hotfix:0.78.1')
const dismissed = new Set<string>()
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: false, dismissedKeys: dismissed })).toBe(false)
dismissed.add(key!)
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: false, dismissedKeys: dismissed })).toBe(true)
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: true, dismissedKeys: dismissed })).toBe(false)
const newerDecision = evaluateUpdateDecision({
shellVersion: '0.78.0',
activeBundleVersion: '0.78.0',
blacklistedVersions: [],
manifest: {
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
bundle: { version: '0.78.2', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
},
})
expect(shouldSuppressUpdatePrompt(newerDecision, { manual: false, dismissedKeys: dismissed })).toBe(false)
expect(getUpdatePromptKey({ kind: 'up-to-date' })).toBeNull()
})
})
+72
View File
@@ -7,6 +7,7 @@ import {
EARTH_MOBILE_MAX_WIDTH, EARTH_MOBILE_MAX_WIDTH,
MIN_WINDOW_HEIGHT, MIN_WINDOW_HEIGHT,
MIN_WINDOW_WIDTH, MIN_WINDOW_WIDTH,
resolveInitialWindowBounds,
type Rect, type Rect,
} from '../src/main/orientation' } from '../src/main/orientation'
@@ -67,4 +68,75 @@ describe('window orientation calculations', () => {
}) })
expect(landscape).toEqual(savedLandscape) expect(landscape).toEqual(savedLandscape)
}) })
test('resolveInitialWindowBounds pre-sizes maximized and fullscreen windows to display work area or bounds', () => {
const displayWorkArea: Rect = { x: 0, y: 0, width: 1920, height: 1032 }
const displayBounds: Rect = { x: 0, y: 0, width: 1920, height: 1080 }
const savedNormal = { x: 160, y: 36, width: 1600, height: 960 }
expect(
resolveInitialWindowBounds({
saved: { ...savedNormal, isMaximized: true, isFullScreen: false },
launchFullScreen: false,
headlessSmoke: false,
displayWorkArea,
displayBounds,
}),
).toEqual({
initialBounds: displayWorkArea,
shouldRestoreNormalBoundsOnUnmaximize: true,
})
expect(
resolveInitialWindowBounds({
saved: { ...savedNormal, isMaximized: true, isFullScreen: true },
launchFullScreen: false,
headlessSmoke: false,
displayWorkArea,
displayBounds,
}),
).toEqual({
initialBounds: displayBounds,
shouldRestoreNormalBoundsOnUnmaximize: true,
})
expect(
resolveInitialWindowBounds({
saved: { ...savedNormal, isMaximized: false, isFullScreen: false },
launchFullScreen: true,
headlessSmoke: false,
displayWorkArea,
displayBounds,
}),
).toEqual({
initialBounds: displayBounds,
shouldRestoreNormalBoundsOnUnmaximize: false,
})
expect(
resolveInitialWindowBounds({
saved: { ...savedNormal, isMaximized: false, isFullScreen: false },
launchFullScreen: false,
headlessSmoke: false,
displayWorkArea,
displayBounds,
}),
).toEqual({
initialBounds: savedNormal,
shouldRestoreNormalBoundsOnUnmaximize: false,
})
expect(
resolveInitialWindowBounds({
saved: { ...savedNormal, isMaximized: true, isFullScreen: true },
launchFullScreen: true,
headlessSmoke: true,
displayWorkArea,
displayBounds,
}),
).toEqual({
initialBounds: savedNormal,
shouldRestoreNormalBoundsOnUnmaximize: false,
})
})
}) })
+54
View File
@@ -92,6 +92,60 @@ describe('protocol-core static and range handling', () => {
const blocked = await handler(new Request('planet://other/earth/index.html')) const blocked = await handler(new Request('planet://other/earth/index.html'))
expect(blocked.status).toBe(403) expect(blocked.status).toBe(403)
}) })
test('forwards Accept-Encoding, If-None-Match, and AbortSignal and preserves 304 null-body responses', async () => {
const capturedHeaders: Array<Headers> = []
let receivedSignal: AbortSignal | undefined
const handler = createEarthProtocolHandler({
earthBundleRoot: bundleRoot,
getBackendUrl: () => 'http://127.0.0.1:8000',
fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => {
capturedHeaders.push(new Headers(init?.headers))
receivedSignal = init?.signal
return new Response(null, {
status: 304,
headers: { ETag: '"sat-v1"', 'Content-Length': '0' },
})
}) as typeof fetch,
})
const abortController = new AbortController()
const response = await handler(
new Request('planet://earth/api/v1/visualization/geo/satellites?format=compact', {
headers: { 'If-None-Match': '"sat-v1"' },
signal: abortController.signal,
}),
)
expect(response.status).toBe(304)
expect(response.headers.get('ETag')).toBe('"sat-v1"')
expect(await response.text()).toBe('')
expect(capturedHeaders[0].get('accept-encoding')).toBe('gzip, deflate, br')
expect(capturedHeaders[0].get('if-none-match')).toBe('"sat-v1"')
expect(receivedSignal?.aborted).toBe(false)
const abortedController = new AbortController()
abortedController.abort(new DOMException('Aborted', 'AbortError'))
const abortHandler = createEarthProtocolHandler({
earthBundleRoot: bundleRoot,
getBackendUrl: () => 'http://127.0.0.1:8000',
fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => {
if (init?.signal?.aborted) {
throw init.signal.reason ?? new DOMException('Aborted', 'AbortError')
}
return Response.json({ ok: true })
}) as typeof fetch,
})
await expect(
abortHandler(
new Request('planet://earth/api/v1/visualization/geo/satellites', {
signal: abortedController.signal,
}),
),
).rejects.toThrow()
})
}) })
describe('external links and runtime config', () => { describe('external links and runtime config', () => {
+39 -9
View File
@@ -7,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
import { DesktopConfigStore, normalizeSplashTheme, parseLaunchArgs } from '../src/main/config' import { DesktopConfigStore, normalizeSplashTheme, parseLaunchArgs } from '../src/main/config'
import { createWindowShowGate } from '../src/main/show-gate' import { createWindowShowGate } from '../src/main/show-gate'
import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from '../src/preload/earth-landmask' import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from '../src/preload/earth-landmask'
import { evaluateBootSplashState } from '../src/preload/splash' import { computeSplashMorphPhases, evaluateBootSplashState } from '../src/preload/splash'
let tempRoot = '' let tempRoot = ''
@@ -37,18 +37,18 @@ describe('splash theme configuration and landmask', () => {
}) })
}) })
test('normalizeSplashTheme validates allowed themes and falls back safely', () => { test('normalizeSplashTheme normalizes unified singularity theme, legacy names, and off', () => {
expect(normalizeSplashTheme('singularity')).toBe('singularity') expect(normalizeSplashTheme('singularity')).toBe('singularity')
expect(normalizeSplashTheme('CONSTELLATION')).toBe('constellation') expect(normalizeSplashTheme('HORIZON')).toBe('singularity')
expect(normalizeSplashTheme('horizon')).toBe('horizon') expect(normalizeSplashTheme('constellation')).toBe('singularity')
expect(normalizeSplashTheme('off')).toBe('off') expect(normalizeSplashTheme('off')).toBe('off')
expect(normalizeSplashTheme('invalid', 'singularity')).toBe('singularity') expect(normalizeSplashTheme('invalid', 'singularity')).toBe('singularity')
expect(normalizeSplashTheme(undefined)).toBe('singularity') expect(normalizeSplashTheme(undefined)).toBe('singularity')
}) })
test('parses --splash-theme CLI flag and persists splashTheme without clobbering endpoints', () => { test('parses --splash-theme CLI flag and persists splashTheme without clobbering endpoints', () => {
const parsed = parseLaunchArgs(['--splash-theme=constellation']) const parsed = parseLaunchArgs(['--splash-theme=off'])
expect(parsed.flags.splashThemeOverride).toBe('constellation') expect(parsed.flags.splashThemeOverride).toBe('off')
const userDataDir = path.join(tempRoot, 'user-data') const userDataDir = path.join(tempRoot, 'user-data')
const exeDir = path.join(tempRoot, 'exe-dir') const exeDir = path.join(tempRoot, 'exe-dir')
@@ -56,18 +56,48 @@ describe('splash theme configuration and landmask', () => {
expect(store.get().splashTheme).toBe('singularity') expect(store.get().splashTheme).toBe('singularity')
store.updateEndpoints({ backendUrl: 'https://api.planet.test:8443' }) store.updateEndpoints({ backendUrl: 'https://api.planet.test:8443' })
store.updateSplashTheme('horizon') store.updateSplashTheme('off')
const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} }) const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
expect(reloaded.get().backendUrl).toBe('https://api.planet.test:8443') expect(reloaded.get().backendUrl).toBe('https://api.planet.test:8443')
expect(reloaded.get().splashTheme).toBe('horizon') expect(reloaded.get().splashTheme).toBe('off')
reloaded.updateSplashTheme('singularity')
reloaded.updateEndpoints({ adminUrl: 'https://admin.planet.test:8443' }) reloaded.updateEndpoints({ adminUrl: 'https://admin.planet.test:8443' })
const reloadedAgain = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} }) const reloadedAgain = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
expect(reloadedAgain.get().splashTheme).toBe('horizon') expect(reloadedAgain.get().splashTheme).toBe('singularity')
expect(reloadedAgain.get().adminUrl).toBe('https://admin.planet.test:8443') expect(reloadedAgain.get().adminUrl).toBe('https://admin.planet.test:8443')
}) })
test('computeSplashMorphPhases choreographs dawn to singularity reveal and climax burst', () => {
const start = computeSplashMorphPhases(0, 0)
expect(start.dawnIntensity).toBe(1)
expect(start.coreReveal).toBe(0)
expect(start.orbitReveal).toBe(0)
expect(start.arcReveal).toBe(0)
expect(start.burst).toBe(0)
expect(start.fade).toBe(1)
const midpoint = computeSplashMorphPhases(0.5, 0)
expect(midpoint.dawnIntensity).toBeGreaterThan(0.5)
expect(midpoint.dawnIntensity).toBeLessThan(1)
expect(midpoint.coreReveal).toBeGreaterThan(0.5)
expect(midpoint.orbitReveal).toBeGreaterThan(0)
expect(midpoint.orbitReveal).toBeLessThan(0.5)
const awakened = computeSplashMorphPhases(0.95, 0)
expect(awakened.dawnIntensity).toBe(0)
expect(awakened.coreReveal).toBe(1)
expect(awakened.orbitReveal).toBe(1)
expect(awakened.arcReveal).toBe(1)
const exitScatter = computeSplashMorphPhases(1, 0.6)
expect(exitScatter.dawnIntensity).toBe(0)
expect(exitScatter.burst).toBeGreaterThan(0.45)
expect(exitScatter.fade).toBeLessThan(0.8)
expect(exitScatter.fade).toBeGreaterThan(0)
})
test('unpackEarthLandMask reconstructs accurate continental and coastal pixels', () => { test('unpackEarthLandMask reconstructs accurate continental and coastal pixels', () => {
const grid = unpackEarthLandMask() const grid = unpackEarthLandMask()
expect(grid.length).toBe(LANDMASK_WIDTH * LANDMASK_HEIGHT) expect(grid.length).toBe(LANDMASK_WIDTH * LANDMASK_HEIGHT)
@@ -0,0 +1,14 @@
[Unit]
Description=Deploy the latest published Planet release
After=network-online.target docker.service
Wants=network-online.target
Requires=docker.service
[Service]
Type=oneshot
UMask=0077
Nice=10
StateDirectory=planet-release-deploy
StateDirectoryMode=0700
TimeoutStartSec=45min
ExecStart=/usr/bin/python3 /usr/local/lib/planet-release/production_deploy.py
@@ -0,0 +1,11 @@
[Unit]
Description=Check Gitea for published Planet releases
[Timer]
OnCalendar=*:0/2
Persistent=true
AccuracySec=5s
Unit=planet-release-deploy.service
[Install]
WantedBy=timers.target
+2
View File
@@ -134,6 +134,7 @@ services:
- "8000" - "8000"
volumes: volumes:
- earth_brand_data:/app/backend/data/earth-brand - earth_brand_data:/app/backend/data/earth-brand
- client_updates_data:/app/backend/data/client-updates
- collector_cache:/root/.cache/planet/downloads - collector_cache:/root/.cache/planet/downloads
mem_limit: ${PLANET_BACKEND_MEM_LIMIT:-2g} mem_limit: ${PLANET_BACKEND_MEM_LIMIT:-2g}
logging: *default-logging logging: *default-logging
@@ -207,6 +208,7 @@ volumes:
postgres_data: postgres_data:
redis_data: redis_data:
earth_brand_data: earth_brand_data:
client_updates_data:
collector_cache: collector_cache:
secrets: secrets:
+57
View File
@@ -8,6 +8,63 @@ 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.80.0] — 2026-11-26
Released: 2026-11-26
### Highlights
- Earth streams AI workbench responses as they arrive and saves conversations and memory notes on the device. Asset and news cards can open a conversation with the selected item as context.
- AI Provider supports streaming across Anthropic Messages, OpenAI-compatible Chat Completions, OpenAI Responses, and Ollama. The Admin console can refresh public model catalogs in one operation.
- Earth bundles the MediaPipe runtime and pose model for local single-camera gesture control. Camera selection supports automatic detection and a manual choice. Dual-camera 3D is planned.
---
## [0.79.2] — 2026-11-25
Released: 2026-11-25
### Highlights
- Earth can load the satellite catalog from a local cache while it checks the server for updates. The server offers a compact catalog with gzip compression and ETag validation, alongside the existing GeoJSON format.
- Turning off the satellite layer cancels pending requests. The desktop proxy forwards cancellation and handles an unchanged catalog without downloading it again.
- Electron restores a maximized or fullscreen window at the target display size on startup and preserves the normal window bounds for later use.
---
## [0.79.1] — 2026-11-24
Released: 2026-11-24
### Highlights
- On Windows, automatic GPU selection checks free discrete GPU memory at startup. Below 2 GiB it requests integrated graphics when available and falls back to software rendering otherwise.
- During use, five seconds below 20 FPS prompts a second memory check before switching away from the discrete GPU. An automatic switch starts a 45-second cooldown. Once it expires, the client checks every five seconds and switches back after two consecutive readings of at least 3.5 GiB free. Automatic relaunches skip the splash and restore the window state.
- The splash screen and Earth interface now use **Intelligent Media Institute** as the English name of 临空智能媒体研究院 (IMI).
---
## [0.79.0] — 2026-11-24
Released: 2026-11-24
### Highlights
- **Unified 3-Act Splash Screen**: Merged horizon and singularity splash animations into a unified Dawn -> Singularity -> Burst sequence, retired the constellation switcher UI, and capped splash canvas pixel budgets on high-DPI displays.
- **Phase 1 L1 Earth Business Hot-Update System**: Added self-hosted update manifest and `.tar.gz` bundle endpoints (`GET /api/v1/client/update-manifest`, `GET /api/v1/client/updates/files/{filename}`, `POST /api/v1/client/updates/bundle`), pure USTAR `.tar.gz` overlay extraction with SHA-256 verification and 2-attempt crash auto-rollback, overlay-first `planet://earth/` resolution, prominent native update dialogs, startup + 12-hour polling, and Alt-menu update checks.
- **Windows Electron GPU/TDR Stability & WebGL Recovery**: Hardened Chromium GPU switches with `--software-gl` fallback and crash forwarding, capped 4K startup DPR and starfield VRAM usage, added `webglcontextlost` / `webglcontextrestored` auto-recovery, and added brand image retry on GPU restarts.
### Added
- Client hot-update modules (`tar-gz.ts`, `hot-update-core.ts`, `hot-updater.ts`) and lightweight `planet-earth-bundle` `.tar.gz` packaging in `build-earth-bundle.mjs` and `scripts/release_publish.py`.
- Backend client updates API (`backend/app/api/v1/client_updates.py`) and `client_updates_data` volume configuration in `docker-compose.deploy.yml`.
### Fixed & Improved
- Removed unstable Windows Chromium GPU switches (`enable-zero-copy`, `enable-gpu-rasterization`, `force_high_performance_gpu`) and prevented duplicate "Later" update prompts within the same session.
---
## [0.78.0] — 2026-11-23 ## [0.78.0] — 2026-11-23
Released: 2026-11-23 Released: 2026-11-23
+1
View File
@@ -36,6 +36,7 @@
- [Earth News Cruise Summary Plan](/home/ray/dev/linkong/planet/docs/plans/earth-news-cruise-summary-plan.md) - [Earth News Cruise Summary Plan](/home/ray/dev/linkong/planet/docs/plans/earth-news-cruise-summary-plan.md)
- [Earth 动作捕捉手势控制计划](/home/ray/dev/linkong/planet/docs/plans/earth-motion-capture-gesture-control-plan.md) - [Earth 动作捕捉手势控制计划](/home/ray/dev/linkong/planet/docs/plans/earth-motion-capture-gesture-control-plan.md)
- [Earth 动捕交互语义 V2 计划](/home/ray/dev/linkong/planet/docs/plans/earth-motion-gesture-interaction-v2-plan.md) - [Earth 动捕交互语义 V2 计划](/home/ray/dev/linkong/planet/docs/plans/earth-motion-gesture-interaction-v2-plan.md)
- [Earth 本地动捕单摄闭环与双摄真 3D 深度规划](/home/ray/dev/linkong/planet/docs/plans/earth-local-motion-single-and-dual-3d-plan.md)
- [Motion Agent v2 控制协议与 3D 标定路线](/home/ray/dev/linkong/planet/docs/plans/motion-agent-v2-control-protocol-plan.md) - [Motion Agent v2 控制协议与 3D 标定路线](/home/ray/dev/linkong/planet/docs/plans/motion-agent-v2-control-protocol-plan.md)
- [Earth Presentation 解耦架构计划](/home/ray/dev/linkong/planet/docs/plans/earth-presentation-decoupled-architecture-plan.md) - [Earth Presentation 解耦架构计划](/home/ray/dev/linkong/planet/docs/plans/earth-presentation-decoupled-architecture-plan.md)
- [Earth Vessel Rendering Performance Plan](/home/ray/dev/linkong/planet/docs/plans/earth-vessel-rendering-performance-plan.md) - [Earth Vessel Rendering Performance Plan](/home/ray/dev/linkong/planet/docs/plans/earth-vessel-rendering-performance-plan.md)
@@ -0,0 +1,95 @@
# Earth 本地动捕单摄闭环与双摄真 3D 深度规划
## 背景与目标
早期动捕 Demo 依赖本机单独启动 `motion_agent`(Python + OpenCV + MediaPipe)并通过 WebSocket 转发骨骼与手势事件。该方式在普通桌面客户端与网页端部署成本高、存在额外跨进程配置负担。
本方案确立统一方向:**默认由 Earth 渲染端(Electron 桌面客户端与 Web 网页版共用同一套运行时)在进程内直接完成本地摄像头采集与 MediaPipe WASM/WebGL 骨骼识别,零外部服务即可工作**;同时根据本机物理摄像头拓扑自动判定运行模式:
- **单摄(Phase 1,已完成)**:自动启用单摄 2D 本地骨骼识别,完成 Web 与 Electron 全链路离线/自托管闭环。
- **双摄(Phase 2,规划占位,目标硬件:罗技 C1000e × 2)**:检测到两台物理摄像头且完成双目标定后,自动进入双摄三角测量真 3D 深度模式,用于展厅近距离交互锁定与过滤背景路人。
---
## Phase 1:单摄本地动捕闭环(已完成)
### 核心落地内容
1. **全离线 / 同源自托管 MediaPipe 资源**
- 将 `pose_landmarker_lite.task`(约 5.5 MiB)置于 `frontend/public/earth/vendor/mediapipe/pose_landmarker_lite.task`,并使 `frontend` 与 `client` 均锁定 `@mediapipe/tasks-vision@0.10.35`。
- Web 构建与开发服务器(`frontend/scripts/earth-runtime-plugin.mjs`)以及 Nginx(`frontend/nginx.conf.template`)同源托管 `vision_bundle.mjs`、`wasm/` 与 `.task` 模型,并启用 WASM gzip 与长缓存,无需访问国外 CDN。
- Electron 构建(`client/scripts/build-earth-bundle.mjs`)将 `vision_bundle.mjs`、`wasm/` 与 `.task` 打入离线 `earth` 资源包,由主进程向渲染层注入 `localMediaPipeBaseUrl` 与 `localPoseModelUrl`(移除未使用的 `vision_bundle.cjs`)。
2. **GPU → CPU 自动降级与低分辨率采集**
- `frontend/public/earth/js/motion-browser-provider.js` 默认采集分辨率收敛为 `640×360`,降低 USB 带宽与纹理上传开销。
- 当客户端处于 `software` 渲染模式或 WebGL/GPU delegate 初始化失败时,自动降级为 `CPU` delegate,并按「Electron 本地注入 → 同源 `./vendor/mediapipe/` → CDN 兜底」顺序加载模型与 WASM。
3. **跨平台权限打通**
- Electron `client/electron-builder.yml` 增加 macOS `NSCameraUsageDescription` 权限声明;`client/src/main/protocol.ts` 在 macOS 下调用 `systemPreferences.askForMediaAccess('camera')` 并配置 `setPermissionCheckHandler`。
- Web 端 `frontend/src/pages/Earth/Earth.tsx` 为 Earth `<iframe>` 显式声明 `allow="camera; fullscreen"`。
4. **物理摄像头过滤与单双摄拓扑占位**
- 新增 `frontend/public/earth/js/motion-camera-topology.js`,过滤常见虚拟摄像头及红外镜头(如 OBS Virtual Camera、Windows Hello IR / C1000e IR 设备),避免误判设备数量。
- 在 Earth 设置面板提供「摄像头模式(自动检测 / 单摄 2D / 双摄 3D(规划中))」与「摄像头设备」选择,监听 `devicechange` 热插拔并在检测为多物理摄像头时向用户提示当前仍运行单摄 2D 兜底。
---
## Phase 2:双摄真 3D 深度识别方案(规划中)
### 1. 自动检测与模式状态机
在 `motion-camera-topology.js` 基础上扩展完整状态机,并响应 `navigator.mediaDevices` 的 `devicechange` 热插拔事件:
| 物理摄像头数量 | 双目标定配置 | 实际生效模式 | 行为说明 |
| --- | --- | --- | --- |
| `0` | 任意 | `unavailable` | 提示未检测到可用物理摄像头 |
| `1` | 任意 | `single` | 自动运行单摄 2D 本地骨骼识别 |
| `>= 2` | 不存在 / 未完成 | `dual_redundant` 或 `single` 兜底 | 自动降级运行,并在设置面板提示“进入双目标定向导” |
| `>= 2` | 存在有效标定文件 | `dual_3d` | 自动启用双路同步采集 + 3D 三角测量深度识别 |
### 2. 目标硬件约束与 C1000e × 2 现场规范
针对两台 **罗技 C1000e(Brio 4K)**:
1. **USB 3.0 带宽隔离**:两台摄像头需尽量接入主机不同的 USB 3.0 根集线器,禁止共用无源 Hub;采集分辨率锁定 `640×360 @ 60fps` 或 `1280×720 @ 60fps`(MJPG)。
2. **锁定光学参数**:使用 Logitech Tune 预先锁定 `90°` 广角 FOV、固定焦距、关闭自动对焦与 RightSight 自动构图,避免展厅光照变化引起骨骼抖动。
3. **同名设备持久化绑定**:两台 C1000e 设备名称相同且自带红外传感器端点;需过滤 IR 端点,持久化保存「左目 `deviceId` / 右目 `deviceId`」,并在 UI 提供「左右镜头互换」按钮。
### 3. 隔离双路 Web Worker 推理与帧对齐
- 严禁两路摄像头共享同一个 `PoseLandmarker` 实例(`VIDEO` 模式及帧间差分状态会互相污染)。
- 将两路推理迁入独立 Web Worker(每路各持有一个 `PoseLandmarker` 实例,且开启多人检测 `numPoses: 3`),主线程仅通过 `createImageBitmap` / `OffscreenCanvas` 投递视频帧并接收骨骼结果,防止阻塞 Three.js 地球渲染。
- 通过 `60fps` 高帧率采集与帧时间戳对齐检查(要求左右帧采集时间差 $\Delta t \le 16\text{ms}$,超时则丢弃该对),抑制无硬件同步 USB 相机的快速挥手 3D 漂移。
### 4. 双目标定与运行期纯 JS 三角测量
将标定与运行期解耦,运行期无需在浏览器/客户端内嵌完整 OpenCV 运行时:
1. **一次性标定导出 `stereo-calibration.json`**:
- **主方案(棋盘格立体标定)**:采集 15~20 组左右同步棋盘格图像,计算左右内参 $(K_L, D_L, K_R, D_R)$、外参 $(R, T)$ 与投影矩阵 $(P_L, P_R)$(可通过标定时按需加载轻量 `opencv.js` 向导,或由离线 Python OpenCV 脚本生成后导入)。Electron 持久化到 `userData`,Web 持久化到 `localStorage`。
- **免标定平行兜底**:支持用户手动输入水平平行安装的两台 C1000e 基线间距 $B$(如 `0.30 m`)与视场角(`90°`),按标准平行双目视差公式 $Z = \frac{f \cdot B}{x_L - x_R}$ 提供粗略测距。
2. **运行期纯 JS 3D 重建(单帧 9 关节点 `< 0.1ms`)**:
- 使用 Brown-Conrady 模型对左右 2D 关键点去畸变;
- 基于基础矩阵 $F$ 的极线距离约束,将左画面人物与右画面同一人物配对;
- 对配对人物的 9 个上半身关节点执行 DLT 线性三角测量(SVD 求解),输出真实物理空间坐标 $(X, Y, Z)$(单位:米)。
### 5. 3D 深度交互围栏与防路人误触
- 设定可配置的有效交互空间围栏(默认 $Z \in [0.8\text{m}, 2.8\text{m}]$、横向 $|X| \le 1.2\text{m}$);
- 在每帧的多人 3D 骨骼结果中,丢弃交互区外人物,仅锁定交互区内距离屏幕最近($Z$ 最小)的主讲人作为控制源,彻底解决展厅后方路人走动抢焦点的问题;
- 在既有 11 项手势基础上,预留基于真实物理深度的扩展手势(如单手前推 `zoom_in` / 后拉 `zoom_out`、手腕相对躯干前伸触发 `confirm`)。
### 6. `motion_agent` 遗留边界说明
- 普通 Electron 桌面端与 Web 端不再依赖 `motion_agent`。
- `motion_agent` 仅作为可选外部桥接服务保留(用于 RTSP/HTTP 网络摄像头或外部 UE 联调);若后续复用 `motion_agent` 接多路摄像头,需先修复其当前两处已知限制:`motion_agent/worker.py` 中多摄像头共用单个 `MediaPipeGestureRecognizer` 实例导致串帧,以及 `motion_agent/cameras.py` 仅支持 Linux `CAP_V4L2` 的问题。
---
## 里程碑与验证清单
- **Phase 1(当前)**:
- Web 与 Electron 均完全脱离外网 CDN 与 `motion_agent` 完成单摄骨骼识别;
- `bun test frontend/public/earth/js/motion-control.test.js`、`cd frontend && bun run build && bun run build:admin`、`cd client && bun run build && bun test`、`scripts/harness/frontend-rules-check.sh`、`scripts/harness/docs-consistency-check.sh` 全量通过。
- **Phase 2(待排期)**:
- 双路 Web Worker `PoseLandmarker` (`numPoses: 3`) 并发推理与主线程 FPS 基准测试;
- 棋盘格双目标定导出与 `stereo-calibration.json` 校验;
- 纯 JS 去畸变 + 极线匹配 + DLT 三角测量单元测试;
- 罗技 C1000e × 2 实机 3D 深度围栏过滤与 60fps 异步延迟实测。
+6 -5
View File
@@ -96,14 +96,15 @@ The AI settings page uses:
- `POST /api/v1/settings/integrations/ai-provider/connect` - `POST /api/v1/settings/integrations/ai-provider/connect`
- `GET /api/v1/settings/integrations/ai-provider/secrets` - `GET /api/v1/settings/integrations/ai-provider/secrets`
- `GET /api/v1/settings/integrations/ai-provider/presets` - `GET /api/v1/settings/integrations/ai-provider/presets`
- `POST /api/v1/settings/integrations/ai-provider/presets/refresh-public`
- `POST /api/v1/settings/integrations/ai-provider/presets/{provider}/refresh` - `POST /api/v1/settings/integrations/ai-provider/presets/{provider}/refresh`
- `GET /api/v1/settings/ai-prompts` - `GET /api/v1/settings/ai-prompts`
- `PUT /api/v1/settings/ai-prompts/{task_key}` - `PUT /api/v1/settings/ai-prompts/{task_key}`
- `POST /api/v1/settings/ai-prompts/{task_key}/reset` - `POST /api/v1/settings/ai-prompts/{task_key}/reset`
These endpoints require an authenticated user. The `secrets` endpoint is only used when the settings page reveals a key or token; hiding the field restores the masked preview. These endpoints require an authenticated user, and preset catalog refresh endpoints require administrator privileges. The `secrets` endpoint is only used when the settings page reveals a key or token; hiding the field restores the masked preview.
Model refresh and lightweight checks share `backend/app/services/llm_model_catalog.py` and query provider endpoints directly, without models.dev. Refresh uses the draft base URL, protocol and credentials, or saved configuration when no draft is supplied. Regional hosts and custom gateway paths are preserved. Missing required credentials return 400; upstream failures return safe errors and retain the previous catalog. Model refresh and lightweight checks share `backend/app/services/llm_model_catalog.py` and query provider endpoints directly, without models.dev. Refresh uses the draft base URL, protocol and credentials, or saved configuration when no draft is supplied. Regional hosts and custom gateway paths are preserved. For official public catalogs (`openrouter.ai`, `opencode.ai`) and local Ollama, catalog refresh does not require or send an API key so stale or invalid credentials do not block public discovery; pointing those providers at a custom private gateway still requires and sends credentials. Lightweight connectivity checks continue sending configured credentials (Ollama remains key-free under both `ollama-generate` and `openai-completions`). Missing required credentials, invalid base URLs, or unsupported protocols return 400; upstream failures return 502 with safe errors and retain the previous catalog. `POST /api/v1/settings/integrations/ai-provider/presets/refresh-public` refreshes and persists all currently credential-free presets in one pass, isolating per-provider failures while preserving prior catalogs.
Successful catalogs and `refreshed_at` are stored under `llm_provider_preset:<provider>` in `system_settings`. Dynamic categories use the provider preset as their defaults and are validated before committing. Listing prefers saved catalogs and otherwise shows bundled suggestions. Refresh never modifies the active model, protocol, URL or credentials in `external_integrations`. The frontend retains the draft and previously loaded models when listing fails, with an explicit error message. Successful catalogs and `refreshed_at` are stored under `llm_provider_preset:<provider>` in `system_settings`. Dynamic categories use the provider preset as their defaults and are validated before committing. Listing prefers saved catalogs and otherwise shows bundled suggestions. Refresh never modifies the active model, protocol, URL or credentials in `external_integrations`. The frontend retains the draft and previously loaded models when listing fails, with an explicit error message.
@@ -119,9 +120,9 @@ These endpoints were checked against official documentation on 2026-09-13. The t
| [DeepSeek](https://api-docs.deepseek.com/api/list-models) | `https://api.deepseek.com/v1/models` | Bearer; `data[].id` | | [DeepSeek](https://api-docs.deepseek.com/api/list-models) | `https://api.deepseek.com/v1/models` | Bearer; `data[].id` |
| [Alibaba Model Studio](https://help.aliyun.com/zh/model-studio/list-models) | `/api/v1/models` on the configured regional host | Bearer; `output.models[].model`; `page_no/page_size/output.total`; filter `capabilities=TG` | | [Alibaba Model Studio](https://help.aliyun.com/zh/model-studio/list-models) | `/api/v1/models` on the configured regional host | Bearer; `output.models[].model`; `page_no/page_size/output.total`; filter `capabilities=TG` |
| [Moonshot / Kimi](https://platform.kimi.ai/docs/api/list-models) | `https://api.moonshot.ai/v1/models`; China: `api.moonshot.cn` | Bearer; `data[].id` | | [Moonshot / Kimi](https://platform.kimi.ai/docs/api/list-models) | `https://api.moonshot.ai/v1/models`; China: `api.moonshot.cn` | Bearer; `data[].id` |
| [OpenRouter](https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties) | `https://openrouter.ai/api/v1/models` | Public catalog; Bearer when supplied; `data[].id` | | [OpenRouter](https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties) | `https://openrouter.ai/api/v1/models` | Official public catalog refreshes without sending a key; custom gateways and connectivity checks send Bearer; `data[].id` |
| [OpenCode Go](https://opencode.ai/docs/go/#models) | `https://opencode.ai/zen/go/v1/models` | Public catalog; Bearer when supplied; `data[].id` | | [OpenCode Go](https://opencode.ai/docs/go/#models) | `https://opencode.ai/zen/go/v1/models` | Official public catalog refreshes without sending a key; custom gateways and connectivity checks send Bearer; `data[].id` |
| [Ollama](https://docs.ollama.com/api/tags) | `/api/tags` on the configured server | Local servers need no key; `models[].model/name`; empty means no installed models | | [Ollama](https://docs.ollama.com/api/tags) | `/api/tags` on the configured server (or `/v1/models` under `openai-completions`) | Local servers need no key; `models[].model/name` or `data[].id`; empty means no installed models |
New Model Studio endpoints for Beijing, Tokyo, Frankfurt and Virginia require the actual workspace host, such as `<WorkspaceId>.cn-beijing.maas.aliyuncs.com`. Singapore uses `dashscope-intl.aliyuncs.com`; Hong Kong uses `cn-hongkong.dashscope.aliyuncs.com`. Discovery changes only the path, never guesses a workspace or switches credential regions. If a legacy Beijing host no longer accepts the account, update the base URL from the provider console. New Model Studio endpoints for Beijing, Tokyo, Frankfurt and Virginia require the actual workspace host, such as `<WorkspaceId>.cn-beijing.maas.aliyuncs.com`. Singapore uses `dashscope-intl.aliyuncs.com`; Hong Kong uses `cn-hongkong.dashscope.aliyuncs.com`. Discovery changes only the path, never guesses a workspace or switches credential regions. If a legacy Beijing host no longer accepts the account, update the base URL from the provider console.
+1 -1
View File
@@ -44,7 +44,7 @@ Earth now supports both a **Web browser entry** and a **native Electron desktop
- **Runtime endpoint injection**: Preload injects synchronous `window.__PLANET_RUNTIME_CONFIG__` (`backendUrl`, `adminUrl`, `wsUrl`, `motionWsUrl`, `localMediaPipeBaseUrl`, `isElectron`) and `window.planetDesktop`. `realtime.js`, `motion-control.js`, and `motion-browser-provider.js` consume those endpoints and load bundled MediaPipe assets locally first. - **Runtime endpoint injection**: Preload injects synchronous `window.__PLANET_RUNTIME_CONFIG__` (`backendUrl`, `adminUrl`, `wsUrl`, `motionWsUrl`, `localMediaPipeBaseUrl`, `isElectron`) and `window.planetDesktop`. `realtime.js`, `motion-control.js`, and `motion-browser-provider.js` consume those endpoints and load bundled MediaPipe assets locally first.
- **Cross-process live synchronization**: Because Electron Earth runs outside the Admin origin, backend API mutations for compute comparison settings, brand config, and about info push `earth_updates` reload hints (`compute_configuration`, `earth_brand`, `earth_about`) over `/ws` alongside same-origin `BroadcastChannel` notices. - **Cross-process live synchronization**: Because Electron Earth runs outside the Admin origin, backend API mutations for compute comparison settings, brand config, and about info push `earth_updates` reload hints (`compute_configuration`, `earth_brand`, `earth_about`) over `/ws` alongside same-origin `BroadcastChannel` notices.
- **Native window controls and frame pacing**: Desktop uses a native dark OS frame so window buttons never overlap `#media-panel`, lowers minimum window dimensions to `360×480` so manual narrowing enters Earth's mobile layout (`<= 820px`), and adds one-click **View → Toggle Portrait & Landscape** (`CmdOrCtrl+Shift+M`) in the native `Alt` menu bar alongside saved portrait/landscape bounds; it also locks Chromium page zoom (`setVisualZoomLevelLimits(1, 1)`) while forwarding pinch (`wheel + ctrlKey`) and `CmdOrCtrl + =/-/0` to 3D globe zoom, and stabilizes frame pacing by coalescing HUD glow pointer moves and globe hover raycasting into `requestAnimationFrame`, caching `DOMRect` via `ResizeObserver`, clamping `deltaTime` (`<= 50 ms`), and pausing renders on minimize via `planet-desktop:visibility`. - **Native window controls and frame pacing**: Desktop uses a native dark OS frame so window buttons never overlap `#media-panel`, lowers minimum window dimensions to `360×480` so manual narrowing enters Earth's mobile layout (`<= 820px`), and adds one-click **View → Toggle Portrait & Landscape** (`CmdOrCtrl+Shift+M`) in the native `Alt` menu bar alongside saved portrait/landscape bounds; it also locks Chromium page zoom (`setVisualZoomLevelLimits(1, 1)`) while forwarding pinch (`wheel + ctrlKey`) and `CmdOrCtrl + =/-/0` to 3D globe zoom, and stabilizes frame pacing by coalescing HUD glow pointer moves and globe hover raycasting into `requestAnimationFrame`, caching `DOMRect` via `ResizeObserver`, clamping `deltaTime` (`<= 50 ms`), and pausing renders on minimize via `planet-desktop:visibility`.
- **Switchable desktop splash screen and zero-flash readiness gate**: [Desktop splash controller](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) mounts via a `document` `MutationObserver` in preload the instant `<html>` is created and synchronously paints frame 1, while [Window show gate](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) waits for both `ready-to-show` and `planet:splash-first-paint` before showing the OS window so raw HTML never flashes; meanwhile `frontend/public/earth/js/main.js` and `controls.js` emit non-visual `earth:startup-progress` and `earth:startup-ready` lifecycle events (with zero Web UI/DOM impact) only after startup layers, `applyDeferredLayerVisibilitySettings` user-preference layers, stats/media readiness, and rendered 3D GPU frames settle before revealing the Earth viewport. It provides three real-coastline 3D Canvas themes (`singularity`, `constellation`, `horizon`, plus `off`), displays the transparent ZJU seal (`zju-emblem.png`) and `PRESENTED BY 临空智能媒体研究院 / Institute of Intelligent Media` lockup, and is controllable via splash pills, `Planet Earth → Splash Screen`, `CmdOrCtrl+Shift+S`, or `--splash-theme`. - **Switchable desktop splash screen and zero-flash readiness gate**: [Desktop splash controller](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) mounts via a `document` `MutationObserver` in preload the instant `<html>` is created and synchronously paints frame 1, while [Window show gate](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) waits for both `ready-to-show` and `planet:splash-first-paint` before showing the OS window so raw HTML never flashes; meanwhile `frontend/public/earth/js/main.js` and `controls.js` emit non-visual `earth:startup-progress` and `earth:startup-ready` lifecycle events (with zero Web UI/DOM impact) only after startup layers, `applyDeferredLayerVisibilitySettings` user-preference layers, stats/media readiness, and rendered 3D GPU frames settle before revealing the Earth viewport. It provides three real-coastline 3D Canvas themes (`singularity`, `constellation`, `horizon`, plus `off`), displays the transparent ZJU seal (`zju-emblem.png`) and `PRESENTED BY 临空智能媒体研究院 / Intelligent Media Institute` lockup, and is controllable via splash pills, `Planet Earth → Splash Screen`, `CmdOrCtrl+Shift+S`, or `--splash-theme`.
Earth frontend is essentially a single shared visualization core under `public/earth` powering both Web and Desktop. Earth frontend is essentially a single shared visualization core under `public/earth` powering both Web and Desktop.
+38
View File
@@ -473,6 +473,44 @@ uv run pytest backend/tests/test_otp_service.py
5. After deployment, open Earth, enable "Border Lines", and inspect China's southeast coast, Taiwan, Hainan, the South China Sea, Zangnan, Kosovo, and Gaza for hover behavior and boundary policy. 5. After deployment, open Earth, enable "Border Lines", and inspect China's southeast coast, Taiwan, Hainan, the South China Sea, Zangnan, Kosovo, and Gaza for hover behavior and boundary policy.
6. If no high-precision manifest/PMTiles exists locally, Earth uses the bundled `frontend/public/earth/data/countries-admin0.min.geojson` fallback. If high-precision assets exist but tile requests fail, troubleshoot PMTiles range requests, manifest provider, Nginx `.pmtiles` static serving, and sha256 consistency. 6. If no high-precision manifest/PMTiles exists locally, Earth uses the bundled `frontend/public/earth/data/countries-admin0.min.geojson` fallback. If high-precision assets exist but tile requests fail, troubleshoot PMTiles range requests, manifest provider, Nginx `.pmtiles` static serving, and sha256 consistency.
## Publish locally and deploy production releases automatically
Push the stable version tag to Gitea. On a new publishing workstation, sign in to the dedicated Docker configuration with a Gitea token scoped to `write:package`. Git release credentials and the package writer credential are stored separately.
```bash
docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.rclaw.top --username linkong
```
Run the following command from the tagged commit.
```bash
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
The publisher builds Linux amd64 images for `admin`, `backend`, and `aiprovider` from the tag, then verifies their revisions and digests in Gitea. Admin uses the lightweight build target. Desktop packages are built from the same commit by default. Pass `--assets-dir client/release` to reuse complete packages and a hotfix built for that tag. Repeat the same command after an interrupted upload to reuse the original build and verified attachments. The workstation can go offline once publication succeeds.
The production host checks the latest stable Gitea Release approximately every two minutes using `planet-release-deploy.timer`. Once all three images and the hotfix checksum are available, it pulls the images by digest, backs up PostgreSQL, updates AI Provider, backend, and Admin in order, verifies their endpoints, publishes the Earth hotfix, and downloads it to verify its checksum. The host retains its Compose configuration, memory limits, and data volumes. Apply the release-specific infrastructure migration first when a release requires new mounts, services, or incompatible database changes.
A failed rollout restores the previous application images and hotfix manifest while preserving database writes. An interrupted rollout resumes recovery on the next check. A failed version waits for an explicit retry or a newer release. The most recent pre-change database backups and version records are under `/var/lib/planet-release-deploy/last-success/` and `last-failed/`. Retry after resolving the underlying error.
```bash
systemctl list-timers planet-release-deploy.timer
journalctl -u planet-release-deploy.service -n 40
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry
```
To provision a replacement host, restore `/etc/planet/deploy.env`, `/opt/planet/current`, and the production volumes. Install the controller from a trusted checkout and verify the current deployment before enabling its timer.
```bash
sudo install -d /usr/local/lib/planet-release
sudo install -m 0644 scripts/{production_deploy,production_registry,release_publish}.py /usr/local/lib/planet-release/
sudo install -m 0644 deploy/systemd/planet-release-deploy.{service,timer} /etc/systemd/system/
sudo systemctl daemon-reload
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo systemctl enable --now planet-release-deploy.timer
```
## Related Docs ## Related Docs
- [planet.sh Startup Mechanism](/home/ray/dev/linkong/planet/docs/technical/en/ops-planet-sh-startup.md) - [planet.sh Startup Mechanism](/home/ray/dev/linkong/planet/docs/technical/en/ops-planet-sh-startup.md)
+6 -5
View File
@@ -96,14 +96,15 @@ AI 配置页使用的接口:
- `POST /api/v1/settings/integrations/ai-provider/connect` - `POST /api/v1/settings/integrations/ai-provider/connect`
- `GET /api/v1/settings/integrations/ai-provider/secrets` - `GET /api/v1/settings/integrations/ai-provider/secrets`
- `GET /api/v1/settings/integrations/ai-provider/presets` - `GET /api/v1/settings/integrations/ai-provider/presets`
- `POST /api/v1/settings/integrations/ai-provider/presets/refresh-public`
- `POST /api/v1/settings/integrations/ai-provider/presets/{provider}/refresh` - `POST /api/v1/settings/integrations/ai-provider/presets/{provider}/refresh`
- `GET /api/v1/settings/ai-prompts` - `GET /api/v1/settings/ai-prompts`
- `PUT /api/v1/settings/ai-prompts/{task_key}` - `PUT /api/v1/settings/ai-prompts/{task_key}`
- `POST /api/v1/settings/ai-prompts/{task_key}/reset` - `POST /api/v1/settings/ai-prompts/{task_key}/reset`
这些接口都需要用户登录。`secrets` 接口只用于配置页点击显示 key/token 时取回明文,隐藏时前端恢复为脱敏预览。 这些接口都需要用户登录;其中模型目录刷新接口需要管理员权限。`secrets` 接口只用于配置页点击显示 key/token 时取回明文,隐藏时前端恢复为脱敏预览。
模型目录刷新和轻量连通性测试共用 `backend/app/services/llm_model_catalog.py`,直接请求当前供应商的模型接口,不再依赖 models.dev。使用当前表单草稿中的基础地址、协议和凭证;不传草稿时读取已保存配置。国内、国际和自定义网关地址保持各自的地域与路径。缺少必需凭证时返回 400 并提示配置 API Key;上游超时、鉴权或响应错误返回安全提示,并保留上次目录。 模型目录刷新和轻量连通性测试共用 `backend/app/services/llm_model_catalog.py`,直接请求当前供应商的模型接口,不再依赖 models.dev。使用当前表单草稿中的基础地址、协议和凭证;不传草稿时读取已保存配置。国内、国际和自定义网关地址保持各自的地域与路径。对于官方公开目录(`openrouter.ai`、`opencode.ai`)以及本地 Ollama,刷新模型列表不需要也不发送 API Key,避免表单或库中残留的无效/过期凭证阻断公开目录刷新;若将这些供应商改配为自定义私有中转地址,则仍按私有网关校验并附带凭证。轻量连通性测试继续按配置附带凭证校验(Ollama 的 `ollama-generate` 与 `openai-completions` 均免 Key)。缺少必需凭证、基础地址非法或协议不支持时返回 400;上游超时、鉴权或响应错误返回 502 安全提示,并保留上次目录。`POST /api/v1/settings/integrations/ai-provider/presets/refresh-public` 可批量刷新所有当前免凭证预设并分别落库,单项失败不影响其余预设且保留原有目录。
成功目录和 `refreshed_at` 按供应商保存到 `system_settings` 的 `llm_provider_preset:<provider>` 分类。该动态分类使用对应供应商预设作为默认值,提交前校验分类,避免已提交却返回失败。列表优先返回已保存目录,未刷新过的供应商显示内置建议。刷新不修改 `external_integrations` 的当前模型、协议、地址或凭证;页面保留草稿,目录加载失败时保留已显示模型并明确提示失败。 成功目录和 `refreshed_at` 按供应商保存到 `system_settings` 的 `llm_provider_preset:<provider>` 分类。该动态分类使用对应供应商预设作为默认值,提交前校验分类,避免已提交却返回失败。列表优先返回已保存目录,未刷新过的供应商显示内置建议。刷新不修改 `external_integrations` 的当前模型、协议、地址或凭证;页面保留草稿,目录加载失败时保留已显示模型并明确提示失败。
@@ -119,9 +120,9 @@ AI 配置页使用的接口:
| [DeepSeek](https://api-docs.deepseek.com/api/list-models) | `https://api.deepseek.com/v1/models` | Bearer;`data[].id` | | [DeepSeek](https://api-docs.deepseek.com/api/list-models) | `https://api.deepseek.com/v1/models` | Bearer;`data[].id` |
| [阿里百炼](https://help.aliyun.com/zh/model-studio/list-models) | 同地域主机的 `/api/v1/models` | Bearer;`output.models[].model`;按 `page_no/page_size/output.total` 翻页,筛选 `capabilities=TG` | | [阿里百炼](https://help.aliyun.com/zh/model-studio/list-models) | 同地域主机的 `/api/v1/models` | Bearer;`output.models[].model`;按 `page_no/page_size/output.total` 翻页,筛选 `capabilities=TG` |
| [Moonshot / Kimi](https://platform.kimi.ai/docs/api/list-models) | `https://api.moonshot.ai/v1/models`;国内站使用 `api.moonshot.cn` | Bearer;`data[].id` | | [Moonshot / Kimi](https://platform.kimi.ai/docs/api/list-models) | `https://api.moonshot.ai/v1/models`;国内站使用 `api.moonshot.cn` | Bearer;`data[].id` |
| [OpenRouter](https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties) | `https://openrouter.ai/api/v1/models` | 支持公共目录;有凭证时附带 Bearer;`data[].id` | | [OpenRouter](https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties) | `https://openrouter.ai/api/v1/models` | 官方公开目录刷新不附带 Key;自定义网关与连通性检查附带 Bearer;`data[].id` |
| [OpenCode Go](https://opencode.ai/docs/go/#models) | `https://opencode.ai/zen/go/v1/models` | 支持公共目录;有凭证时附带 Bearer;`data[].id` | | [OpenCode Go](https://opencode.ai/docs/go/#models) | `https://opencode.ai/zen/go/v1/models` | 官方公开目录刷新不附带 Key;自定义网关与连通性检查附带 Bearer;`data[].id` |
| [Ollama](https://docs.ollama.com/api/tags) | 本机或配置服务器的 `/api/tags` | 本地无需 Key;`models[].model/name`;空目录表示尚未安装模型 | | [Ollama](https://docs.ollama.com/api/tags) | 本机或配置服务器的 `/api/tags`(或 `openai-completions` 下的 `/v1/models`) | 本地无需 Key;`models[].model/name` 或 `data[].id`;空目录表示尚未安装模型 |
百炼的北京、东京、法兰克福、弗吉尼亚新接口要求实际业务空间主机,例如 `<WorkspaceId>.cn-beijing.maas.aliyuncs.com`;新加坡使用 `dashscope-intl.aliyuncs.com`,香港使用 `cn-hongkong.dashscope.aliyuncs.com`。系统只替换目录路径,不猜测业务空间或跨地域切换凭证。旧北京域名若不再接受账号凭证,应按控制台给出的业务空间地址更新基础地址。 百炼的北京、东京、法兰克福、弗吉尼亚新接口要求实际业务空间主机,例如 `<WorkspaceId>.cn-beijing.maas.aliyuncs.com`;新加坡使用 `dashscope-intl.aliyuncs.com`,香港使用 `cn-hongkong.dashscope.aliyuncs.com`。系统只替换目录路径,不猜测业务空间或跨地域切换凭证。旧北京域名若不再接受账号凭证,应按控制台给出的业务空间地址更新基础地址。
+1 -1
View File
@@ -42,7 +42,7 @@ Earth 现同时支持**Web 浏览入口**与**原生 Electron 桌面客户端入
- **运行时端点注入**:桌面预加载脚本暴露同步 `window.__PLANET_RUNTIME_CONFIG__`(`backendUrl`、`adminUrl`、`wsUrl`、`motionWsUrl`、`localMediaPipeBaseUrl`、`isElectron`)及受控 `window.planetDesktop` 桥接,`realtime.js`、`motion-control.js` 与 `motion-browser-provider.js` 自动读取该配置并优先加载本地 MediaPipe WASM。 - **运行时端点注入**:桌面预加载脚本暴露同步 `window.__PLANET_RUNTIME_CONFIG__`(`backendUrl`、`adminUrl`、`wsUrl`、`motionWsUrl`、`localMediaPipeBaseUrl`、`isElectron`)及受控 `window.planetDesktop` 桥接,`realtime.js`、`motion-control.js` 与 `motion-browser-provider.js` 自动读取该配置并优先加载本地 MediaPipe WASM。
- **跨进程实时同步**:由于 Electron 桌面端与 `planet_admin` 容器不在同一浏览器源,后台对算力配置、Earth 品牌信息及关于信息的修改除广播 `BroadcastChannel` 外,同时经后端 WebSocket 推送 `earth_updates`(`compute_configuration` / `earth_brand` / `earth_about`),使桌面端与浏览器端同步刷新。 - **跨进程实时同步**:由于 Electron 桌面端与 `planet_admin` 容器不在同一浏览器源,后台对算力配置、Earth 品牌信息及关于信息的修改除广播 `BroadcastChannel` 外,同时经后端 WebSocket 推送 `earth_updates`(`compute_configuration` / `earth_brand` / `earth_about`),使桌面端与浏览器端同步刷新。
- **原生窗口与帧率稳定**:桌面端使用原生暗色标题栏避免遮挡右上角 `#media-panel`,窗口最小尺寸放宽至 `360×480` 以支持手动拖窄进入移动端布局(`<= 820px`),并可通过 `Alt` 菜单栏 **视图 / View → 切换横竖屏 / Toggle Portrait & Landscape**(或 `CmdOrCtrl+Shift+M`)一键切换横竖屏比例;同时禁用 Chromium 页面缩放并将触控板捏合(`wheel + ctrlKey`)及 `CmdOrCtrl + =/-/0` 映射至 3D 视角缩放;`controls.js` 对液态玻璃光斑响应、`frame-stats.js` 布局刷新与 `main.js` 地球悬停拾取采用 `ResizeObserver` + `requestAnimationFrame` 合帧并限制 `deltaTime` 尖峰,窗口最小化时通过 `planet-desktop:visibility` 暂停空转渲染。 - **原生窗口与帧率稳定**:桌面端使用原生暗色标题栏避免遮挡右上角 `#media-panel`,窗口最小尺寸放宽至 `360×480` 以支持手动拖窄进入移动端布局(`<= 820px`),并可通过 `Alt` 菜单栏 **视图 / View → 切换横竖屏 / Toggle Portrait & Landscape**(或 `CmdOrCtrl+Shift+M`)一键切换横竖屏比例;同时禁用 Chromium 页面缩放并将触控板捏合(`wheel + ctrlKey`)及 `CmdOrCtrl + =/-/0` 映射至 3D 视角缩放;`controls.js` 对液态玻璃光斑响应、`frame-stats.js` 布局刷新与 `main.js` 地球悬停拾取采用 `ResizeObserver` + `requestAnimationFrame` 合帧并限制 `deltaTime` 尖峰,窗口最小化时通过 `planet-desktop:visibility` 暂停空转渲染。
- **多方案桌面端启动画面与无闪烁就绪门控**:[桌面端启动画面控制器](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) 通过预加载脚本里的 `document` `MutationObserver` 在解析出 `<html>` 的第一时间挂载隔离 Shadow DOM 蒙层并同步绘制首帧,[窗口展示门控](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) 同时等待 `ready-to-show` 与 `planet:splash-first-paint` 后才显示窗口,彻底消除启动瞬间的原始网页闪屏;同时 `frontend/public/earth/js/main.js` 与 `controls.js` 在保持 Web 端视觉与交互完全一致的前提下,通过非可视化的 `earth:startup-progress` / `earth:startup-ready` 生命周期事件在完成 `applyDeferredLayerVisibilitySettings` 用户偏好图层恢复、统计/新闻直播初始化及首帧 3D GPU 渲染后再触发星核/星轨/破晓退场;内置三套 3D Canvas 动态启动方案(`singularity` / `constellation` / `horizon`),展示透明浙大校徽与 `PRESENTED BY 临空智能媒体研究院 / Institute of Intelligent Media` 署名,可通过启动页切换按钮、`Alt → Planet Earth → 启动画面方案`、`CmdOrCtrl+Shift+S` 重播及 `--splash-theme` 切换。 - **多方案桌面端启动画面与无闪烁就绪门控**:[桌面端启动画面控制器](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) 通过预加载脚本里的 `document` `MutationObserver` 在解析出 `<html>` 的第一时间挂载隔离 Shadow DOM 蒙层并同步绘制首帧,[窗口展示门控](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) 同时等待 `ready-to-show` 与 `planet:splash-first-paint` 后才显示窗口,彻底消除启动瞬间的原始网页闪屏;同时 `frontend/public/earth/js/main.js` 与 `controls.js` 在保持 Web 端视觉与交互完全一致的前提下,通过非可视化的 `earth:startup-progress` / `earth:startup-ready` 生命周期事件在完成 `applyDeferredLayerVisibilitySettings` 用户偏好图层恢复、统计/新闻直播初始化及首帧 3D GPU 渲染后再触发星核/星轨/破晓退场;内置三套 3D Canvas 动态启动方案(`singularity` / `constellation` / `horizon`),展示透明浙大校徽与 `PRESENTED BY 临空智能媒体研究院 / Intelligent Media Institute` 署名,可通过启动页切换按钮、`Alt → Planet Earth → 启动画面方案`、`CmdOrCtrl+Shift+S` 重播及 `--splash-theme` 切换。
所以 Earth 前端本质上是 `public/earth` 下的一套独立可视化内核,同时服务 Web 与桌面端。 所以 Earth 前端本质上是 `public/earth` 下的一套独立可视化内核,同时服务 Web 与桌面端。
+38
View File
@@ -473,6 +473,44 @@ uv run pytest backend/tests/test_otp_service.py
5. 部署后打开智能星球,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover 和边界口径。 5. 部署后打开智能星球,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover 和边界口径。
6. 如果本地没有高精 manifest/PMTiles,Earth 会使用 `frontend/public/earth/data/countries-admin0.min.geojson` 低精度 fallback;如果高精产物存在但瓦片请求失败,按 PMTiles range 请求、manifest provider、Nginx `.pmtiles` 静态返回和 sha256 一致性排查。 6. 如果本地没有高精 manifest/PMTiles,Earth 会使用 `frontend/public/earth/data/countries-admin0.min.geojson` 低精度 fallback;如果高精产物存在但瓦片请求失败,按 PMTiles range 请求、manifest provider、Nginx `.pmtiles` 静态返回和 sha256 一致性排查。
## 在本机发版,生产机自动部署
把正式版本标签推送到 Gitea 后,在发版机的 Planet 仓库执行以下命令。首次配置发版机时,使用具有 `write:package` 权限的 Gitea 令牌登录专用 Docker 配置目录。Git 发布凭据与镜像推送凭据分别保存。
```bash
docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.rclaw.top --username linkong
```
日常发版时在已打标签的提交上执行以下命令。
```bash
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
发布器从标签提交构建 Linux amd64 的 `admin`、`backend`、`aiprovider` 镜像,并核验仓库中的提交标签与摘要。Admin 使用轻量构建目标。默认从同一提交打包桌面客户端。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。
生产机的 `planet-release-deploy.timer` 约每两分钟读取 Gitea 最新正式 Release。新版本的三个镜像和热更新校验文件齐全后,服务按不可变摘要拉取镜像,备份 PostgreSQL,依次更新 AI Provider、后端和 Admin,再验证接口、发布并回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。
上线失败时,服务恢复上一版的镜像摘要和热更新清单,保留数据库里的业务写入。事务记录在重启后仍可恢复。失败的版本会暂停自动重试,较新的正式版仍可上线。`/var/lib/planet-release-deploy/last-success/` 和 `last-failed/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。
```bash
systemctl list-timers planet-release-deploy.timer
journalctl -u planet-release-deploy.service -n 40
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry
```
替换部署主机时,从受信任的运维检出中安装控制程序和定时器。先恢复 `/etc/planet/deploy.env`、`/opt/planet/current` 及当前生产数据卷,再校验当前版本并启用定时器。
```bash
sudo install -d /usr/local/lib/planet-release
sudo install -m 0644 scripts/{production_deploy,production_registry,release_publish}.py /usr/local/lib/planet-release/
sudo install -m 0644 deploy/systemd/planet-release-deploy.{service,timer} /etc/systemd/system/
sudo systemctl daemon-reload
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo systemctl enable --now planet-release-deploy.timer
```
## 相关文档 ## 相关文档
- [planet.sh 启动机制](/home/ray/dev/linkong/planet/docs/technical/zh/ops-planet-sh-startup.md) - [planet.sh 启动机制](/home/ray/dev/linkong/planet/docs/technical/zh/ops-planet-sh-startup.md)
+5 -1
View File
@@ -16,12 +16,16 @@
## Current Version ## Current Version
- `main` 当前主线历史推导到:`0.16.5` - `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.78.0` - `dev` 当前开发分支历史推导到:`0.80.0`
## Timeline ## Timeline
| Version | Type | Branch | Commit | Summary | | Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| `0.80.0` | feature | `dev` | `v0.80.0` | Earth AI 工作台支持流式多轮对话和本地会话,新增单摄手势控制与公共模型目录批量刷新 |
| `0.79.2` | improvement | `dev` | `v0.79.2` | 卫星目录支持紧凑传输、本地缓存和后台校验,改进桌面客户端启动时的窗口尺寸恢复 |
| `0.79.1` | improvement | `dev` | `v0.79.1` | Windows 根据显存与帧率自动切换显卡,保留 45 秒切换冷却与窗口状态,统一 IMI 英文名称 |
| `0.79.0` | feature | `dev` | `v0.79.0` | 破晓-星核统一启动动效、Phase 1 L1 热更新体系与 Windows GPU/WebGL 恢复加固 |
| `0.78.0` | feature | `dev` | `v0.78.0` | 全局单份采集策略、短期船舶航迹、精简生产部署和桌面协议注册 | | `0.78.0` | feature | `dev` | `v0.78.0` | 全局单份采集策略、短期船舶航迹、精简生产部署和桌面协议注册 |
| `0.77.0` | feature | `dev` | `v0.77.0` | 新增原生 Electron Earth 桌面客户端(多方案 3D 启动页/横竖屏/离线协议/Gitea 自动发布)、轻量 Admin 独立容器、全球综合态势工作台与算力对比增强 | | `0.77.0` | feature | `dev` | `v0.77.0` | 新增原生 Electron Earth 桌面客户端(多方案 3D 启动页/横竖屏/离线协议/Gitea 自动发布)、轻量 Admin 独立容器、全球综合态势工作台与算力对比增强 |
| `0.76.20` | improvement | `dev` | `v0.76.20` | 统一 Earth 卡片布局仲裁与连接线,修复悬停展开和固定深度,并优化卫星分批查询与连接测试反馈 | | `0.76.20` | improvement | `dev` | `v0.76.20` | 统一 Earth 卡片布局仲裁与连接线,修复悬停展开和固定深度,并优化卫星分批查询与连接测试反馈 |
+3
View File
@@ -42,6 +42,7 @@
"zustand": "^4.4.7", "zustand": "^4.4.7",
}, },
"devDependencies": { "devDependencies": {
"@mediapipe/tasks-vision": "0.10.35",
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"@types/react": "^18.2.45", "@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18", "@types/react-dom": "^18.2.18",
@@ -172,6 +173,8 @@
"@mapbox/vector-tile": ["@mapbox/vector-tile@2.0.4", "", { "dependencies": { "@mapbox/point-geometry": "~1.1.0", "@types/geojson": "^7946.0.16", "pbf": "^4.0.1" } }, "sha512-AkOLcbgGTdXScosBWwmmD7cDlvOjkg/DetGva26pIRiZPdeJYjYKarIlb4uxVzi6bwHO6EWH82eZ5Nuv4T5DUg=="], "@mapbox/vector-tile": ["@mapbox/vector-tile@2.0.4", "", { "dependencies": { "@mapbox/point-geometry": "~1.1.0", "@types/geojson": "^7946.0.16", "pbf": "^4.0.1" } }, "sha512-AkOLcbgGTdXScosBWwmmD7cDlvOjkg/DetGva26pIRiZPdeJYjYKarIlb4uxVzi6bwHO6EWH82eZ5Nuv4T5DUg=="],
"@mediapipe/tasks-vision": ["@mediapipe/tasks-vision@0.10.35", "", {}, "sha512-HOvadwVRE6JC+45nyYhmnywnr5h/J8KZvOeUNVOG9q/0875pZgItznFB9bRTvLc264YSJqiZ1NsIpCStJw/egg=="],
"@mermaid-js/parser": ["@mermaid-js/parser@1.1.1", "", { "dependencies": { "@chevrotain/types": "~11.1.1" } }, "sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw=="], "@mermaid-js/parser": ["@mermaid-js/parser@1.1.1", "", { "dependencies": { "@chevrotain/types": "~11.1.1" } }, "sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw=="],
"@radix-ui/number": ["@radix-ui/number@1.1.1", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="], "@radix-ui/number": ["@radix-ui/number@1.1.1", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],
+15 -1
View File
@@ -10,7 +10,11 @@ server {
add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always;
gzip on; gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml; gzip_proxied any;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_types text/plain text/css application/javascript application/json application/wasm image/svg+xml;
location = /health { location = /health {
add_header Content-Type text/plain; add_header Content-Type text/plain;
@@ -104,6 +108,16 @@ server {
try_files $uri =404; try_files $uri =404;
} }
location /earth/vendor/mediapipe/ {
types {
text/javascript mjs js;
application/wasm wasm;
application/octet-stream task;
}
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri =404;
}
location / { location / {
try_files $uri $uri/ /index.html; try_files $uri $uri/ /index.html;
} }
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "planet-frontend", "name": "planet-frontend",
"version": "0.78.0", "version": "0.80.0",
"private": true, "private": true,
"packageManager": "bun@1", "packageManager": "bun@1",
"dependencies": { "dependencies": {
@@ -41,6 +41,7 @@
"zustand": "^4.4.7" "zustand": "^4.4.7"
}, },
"devDependencies": { "devDependencies": {
"@mediapipe/tasks-vision": "0.10.35",
"@types/react": "^18.2.45", "@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18", "@types/react-dom": "^18.2.18",
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
+2 -2
View File
@@ -10,7 +10,7 @@
.card-image-layer.is-loaded { animation:card-image-appear 220ms ease both; } .card-image-layer.is-loaded { animation:card-image-appear 220ms ease both; }
.card-image-data { position:relative; z-index:1; } .card-image-data { position:relative; z-index:1; }
.card-image-body:has(.card-image-layer:not([hidden])) .card-image-data { text-shadow:0 1px 3px #020812; } .card-image-body:has(.card-image-layer:not([hidden])) .card-image-data { text-shadow:0 1px 3px #020812; }
.card-image-source { display:inline-flex; align-items:center; justify-content:center; flex-shrink:0; text-decoration:none; color:inherit; } .card-image-source { display:inline-flex; align-items:center; justify-content:center; flex-shrink:0; text-decoration:none; }
.card-image-source .material-symbols-rounded { font-size:calc(16px * var(--hud-scale,1)); } .card-image-source.hud-panel__action .material-symbols-rounded { font-size:var(--hud-action-icon-size,calc(16px * var(--hud-scale,1))); font-variation-settings:'FILL' 0,'wght' 400,'GRAD' 0,'opsz' 20; }
@keyframes card-image-appear { from { opacity:0; } to { opacity:1; } } @keyframes card-image-appear { from { opacity:0; } to { opacity:1; } }
@media (prefers-reduced-motion:reduce) { .card-image-layer.is-loaded { animation:none; opacity:1; } } @media (prefers-reduced-motion:reduce) { .card-image-layer.is-loaded { animation:none; opacity:1; } }
+613 -53
View File
@@ -1475,6 +1475,7 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
.situational-copilot.hud-panel--collapsed .situational-copilot__context, .situational-copilot.hud-panel--collapsed .situational-copilot__context,
.situational-copilot.hud-panel--collapsed .workbench-pinned-tabs--docked, .situational-copilot.hud-panel--collapsed .workbench-pinned-tabs--docked,
.situational-copilot.hud-panel--collapsed .situational-copilot__stage,
.situational-copilot.hud-panel--collapsed .situational-copilot__messages, .situational-copilot.hud-panel--collapsed .situational-copilot__messages,
.situational-copilot.hud-panel--collapsed .situational-copilot__suggestions, .situational-copilot.hud-panel--collapsed .situational-copilot__suggestions,
.situational-copilot.hud-panel--collapsed .situational-copilot__form { .situational-copilot.hud-panel--collapsed .situational-copilot__form {
@@ -1485,6 +1486,15 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
flex: 0 0 auto; flex: 0 0 auto;
} }
.situational-copilot .hud-panel__actions {
gap: calc(2px * var(--hud-scale));
}
.situational-copilot .hud-panel__action {
--hud-action-padding: calc(5px * var(--hud-scale));
--hud-action-icon-size: calc(15px * var(--hud-scale));
}
.situational-copilot__pin-tag { .situational-copilot__pin-tag {
flex: 0 0 auto; flex: 0 0 auto;
padding: 1px calc(6px * var(--hud-scale)); padding: 1px calc(6px * var(--hud-scale));
@@ -1548,6 +1558,426 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
} }
.copilot-compacted-chip {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: calc(3px * var(--hud-scale));
height: calc(20px * var(--hud-scale));
padding: 0 calc(6px * var(--hud-scale));
border-radius: calc(4px * var(--hud-scale));
border: 1px solid rgba(145, 195, 255, 0.24);
background: rgba(120, 180, 255, 0.12);
color: var(--hud-accent-strong);
font: inherit;
font-size: calc(10px * var(--hud-scale));
font-weight: 500;
line-height: 1;
cursor: pointer;
}
.copilot-compacted-chip:hover {
border-color: rgba(164, 214, 255, 0.45);
background: rgba(120, 180, 255, 0.2);
}
.copilot-compacted-chip .material-symbols-rounded,
.copilot-compacted-chip__icon.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(12px * var(--hud-scale));
font-weight: 500;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0;
user-select: none;
pointer-events: none;
}
/* History & Memory Drawer inside .situational-copilot__stage */
.copilot-drawer {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
padding: calc(10px * var(--hud-scale)) calc(12px * var(--hud-scale));
gap: calc(8px * var(--hud-scale));
}
.copilot-drawer__bar {
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: calc(8px * var(--hud-scale));
}
.copilot-drawer__tabs {
display: inline-flex;
align-items: center;
gap: calc(4px * var(--hud-scale));
min-width: 0;
}
.copilot-drawer__tab {
display: inline-flex;
align-items: center;
gap: calc(5px * var(--hud-scale));
height: calc(24px * var(--hud-scale));
padding: 0 calc(9px * var(--hud-scale));
border-radius: calc(4px * var(--hud-scale));
border: 1px solid rgba(201, 225, 247, 0.14);
background: rgba(255, 255, 255, 0.03);
color: var(--hud-text-soft);
font: inherit;
font-size: calc(11px * var(--hud-scale));
font-weight: 500;
line-height: 1;
cursor: pointer;
}
.copilot-drawer__tab:hover {
border-color: rgba(147, 202, 255, 0.3);
color: var(--hud-text);
}
.copilot-drawer__tab.is-active {
border-color: rgba(147, 202, 255, 0.45);
background: rgba(120, 180, 255, 0.18);
color: #ffffff;
font-weight: 600;
}
.copilot-drawer__count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: calc(15px * var(--hud-scale));
height: calc(15px * var(--hud-scale));
padding: 0 calc(4px * var(--hud-scale));
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
font-size: calc(9.5px * var(--hud-scale));
font-weight: 600;
line-height: 1;
}
.copilot-drawer__back {
flex: 0 0 auto;
}
.copilot-drawer__list {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: calc(7px * var(--hud-scale));
padding-right: calc(2px * var(--hud-scale));
scrollbar-width: thin;
scrollbar-color: rgba(160, 186, 216, 0.32) transparent;
}
.copilot-drawer__empty,
.copilot-drawer__hint {
padding: calc(10px * var(--hud-scale));
border-radius: calc(6px * var(--hud-scale));
border: 1px dashed rgba(201, 225, 247, 0.16);
background: rgba(255, 255, 255, 0.02);
color: var(--hud-text-muted);
font-size: calc(11px * var(--hud-scale));
line-height: 1.48;
}
.copilot-history-item {
display: flex;
align-items: center;
gap: calc(6px * var(--hud-scale));
padding: calc(7px * var(--hud-scale)) calc(8px * var(--hud-scale));
border-radius: calc(6px * var(--hud-scale));
border: 1px solid rgba(201, 225, 247, 0.12);
background: rgba(255, 255, 255, 0.03);
transition: border-color 150ms ease, background 150ms ease;
}
.copilot-history-item:hover {
border-color: rgba(147, 202, 255, 0.3);
background: rgba(120, 180, 255, 0.08);
}
.copilot-history-item.is-active {
border-color: rgba(147, 202, 255, 0.44);
background: rgba(120, 180, 255, 0.14);
}
.copilot-history-item__main {
flex: 1 1 auto;
min-width: 0;
display: flex;
flex-direction: column;
gap: calc(3px * var(--hud-scale));
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.copilot-history-item__title {
color: var(--hud-text);
font-size: calc(11.6px * var(--hud-scale));
font-weight: 600;
line-height: 1.32;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.copilot-history-item__meta {
color: var(--hud-text-muted);
font-size: calc(10px * var(--hud-scale));
font-weight: 500;
line-height: 1.2;
}
.copilot-history-item__delete,
.copilot-memory-item__delete {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
justify-content: center;
width: calc(24px * var(--hud-scale));
height: calc(24px * var(--hud-scale));
padding: 0;
border-radius: calc(4px * var(--hud-scale));
border: 1px solid transparent;
background: transparent;
color: var(--hud-text-muted);
cursor: pointer;
}
.copilot-history-item__delete:hover,
.copilot-memory-item__delete:hover {
border-color: rgba(244, 63, 94, 0.35);
background: rgba(244, 63, 94, 0.14);
color: #fda4af;
}
.copilot-history-item__delete .material-symbols-rounded,
.copilot-memory-item__delete .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(14px * var(--hud-scale));
font-weight: 500;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0;
user-select: none;
pointer-events: none;
}
.copilot-memory-summary {
padding: calc(8px * var(--hud-scale)) calc(9px * var(--hud-scale));
border-radius: calc(6px * var(--hud-scale));
border: 1px solid rgba(145, 195, 255, 0.22);
background: rgba(120, 180, 255, 0.06);
display: flex;
flex-direction: column;
gap: calc(6px * var(--hud-scale));
}
.copilot-memory-summary__head {
display: flex;
align-items: center;
gap: calc(5px * var(--hud-scale));
color: var(--hud-accent-strong);
font-size: calc(11px * var(--hud-scale));
font-weight: 600;
line-height: 1.2;
}
.copilot-memory-summary__head .wb-mini-btn {
margin-left: auto;
}
.copilot-memory-summary__icon.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(14px * var(--hud-scale));
font-weight: 500;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0;
user-select: none;
pointer-events: none;
}
.copilot-memory-summary__body {
color: var(--hud-text-soft);
font-size: calc(11px * var(--hud-scale));
line-height: 1.48;
max-height: calc(130px * var(--hud-scale));
overflow-y: auto;
}
.copilot-memory-pins {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: calc(4px * var(--hud-scale));
padding: calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale));
border-radius: calc(5px * var(--hud-scale));
border: 1px solid rgba(201, 225, 247, 0.12);
background: rgba(255, 255, 255, 0.03);
color: var(--hud-text-soft);
font-size: calc(10.5px * var(--hud-scale));
}
.copilot-memory-pins__label {
color: var(--hud-accent-strong);
font-weight: 600;
}
.copilot-memory-form {
display: flex;
align-items: center;
gap: calc(6px * var(--hud-scale));
}
.copilot-memory-form__input {
flex: 1 1 auto;
min-width: 0;
height: calc(26px * var(--hud-scale));
padding: 0 calc(8px * var(--hud-scale));
border-radius: calc(4px * var(--hud-scale));
border: 1px solid rgba(201, 225, 247, 0.18);
background: rgba(10, 18, 30, 0.34);
color: var(--hud-text);
font: inherit;
font-size: calc(11px * var(--hud-scale));
outline: none;
}
.copilot-memory-form__input:focus {
border-color: rgba(147, 202, 255, 0.45);
}
.copilot-memory-form__add {
height: calc(26px * var(--hud-scale));
}
.copilot-memory-item {
display: flex;
align-items: center;
gap: calc(6px * var(--hud-scale));
padding: calc(6px * var(--hud-scale)) calc(8px * var(--hud-scale));
border-radius: calc(5px * var(--hud-scale));
border: 1px solid rgba(201, 225, 247, 0.12);
background: rgba(255, 255, 255, 0.03);
font-size: calc(11px * var(--hud-scale));
line-height: 1.4;
}
.copilot-memory-item__icon.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(13.5px * var(--hud-scale));
font-weight: 500;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
color: var(--hud-accent);
flex-shrink: 0;
user-select: none;
pointer-events: none;
}
.copilot-memory-item__text {
flex: 1 1 auto;
min-width: 0;
color: var(--hud-text);
word-break: break-word;
}
.situational-copilot__stage {
position: relative;
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.copilot-jump-latest {
position: absolute;
right: calc(16px * var(--hud-scale));
bottom: calc(10px * var(--hud-scale));
z-index: 4;
display: inline-flex;
align-items: center;
justify-content: center;
width: calc(28px * var(--hud-scale));
height: calc(28px * var(--hud-scale));
padding: 0;
border-radius: calc(6px * var(--hud-scale));
border: 1px solid rgba(147, 202, 255, 0.28);
background: rgba(18, 30, 48, 0.34);
backdrop-filter: blur(12px) saturate(140%);
-webkit-backdrop-filter: blur(12px) saturate(140%);
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255, 255, 255, 0.12);
color: var(--hud-text);
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease, color 150ms ease, transform 150ms ease;
}
.copilot-jump-latest[hidden] {
display: none;
}
.copilot-jump-latest:hover {
border-color: rgba(164, 214, 255, 0.52);
background: rgba(120, 180, 255, 0.24);
color: var(--hud-accent-strong);
transform: translateY(-1px);
}
.copilot-jump-latest:active {
transform: translateY(0);
}
.copilot-jump-latest .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(16px * var(--hud-scale));
font-weight: 500;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 500, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0;
user-select: none;
pointer-events: none;
}
.situational-copilot__messages { .situational-copilot__messages {
position: relative; position: relative;
flex: 1 1 auto; flex: 1 1 auto;
@@ -1774,9 +2204,44 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
.copilot-msg--assistant.is-error { .copilot-msg--assistant.is-error {
display: flex; display: flex;
align-items: center; align-items: center;
gap: calc(7px * var(--hud-scale)); gap: calc(8px * var(--hud-scale));
color: var(--hud-text-soft); color: var(--hud-text-soft);
font-size: calc(11.5px * var(--hud-scale)); font-size: calc(11.5px * var(--hud-scale));
font-weight: 500;
line-height: 1.42;
}
.copilot-status-text,
.copilot-error__text {
flex: 1 1 auto;
min-width: 0;
}
.copilot-msg--assistant.is-loading.is-retrying {
border-color: rgba(251, 191, 36, 0.28);
color: #fde68a;
}
.copilot-msg--assistant.is-loading.is-retrying .copilot-msg__pulse {
background: #fbbf24;
box-shadow: 0 0 8px rgba(251, 191, 36, 0.72);
}
.copilot-status-pill {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
height: calc(20px * var(--hud-scale));
padding: 0 calc(6px * var(--hud-scale));
border-radius: calc(4px * var(--hud-scale));
border: 1px solid rgba(251, 191, 36, 0.32);
background: rgba(251, 191, 36, 0.12);
color: #fcd34d;
font-size: calc(10px * var(--hud-scale));
font-weight: 600;
line-height: 1;
font-variant-numeric: tabular-nums;
white-space: nowrap;
} }
.copilot-msg--assistant.is-error { .copilot-msg--assistant.is-error {
@@ -1784,7 +2249,8 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
color: #fda4af; color: #fda4af;
} }
.copilot-msg--assistant.is-error .material-symbols-rounded { .copilot-msg--assistant.is-error .material-symbols-rounded,
.copilot-error__icon.material-symbols-rounded {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -1792,6 +2258,7 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
height: 1em; height: 1em;
overflow: hidden; overflow: hidden;
font-size: calc(15px * var(--hud-scale)); font-size: calc(15px * var(--hud-scale));
font-weight: 500;
line-height: 1; line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0; flex-shrink: 0;
@@ -1799,6 +2266,19 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
pointer-events: none; pointer-events: none;
} }
.copilot-error__retry {
flex: 0 0 auto;
margin-left: auto;
border-color: rgba(244, 63, 94, 0.36);
background: rgba(244, 63, 94, 0.14);
color: #fecdd3;
}
.copilot-error__retry:hover {
border-color: rgba(251, 113, 133, 0.56);
background: rgba(244, 63, 94, 0.24);
}
.copilot-msg__pulse { .copilot-msg__pulse {
width: calc(7px * var(--hud-scale)); width: calc(7px * var(--hud-scale));
height: calc(7px * var(--hud-scale)); height: calc(7px * var(--hud-scale));
@@ -1809,6 +2289,113 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
flex-shrink: 0; flex-shrink: 0;
} }
/* Thinking disclosure, streaming indicator, and model badge */
.copilot-thinking {
margin-bottom: calc(8px * var(--hud-scale));
border-radius: calc(7px * var(--hud-scale));
border: 1px solid rgba(145, 195, 255, 0.16);
background: rgba(120, 180, 255, 0.05);
overflow: hidden;
}
.copilot-thinking[data-active="true"] {
border-color: rgba(145, 195, 255, 0.3);
}
.copilot-thinking__toggle {
display: flex;
align-items: center;
gap: calc(6px * var(--hud-scale));
width: 100%;
padding: calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale));
border: 0;
background: transparent;
color: var(--hud-accent-strong);
font: inherit;
font-size: calc(10.8px * var(--hud-scale));
font-weight: 600;
cursor: pointer;
text-align: left;
}
.copilot-thinking__toggle:hover {
background: rgba(145, 195, 255, 0.08);
}
.copilot-thinking__toggle .material-symbols-rounded,
.copilot-thinking__icon.material-symbols-rounded,
.copilot-thinking__chevron.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(14px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0;
user-select: none;
pointer-events: none;
}
.copilot-thinking__chevron {
margin-left: auto;
}
.copilot-thinking__pulse {
width: calc(6px * var(--hud-scale));
height: calc(6px * var(--hud-scale));
border-radius: 50%;
background: var(--hud-accent);
animation: earthLoadingPulse 1.2s ease-in-out infinite;
flex-shrink: 0;
}
.copilot-thinking__body {
padding: calc(6px * var(--hud-scale)) calc(9px * var(--hud-scale)) calc(8px * var(--hud-scale));
border-top: 1px solid rgba(197, 220, 242, 0.08);
color: var(--hud-text-muted);
font-size: calc(11px * var(--hud-scale));
line-height: 1.5;
max-height: calc(190px * var(--hud-scale));
overflow: auto;
}
.copilot-streaming-wait {
display: flex;
align-items: center;
gap: calc(7px * var(--hud-scale));
color: var(--hud-text-soft);
font-size: calc(11px * var(--hud-scale));
padding: calc(3px * var(--hud-scale)) 0;
}
.copilot-stream-cursor {
display: inline-block;
width: calc(2px * var(--hud-scale));
height: 1em;
margin-left: calc(3px * var(--hud-scale));
vertical-align: -0.14em;
border-radius: 1px;
background: var(--hud-accent-strong);
animation: earthLoadingPulse 0.9s ease-in-out infinite;
}
.copilot-model-badge {
display: inline-flex;
align-items: center;
color: rgba(188, 212, 238, 0.58);
font-size: calc(10px * var(--hud-scale));
font-weight: 400;
line-height: 1.2;
white-space: nowrap;
}
.copilot-model-badge--fallback {
color: rgba(188, 212, 238, 0.48);
}
/* Rendered Markdown inside Copilot chat bubble */ /* Rendered Markdown inside Copilot chat bubble */
.situational-copilot__answer.copilot-md { .situational-copilot__answer.copilot-md {
padding: 0; padding: 0;
@@ -3516,9 +4103,9 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
/* Narrative Synthesis Disclosure & Turn Toolbar */ /* Narrative Synthesis Disclosure & Turn Toolbar */
.wb-narrative-details { .wb-narrative-details {
margin-top: calc(6px * var(--hud-scale)); margin: calc(2px * var(--hud-scale)) 0 calc(10px * var(--hud-scale));
padding-top: calc(5px * var(--hud-scale)); padding: calc(4px * var(--hud-scale)) 0 calc(8px * var(--hud-scale));
border-top: 1px solid rgba(201, 225, 247, 0.08); border-bottom: 1px solid rgba(201, 225, 247, 0.1);
} }
.wb-narrative-details > summary { .wb-narrative-details > summary {
@@ -3526,11 +4113,12 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
color: var(--hud-text-muted); color: var(--hud-text-muted);
font-size: calc(10.6px * var(--hud-scale)); font-size: calc(10.6px * var(--hud-scale));
font-weight: 600; font-weight: 600;
line-height: 1.4;
user-select: none; user-select: none;
} }
.wb-narrative-details[open] > summary { .wb-narrative-details[open] > summary {
margin-bottom: calc(5px * var(--hud-scale)); margin-bottom: calc(6px * var(--hud-scale));
color: var(--hud-accent-strong); color: var(--hud-accent-strong);
} }
@@ -3549,6 +4137,7 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
align-items: center; align-items: center;
gap: calc(4px * var(--hud-scale)); gap: calc(4px * var(--hud-scale));
height: calc(22px * var(--hud-scale)); height: calc(22px * var(--hud-scale));
box-sizing: border-box;
padding: 0 calc(7px * var(--hud-scale)); padding: 0 calc(7px * var(--hud-scale));
border: 1px solid rgba(145, 195, 255, 0.24); border: 1px solid rgba(145, 195, 255, 0.24);
border-radius: calc(4px * var(--hud-scale)); border-radius: calc(4px * var(--hud-scale));
@@ -3557,6 +4146,7 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
font: inherit; font: inherit;
font-size: calc(10.4px * var(--hud-scale)); font-size: calc(10.4px * var(--hud-scale));
font-weight: 600; font-weight: 600;
line-height: 1;
cursor: pointer; cursor: pointer;
} }
@@ -3574,16 +4164,32 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
height: 1em; height: 1em;
overflow: hidden; overflow: hidden;
font-size: calc(12.5px * var(--hud-scale)); font-size: calc(12.5px * var(--hud-scale));
font-weight: 500;
line-height: 1; line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-variation-settings: 'FILL' 0, 'wght' 500, 'GRAD' 0, 'opsz' 20;
user-select: none; user-select: none;
pointer-events: none; pointer-events: none;
} }
.wb-turn-meta { .wb-turn-meta {
margin-left: auto; margin-left: auto;
display: inline-flex;
align-items: center;
gap: calc(5px * var(--hud-scale));
height: calc(22px * var(--hud-scale));
color: var(--hud-text-muted); color: var(--hud-text-muted);
font-size: calc(10px * var(--hud-scale)); font-size: calc(10px * var(--hud-scale));
font-weight: 500;
line-height: 1;
}
.wb-turn-meta__sep,
.wb-turn-meta__rev {
display: inline-flex;
align-items: center;
height: 100%;
font-weight: 500;
line-height: 1;
} }
.wb-inline-pin-preview { .wb-inline-pin-preview {
@@ -3604,52 +4210,6 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
color: var(--hud-accent-strong); color: var(--hud-accent-strong);
} }
/* BGP Info Card Forensics Trigger */
.info-card-forensics-row {
margin-top: calc(8px * var(--hud-scale));
padding-top: calc(8px * var(--hud-scale));
border-top: 1px solid var(--hud-line);
}
.info-card-forensics-btn {
width: 100%;
display: inline-flex;
align-items: center;
justify-content: center;
gap: calc(5px * var(--hud-scale));
height: calc(28px * var(--hud-scale));
padding: 0 calc(10px * var(--hud-scale));
border: 1px solid rgba(145, 195, 255, 0.3);
border-radius: calc(5px * var(--hud-scale));
background: rgba(120, 180, 255, 0.14);
color: #eaf3ff;
font: inherit;
font-size: calc(11.4px * var(--hud-scale));
font-weight: 600;
cursor: pointer;
}
.info-card-forensics-btn:hover {
border-color: rgba(164, 214, 255, 0.5);
background: rgba(120, 180, 255, 0.24);
}
.info-card-forensics-btn .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(14px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
color: var(--hud-accent);
user-select: none;
pointer-events: none;
}
/* Mobile Situation Tab Workbench Launcher Chips */ /* Mobile Situation Tab Workbench Launcher Chips */
.earth-mobile-workbench-actions { .earth-mobile-workbench-actions {
display: flex; display: flex;
+15 -2
View File
@@ -241,14 +241,18 @@
.hud-panel-close { .hud-panel-close {
--hud-action-padding: calc(7px * var(--hud-scale)); --hud-action-padding: calc(7px * var(--hud-scale));
--hud-action-icon-size: calc(16px * var(--hud-scale)); --hud-action-icon-size: calc(16px * var(--hud-scale));
--hud-action-size: calc(var(--hud-action-icon-size) + (2 * var(--hud-action-padding)) + 2px);
box-sizing: border-box;
border: 1px solid transparent; border: 1px solid transparent;
border-radius: calc(4px * var(--hud-scale)); border-radius: calc(4px * var(--hud-scale));
background: transparent; background: transparent;
color: var(--hud-text-muted); color: var(--hud-text-muted);
padding: var(--hud-action-padding); padding: var(--hud-action-padding);
width: auto; width: auto;
height: auto; min-width: var(--hud-action-size);
min-width: 0; height: var(--hud-action-size);
line-height: 1;
flex-shrink: 0;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -264,9 +268,18 @@
.hud-panel__action .material-symbols-rounded, .hud-panel__action .material-symbols-rounded,
.hud-panel-close .material-symbols-rounded { .hud-panel-close .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: var(--hud-action-icon-size); font-size: var(--hud-action-icon-size);
font-weight: 400;
line-height: 1; line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0;
user-select: none;
pointer-events: none; pointer-events: none;
} }
+16 -9
View File
@@ -372,7 +372,13 @@ body[data-callout-line-style="bold"] .callout-connector circle {
} }
.info-card-icon { .info-card-icon {
font-size: calc(16px * var(--hud-scale)); display: inline-flex;
align-items: center;
justify-content: center;
width: calc(18px * var(--hud-scale));
height: calc(18px * var(--hud-scale));
font-size: calc(15px * var(--hud-scale));
line-height: 1;
flex-shrink: 0; flex-shrink: 0;
} }
@@ -380,6 +386,7 @@ body[data-callout-line-style="bold"] .callout-connector circle {
flex: 1; flex: 1;
margin: 0; margin: 0;
font-size: var(--hud-panel-header-title-size); font-size: var(--hud-panel-header-title-size);
line-height: 1.25;
color: var(--hud-title); color: var(--hud-title);
font-weight: 600; font-weight: 600;
white-space: nowrap; white-space: nowrap;
@@ -387,17 +394,17 @@ body[data-callout-line-style="bold"] .callout-connector circle {
text-overflow: ellipsis; text-overflow: ellipsis;
} }
.info-card-header-actions {
margin-left: auto;
}
.info-card-workbench-btn[hidden] {
display: none;
}
.info-card-close { .info-card-close {
flex-shrink: 0; flex-shrink: 0;
align-self: auto; align-self: auto;
width: auto;
height: auto;
min-width: 0;
padding: calc(7px * var(--hud-scale));
}
.info-card-close .material-symbols-rounded {
font-size: calc(16px * var(--hud-scale));
} }
.info-card-content { .info-card-content {
+37
View File
@@ -703,9 +703,17 @@
.news-story-meta { .news-story-meta {
justify-content: space-between; justify-content: space-between;
flex-wrap: nowrap;
min-width: 0; min-width: 0;
} }
.news-story-meta-right {
display: inline-flex;
align-items: center;
gap: calc(4px * var(--hud-scale));
flex-shrink: 0;
}
.news-story-tags { .news-story-tags {
justify-content: flex-start; justify-content: flex-start;
} }
@@ -742,6 +750,35 @@
line-height: 1.4; line-height: 1.4;
} }
.news-story-link {
display: flex;
flex-direction: column;
gap: calc(4px * var(--hud-scale));
color: inherit;
text-decoration: none;
}
.hud-panel__action.news-story-analyze-btn {
--hud-action-padding: calc(4px * var(--hud-scale));
--hud-action-icon-size: calc(14px * var(--hud-scale));
flex-shrink: 0;
}
.hud-panel__action.news-story-analyze-btn .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1em;
height: 1em;
overflow: hidden;
font-size: var(--hud-action-icon-size);
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex-shrink: 0;
user-select: none;
pointer-events: none;
}
.news-story-summary { .news-story-summary {
color: var(--hud-text-muted); color: var(--hud-text-muted);
font-size: calc(0.74rem * var(--hud-scale)); font-size: calc(0.74rem * var(--hud-scale));
@@ -94,11 +94,6 @@ body:not(.layout-mode-mobile) .news-region-card.is-hover-expanded .hud-panel__ac
overflow: visible !important; overflow: visible !important;
} }
body:not(.layout-mode-mobile) .news-region-card.is-hover-expanded .info-card-header h3 {
overflow: visible;
white-space: normal;
}
.news-region-card .news-region-card__body { .news-region-card .news-region-card__body {
transform-origin: top left; transform-origin: top left;
will-change: opacity, transform; will-change: opacity, transform;
@@ -187,7 +182,7 @@ body:not(.layout-mode-mobile) .news-region-card.is-spotlight:hover:not(.is-dragg
overflow:auto; min-height:0; overflow:auto; min-height:0;
} }
.news-region-card__footer { display:flex; align-items:center; gap:calc(4px * var(--hud-scale)); padding:calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale)); flex-shrink:0; border-top:1px solid var(--hud-border); } .news-region-card__footer { display:flex; align-items:center; gap:calc(4px * var(--hud-scale)); padding:calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale)); flex-shrink:0; border-top:1px solid var(--hud-border); }
.news-region-card__footer a { margin-left:auto; color:var(--hud-accent,#91baff); font-size:var(--hud-font-size-sm); text-decoration:none; } .news-region-card__footer a { margin-left:auto; color:var(--hud-accent,#91baff); font-size:var(--hud-font-size-sm); text-decoration:none; white-space:nowrap; }
.news-region-card__count { min-width:calc(36px * var(--hud-scale)); text-align:center; font-size:var(--hud-font-size-sm); } .news-region-card__count { min-width:calc(36px * var(--hud-scale)); text-align:center; font-size:var(--hud-font-size-sm); }
.news-region-card button { cursor:pointer; } .news-region-card button { cursor:pointer; }
.news-region-card button:disabled { opacity:.35; cursor:default; } .news-region-card button:disabled { opacity:.35; cursor:default; }
@@ -200,7 +195,23 @@ body:not(.layout-mode-mobile) .news-region-card.is-spotlight:hover:not(.is-dragg
} }
.news-region-card .info-card-header h3 { min-width:0; } .news-region-card .info-card-header h3 { min-width:0; }
.news-region-card__region { flex-shrink:0; font-size:var(--hud-font-size-sm); color:#ffd77a; } .news-region-card__region { display:inline-flex; align-items:center; flex-shrink:0; font-size:var(--hud-font-size-sm); line-height:1.25; color:#ffd77a; }
/* Expanded regional cards show only the region label in the header; compact/collapsed cards show headline + region. */
body:not(.layout-mode-mobile) .news-region-card:is(.is-spotlight, .is-hover-expanded):not(.hud-panel--collapsed) .news-region-card__headline,
#news-region-workspace.is-mobile .news-region-card:not(.hud-panel--collapsed) .news-region-card__headline {
display: none;
}
body:not(.layout-mode-mobile) .news-region-card:is(.is-spotlight, .is-hover-expanded):not(.hud-panel--collapsed) .news-region-card__region,
#news-region-workspace.is-mobile .news-region-card:not(.hud-panel--collapsed) .news-region-card__region {
flex: 1 1 auto;
min-width: 0;
font-size: var(--hud-panel-header-title-size);
font-weight: 600;
color: #ffd77a;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.hud-panel__action:is([data-news-region-cards], [data-action="toggle-cards"])[aria-pressed="true"], .hud-panel__action:is([data-news-region-cards], [data-action="toggle-cards"])[aria-pressed="true"],
.earth-mobile-action-btn[data-news-region-cards][aria-pressed="true"] { .earth-mobile-action-btn[data-news-region-cards][aria-pressed="true"] {
background:rgba(116,180,255,.22); border:1px solid rgba(145,195,255,.8); background:rgba(116,180,255,.22); border:1px solid rgba(145,195,255,.8);
+6 -3
View File
@@ -98,15 +98,18 @@
.tv-panel-select { .tv-panel-select {
flex: 1 1 auto; flex: 1 1 auto;
min-width: 0; min-width: 0;
height: calc(30px * var(--hud-scale) + 2px);
box-sizing: border-box;
appearance: none; appearance: none;
-webkit-appearance: none; -webkit-appearance: none;
color-scheme: dark; color-scheme: dark;
border: 1px solid rgba(201, 225, 247, 0.14); border: 1px solid rgba(201, 225, 247, 0.14);
border-radius: calc(12px * var(--hud-scale)); border-radius: calc(8px * var(--hud-scale));
background: rgba(255, 255, 255, 0.04); background: rgba(255, 255, 255, 0.04);
color: var(--hud-text); color: var(--hud-text);
padding: calc(10px * var(--hud-scale)) calc(12px * var(--hud-scale)); padding: 0 calc(10px * var(--hud-scale));
font-size: calc(0.84rem * var(--hud-scale)); font-size: calc(0.8rem * var(--hud-scale));
line-height: 1;
} }
.earth-mobile-page--tv > .hud-select-trigger { .earth-mobile-page--tv > .hud-select-trigger {
+56 -4
View File
@@ -1205,13 +1205,39 @@
> >
<div class="earth-mobile-settings-copy"> <div class="earth-mobile-settings-copy">
<span class="earth-mobile-settings-label">动捕输入源</span> <span class="earth-mobile-settings-label">动捕输入源</span>
<span class="earth-mobile-settings-subtitle">网页摄像头无需安装;Motion Agent 用于双摄或网络摄像头</span> <span class="earth-mobile-settings-subtitle">本机摄像头内置识别无需装服务;Motion Agent 仅用于外接或 RTSP</span>
</div> </div>
<div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择动捕输入源"> <div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择动捕输入源">
<button type="button" class="earth-mobile-settings-pill is-active" data-motion-provider="browser_camera" aria-pressed="true">浏览器摄像头</button> <button type="button" class="earth-mobile-settings-pill is-active" data-motion-provider="browser_camera" aria-pressed="true">本机摄像头</button>
<button type="button" class="earth-mobile-settings-pill" data-motion-provider="motion_agent" aria-pressed="false">Motion Agent</button> <button type="button" class="earth-mobile-settings-pill" data-motion-provider="motion_agent" aria-pressed="false">Motion Agent</button>
</div> </div>
</div> </div>
<div
class="earth-mobile-settings-card earth-mobile-settings-card--stacked"
data-gatekeeper-permission="earth.motion_debug"
>
<div class="earth-mobile-settings-copy">
<span class="earth-mobile-settings-label">摄像头模式</span>
<span class="earth-mobile-settings-subtitle" data-motion-camera-mode-summary>自动检测可用物理摄像头;单摄走 2D,双摄 3D 深度规划中</span>
</div>
<div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择摄像头模式">
<button type="button" class="earth-mobile-settings-pill is-active" data-motion-camera-mode="auto" aria-pressed="true">自动检测</button>
<button type="button" class="earth-mobile-settings-pill" data-motion-camera-mode="single" aria-pressed="false">单摄 2D</button>
<button type="button" class="earth-mobile-settings-pill" data-motion-camera-mode="dual_3d" aria-pressed="false" disabled title="双摄真 3D 深度识别已在规划中">双摄 3D (规划中)</button>
</div>
</div>
<div
class="earth-mobile-settings-card earth-mobile-settings-card--stacked"
data-gatekeeper-permission="earth.motion_debug"
>
<div class="earth-mobile-settings-copy">
<span class="earth-mobile-settings-label">摄像头设备</span>
<span class="earth-mobile-settings-subtitle">仅列物理摄像头(自动过滤常见虚拟/红外设备)</span>
</div>
<div class="earth-mobile-settings-chip-group" role="group" aria-label="移动端选择摄像头设备" data-motion-camera-device-list>
<button type="button" class="earth-mobile-settings-chip is-active" data-motion-camera-device="" aria-pressed="true">自动选择</button>
</div>
</div>
<div <div
class="earth-mobile-settings-card earth-mobile-settings-card--stacked" class="earth-mobile-settings-card earth-mobile-settings-card--stacked"
data-gatekeeper-permission="earth.motion_debug" data-gatekeeper-permission="earth.motion_debug"
@@ -1898,13 +1924,39 @@
> >
<div class="earth-settings-copy"> <div class="earth-settings-copy">
<span class="earth-settings-item-title">动捕输入源</span> <span class="earth-settings-item-title">动捕输入源</span>
<span class="earth-settings-item-subtitle">浏览器摄像头适合网页/SaaS;Motion Agent 适合双摄、RTSP/HTTP 和客户端</span> <span class="earth-settings-item-subtitle">本机摄像头内置本地骨骼识别(Web 与客户端通用);Motion Agent 仅用于外接或 RTSP 服务</span>
</div> </div>
<div class="earth-settings-segmented" role="group" aria-label="选择动捕输入源" style="--item-count: 2;"> <div class="earth-settings-segmented" role="group" aria-label="选择动捕输入源" style="--item-count: 2;">
<button type="button" class="earth-settings-segmented-btn is-active" data-motion-provider="browser_camera" aria-pressed="true">浏览器摄像头</button> <button type="button" class="earth-settings-segmented-btn is-active" data-motion-provider="browser_camera" aria-pressed="true">本机摄像头</button>
<button type="button" class="earth-settings-segmented-btn" data-motion-provider="motion_agent" aria-pressed="false">Motion Agent</button> <button type="button" class="earth-settings-segmented-btn" data-motion-provider="motion_agent" aria-pressed="false">Motion Agent</button>
</div> </div>
</div> </div>
<div
class="earth-settings-item earth-settings-item--stacked"
data-gatekeeper-permission="earth.motion_debug"
>
<div class="earth-settings-copy">
<span class="earth-settings-item-title">摄像头模式</span>
<span class="earth-settings-item-subtitle" data-motion-camera-mode-summary>自动检测可用物理摄像头;单摄走 2D,双摄 3D 深度规划中</span>
</div>
<div class="earth-settings-segmented" role="group" aria-label="选择摄像头模式" style="--item-count: 3;">
<button type="button" class="earth-settings-segmented-btn is-active" data-motion-camera-mode="auto" aria-pressed="true">自动检测</button>
<button type="button" class="earth-settings-segmented-btn" data-motion-camera-mode="single" aria-pressed="false">单摄 2D</button>
<button type="button" class="earth-settings-segmented-btn" data-motion-camera-mode="dual_3d" aria-pressed="false" disabled title="双摄真 3D 深度识别已在规划中">双摄 3D (规划中)</button>
</div>
</div>
<div
class="earth-settings-item earth-settings-item--stacked"
data-gatekeeper-permission="earth.motion_debug"
>
<div class="earth-settings-copy">
<span class="earth-settings-item-title">摄像头设备</span>
<span class="earth-settings-item-subtitle">仅列物理摄像头(自动过滤常见虚拟/红外设备)</span>
</div>
<div class="earth-settings-chip-group" role="group" aria-label="选择摄像头设备" data-motion-camera-device-list>
<button type="button" class="earth-settings-chip is-active" data-motion-camera-device="" aria-pressed="true">自动选择</button>
</div>
</div>
<div <div
class="earth-settings-item earth-settings-item--stacked" class="earth-settings-item earth-settings-item--stacked"
data-gatekeeper-permission="earth.motion_debug" data-gatekeeper-permission="earth.motion_debug"
+93 -1
View File
@@ -114,15 +114,105 @@ function normalizeBrandConfig(config = {}, variant = DEFAULT_BRAND_LANGUAGE) {
return normalized; return normalized;
} }
export function renderBrand(configOrVariant = DEFAULT_BRAND_LANGUAGE) { const MAX_BRAND_IMAGE_RETRIES = 2;
const BRAND_RETRY_DELAYS_MS = [350, 1100];
export function appendBrandRetryParam(url, attempt) {
if (!url || typeof url !== "string") return "";
const [basePart, hashPart = ""] = url.split("#");
const [pathPart, queryPart = ""] = basePart.split("?");
const params = new URLSearchParams(queryPart);
params.set("brand_retry", String(attempt));
const query = params.toString();
return `${pathPart}${query ? `?${query}` : ""}${hashPart ? `#${hashPart}` : ""}`;
}
function resolveBrandMountInputs(configOrVariant = DEFAULT_BRAND_LANGUAGE) {
const variant = const variant =
typeof configOrVariant === "string" typeof configOrVariant === "string"
? configOrVariant ? configOrVariant
: configOrVariant.variant ?? DEFAULT_BRAND_LANGUAGE; : configOrVariant.variant ?? DEFAULT_BRAND_LANGUAGE;
const defaults = getDefaultBrandConfig(variant);
const config = const config =
typeof configOrVariant === "string" typeof configOrVariant === "string"
? normalizeBrandConfig({}, variant) ? normalizeBrandConfig({}, variant)
: normalizeBrandConfig(configOrVariant, variant); : normalizeBrandConfig(configOrVariant, variant);
return { variant, defaults, config };
}
function bindBrandImageRetry(img, baseSrc, fallbackSrc, scheduleTimer = setTimeout) {
if (!img || typeof img.addEventListener !== "function") return;
if (img.dataset) {
img.dataset.brandBaseSrc = baseSrc || "";
img.dataset.brandFallbackSrc = fallbackSrc || "";
img.dataset.brandRetryCount = "0";
}
img.addEventListener("error", () => {
const attempt = Number(img.dataset?.brandRetryCount || "0");
if (attempt >= MAX_BRAND_IMAGE_RETRIES) return;
const nextAttempt = attempt + 1;
if (img.dataset) {
img.dataset.brandRetryCount = String(nextAttempt);
}
const candidate =
nextAttempt >= MAX_BRAND_IMAGE_RETRIES && fallbackSrc && fallbackSrc !== baseSrc
? fallbackSrc
: baseSrc || fallbackSrc;
if (!candidate) return;
const delay = BRAND_RETRY_DELAYS_MS[attempt] ?? 1100;
scheduleTimer(() => {
if ("isConnected" in img && !img.isConnected) return;
img.setAttribute("src", appendBrandRetryParam(candidate, nextAttempt));
}, delay);
});
}
export function attachBrandImageResilience(target, defaults, scheduleTimer = setTimeout) {
if (!target || typeof target.querySelector !== "function") return;
const logoImg = target.querySelector(".earth-brand__logo");
const titleImg = target.querySelector(".earth-brand__title");
if (logoImg) {
bindBrandImageRetry(
logoImg,
logoImg.getAttribute("src") || defaults?.logoSrc || "",
defaults?.logoSrc || "",
scheduleTimer,
);
}
if (titleImg) {
bindBrandImageRetry(
titleImg,
titleImg.getAttribute("src") || defaults?.titleSrc || "",
defaults?.titleSrc || "",
scheduleTimer,
);
}
}
export function recoverBrokenBrandImages(target, cacheBustToken = Date.now()) {
if (!target || typeof target.querySelectorAll !== "function") return 0;
let recoveredCount = 0;
const images = target.querySelectorAll(".earth-brand__logo, .earth-brand__title");
for (const img of images) {
if (!img || !img.complete || img.naturalWidth > 0) continue;
const baseSrc =
img.dataset?.brandBaseSrc ||
img.getAttribute("src") ||
img.dataset?.brandFallbackSrc ||
"";
if (!baseSrc) continue;
if (img.dataset) {
img.dataset.brandRetryCount = "0";
}
img.setAttribute("src", appendBrandRetryParam(baseSrc, cacheBustToken));
recoveredCount += 1;
}
return recoveredCount;
}
export function renderBrand(configOrVariant = DEFAULT_BRAND_LANGUAGE) {
const { variant, config } = resolveBrandMountInputs(configOrVariant);
const titleMarkup = config.titleSrc const titleMarkup = config.titleSrc
? ` ? `
<img <img
@@ -158,7 +248,9 @@ export function renderBrand(configOrVariant = DEFAULT_BRAND_LANGUAGE) {
export function mountBrand(target, configOrVariant = DEFAULT_BRAND_LANGUAGE) { export function mountBrand(target, configOrVariant = DEFAULT_BRAND_LANGUAGE) {
if (!target) return; if (!target) return;
const { defaults } = resolveBrandMountInputs(configOrVariant);
target.innerHTML = renderBrand(configOrVariant); target.innerHTML = renderBrand(configOrVariant);
attachBrandImageResilience(target, defaults);
} }
export async function fetchEarthBrandConfig() { export async function fetchEarthBrandConfig() {
+5 -1
View File
@@ -83,7 +83,11 @@ export function mountCardImage(content, header) {
const credit=document.createElement("a");credit.className="card-image-source hud-panel__action"; const credit=document.createElement("a");credit.className="card-image-source hud-panel__action";
credit.hidden=true;credit.target="_blank";credit.rel="noopener noreferrer"; credit.hidden=true;credit.target="_blank";credit.rel="noopener noreferrer";
const icon=document.createElement("span");icon.className="material-symbols-rounded";icon.textContent="image";icon.setAttribute("aria-hidden","true");credit.append(icon); const icon=document.createElement("span");icon.className="material-symbols-rounded";icon.textContent="image";icon.setAttribute("aria-hidden","true");credit.append(icon);
if(header) header.insertBefore(credit,header.querySelector(".info-card-close")); if(header) {
const anchor=header.querySelector("#info-card-workbench, .info-card-close");
if(anchor?.parentNode) anchor.parentNode.insertBefore(credit,anchor);
else header.appendChild(credit);
}
const presenter=createCardImagePresenter({layer,image,credit,getWidth:()=>body.clientWidth*(window.devicePixelRatio||1)}); const presenter=createCardImagePresenter({layer,image,credit,getWidth:()=>body.clientWidth*(window.devicePixelRatio||1)});
presenters.add(presenter); presenters.add(presenter);
return presenter; return presenter;
@@ -0,0 +1,166 @@
import { describe, expect, it } from "bun:test";
import { readFileSync } from "node:fs";
import { mountCardImage } from "./card-images.js";
function createMockNode(tagName = "div") {
const attributes = new Map();
const children = [];
const classNames = new Set();
const node = {
tagName: tagName.toUpperCase(),
id: "",
_className: "",
children,
parentNode: null,
style: {},
set className(val) {
node._className = String(val || "");
classNames.clear();
for (const cls of node._className.split(/\s+/).filter(Boolean)) classNames.add(cls);
},
get className() {
return [...classNames].join(" ");
},
classList: {
add: (...names) => names.forEach((n) => classNames.add(n)),
remove: (...names) => names.forEach((n) => classNames.delete(n)),
contains: (name) => classNames.has(name),
},
setAttribute: (k, v) => attributes.set(k, String(v)),
getAttribute: (k) => attributes.get(k) ?? null,
removeAttribute: (k) => attributes.delete(k),
append: (...items) => {
for (const item of items) {
if (item && typeof item === "object") {
item.parentNode = node;
children.push(item);
}
}
},
appendChild: (item) => {
node.append(item);
return item;
},
prepend: (...items) => {
for (let i = items.length - 1; i >= 0; i--) {
const item = items[i];
if (item && typeof item === "object") {
item.parentNode = node;
children.unshift(item);
}
}
},
before: (...items) => {
const parent = node.parentNode;
if (!parent) return;
const idx = parent.children.indexOf(node);
if (idx < 0) return;
for (let i = items.length - 1; i >= 0; i--) {
const item = items[i];
if (item && typeof item === "object") {
item.parentNode = parent;
parent.children.splice(idx, 0, item);
}
}
},
insertBefore: (newNode, refNode) => {
if (!refNode) {
return node.appendChild(newNode);
}
const idx = children.indexOf(refNode);
if (idx < 0) {
throw new Error("NotFoundError: reference node is not a child of this node");
}
newNode.parentNode = node;
children.splice(idx, 0, newNode);
return newNode;
},
querySelector: (selector) => {
const selectors = selector.split(",").map((s) => s.trim()).filter(Boolean);
const visit = (cur) => {
for (const child of cur.children) {
for (const sel of selectors) {
if (sel.startsWith("#") && child.id === sel.slice(1)) return child;
if (sel.startsWith(".") && child.classList.contains(sel.slice(1))) return child;
}
const nested = visit(child);
if (nested) return nested;
}
return null;
};
return visit(node);
},
};
return node;
}
describe("card workbench header actions & mountCardImage compatibility", () => {
it("mounts card-image-source inside .hud-panel__actions before #info-card-workbench when close button is nested", () => {
const origDocument = globalThis.document;
const origWindow = globalThis.window;
globalThis.document = { createElement: (tag) => createMockNode(tag) };
globalThis.window = { devicePixelRatio: 1, addEventListener() {} };
try {
const card = createMockNode("div");
const header = createMockNode("div");
header.className = "info-card-header";
const actions = createMockNode("div");
actions.className = "hud-panel__actions info-card-header-actions";
const wbBtn = createMockNode("button");
wbBtn.id = "info-card-workbench";
wbBtn.className = "hud-panel__action info-card-workbench-btn";
const closeBtn = createMockNode("button");
closeBtn.className = "info-card-close hud-panel__action hud-panel-close";
actions.append(wbBtn, closeBtn);
header.append(actions);
const content = createMockNode("div");
content.id = "info-card-content";
card.append(header, content);
expect(() => mountCardImage(content, header)).not.toThrow();
expect(actions.children.map((c) => c.id || c.className.split(" ")[0])).toEqual([
"card-image-source",
"info-card-workbench",
"info-card-close",
]);
} finally {
globalThis.document = origDocument;
globalThis.window = origWindow;
}
});
it("replaces bottom AI pills/buttons with square borderless-until-hover forum icon buttons", () => {
const infoCardSrc = readFileSync(new URL("./info-card.js", import.meta.url), "utf8");
const regionCardSrc = readFileSync(new URL("./news-region-cards.js", import.meta.url), "utf8");
const newsSrc = readFileSync(new URL("./news.js", import.meta.url), "utf8");
const computeTopicSrc = readFileSync(new URL("./compute-topic.js", import.meta.url), "utf8");
expect(infoCardSrc).not.toContain("info-card-forensics-btn");
expect(infoCardSrc).not.toContain("auto_awesome");
expect(infoCardSrc).toContain('id="info-card-workbench" class="hud-panel__action info-card-workbench-btn"');
expect(regionCardSrc).not.toContain("news-region-card__analyze");
expect(regionCardSrc).not.toContain("auto_awesome");
expect(regionCardSrc).toContain('news-region-card__headline');
expect(regionCardSrc).toContain('<div class="hud-panel__actions">${iconButton("news-analyze","forum"');
const headerSlice = regionCardSrc.slice(
regionCardSrc.indexOf("<header"),
regionCardSrc.indexOf("</header>"),
);
const footerSlice = regionCardSrc.slice(
regionCardSrc.indexOf("<footer"),
regionCardSrc.indexOf("</footer>"),
);
expect(headerSlice).toContain("news-analyze");
expect(headerSlice.indexOf("news-analyze")).toBeLessThan(headerSlice.indexOf("card-collapse"));
expect(footerSlice).not.toContain("news-analyze");
expect(newsSrc).not.toContain("auto_awesome");
expect(newsSrc).toContain('class="hud-panel__action news-story-analyze-btn"');
expect(newsSrc).not.toContain("news-story-footer-row");
expect(computeTopicSrc).toContain('data-action="open-copilot"');
expect(computeTopicSrc).toContain(">forum<");
});
});
+139 -14
View File
@@ -8,6 +8,10 @@ import {
} from "./constants.js"; } from "./constants.js";
import { latLonToVector3 } from "./utils.js"; import { latLonToVector3 } from "./utils.js";
import { configureColorTexture, preserveTextureOutput } from "./texture-colors.js"; import { configureColorTexture, preserveTextureOutput } from "./texture-colors.js";
import { isDetachedImageBitmap } from "./webgl-recovery.js";
const CELESTIAL_SKY_MAX_WIDTH = 4096;
const CELESTIAL_SKY_MAX_HEIGHT = 2048;
const textureLoader = new THREE.TextureLoader(); const textureLoader = new THREE.TextureLoader();
const defaultSunDirection = new THREE.Vector3(1, 0.2, 0.4).normalize(); const defaultSunDirection = new THREE.Vector3(1, 0.2, 0.4).normalize();
@@ -15,6 +19,8 @@ const defaultMoonDirection = new THREE.Vector3(-0.6, 0.45, -0.2).normalize();
let celestialRoot = null; let celestialRoot = null;
let skySphere = null; let skySphere = null;
let skyStarMapRequested = false;
let skyStarMapLoadPromise = null;
let skyBrightness = CELESTIAL_CONFIG.skyBrightness; let skyBrightness = CELESTIAL_CONFIG.skyBrightness;
export function getSkyBrightness() { return skyBrightness; } export function getSkyBrightness() { return skyBrightness; }
export function setSkyBrightness(value) { export function setSkyBrightness(value) {
@@ -192,7 +198,87 @@ function createSprite({ texture, scale, opacity = 1, name, color = 0xffffff }) {
return sprite; return sprite;
} }
function createSkySphere() { function loadSkyStarMapFallback(material, resolve, reject) {
textureLoader.load(
CELESTIAL_CONFIG.starMapUrl,
(texture) => {
configureColorTexture(texture);
if (!skySphere || skySphere.material !== material) {
texture.dispose();
resolve(null);
return;
}
if (material.map && material.map !== texture) {
material.map.dispose?.();
}
material.map = texture;
material.needsUpdate = true;
resolve(texture);
},
undefined,
(error) => {
console.warn("Failed to load celestial star map texture");
reject(error || new Error("Failed to load celestial star map texture"));
},
);
}
function loadSkyStarMapTexture(material) {
if (!material) return Promise.resolve(null);
if (skyStarMapLoadPromise) return skyStarMapLoadPromise;
skyStarMapRequested = true;
const currentPromise = (async () => {
if (typeof createImageBitmap === "function" && typeof fetch === "function") {
try {
const response = await fetch(CELESTIAL_CONFIG.starMapUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const blob = await response.blob();
const bitmap = await createImageBitmap(blob, {
imageOrientation: "flipY",
premultiplyAlpha: "none",
colorSpaceConversion: "none",
resizeWidth: CELESTIAL_SKY_MAX_WIDTH,
resizeHeight: CELESTIAL_SKY_MAX_HEIGHT,
resizeQuality: "high",
});
const texture = new THREE.Texture(bitmap);
texture.flipY = false;
texture.addEventListener("dispose", () => bitmap.close?.());
configureColorTexture(texture);
texture.needsUpdate = true;
if (!skySphere || skySphere.material !== material) {
texture.dispose();
return null;
}
if (material.map && material.map !== texture) {
material.map.dispose?.();
}
material.map = texture;
material.needsUpdate = true;
return texture;
} catch {
// Fall through to THREE.TextureLoader for environments without createImageBitmap resize support.
}
}
return new Promise((resolve, reject) => {
loadSkyStarMapFallback(material, resolve, reject);
});
})().finally(() => {
if (skyStarMapLoadPromise === currentPromise) {
skyStarMapLoadPromise = null;
}
});
skyStarMapLoadPromise = currentPromise;
return currentPromise;
}
function createSkySphere({ deferStarMap = false } = {}) {
const geometry = new THREE.SphereGeometry( const geometry = new THREE.SphereGeometry(
CELESTIAL_CONFIG.skyRadius, CELESTIAL_CONFIG.skyRadius,
64, 64,
@@ -221,18 +307,9 @@ function createSkySphere() {
mesh.renderOrder = -1000; mesh.renderOrder = -1000;
mesh.raycast = () => {}; mesh.raycast = () => {};
textureLoader.load( if (!deferStarMap) {
CELESTIAL_CONFIG.starMapUrl, void loadSkyStarMapTexture(material).catch(() => {});
(texture) => { }
configureColorTexture(texture);
material.map = texture;
material.needsUpdate = true;
},
undefined,
() => {
console.warn("Failed to load celestial star map texture");
},
);
return mesh; return mesh;
} }
@@ -458,6 +535,7 @@ export function initCelestialLayer(
ambientLight = null, ambientLight = null,
pointLight = null, pointLight = null,
earth = null, earth = null,
deferStarMap = false,
} = {}, } = {},
) { ) {
if (!scene || !CELESTIAL_CONFIG.enabled) return null; if (!scene || !CELESTIAL_CONFIG.enabled) return null;
@@ -477,7 +555,7 @@ export function initCelestialLayer(
refreshCelestialOrientation(); refreshCelestialOrientation();
skySphere = createSkySphere(); skySphere = createSkySphere({ deferStarMap });
brightStarsGroup = createBrightStarsGroup(); brightStarsGroup = createBrightStarsGroup();
const sunTexture = createDiscTexture([ const sunTexture = createDiscTexture([
@@ -609,6 +687,51 @@ export function setCelestialDayNightEnabled(enabled) {
updateLighting(); updateLighting();
} }
export function loadCelestialStarMap() {
if (!skySphere?.material) return Promise.resolve(null);
const currentMap = skySphere.material.map;
if (currentMap && !isDetachedImageBitmap(currentMap.image)) {
skyStarMapRequested = true;
return Promise.resolve(currentMap);
}
skyStarMapRequested = true;
return loadSkyStarMapTexture(skySphere.material);
}
export function refreshCelestialAfterContextRestore() {
for (const sprite of [sunSprite, moonSprite, sunHaloSprite, moonHaloSprite]) {
if (sprite?.material?.map) {
sprite.material.map.needsUpdate = true;
sprite.material.needsUpdate = true;
}
}
if (brightStarTexture) {
brightStarTexture.needsUpdate = true;
}
if (!skySphere?.material) {
return Promise.resolve(null);
}
const currentMap = skySphere.material.map;
if (currentMap) {
if (isDetachedImageBitmap(currentMap.image)) {
currentMap.dispose?.();
skySphere.material.map = null;
skySphere.material.needsUpdate = true;
return loadCelestialStarMap();
}
currentMap.needsUpdate = true;
skySphere.material.needsUpdate = true;
return Promise.resolve(currentMap);
}
if (skyStarMapRequested) {
return loadCelestialStarMap();
}
return Promise.resolve(null);
}
export function disposeCelestialLayer() { export function disposeCelestialLayer() {
if (celestialRoot?.parent) { if (celestialRoot?.parent) {
celestialRoot.parent.remove(celestialRoot); celestialRoot.parent.remove(celestialRoot);
@@ -624,6 +747,8 @@ export function disposeCelestialLayer() {
}); });
skySphere = null; skySphere = null;
skyStarMapRequested = false;
skyStarMapLoadPromise = null;
brightStarsGroup = null; brightStarsGroup = null;
sunSprite = null; sunSprite = null;
moonSprite = null; moonSprite = null;
@@ -613,6 +613,10 @@ export function initComputeTopic({
const expanded = expandedCards.has(entry.code); const expanded = expandedCards.has(entry.code);
const toggleLabel = expanded ? text("收起详情", "Collapse details") : text("展开详情", "Expand details"); const toggleLabel = expanded ? text("收起详情", "Collapse details") : text("展开详情", "Expand details");
const analyzeLabel = text(
`在 AI 参谋中分析${nameOf(entry)}`,
`Analyze ${nameOf(entry)} in AI Copilot`,
);
const rotateLabel = text( const rotateLabel = text(
`将地球旋转对准${nameOf(entry)}正面`, `将地球旋转对准${nameOf(entry)}正面`,
`Rotate globe to face ${nameOf(entry)}`, `Rotate globe to face ${nameOf(entry)}`,
@@ -630,6 +634,7 @@ export function initComputeTopic({
</div> </div>
<span class="compute-card__capsule-metric" aria-hidden="true">${escape(capsuleMetric)}</span> <span class="compute-card__capsule-metric" aria-hidden="true">${escape(capsuleMetric)}</span>
<div class="hud-panel__actions"> <div class="hud-panel__actions">
<button type="button" class="hud-panel__action" data-action="open-copilot" data-card="${escape(entry.code)}" aria-label="${escape(analyzeLabel)}" title="${escape(analyzeLabel)}"><span class="material-symbols-rounded" aria-hidden="true">forum</span></button>
<button type="button" class="hud-panel__action compute-card__rotate-btn" data-action="rotate-to-front" data-card="${escape(entry.code)}" aria-label="${escape(rotateLabel)}" title="${escape(rotateLabel)}"><span class="material-symbols-rounded" aria-hidden="true">explore</span></button> <button type="button" class="hud-panel__action compute-card__rotate-btn" data-action="rotate-to-front" data-card="${escape(entry.code)}" aria-label="${escape(rotateLabel)}" title="${escape(rotateLabel)}"><span class="material-symbols-rounded" aria-hidden="true">explore</span></button>
<button type="button" class="hud-panel__action" data-action="card-collapse" data-card="${escape(entry.code)}" aria-expanded="${String(expanded)}" aria-label="${escape(toggleLabel)}" title="${escape(toggleLabel)}"><span class="material-symbols-rounded" aria-hidden="true">${expanded ? "expand_less" : "expand_more"}</span></button> <button type="button" class="hud-panel__action" data-action="card-collapse" data-card="${escape(entry.code)}" aria-expanded="${String(expanded)}" aria-label="${escape(toggleLabel)}" title="${escape(toggleLabel)}"><span class="material-symbols-rounded" aria-hidden="true">${expanded ? "expand_less" : "expand_more"}</span></button>
</div> </div>
+225 -1
View File
@@ -136,6 +136,12 @@ import {
MOTION_GESTURES, MOTION_GESTURES,
normalizeMotionProvider, normalizeMotionProvider,
} from "./motion-protocol.js"; } from "./motion-protocol.js";
import {
DEFAULT_MOTION_CAMERA_MODE,
inspectCameraTopology,
normalizeMotionCameraMode,
} from "./motion-camera-topology.js";
import { MOTION_CONTROL_STATE_EVENT } from "./motion-events.js";
export let autoRotate = true; export let autoRotate = true;
export let zoomLevel = 1.0; export let zoomLevel = 1.0;
@@ -147,6 +153,10 @@ let defaultEarthZoom = CONFIG.defaultViewZoom;
let autoRotationSpeed = CONFIG.rotationSpeed; let autoRotationSpeed = CONFIG.rotationSpeed;
let motionDebugEnabled = false; let motionDebugEnabled = false;
let motionProvider = DEFAULT_MOTION_PROVIDER; let motionProvider = DEFAULT_MOTION_PROVIDER;
let motionCameraMode = DEFAULT_MOTION_CAMERA_MODE;
let motionCameraDeviceId = "";
let motionDetectedCameras = [];
let motionDualCameraDetected = false;
let motionDebugSkeletonOnly = false; let motionDebugSkeletonOnly = false;
let motionEnabledGestures = []; let motionEnabledGestures = [];
let activeCamera = null; let activeCamera = null;
@@ -179,7 +189,7 @@ const SETTINGS_SHEET_MIN_SCALE = 0.06;
const SETTINGS_SHEET_MAX_SCALE_X = 0.22; const SETTINGS_SHEET_MAX_SCALE_X = 0.22;
const SETTINGS_SHEET_MAX_SCALE_Y = 0.18; const SETTINGS_SHEET_MAX_SCALE_Y = 0.18;
const LEGACY_EARTH_SETTINGS_STORAGE_KEY = "planet.earth.settings.v1"; const LEGACY_EARTH_SETTINGS_STORAGE_KEY = "planet.earth.settings.v1";
const EARTH_SETTINGS_VERSION = 19; const EARTH_SETTINGS_VERSION = 20;
const GRID_LINES_DEFAULT_VERSION = 3; const GRID_LINES_DEFAULT_VERSION = 3;
const SATELLITE_DISPLAY_DEFAULT_VERSION = 4; const SATELLITE_DISPLAY_DEFAULT_VERSION = 4;
const MEDIA_PANEL_DEFAULT_VERSION = 5; const MEDIA_PANEL_DEFAULT_VERSION = 5;
@@ -195,6 +205,7 @@ const AUTO_ROTATION_SPEED_DEFAULT_VERSION = 15;
const NEWS_CATEGORY_FILTERS_DEFAULT_VERSION = 16; const NEWS_CATEGORY_FILTERS_DEFAULT_VERSION = 16;
const MOTION_GESTURES_DEFAULT_VERSION = 17; const MOTION_GESTURES_DEFAULT_VERSION = 17;
const EARTH_MAP_SOURCE_DEFAULT_VERSION = 18; const EARTH_MAP_SOURCE_DEFAULT_VERSION = 18;
const MOTION_CAMERA_DEFAULT_VERSION = 20;
const MOTION_GESTURE_DEFINITIONS = [ const MOTION_GESTURE_DEFINITIONS = [
{ id: "rotate_left", label: "左旋" }, { id: "rotate_left", label: "左旋" },
{ id: "rotate_right", label: "右旋" }, { id: "rotate_right", label: "右旋" },
@@ -1570,6 +1581,8 @@ function getCurrentSharedSettingsSnapshot() {
autoRotationSpeed, autoRotationSpeed,
motionDebugEnabled, motionDebugEnabled,
motionProvider, motionProvider,
motionCameraMode,
motionCameraDeviceId,
motionDebugSkeletonOnly, motionDebugSkeletonOnly,
motionEnabledGestures: getMotionEnabledGestures(), motionEnabledGestures: getMotionEnabledGestures(),
mediaPanelActiveTab: normalizeMediaPanelActiveTab(getActiveTVTab()), mediaPanelActiveTab: normalizeMediaPanelActiveTab(getActiveTVTab()),
@@ -1639,6 +1652,11 @@ function cloneEarthSettings(settings) {
settings.shared.motionProvider, settings.shared.motionProvider,
DEFAULT_MOTION_PROVIDER, DEFAULT_MOTION_PROVIDER,
), ),
motionCameraMode: normalizeMotionCameraMode(
settings.shared.motionCameraMode,
DEFAULT_MOTION_CAMERA_MODE,
),
motionCameraDeviceId: String(settings.shared.motionCameraDeviceId || "").trim(),
motionDebugSkeletonOnly: Boolean(settings.shared.motionDebugSkeletonOnly), motionDebugSkeletonOnly: Boolean(settings.shared.motionDebugSkeletonOnly),
motionEnabledGestures: normalizeMotionEnabledGestures(settings.shared.motionEnabledGestures), motionEnabledGestures: normalizeMotionEnabledGestures(settings.shared.motionEnabledGestures),
mediaPanelActiveTab: normalizeMediaPanelActiveTab(settings.shared.mediaPanelActiveTab), mediaPanelActiveTab: normalizeMediaPanelActiveTab(settings.shared.mediaPanelActiveTab),
@@ -1773,6 +1791,15 @@ function normalizeEarthSettings(rawSettings, defaults) {
(rawSettings?.version || 0) >= MOTION_PROVIDER_DEFAULT_VERSION (rawSettings?.version || 0) >= MOTION_PROVIDER_DEFAULT_VERSION
? normalizeMotionProvider(sharedSettings?.motionProvider, defaults.shared.motionProvider) ? normalizeMotionProvider(sharedSettings?.motionProvider, defaults.shared.motionProvider)
: defaults.shared.motionProvider; : defaults.shared.motionProvider;
const nextMotionCameraMode =
(rawSettings?.version || 0) >= MOTION_CAMERA_DEFAULT_VERSION
? normalizeMotionCameraMode(sharedSettings?.motionCameraMode, defaults.shared.motionCameraMode)
: defaults.shared.motionCameraMode;
const nextMotionCameraDeviceId =
(rawSettings?.version || 0) >= MOTION_CAMERA_DEFAULT_VERSION &&
typeof sharedSettings?.motionCameraDeviceId === "string"
? sharedSettings.motionCameraDeviceId.trim()
: defaults.shared.motionCameraDeviceId;
const nextMotionDebugSkeletonOnly = const nextMotionDebugSkeletonOnly =
(rawSettings?.version || 0) >= MOTION_DEBUG_SKELETON_ONLY_DEFAULT_VERSION && (rawSettings?.version || 0) >= MOTION_DEBUG_SKELETON_ONLY_DEFAULT_VERSION &&
typeof sharedSettings?.motionDebugSkeletonOnly === "boolean" typeof sharedSettings?.motionDebugSkeletonOnly === "boolean"
@@ -1853,6 +1880,8 @@ function normalizeEarthSettings(rawSettings, defaults) {
autoRotationSpeed: nextAutoRotationSpeed, autoRotationSpeed: nextAutoRotationSpeed,
motionDebugEnabled: nextMotionDebugEnabled, motionDebugEnabled: nextMotionDebugEnabled,
motionProvider: nextMotionProvider, motionProvider: nextMotionProvider,
motionCameraMode: nextMotionCameraMode,
motionCameraDeviceId: nextMotionCameraDeviceId,
motionDebugSkeletonOnly: nextMotionDebugSkeletonOnly, motionDebugSkeletonOnly: nextMotionDebugSkeletonOnly,
motionEnabledGestures: nextMotionEnabledGestures, motionEnabledGestures: nextMotionEnabledGestures,
mediaPanelActiveTab: nextMediaPanelActiveTab, mediaPanelActiveTab: nextMediaPanelActiveTab,
@@ -1904,6 +1933,84 @@ function syncMotionProviderControls(nextProvider = motionProvider) {
syncRuntimeModeSections(); syncRuntimeModeSections();
} }
function syncMotionCameraModeControls(nextMode = motionCameraMode) {
const effectiveMode =
nextMode === "dual_3d" ? DEFAULT_MOTION_CAMERA_MODE : nextMode;
document.querySelectorAll("[data-motion-camera-mode]").forEach((button) => {
if (!(button instanceof HTMLButtonElement)) return;
const mode = normalizeMotionCameraMode(button.dataset.motionCameraMode);
const active = mode === effectiveMode;
button.classList.toggle("is-active", active);
button.setAttribute("aria-pressed", active ? "true" : "false");
});
syncSegmentedControlSliders();
}
function syncMotionCameraTopologySummary() {
const count = motionDetectedCameras.length;
let summaryText = "自动检测可用物理摄像头;单摄走 2D,双摄 3D 深度规划中";
if (motionDualCameraDetected) {
summaryText = `检测到 ${count} 个物理摄像头:当前运行单摄 2D(双摄 3D 深度规划中)`;
} else if (count === 1) {
summaryText = "已检测到 1 个物理摄像头(单摄 2D 本地骨骼识别)";
}
document.querySelectorAll("[data-motion-camera-mode-summary]").forEach((el) => {
if (el instanceof HTMLElement) {
el.textContent = translateText(summaryText);
}
});
}
function renderMotionCameraDeviceChips() {
const lists = document.querySelectorAll("[data-motion-camera-device-list]");
if (lists.length === 0) return;
const hasValidSelected =
Boolean(motionCameraDeviceId) &&
motionDetectedCameras.some((camera) => camera.deviceId === motionCameraDeviceId);
const effectiveDeviceId = hasValidSelected ? motionCameraDeviceId : "";
lists.forEach((list) => {
if (!(list instanceof HTMLElement)) return;
const isMobile = list.classList.contains("earth-mobile-settings-chip-group");
const chipClass = isMobile ? "earth-mobile-settings-chip" : "earth-settings-chip";
list.innerHTML = "";
const autoBtn = document.createElement("button");
autoBtn.type = "button";
autoBtn.className = `${chipClass}${effectiveDeviceId === "" ? " is-active" : ""}`;
autoBtn.dataset.motionCameraDevice = "";
autoBtn.setAttribute("aria-pressed", effectiveDeviceId === "" ? "true" : "false");
autoBtn.textContent = translateText("自动选择");
list.appendChild(autoBtn);
motionDetectedCameras.forEach((camera, index) => {
if (!camera.deviceId) return;
const btn = document.createElement("button");
btn.type = "button";
const active = camera.deviceId === effectiveDeviceId;
btn.className = `${chipClass}${active ? " is-active" : ""}`;
btn.dataset.motionCameraDevice = camera.deviceId;
btn.setAttribute("aria-pressed", active ? "true" : "false");
btn.textContent = camera.rawLabel || `${translateText("摄像头")} ${index + 1}`;
btn.title = btn.textContent;
list.appendChild(btn);
});
});
}
async function refreshAvailableMotionCameras() {
if (typeof navigator === "undefined" || !navigator.mediaDevices) return;
const topology = await inspectCameraTopology(navigator.mediaDevices, {
requestedMode: motionCameraMode,
preferredDeviceId: motionCameraDeviceId,
});
motionDetectedCameras = topology.physicalCameras || [];
motionDualCameraDetected = Boolean(topology.dualCameraDetected);
syncMotionCameraTopologySummary();
renderMotionCameraDeviceChips();
}
function syncMotionDebugSkeletonOnlyToggle(nextEnabled = motionDebugSkeletonOnly) { function syncMotionDebugSkeletonOnlyToggle(nextEnabled = motionDebugSkeletonOnly) {
document.querySelectorAll("[data-motion-skeleton-only-toggle]").forEach((input) => { document.querySelectorAll("[data-motion-skeleton-only-toggle]").forEach((input) => {
if (input instanceof HTMLInputElement) { if (input instanceof HTMLInputElement) {
@@ -1932,6 +2039,8 @@ function dispatchMotionSettingsChange() {
enabled: effectiveDebugEnabled, enabled: effectiveDebugEnabled,
preferredEnabled: motionDebugEnabled, preferredEnabled: motionDebugEnabled,
provider: motionProvider, provider: motionProvider,
cameraMode: motionCameraMode,
cameraDeviceId: motionCameraDeviceId,
skeletonOnly: motionDebugSkeletonOnly, skeletonOnly: motionDebugSkeletonOnly,
enabledGestures: getMotionEnabledGestures(), enabledGestures: getMotionEnabledGestures(),
}, },
@@ -2734,6 +2843,14 @@ async function applyEarthSettings(settings, { applyLayers = true } = {}) {
persist: false, persist: false,
suppressStatus: true, suppressStatus: true,
}); });
setMotionCameraMode(settings.shared.motionCameraMode, {
persist: false,
suppressStatus: true,
});
setMotionCameraDeviceId(settings.shared.motionCameraDeviceId, {
persist: false,
suppressStatus: true,
});
setMotionDebugSkeletonOnly(settings.shared.motionDebugSkeletonOnly, { setMotionDebugSkeletonOnly(settings.shared.motionDebugSkeletonOnly, {
persist: false, persist: false,
suppressStatus: true, suppressStatus: true,
@@ -2770,6 +2887,14 @@ export function getMotionProvider() {
return motionProvider; return motionProvider;
} }
export function getMotionCameraMode() {
return motionCameraMode;
}
export function getMotionCameraDeviceId() {
return motionCameraDeviceId;
}
export function getMotionDebugSkeletonOnly() { export function getMotionDebugSkeletonOnly() {
return motionDebugSkeletonOnly; return motionDebugSkeletonOnly;
} }
@@ -2836,6 +2961,63 @@ export function setMotionProvider(
return motionProvider; return motionProvider;
} }
export function setMotionCameraMode(
nextMode,
{ persist = true, suppressStatus = false } = {},
) {
const normalized = normalizeMotionCameraMode(nextMode, DEFAULT_MOTION_CAMERA_MODE);
if (normalized === "dual_3d") {
if (!suppressStatus) {
showStatusMessage(earthMessage("status.motionDual3dPlanned"), "info");
}
return motionCameraMode;
}
const changed = motionCameraMode !== normalized;
motionCameraMode = normalized;
syncMotionCameraModeControls(motionCameraMode);
syncMotionCameraTopologySummary();
ensureMutableEarthSettingsState();
earthSettingsState.shared.motionCameraMode = motionCameraMode;
if (changed) {
dispatchMotionSettingsChange();
}
if (persist) {
persistEarthSettings();
}
if (!suppressStatus && changed) {
showStatusMessage(earthMessage("status.motionCameraMode", { mode: motionCameraMode }), "info");
}
return motionCameraMode;
}
export function setMotionCameraDeviceId(
nextDeviceId,
{ persist = true, suppressStatus = false } = {},
) {
const normalized = String(nextDeviceId || "").trim();
const changed = motionCameraDeviceId !== normalized;
motionCameraDeviceId = normalized;
renderMotionCameraDeviceChips();
ensureMutableEarthSettingsState();
earthSettingsState.shared.motionCameraDeviceId = motionCameraDeviceId;
if (changed) {
dispatchMotionSettingsChange();
}
if (persist) {
persistEarthSettings();
}
if (!suppressStatus && changed) {
const matched = motionDetectedCameras.find((camera) => camera.deviceId === motionCameraDeviceId);
const label = matched?.rawLabel || (motionCameraDeviceId ? motionCameraDeviceId : "自动选择");
showStatusMessage(earthMessage("status.motionCameraDevice", { label }), "info");
}
return motionCameraDeviceId;
}
export function setMotionDebugSkeletonOnly( export function setMotionDebugSkeletonOnly(
nextEnabled, nextEnabled,
{ persist = true, suppressStatus = false } = {}, { persist = true, suppressStatus = false } = {},
@@ -4297,6 +4479,8 @@ function integrateMotionSettingsIntoRuntime() {
markRuntimeModeSection("[data-auto-rotation-speed-slider]", ROTATION_MODE.ROTATE); markRuntimeModeSection("[data-auto-rotation-speed-slider]", ROTATION_MODE.ROTATE);
markRuntimeModeSection("[data-motion-debug-toggle]", ROTATION_MODE.MOTION); markRuntimeModeSection("[data-motion-debug-toggle]", ROTATION_MODE.MOTION);
markRuntimeModeSection("[data-motion-provider]", ROTATION_MODE.MOTION); markRuntimeModeSection("[data-motion-provider]", ROTATION_MODE.MOTION);
markRuntimeModeSection("[data-motion-camera-mode]", ROTATION_MODE.MOTION);
markRuntimeModeSection("[data-motion-camera-device-list]", ROTATION_MODE.MOTION);
markRuntimeModeSection("[data-motion-gesture-toggle]", ROTATION_MODE.MOTION); markRuntimeModeSection("[data-motion-gesture-toggle]", ROTATION_MODE.MOTION);
syncRuntimeModeSections(); syncRuntimeModeSections();
} }
@@ -4927,6 +5111,42 @@ function setupSettingsControls() {
}); });
}); });
document.querySelectorAll("[data-motion-camera-mode]").forEach((cameraModeButton) => {
if (!(cameraModeButton instanceof HTMLButtonElement)) return;
bindListener(cameraModeButton, "click", () => {
setMotionCameraMode(cameraModeButton.dataset.motionCameraMode);
});
});
document.querySelectorAll("[data-motion-camera-device-list]").forEach((deviceList) => {
if (!(deviceList instanceof HTMLElement)) return;
bindListener(deviceList, "click", (event) => {
const target = event.target instanceof Element ? event.target : null;
const button = target?.closest("[data-motion-camera-device]");
if (!(button instanceof HTMLButtonElement)) return;
setMotionCameraDeviceId(button.dataset.motionCameraDevice || "");
});
});
bindListener(window, MOTION_CONTROL_STATE_EVENT, (event) => {
const topology = event?.detail?.topology;
if (!topology || typeof topology !== "object") return;
motionDetectedCameras = Array.isArray(topology.physicalCameras) ? topology.physicalCameras : [];
motionDualCameraDetected = Boolean(topology.dualCameraDetected);
syncMotionCameraTopologySummary();
renderMotionCameraDeviceChips();
});
if (typeof navigator !== "undefined" && navigator.mediaDevices?.addEventListener) {
const handleDeviceChange = () => {
void refreshAvailableMotionCameras();
};
navigator.mediaDevices.addEventListener("devicechange", handleDeviceChange);
cleanupFns.push(() => {
navigator.mediaDevices?.removeEventListener?.("devicechange", handleDeviceChange);
});
}
document.querySelectorAll("[data-motion-skeleton-only-toggle]").forEach((motionSkeletonOnlyToggle) => { document.querySelectorAll("[data-motion-skeleton-only-toggle]").forEach((motionSkeletonOnlyToggle) => {
if (!(motionSkeletonOnlyToggle instanceof HTMLInputElement)) return; if (!(motionSkeletonOnlyToggle instanceof HTMLInputElement)) return;
bindListener(motionSkeletonOnlyToggle, "change", () => { bindListener(motionSkeletonOnlyToggle, "change", () => {
@@ -4967,6 +5187,10 @@ function setupSettingsControls() {
syncDayNightToggle(dayNightEnabled); syncDayNightToggle(dayNightEnabled);
syncMotionDebugToggle(motionDebugEnabled); syncMotionDebugToggle(motionDebugEnabled);
syncMotionProviderControls(motionProvider); syncMotionProviderControls(motionProvider);
syncMotionCameraModeControls(motionCameraMode);
syncMotionCameraTopologySummary();
renderMotionCameraDeviceChips();
void refreshAvailableMotionCameras();
syncMotionDebugSkeletonOnlyToggle(motionDebugSkeletonOnly); syncMotionDebugSkeletonOnlyToggle(motionDebugSkeletonOnly);
syncMotionGestureControls(); syncMotionGestureControls();
void setupBoundaryPrecisionControls(); void setupBoundaryPrecisionControls();
+326
View File
@@ -0,0 +1,326 @@
import { splitCopilotResponse } from "./copilot-stream.js";
const COPILOT_DB_NAME = "planet-earth-copilot-store";
const COPILOT_DB_VERSION = 1;
const SESSIONS_STORE = "sessions";
const META_STORE = "meta";
const ACTIVE_SESSION_META_KEY = "active_session_id";
const MEMORY_NOTES_META_KEY = "memory_notes";
export const MAX_SAVED_SESSIONS = 30;
export const MAX_SAVED_TURNS_PER_SESSION = 24;
export const MAX_MEMORY_NOTES = 12;
/**
* Derive a short readable title from the first completed/user question in a session.
*/
export function deriveSessionTitle(turns, fallbackLabel = "新对话") {
const firstQuestion = (Array.isArray(turns) ? turns : [])
.map((t) => String(t?.question || "").trim())
.find(Boolean);
if (!firstQuestion) return fallbackLabel;
return firstQuestion.length > 28 ? `${firstQuestion.slice(0, 28)}…` : firstQuestion;
}
/**
* Serialize completed turns into sanitized `{ role, content }` history without `<think>` blocks.
*/
export function buildTurnHistoryPayload(turns, { maxMessages = 24 } = {}) {
const out = [];
for (const turn of Array.isArray(turns) ? turns : []) {
if (!turn || turn.status !== "done") continue;
const q = String(turn.question || "").trim();
if (!q) continue;
const rawAns = String(turn.rawText || turn.reply?.answer_markdown || "").trim();
const { markdown } = splitCopilotResponse(rawAns, turn.rawReasoning || "");
const cleanAns = (markdown || rawAns).trim();
if (!cleanAns) continue;
out.push({ role: "user", content: q.slice(0, 2000) });
out.push({ role: "assistant", content: cleanAns.slice(0, 4000) });
}
return out.slice(-Math.max(2, maxMessages));
}
function sanitizeStoredTurn(turn) {
if (!turn || typeof turn !== "object") return null;
const question = String(turn.question || "").trim();
if (!question) return null;
// Never persist in-flight loading spinners across restarts.
const status = (turn.status === "done" || turn.status === "error" || turn.status === "cancelled")
? turn.status
: "cancelled";
return {
id: String(turn.id || ""),
runId: turn.runId ? String(turn.runId) : null,
domain: String(turn.domain || "global"),
question,
status,
reply: turn.reply && typeof turn.reply === "object" ? turn.reply : null,
rawText: String(turn.rawText || ""),
rawReasoning: String(turn.rawReasoning || ""),
provider: turn.provider ? String(turn.provider) : null,
model: turn.model ? String(turn.model) : null,
generationMode: turn.generationMode ? String(turn.generationMode) : null,
thinkingUserToggled: turn.thinkingUserToggled ?? null,
viewSpec: turn.viewSpec && typeof turn.viewSpec === "object" ? turn.viewSpec : null,
sceneSpec: turn.sceneSpec && typeof turn.sceneSpec === "object" ? turn.sceneSpec : null,
resultId: turn.resultId ?? null,
revision: turn.revision ?? null,
zeroToken: turn.zeroToken !== false,
evidence: turn.evidence && typeof turn.evidence === "object" ? turn.evidence : {},
activeEvidenceId: turn.activeEvidenceId ?? null,
matrixModeOverride: turn.matrixModeOverride ?? null,
collapsedBlocks: turn.collapsedBlocks && typeof turn.collapsedBlocks === "object" ? turn.collapsedBlocks : {},
errorIcon: turn.errorIcon ? String(turn.errorIcon) : "error",
errorText: String(turn.errorText || ""),
};
}
function sanitizeMemoryNotesList(items) {
const out = [];
const seen = new Set();
for (const item of Array.isArray(items) ? items : []) {
const rawText = typeof item === "string" ? item : item?.text;
const text = String(rawText || "").replace(/\s+/g, " ").trim().slice(0, 160);
if (!text || seen.has(text)) continue;
seen.add(text);
out.push({
id: String((typeof item === "object" && item?.id) || `mem-${out.length + 1}-${Date.now().toString(36)}`),
text,
updatedAt: Number(typeof item === "object" && item?.updatedAt) || Date.now(),
});
if (out.length >= MAX_MEMORY_NOTES) break;
}
return out;
}
/**
* Create a Desktop + Web unified conversation & memory store backed by IndexedDB
* (with automatic per-instance in-memory fallback when IndexedDB is unavailable).
*/
export function createCopilotStore({ useIndexedDb = true } = {}) {
let dbPromise = null;
const memSessions = new Map();
const memMeta = new Map();
function openDb() {
if (!useIndexedDb || typeof indexedDB === "undefined") {
return Promise.resolve(null);
}
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve) => {
try {
const request = indexedDB.open(COPILOT_DB_NAME, COPILOT_DB_VERSION);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(SESSIONS_STORE)) {
db.createObjectStore(SESSIONS_STORE, { keyPath: "id" });
}
if (!db.objectStoreNames.contains(META_STORE)) {
db.createObjectStore(META_STORE, { keyPath: "key" });
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => {
dbPromise = null;
resolve(null);
};
} catch {
dbPromise = null;
resolve(null);
}
});
return dbPromise;
}
async function listSessions() {
const db = await openDb();
let rows;
if (!db) {
rows = [...memSessions.values()];
} else {
rows = await new Promise((resolve) => {
try {
const tx = db.transaction(SESSIONS_STORE, "readonly");
const store = tx.objectStore(SESSIONS_STORE);
const req = store.getAll();
req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []);
req.onerror = () => resolve([]);
} catch {
resolve([]);
}
});
}
return rows
.filter((r) => r && typeof r === "object" && r.id)
.sort((a, b) => (Number(b.updatedAt) || 0) - (Number(a.updatedAt) || 0));
}
async function getSession(id) {
if (!id) return null;
const db = await openDb();
if (!db) {
return memSessions.get(String(id)) || null;
}
return new Promise((resolve) => {
try {
const tx = db.transaction(SESSIONS_STORE, "readonly");
const req = tx.objectStore(SESSIONS_STORE).get(String(id));
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => resolve(null);
} catch {
resolve(null);
}
});
}
async function deleteSession(id) {
if (!id) return;
const key = String(id);
const db = await openDb();
if (!db) {
memSessions.delete(key);
if (memMeta.get(ACTIVE_SESSION_META_KEY) === key) {
memMeta.delete(ACTIVE_SESSION_META_KEY);
}
return;
}
await new Promise((resolve) => {
try {
const tx = db.transaction(SESSIONS_STORE, "readwrite");
tx.objectStore(SESSIONS_STORE).delete(key);
tx.oncomplete = () => resolve();
tx.onerror = () => resolve();
tx.onabort = () => resolve();
} catch {
resolve();
}
});
const activeId = await getActiveSessionId();
if (activeId === key) {
await setActiveSessionId(null);
}
}
async function saveSession(record) {
if (!record || !record.id) return null;
const cleanTurns = (Array.isArray(record.turns) ? record.turns : [])
.map(sanitizeStoredTurn)
.filter(Boolean)
.slice(-MAX_SAVED_TURNS_PER_SESSION);
if (!cleanTurns.length) return null;
const normalized = {
id: String(record.id),
title: String(record.title || deriveSessionTitle(cleanTurns)),
domain: String(record.domain || "global"),
serverSessionId: record.serverSessionId ? String(record.serverSessionId) : null,
serverSessionToken: record.serverSessionToken ? String(record.serverSessionToken) : null,
contextState: record.contextState && typeof record.contextState === "object" ? { ...record.contextState } : {},
pinnedItems: Array.isArray(record.pinnedItems) ? record.pinnedItems.slice(0, 12) : [],
conversationSummary: String(record.conversationSummary || ""),
compactedCount: Number(record.compactedCount) || 0,
turns: cleanTurns,
createdAt: Number(record.createdAt) || Date.now(),
updatedAt: Number(record.updatedAt) || Date.now(),
};
const db = await openDb();
if (!db) {
memSessions.set(normalized.id, normalized);
const all = await listSessions();
for (const extra of all.slice(MAX_SAVED_SESSIONS)) {
memSessions.delete(extra.id);
}
return normalized;
}
await new Promise((resolve) => {
try {
const tx = db.transaction(SESSIONS_STORE, "readwrite");
tx.objectStore(SESSIONS_STORE).put(normalized);
tx.oncomplete = () => resolve();
tx.onerror = () => resolve();
tx.onabort = () => resolve();
} catch {
resolve();
}
});
const all = await listSessions();
for (const extra of all.slice(MAX_SAVED_SESSIONS)) {
await deleteSession(extra.id);
}
return normalized;
}
async function readMeta(key, fallbackValue = null) {
const db = await openDb();
if (!db) {
return memMeta.has(key) ? memMeta.get(key) : fallbackValue;
}
return new Promise((resolve) => {
try {
const tx = db.transaction(META_STORE, "readonly");
const req = tx.objectStore(META_STORE).get(key);
req.onsuccess = () => resolve(req.result ? req.result.value : fallbackValue);
req.onerror = () => resolve(fallbackValue);
} catch {
resolve(fallbackValue);
}
});
}
async function writeMeta(key, value) {
const db = await openDb();
if (!db) {
if (value === null || value === undefined) memMeta.delete(key);
else memMeta.set(key, value);
return;
}
await new Promise((resolve) => {
try {
const tx = db.transaction(META_STORE, "readwrite");
const store = tx.objectStore(META_STORE);
if (value === null || value === undefined) store.delete(key);
else store.put({ key, value });
tx.oncomplete = () => resolve();
tx.onerror = () => resolve();
tx.onabort = () => resolve();
} catch {
resolve();
}
});
}
async function getActiveSessionId() {
const val = await readMeta(ACTIVE_SESSION_META_KEY, null);
return val ? String(val) : null;
}
async function setActiveSessionId(id) {
await writeMeta(ACTIVE_SESSION_META_KEY, id ? String(id) : null);
}
async function getMemoryNotes() {
const items = await readMeta(MEMORY_NOTES_META_KEY, []);
return sanitizeMemoryNotesList(items);
}
async function saveMemoryNotes(items) {
const cleaned = sanitizeMemoryNotesList(items);
await writeMeta(MEMORY_NOTES_META_KEY, cleaned);
return cleaned;
}
return {
listSessions,
getSession,
saveSession,
deleteSession,
getActiveSessionId,
setActiveSessionId,
getMemoryNotes,
saveMemoryNotes,
};
}
@@ -0,0 +1,69 @@
import { describe, expect, it } from "bun:test";
import {
MAX_SAVED_SESSIONS,
buildTurnHistoryPayload,
createCopilotStore,
deriveSessionTitle,
} from "./copilot-store.js";
describe("copilot-store session persistence, history serialization, and memory notes", () => {
it("strips <think> reasoning tags and keeps only completed turns in buildTurnHistoryPayload", () => {
const history = buildTurnHistoryPayload([
{
status: "done",
question: "第一问",
rawText: "<think>hidden thought</think>### 第一答\n\n事实清晰。",
rawReasoning: "structured reasoning",
},
{ status: "error", question: "失败轮次", rawText: "不应进入历史" },
{
status: "done",
question: "第二问",
reply: { answer_markdown: "第二答正文" },
},
]);
expect(history).toEqual([
{ role: "user", content: "第一问" },
{ role: "assistant", content: "### 第一答\n\n事实清晰。" },
{ role: "user", content: "第二问" },
{ role: "assistant", content: "第二答正文" },
]);
});
it("saves/loads/evicts up to MAX_SAVED_SESSIONS and manages deduplicated memory notes", async () => {
const store = createCopilotStore({ useIndexedDb: false });
expect(deriveSessionTitle([{ question: "这是一个超过二十八个字符的地球全图层综合态势对比测试标题问题" }])).toContain("…");
for (let i = 1; i <= MAX_SAVED_SESSIONS + 3; i += 1) {
await store.saveSession({
id: `sess-${i}`,
domain: "global",
turns: [{ id: `t-${i}`, status: "done", question: `问题 ${i}`, rawText: `回答 ${i}` }],
updatedAt: 1000 + i,
});
}
const sessions = await store.listSessions();
expect(sessions).toHaveLength(MAX_SAVED_SESSIONS);
expect(sessions[0].id).toBe(`sess-${MAX_SAVED_SESSIONS + 3}`);
expect(sessions.some((s) => s.id === "sess-1")).toBe(false);
await store.setActiveSessionId(sessions[0].id);
expect(await store.getActiveSessionId()).toBe(sessions[0].id);
await store.deleteSession(sessions[0].id);
expect(await store.getActiveSessionId()).toBeNull();
const savedNotes = await store.saveMemoryNotes([
{ id: "m1", text: "关注亚太海底光缆" },
{ id: "m2", text: "关注亚太海底光缆" },
{ id: "m3", text: "算力按统一口径比较" },
]);
expect(savedNotes).toHaveLength(2);
expect((await store.getMemoryNotes()).map((n) => n.text)).toEqual([
"关注亚太海底光缆",
"算力按统一口径比较",
]);
});
});
+177
View File
@@ -0,0 +1,177 @@
const REASONING_TAG_NAMES = ["think", "thinking", "reasoning", "analysis", "thought", "reflection"];
const REASONING_TAG_RE = /<\s*(\/?)\s*(think|thinking|reasoning|analysis|thought|reflection)\b[^>]*>/gi;
function withoutPartialReasoningTag(value) {
const start = value.lastIndexOf("<");
if (start < 0 || start < value.lastIndexOf(">")) return value;
const suffix = value.slice(start);
const match = suffix.match(/^<\s*\/?\s*([a-z]*)[^>]*$/i);
const candidate = match?.[1]?.toLowerCase();
if (candidate !== undefined && REASONING_TAG_NAMES.some((tag) => tag.startsWith(candidate))) {
return value.slice(0, start);
}
return value;
}
/**
* Split raw streaming/complete assistant text into clean visible Markdown and extracted reasoning/thinking text.
* Supports both structured reasoning deltas and inline `<think>...</think>` blocks.
*/
export function splitCopilotResponse(value, structuredReasoning = "") {
const completeValue = withoutPartialReasoningTag(String(value ?? ""));
const answerParts = [];
const reasoningParts = [];
let currentReasoning = "";
let depth = 0;
let cursor = 0;
for (const match of completeValue.matchAll(REASONING_TAG_RE)) {
const index = match.index ?? cursor;
const content = completeValue.slice(cursor, index);
if (depth > 0) currentReasoning += content;
else answerParts.push(content);
const closing = Boolean(match[1]);
if (closing) {
if (depth === 0) {
answerParts.push(match[0]);
} else {
depth -= 1;
if (depth === 0) {
const trimmed = currentReasoning.trim();
if (trimmed) reasoningParts.push(trimmed);
currentReasoning = "";
}
}
} else {
if (depth === 0) currentReasoning = "";
depth += 1;
}
cursor = index + match[0].length;
}
const remainder = completeValue.slice(cursor);
if (depth > 0) {
currentReasoning += remainder;
const trimmed = currentReasoning.trim();
if (trimmed) reasoningParts.push(trimmed);
} else {
answerParts.push(remainder);
}
const structured = String(structuredReasoning ?? "").trim();
const tagged = reasoningParts.join("\n\n").trim();
const reasoning = structured && tagged && structured !== tagged
? `${structured}\n\n${tagged}`
: (structured || tagged);
return {
markdown: answerParts.join("").trim(),
reasoning,
reasoningActive: depth > 0,
};
}
/**
* Parse incremental SSE text buffer into complete `{ event, data }` frames and remaining unclosed tail.
*/
export function consumeSSEFrames(buffer, flush = false) {
const normalized = String(buffer ?? "").replace(/\r\n/g, "\n");
const chunks = normalized.split("\n\n");
const remainder = flush ? "" : (chunks.pop() ?? "");
const frames = [];
for (const chunk of chunks) {
if (!chunk.trim()) continue;
let event = "message";
const dataLines = [];
for (const line of chunk.split("\n")) {
if (line.startsWith(":")) continue;
if (line.startsWith("event:")) event = line.slice(6).trim() || "message";
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
}
if (dataLines.length > 0) {
frames.push({ event, data: dataLines.join("\n") });
}
}
return { frames, remainder };
}
/**
* Consume an SSE Response from `/api/v1/situational-awareness/sessions/{id}/turns/stream`.
*/
export async function consumeCopilotStream(
response,
callbacks = {},
{ signal } = {},
) {
if (!response?.body?.getReader) {
throw new Error("Copilot SSE stream response has no readable body");
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffered = "";
let donePayload = null;
let failed = false;
const handleFrame = ({ event, data }) => {
if (!data || data === "[DONE]") return;
let parsed;
try {
parsed = JSON.parse(data);
} catch {
return;
}
if (!parsed || typeof parsed !== "object") return;
const eventName = event || parsed.event || "message";
if (eventName === "meta") {
callbacks.onMeta?.(parsed);
} else if (eventName === "reasoning") {
if (typeof parsed.delta === "string" && parsed.delta) {
callbacks.onReasoningDelta?.(parsed.delta, parsed);
}
} else if (eventName === "text") {
if (typeof parsed.delta === "string" && parsed.delta) {
callbacks.onTextDelta?.(parsed.delta, parsed);
}
} else if (eventName === "done") {
donePayload = parsed;
callbacks.onDone?.(parsed);
} else if (eventName === "error") {
const err = new Error(parsed.detail || "AI stream error");
err.partial = Boolean(parsed.partial);
throw err;
}
};
try {
while (true) {
if (signal?.aborted) {
const abortErr = typeof DOMException !== "undefined"
? new DOMException("Aborted", "AbortError")
: Object.assign(new Error("Aborted"), { name: "AbortError" });
throw abortErr;
}
const chunk = await reader.read();
if (chunk.done) break;
buffered += decoder.decode(chunk.value, { stream: true });
const { frames, remainder } = consumeSSEFrames(buffered, false);
buffered = remainder;
for (const frame of frames) handleFrame(frame);
}
buffered += decoder.decode();
for (const frame of consumeSSEFrames(buffered, true).frames) handleFrame(frame);
return donePayload;
} catch (err) {
failed = true;
throw err;
} finally {
if (failed || signal?.aborted) {
await reader.cancel().catch(() => {});
}
reader.releaseLock?.();
}
}
@@ -0,0 +1,70 @@
import { describe, expect, it } from "bun:test";
import {
consumeCopilotStream,
consumeSSEFrames,
splitCopilotResponse,
} from "./copilot-stream.js";
describe("copilot-stream SSE & reasoning utilities", () => {
it("parses incremental CRLF/LF SSE chunks cleanly", () => {
const first = consumeSSEFrames("event: meta\r\ndata: {\"model\":\"MiniMax-M2.7\"}\r\n\r\nevent: tex", false);
expect(first.frames).toEqual([{ event: "meta", data: "{\"model\":\"MiniMax-M2.7\"}" }]);
expect(first.remainder).toBe("event: tex");
const second = consumeSSEFrames(`${first.remainder}t\ndata: {"delta":"hello"}\n\n`, true);
expect(second.frames).toEqual([{ event: "text", data: "{\"delta\":\"hello\"}" }]);
});
it("extracts structured + inline <think> reasoning without leaking partial tags", () => {
const midStream = splitCopilotResponse("正文未开始<think>推理一步<thi", "");
expect(midStream.reasoningActive).toBe(true);
expect(midStream.reasoning).toBe("推理一步");
expect(midStream.markdown).toBe("正文未开始");
const completed = splitCopilotResponse("<think>内部链路</think>\n### 结论\n一切正常", "结构化思考");
expect(completed.reasoningActive).toBe(false);
expect(completed.reasoning).toContain("结构化思考");
expect(completed.reasoning).toContain("内部链路");
expect(completed.markdown).toBe("### 结论\n一切正常");
});
it("consumes SSE response streams in order", async () => {
const encoder = new TextEncoder();
const chunks = [
"event: meta\ndata: {\"provider\":\"minimax\",\"model\":\"MiniMax-M2.7\"}\n\n",
"event: reasoning\ndata: {\"delta\":\"先查新闻\"}\n\n",
"event: text\ndata: {\"delta\":\"国际局势摘要\"}\n\n",
"event: done\ndata: {\"generation_mode\":\"llm_verified\",\"zero_token\":false,\"model\":\"MiniMax-M2.7\"}\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 = { meta: null, reasoning: "", text: "", done: null };
await consumeCopilotStream(fakeResponse, {
onMeta: (m) => { seen.meta = m; },
onReasoningDelta: (d) => { seen.reasoning += d; },
onTextDelta: (d) => { seen.text += d; },
onDone: (d) => { seen.done = d; },
});
expect(seen.meta?.model).toBe("MiniMax-M2.7");
expect(seen.reasoning).toBe("先查新闻");
expect(seen.text).toBe("国际局势摘要");
expect(seen.done?.generation_mode).toBe("llm_verified");
});
});
+34
View File
@@ -15,6 +15,7 @@ import { configureColorTexture, preserveTextureOutput, shaderOutputMarker } from
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, createEarthSurfaceMaterial } from './earth-surface-material.js';
import { isDetachedImageBitmap } from './webgl-recovery.js';
export let earth = null; export let earth = null;
export let clouds = null; export let clouds = null;
@@ -434,3 +435,36 @@ export function setEarthTextureVisible(visible) {
export function getEarthTextureVisible() { export function getEarthTextureVisible() {
return _textureVisible; return _textureVisible;
} }
export function reloadEarthTextureAfterContextRestore() {
if (_cloudTexture) {
if (isDetachedImageBitmap(_cloudTexture.image)) {
_cloudTexture = null;
if (clouds?.material) {
clouds.material.map = null;
}
void loadCloudTexture().catch(() => {});
} else {
_cloudTexture.needsUpdate = true;
if (clouds?.material) {
clouds.material.needsUpdate = true;
}
}
}
if (!_textureVisible) {
return Promise.resolve(null);
}
const currentTexture = earthMap.getTexture();
if (!currentTexture || isDetachedImageBitmap(currentTexture.image)) {
earthMap.clear();
return earthMap.load();
}
currentTexture.needsUpdate = true;
if (_earthTextureOverlayMaterial) {
_earthTextureOverlayMaterial.needsUpdate = true;
}
return Promise.resolve(currentTexture);
}
+59 -4
View File
@@ -235,8 +235,20 @@ const EARTH_MESSAGE_TEMPLATES = {
: "Motion debug mode disabled", : "Motion debug mode disabled",
}, },
"status.motionProvider": { "status.motionProvider": {
zh: ({ provider }) => (provider === "motion_agent" ? "Motion Agent 已接管动捕输入" : "动捕已切换到浏览器传感器"), zh: ({ provider }) => (provider === "motion_agent" ? "Motion Agent 已接管动捕输入" : "动捕已切换到本机摄像头(内置识别)"),
en: ({ provider }) => (provider === "motion_agent" ? "Motion Agent now controls motion input" : "Motion switched to browser sensors"), en: ({ provider }) => (provider === "motion_agent" ? "Motion Agent now controls motion input" : "Motion switched to built-in local camera"),
},
"status.motionCameraMode": {
zh: ({ mode }) => (mode === "single" ? "摄像头模式已切换为单摄 2D" : "摄像头模式已切换为自动检测"),
en: ({ mode }) => (mode === "single" ? "Camera mode switched to Single 2D" : "Camera mode switched to Auto Detect"),
},
"status.motionDual3dPlanned": {
zh: "双摄真 3D 深度模式规划中,当前自动使用单摄 2D",
en: "Dual-camera 3D depth mode is planned; using Single 2D for now",
},
"status.motionCameraDevice": {
zh: ({ label }) => `动捕摄像头已切换为 ${localizedParam(label, "zh-CN")}`,
en: ({ label }) => `Motion camera switched to ${localizedParam(label, "en-US")}`,
}, },
"status.motionDebugView": { "status.motionDebugView": {
zh: ({ skeletonOnly }) => (skeletonOnly ? "动捕调试已切换为只显示骨骼" : "动捕调试已显示实时画面"), zh: ({ skeletonOnly }) => (skeletonOnly ? "动捕调试已切换为只显示骨骼" : "动捕调试已显示实时画面"),
@@ -354,6 +366,22 @@ const EARTH_MESSAGE_TEMPLATES = {
zh: "巡航已暂停,按空格恢复", zh: "巡航已暂停,按空格恢复",
en: "Cruise paused. Press Space to resume.", en: "Cruise paused. Press Space to resume.",
}, },
"status.webglContextLost": {
zh: "显卡渲染上下文已重置,正在自动恢复三维地球…",
en: "Graphics context reset — restoring 3D Earth…",
},
"status.webglReloading": {
zh: "显卡驱动重置后正在自动重新加载三维地球…",
en: "Reloading 3D Earth after graphics driver reset…",
},
"status.webglReloadRequired": {
zh: "显卡驱动已重置,三维渲染暂未自动恢复,请按 Ctrl+R 或 F5 刷新。",
en: "Graphics driver reset; press Ctrl+R or F5 to reload 3D Earth.",
},
"status.webglRestored": {
zh: "三维地球渲染已恢复",
en: "3D Earth rendering restored.",
},
}; };
const EXACT_TRANSLATIONS = { const EXACT_TRANSLATIONS = {
@@ -384,6 +412,11 @@ const EXACT_TRANSLATIONS = {
"在工作台分析卫星": "Analyze satellite in workbench", "在工作台分析卫星": "Analyze satellite in workbench",
"在工作台分析船舶": "Analyze vessel in workbench", "在工作台分析船舶": "Analyze vessel in workbench",
"在工作台分析算力": "Analyze compute resource in workbench", "在工作台分析算力": "Analyze compute resource in workbench",
"AI 分析这条新闻": "Analyze news with AI",
"AI 分析": "AI Analyze",
"全球新闻": "News Intel",
"正在思考…": "Thinking…",
"思考过程": "Thought process",
"算力对比浮层": "Compute comparison panel", "算力对比浮层": "Compute comparison panel",
"折叠图层列表": "Collapse layer list", "折叠图层列表": "Collapse layer list",
"关闭图层面板": "Close layer panel", "关闭图层面板": "Close layer panel",
@@ -803,9 +836,27 @@ const EXACT_TRANSLATIONS = {
"动捕输入源": "Motion Input", "动捕输入源": "Motion Input",
"网页摄像头无需安装;Motion Agent 用于双摄或网络摄像头": "Browser camera needs no install; Motion Agent is for dual-camera or network-camera setups.", "网页摄像头无需安装;Motion Agent 用于双摄或网络摄像头": "Browser camera needs no install; Motion Agent is for dual-camera or network-camera setups.",
"浏览器摄像头适合网页/SaaS;Motion Agent 适合双摄、RTSP/HTTP 和客户端": "Browser camera fits web/SaaS; Motion Agent fits dual cameras, RTSP/HTTP, and clients.", "浏览器摄像头适合网页/SaaS;Motion Agent 适合双摄、RTSP/HTTP 和客户端": "Browser camera fits web/SaaS; Motion Agent fits dual cameras, RTSP/HTTP, and clients.",
"本机摄像头内置识别无需装服务;Motion Agent 仅用于外接或 RTSP": "Built-in local camera needs no service; Motion Agent is only for external/RTSP setups.",
"本机摄像头内置本地骨骼识别(Web 与客户端通用);Motion Agent 仅用于外接或 RTSP 服务": "Built-in local camera runs pose tracking in-process (Web & Desktop); Motion Agent is only for external/RTSP services.",
"选择动捕输入源": "Select motion input", "选择动捕输入源": "Select motion input",
"移动端选择动捕输入源": "Select motion input on mobile", "移动端选择动捕输入源": "Select motion input on mobile",
"浏览器摄像头": "Browser Camera", "浏览器摄像头": "Browser Camera",
"本机摄像头": "Local Camera",
"摄像头模式": "Camera Mode",
"选择摄像头模式": "Select camera mode",
"移动端选择摄像头模式": "Select camera mode on mobile",
"自动检测": "Auto Detect",
"单摄 2D": "Single 2D",
"双摄 3D (规划中)": "Dual 3D (Planned)",
"双摄真 3D 深度识别已在规划中": "Dual-camera 3D depth tracking is planned for Phase 2",
"自动检测可用物理摄像头;单摄走 2D,双摄 3D 深度规划中": "Auto-detects physical cameras; Single 2D is active, Dual 3D is planned",
"已检测到 1 个物理摄像头(单摄 2D 本地骨骼识别)": "1 physical camera detected (Single 2D local pose tracking)",
"摄像头设备": "Camera Device",
"仅列物理摄像头(自动过滤常见虚拟/红外设备)": "Physical cameras only (virtual & IR devices filtered)",
"选择摄像头设备": "Select camera device",
"移动端选择摄像头设备": "Select camera device on mobile",
"自动选择": "Auto",
"摄像头": "Camera",
"识别动作": "Recognized Gestures", "识别动作": "Recognized Gestures",
"关闭后不会触发对应星球控制": "Disabled gestures will not trigger Earth controls", "关闭后不会触发对应星球控制": "Disabled gestures will not trigger Earth controls",
"未勾选的动作不会触发星球端控制;Motion Agent 会同步过滤这些动作": "Unchecked gestures will not trigger Earth controls; Motion Agent filters them too.", "未勾选的动作不会触发星球端控制;Motion Agent 会同步过滤这些动作": "Unchecked gestures will not trigger Earth controls; Motion Agent filters them too.",
@@ -855,7 +906,7 @@ const EXACT_TRANSLATIONS = {
"出品方": "Producer", "出品方": "Producer",
"策划人": "Planners", "策划人": "Planners",
"产品兼开发者": "Product & Development", "产品兼开发者": "Product & Development",
"浙江大学临空智能媒体研究院": "Zhejiang University Linkong Institute of Intelligent Media", "浙江大学临空智能媒体研究院": "Zhejiang University Linkong Intelligent Media Institute",
"方兴东、黄柳青": "Fang Xingdong, Huang Liuqing", "方兴东、黄柳青": "Fang Xingdong, Huang Liuqing",
"钱坤、张鸽、齐鹏": "Qian Kun, Zhang Ge, Qi Peng", "钱坤、张鸽、齐鹏": "Qian Kun, Zhang Ge, Qi Peng",
"面向临空场景下的智能媒体研究、全球态势感知与多源开放数据巡航,提供可视化观测、事件聚合与交互式探索能力。": "For intelligent media research, global situational awareness, and multi-source open-data cruise in linkong scenarios, providing visual observation, event aggregation, and interactive exploration.", "面向临空场景下的智能媒体研究、全球态势感知与多源开放数据巡航,提供可视化观测、事件聚合与交互式探索能力。": "For intelligent media research, global situational awareness, and multi-source open-data cruise in linkong scenarios, providing visual observation, event aggregation, and interactive exploration.",
@@ -923,6 +974,10 @@ const EXACT_TRANSLATIONS = {
"动捕调试已显示实时画面": "Motion debug now shows live video", "动捕调试已显示实时画面": "Motion debug now shows live video",
"动捕输入源已切换为 Motion Agent": "Motion input switched to Motion Agent", "动捕输入源已切换为 Motion Agent": "Motion input switched to Motion Agent",
"动捕输入源已切换为浏览器摄像头": "Motion input switched to browser camera", "动捕输入源已切换为浏览器摄像头": "Motion input switched to browser camera",
"动捕已切换到本机摄像头(内置识别)": "Motion switched to built-in local camera",
"摄像头模式已切换为自动检测": "Camera mode switched to Auto Detect",
"摄像头模式已切换为单摄 2D": "Camera mode switched to Single 2D",
"双摄真 3D 深度模式规划中,当前自动使用单摄 2D": "Dual-camera 3D depth mode is planned; using Single 2D for now",
"动捕: 已切换巡航目标": "Motion: cruise target changed", "动捕: 已切换巡航目标": "Motion: cruise target changed",
"动捕: 当前没有可用图层": "Motion: no available layers", "动捕: 当前没有可用图层": "Motion: no available layers",
"动捕: 当前没有可切换的可见图层": "Motion: no switchable visible layers", "动捕: 当前没有可切换的可见图层": "Motion: no switchable visible layers",
@@ -965,7 +1020,7 @@ const EXACT_TRANSLATIONS = {
"搜索结果": "Search results", "搜索结果": "Search results",
"调整地球默认大小": "Adjust default Earth size", "调整地球默认大小": "Adjust default Earth size",
"调整地形透明度": "Adjust terrain opacity", "调整地形透明度": "Adjust terrain opacity",
"浙江大学临空智能媒体研究院 Logo": "Zhejiang University Linkong Institute of Intelligent Media Logo", "浙江大学临空智能媒体研究院 Logo": "Zhejiang University Linkong Intelligent Media Institute Logo",
"Earth 页面发生未捕获错误": "Earth page uncaught error", "Earth 页面发生未捕获错误": "Earth page uncaught error",
"Earth 页面发生未处理 Promise 错误": "Earth page unhandled Promise error", "Earth 页面发生未处理 Promise 错误": "Earth page unhandled Promise error",
"等待动捕数据": "Waiting for motion data", "等待动捕数据": "Waiting for motion data",
+98 -58
View File
@@ -18,6 +18,7 @@ import {
let cardMounted = false; let cardMounted = false;
let desktopCardImage = null; let desktopCardImage = null;
let mobileCardImage = null; let mobileCardImage = null;
let activeWorkbenchAction = null;
const infoCardTypewriter = createTypewriter(); const infoCardTypewriter = createTypewriter();
export const NEWS_CARD_ICON = "📰"; export const NEWS_CARD_ICON = "📰";
let pendingMobileDetailState = null; let pendingMobileDetailState = null;
@@ -653,38 +654,8 @@ function ensureMobileDetailsListener() {
}); });
} }
function renderDefaultCardContent(content, config, data) { export function buildWorkbenchTarget(config, data) {
if (config.className === 'compute_unresolved') { if (!config || !data) return null;
renderComputeCenterUnresolvedContent(content, data);
return;
}
let html = '';
for (const field of config.fields) {
if (field.omitIfSameAs && data[field.key] === data[field.omitIfSameAs]) continue;
const value = formatInfoCardValue(field, data[field.key]);
const sourceLabel = getFieldSourceLabel(data, field.key);
html += `
<div class="info-card-property">
<span class="info-card-label">${escapeInfoCardHtml(infoText(field.label))}</span>
<span class="info-card-value">${value}${sourceLabel}</span>
</div>
`;
}
if (config.className === 'vessel') {
html += renderVesselEnrichmentSection(data?.enrichment);
}
if (['supercomputer', 'gpu_cluster'].includes(config.className) && data.metadata?.compute_contract === 'v1') {
const metadata = data.metadata;
const fields = [['精度 / 测量', `${metadata.precision || '—'} / ${metadata.measurement || '—'}`]];
html += fields.map(([label, value]) => `<div class="info-card-property"><span class="info-card-label">${escapeInfoCardHtml(infoText(label))}</span><span class="info-card-value">${escapeInfoCardHtml(value)}</span></div>`).join('');
if (/^https?:\/\//i.test(metadata.source_url || '')) {
html += `<a class="info-card-source-link" href="${escapeInfoCardHtml(metadata.source_url)}" target="_blank" rel="noopener noreferrer">${escapeInfoCardHtml(infoText('查看原始来源'))} ↗</a>`;
}
}
const workbenchTarget = (() => {
const targetName = data?.name || data?.city || data?.collector || ''; const targetName = data?.name || data?.city || data?.collector || '';
switch (config.className) { switch (config.className) {
case 'bgp': case 'bgp':
@@ -692,7 +663,7 @@ function renderDefaultCardContent(content, config, data) {
domain: 'bgp', domain: 'bgp',
entityId: data.incident_key || data.event_key || data.id || null, entityId: data.incident_key || data.event_key || data.id || null,
label: '参谋取证调查', label: '参谋取证调查',
icon: 'troubleshoot', icon: 'forum',
question: '请取证分析此次 BGP 路由异动的影响范围、观测采集点与海缆物理边界。', question: '请取证分析此次 BGP 路由异动的影响范围、观测采集点与海缆物理边界。',
}; };
case 'cable': case 'cable':
@@ -749,21 +720,63 @@ function renderDefaultCardContent(content, config, data) {
? `请结合算力节点「${targetName}」,分析所在区域的全球算力格局与演进趋势。` ? `请结合算力节点「${targetName}」,分析所在区域的全球算力格局与演进趋势。`
: '请对比分析主要区域的全球算力份额与结构演进态势。', : '请对比分析主要区域的全球算力份额与结构演进态势。',
}; };
case 'news': case 'news': {
const newsTitle = data?.title || data?.name || '';
return { return {
domain: 'global', domain: 'news',
entityId: null, entityId: data?.id || null,
label: '纳入全球态势工作台', label: '在 AI 参谋中分析',
icon: 'forum', icon: 'forum',
question: '请结合当前地球多图层内置遥测数据,综合评估近期态势新闻关注区域的整体动态。', question: newsTitle
? `请深度分析这条新闻:「${newsTitle}」`
: '请结合当前地球多图层内置遥测数据,综合评估近期态势新闻关注区域的整体动态。',
newsContext: {
id: data?.id || null,
title: newsTitle,
summary: data?.summary || '',
source: data?.source || '',
region: data?.region || data?.regionLabel || '',
region_key: data?.region_key || '',
published_at: data?.published_at || '',
category: data?.category || '',
url: data?.url || '',
},
}; };
}
default: default:
return null; return null;
} }
})(); }
if (workbenchTarget) { function renderDefaultCardContent(content, config, data) {
html += `<div class="info-card-forensics-row"><button type="button" class="info-card-forensics-btn" data-workbench-open="${escapeInfoCardHtml(workbenchTarget.domain)}" data-workbench-entity="${escapeInfoCardHtml(String(workbenchTarget.entityId || ''))}" data-workbench-question="${escapeInfoCardHtml(String(workbenchTarget.question || ''))}"><span class="material-symbols-rounded" aria-hidden="true">${escapeInfoCardHtml(workbenchTarget.icon)}</span><span>${escapeInfoCardHtml(infoText(workbenchTarget.label))}</span></button></div>`; if (config.className === 'compute_unresolved') {
renderComputeCenterUnresolvedContent(content, data);
return;
}
let html = '';
for (const field of config.fields) {
if (field.omitIfSameAs && data[field.key] === data[field.omitIfSameAs]) continue;
const value = formatInfoCardValue(field, data[field.key]);
const sourceLabel = getFieldSourceLabel(data, field.key);
html += `
<div class="info-card-property">
<span class="info-card-label">${escapeInfoCardHtml(infoText(field.label))}</span>
<span class="info-card-value">${value}${sourceLabel}</span>
</div>
`;
}
if (config.className === 'vessel') {
html += renderVesselEnrichmentSection(data?.enrichment);
}
if (['supercomputer', 'gpu_cluster'].includes(config.className) && data.metadata?.compute_contract === 'v1') {
const metadata = data.metadata;
const fields = [['精度 / 测量', `${metadata.precision || '—'} / ${metadata.measurement || '—'}`]];
html += fields.map(([label, value]) => `<div class="info-card-property"><span class="info-card-label">${escapeInfoCardHtml(infoText(label))}</span><span class="info-card-value">${escapeInfoCardHtml(value)}</span></div>`).join('');
if (/^https?:\/\//i.test(metadata.source_url || '')) {
html += `<a class="info-card-source-link" href="${escapeInfoCardHtml(metadata.source_url)}" target="_blank" rel="noopener noreferrer">${escapeInfoCardHtml(infoText('查看原始来源'))} ↗</a>`;
}
} }
const collectContext = buildLocationCollectContext(config, data); const collectContext = buildLocationCollectContext(config, data);
@@ -773,21 +786,6 @@ function renderDefaultCardContent(content, config, data) {
content.innerHTML = html; content.innerHTML = html;
const workbenchBtn = content.querySelector('[data-workbench-open]');
if (workbenchBtn) {
workbenchBtn.addEventListener('click', () => {
window.dispatchEvent(new CustomEvent('earth:open-workbench', {
detail: {
domain: workbenchBtn.dataset.workbenchOpen || 'global',
entityId: workbenchBtn.dataset.workbenchEntity || null,
initialQuestion: workbenchBtn.dataset.workbenchQuestion || '',
autoAsk: true,
data,
},
}));
});
}
if (collectContext) { if (collectContext) {
bindLocationCollectControls(content, collectContext); bindLocationCollectControls(content, collectContext);
} }
@@ -2142,9 +2140,14 @@ function mountCard() {
<div class="info-card-header hud-panel-drag-handle"> <div class="info-card-header hud-panel-drag-handle">
<span class="info-card-icon" id="info-card-icon">🛰️</span> <span class="info-card-icon" id="info-card-icon">🛰️</span>
<h3 id="info-card-title">${escapeInfoCardHtml(infoText('详情'))}</h3> <h3 id="info-card-title">${escapeInfoCardHtml(infoText('详情'))}</h3>
<button class="info-card-close hud-panel-close" type="button" aria-label="${escapeInfoCardHtml(infoText('关闭详情'))}"> <div class="hud-panel__actions info-card-header-actions">
<span class="material-symbols-rounded">close</span> <button id="info-card-workbench" class="hud-panel__action info-card-workbench-btn" type="button" hidden aria-label="${escapeInfoCardHtml(infoText('在 AI 参谋中分析'))}" title="${escapeInfoCardHtml(infoText('在 AI 参谋中分析'))}">
<span class="material-symbols-rounded" aria-hidden="true">forum</span>
</button> </button>
<button class="info-card-close hud-panel__action hud-panel-close" type="button" aria-label="${escapeInfoCardHtml(infoText('关闭详情'))}">
<span class="material-symbols-rounded" aria-hidden="true">close</span>
</button>
</div>
</div> </div>
<div id="info-card-content" class="info-card-content"></div> <div id="info-card-content" class="info-card-content"></div>
</div> </div>
@@ -2166,6 +2169,26 @@ function mountCard() {
'touchstart', 'touchmove', 'touchend', 'touchstart', 'touchmove', 'touchend',
].forEach((evt) => card.addEventListener(evt, stopEvent, { passive: false })); ].forEach((evt) => card.addEventListener(evt, stopEvent, { passive: false }));
// Header workbench button
const workbenchBtn = card.querySelector('#info-card-workbench');
if (workbenchBtn) {
workbenchBtn.addEventListener('click', (event) => {
event.stopPropagation();
if (!activeWorkbenchAction?.target) return;
const { target, data: targetData } = activeWorkbenchAction;
window.dispatchEvent(new CustomEvent('earth:open-workbench', {
detail: {
domain: target.domain || 'global',
entityId: target.entityId || null,
initialQuestion: target.question || '',
autoAsk: true,
newsContext: target.newsContext || null,
data: targetData,
},
}));
});
}
// Close button // Close button
const closeBtn = card.querySelector('.info-card-close'); const closeBtn = card.querySelector('.info-card-close');
if (closeBtn) { if (closeBtn) {
@@ -2356,6 +2379,7 @@ export function showInfoCard(type, data, options = {}) {
const icon = document.getElementById('info-card-icon'); const icon = document.getElementById('info-card-icon');
const title = document.getElementById('info-card-title'); const title = document.getElementById('info-card-title');
const content = document.getElementById('info-card-content'); const content = document.getElementById('info-card-content');
const workbenchBtn = document.getElementById('info-card-workbench');
stopTypewriterAnimation(); stopTypewriterAnimation();
card.className = 'info-card ' + config.className; card.className = 'info-card ' + config.className;
@@ -2364,6 +2388,19 @@ export function showInfoCard(type, data, options = {}) {
? getNewsCardTitle(data) ? getNewsCardTitle(data)
: infoText(config.title); : infoText(config.title);
const workbenchTarget = buildWorkbenchTarget(config, data);
activeWorkbenchAction = workbenchTarget ? { target: workbenchTarget, data } : null;
if (workbenchBtn) {
if (workbenchTarget) {
const actionLabel = infoText(workbenchTarget.label);
workbenchBtn.hidden = false;
workbenchBtn.title = actionLabel;
workbenchBtn.setAttribute('aria-label', actionLabel);
} else {
workbenchBtn.hidden = true;
}
}
if (type === 'news') { if (type === 'news') {
renderNewsCardContent(content, data); renderNewsCardContent(content, data);
} else { } else {
@@ -2374,6 +2411,9 @@ export function showInfoCard(type, data, options = {}) {
} }
export function hideInfoCard() { export function hideInfoCard() {
activeWorkbenchAction = null;
const workbenchBtn = document.getElementById('info-card-workbench');
if (workbenchBtn) workbenchBtn.hidden = true;
desktopCardImage?.hide(); desktopCardImage?.hide();
mobileCardImage?.hide(); mobileCardImage?.hide();
getMobileDetailsImagePresenter()?.hide(); getMobileDetailsImagePresenter()?.hide();
@@ -167,10 +167,23 @@ function registerSatelliteStartupTask() {
await context.yieldFrame(12); await context.yieldFrame(12);
try { try {
clearSatelliteData(); clearSatelliteData();
const canApplyUpdate = () => !context.isCancelled() && context.isSatellitesEnabled();
const loadResult = await loadSatellites({ const loadResult = await loadSatellites({
limit: context.getInitialSatelliteLoadLimit(), limit: context.getInitialSatelliteLoadLimit(),
shouldApplyBackgroundUpdate: canApplyUpdate,
onBackgroundUpdated: (nextResult) => {
if (!canApplyUpdate()) return;
context.updateSatelliteToggleUi(true, nextResult.count);
context.setLegendItems("satellites", getSatelliteLegendItems());
context.refreshLegend();
context.scheduleSatellitePositionWarmup(() => {
if (canApplyUpdate()) {
toggleSatellites(true);
}
}); });
if (!context.isCancelled() && context.isSatellitesEnabled()) { },
});
if (canApplyUpdate()) {
context.updateSatelliteToggleUi(true, loadResult.count); context.updateSatelliteToggleUi(true, loadResult.count);
context.setLegendItems("satellites", getSatelliteLegendItems()); context.setLegendItems("satellites", getSatelliteLegendItems());
context.refreshLegend(); context.refreshLegend();
+168 -8
View File
@@ -75,6 +75,7 @@ import {
getEarthSurfacePickTarget, getEarthSurfacePickTarget,
loadCloudTexture, loadCloudTexture,
loadEarthTexture, loadEarthTexture,
reloadEarthTextureAfterContextRestore,
isEarthTextureReady, isEarthTextureReady,
clearEarthTexture, clearEarthTexture,
setEarthSunDirection, setEarthSunDirection,
@@ -86,6 +87,8 @@ import {
import { registerTerrainMesh, clearTerrainData, sampleElevationAt } from "./terrain.js"; import { registerTerrainMesh, clearTerrainData, sampleElevationAt } from "./terrain.js";
import { import {
initCelestialLayer, initCelestialLayer,
loadCelestialStarMap,
refreshCelestialAfterContextRestore,
updateCelestialLayer, updateCelestialLayer,
disposeCelestialLayer, disposeCelestialLayer,
getCelestialDebugState, getCelestialDebugState,
@@ -94,6 +97,11 @@ import {
setCelestialFollow, setCelestialFollow,
setCelestialDayNightEnabled, setCelestialDayNightEnabled,
} from "./celestial.js"; } from "./celestial.js";
import {
computeEffectivePixelRatio,
createWebglRecoveryGuard,
markSceneTexturesNeedsUpdate,
} from "./webgl-recovery.js";
import { import {
clearCountryBoundaryData, clearCountryBoundaryData,
clearCountryBoundaryHover, clearCountryBoundaryHover,
@@ -280,6 +288,8 @@ import {
getMotionEnabledGestures, getMotionEnabledGestures,
getMotionProvider, getMotionProvider,
getVisibleMotionLayerDefinitions, getVisibleMotionLayerDefinitions,
getMotionCameraMode,
getMotionCameraDeviceId,
setMotionDebugEnabled, setMotionDebugEnabled,
setDayNightEnabledExternal, setDayNightEnabledExternal,
setTerrainLayerInteractable, setTerrainLayerInteractable,
@@ -322,7 +332,7 @@ import {
refreshLegend, refreshLegend,
setLegendItems, setLegendItems,
} from "./legend.js"; } from "./legend.js";
import { fetchEarthBrandConfig, mountBrand } from "./brand.js"; import { fetchEarthBrandConfig, mountBrand, recoverBrokenBrandImages } from "./brand.js";
import { runEarthStartup } from "./earth-startup.js"; import { runEarthStartup } from "./earth-startup.js";
import { initEarthAbout } from "./about.js"; import { initEarthAbout } from "./about.js";
import { initEarthOobe } from "./oobe.js"; import { initEarthOobe } from "./oobe.js";
@@ -396,6 +406,7 @@ let isDataLoading = false;
let currentLoadToken = 0; let currentLoadToken = 0;
let cablesEnabled = true; let cablesEnabled = true;
let satellitesEnabled = false; let satellitesEnabled = false;
let satelliteLoadAbortController = null;
let vesselsEnabled = false; let vesselsEnabled = false;
let cableToggleToken = 0; let cableToggleToken = 0;
let satelliteToggleToken = 0; let satelliteToggleToken = 0;
@@ -485,6 +496,9 @@ let canvasResizeObserver = null;
let pendingHoverEvent = null; let pendingHoverEvent = null;
let pendingHoverFrameId = null; let pendingHoverFrameId = null;
let desktopMinimized = false; let desktopMinimized = false;
let webglContextLost = false;
let webglRecoveryTimer = null;
const webglRecoveryGuard = createWebglRecoveryGuard();
const EARTH_UPDATES_CHANNEL = "earth_updates"; const EARTH_UPDATES_CHANNEL = "earth_updates";
const EARTH_UPDATES_RECONNECT_DELAY_MS = 5000; const EARTH_UPDATES_RECONNECT_DELAY_MS = 5000;
@@ -635,7 +649,11 @@ function syncRendererViewport() {
if (!camera || !renderer) return; if (!camera || !renderer) return;
camera.aspect = getViewportAspect(); camera.aspect = getViewportAspect();
camera.updateProjectionMatrix(); camera.updateProjectionMatrix();
const pixelRatio = Math.min(window.devicePixelRatio || 1, 2); const pixelRatio = computeEffectivePixelRatio(
window.innerWidth,
window.innerHeight,
window.devicePixelRatio || 1,
);
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);
updateCachedCanvasRect(); updateCachedCanvasRect();
@@ -4259,7 +4277,14 @@ function disableCables() {
refreshLegend(); refreshLegend();
} }
async function ensureSatellitesEnabled() { function abortPendingSatelliteLoad() {
if (satelliteLoadAbortController) {
satelliteLoadAbortController.abort();
satelliteLoadAbortController = null;
}
}
async function ensureSatellitesEnabled(options = {}) {
if (!scene || !camera || !renderer || destroyed) return 0; if (!scene || !camera || !renderer || destroyed) return 0;
const earth = getEarth(); const earth = getEarth();
@@ -4267,16 +4292,47 @@ async function ensureSatellitesEnabled() {
satellitesEnabled = true; satellitesEnabled = true;
const requestToken = ++satelliteToggleToken; const requestToken = ++satelliteToggleToken;
abortPendingSatelliteLoad();
const loadController = new AbortController();
satelliteLoadAbortController = loadController;
if (!getSatellitePoints()) { if (!getSatellitePoints()) {
createSatellites(scene, earth); createSatellites(scene, earth);
} }
clearSatelliteData(); clearSatelliteData();
const loadResult = await loadSatellites({ let loadResult;
try {
loadResult = await loadSatellites({
limit: getInitialSatelliteLoadLimit(), limit: getInitialSatelliteLoadLimit(),
cacheBust: true, forceNetwork: Boolean(options.forceNetwork),
signal: loadController.signal,
shouldApplyBackgroundUpdate: () =>
requestToken === satelliteToggleToken &&
satellitesEnabled &&
!destroyed,
onBackgroundUpdated: (nextResult) => {
reconcileSelectedSatellite();
updateSatelliteToggleUi(true, nextResult.count);
setLegendItems("satellites", getSatelliteLegendItems());
refreshLegend();
scheduleSatellitePositionWarmup();
},
}); });
} catch (error) {
if (
requestToken !== satelliteToggleToken ||
!satellitesEnabled ||
destroyed
) {
return 0;
}
throw error;
} finally {
if (satelliteLoadAbortController === loadController) {
satelliteLoadAbortController = null;
}
}
if ( if (
requestToken !== satelliteToggleToken || requestToken !== satelliteToggleToken ||
@@ -4346,6 +4402,7 @@ function disableSatellites() {
satellitesEnabled = false; satellitesEnabled = false;
satelliteToggleToken += 1; satelliteToggleToken += 1;
satelliteHydrationToken += 1; satelliteHydrationToken += 1;
abortPendingSatelliteLoad();
toggleSatellites(false); toggleSatellites(false);
resetSatelliteState(); resetSatelliteState();
updateSatelliteToggleUi(false, 0); updateSatelliteToggleUi(false, 0);
@@ -4461,6 +4518,72 @@ export function init() {
renderer.setClearColor(0x02040a, 1); renderer.setClearColor(0x02040a, 1);
publishWebGLGpuDiagnostics(renderer); publishWebGLGpuDiagnostics(renderer);
const clearWebglRecoveryTimer = () => {
if (webglRecoveryTimer) {
window.clearTimeout(webglRecoveryTimer);
webglRecoveryTimer = null;
}
};
cleanupFns.push(clearWebglRecoveryTimer);
const handleWebglContextLost = (event) => {
event?.preventDefault?.();
if (destroyed || webglContextLost) return;
webglContextLost = true;
document.documentElement.dataset.earthWebglContextLost = "1";
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
}
showStatusMessage(earthMessage("status.webglContextLost"), "info");
clearWebglRecoveryTimer();
webglRecoveryTimer = window.setTimeout(() => {
webglRecoveryTimer = null;
if (destroyed || !webglContextLost) return;
if (webglRecoveryGuard.canAutoReload()) {
webglRecoveryGuard.recordAutoReload();
showStatusMessage(earthMessage("status.webglReloading"), "info");
window.location.reload();
return;
}
showStatusMessage(earthMessage("status.webglReloadRequired"), "error");
}, 4500);
};
const handleWebglContextRestored = () => {
clearWebglRecoveryTimer();
if (destroyed) return;
webglContextLost = false;
delete document.documentElement.dataset.earthWebglContextLost;
renderer?.setClearColor?.(0x02040a, 1);
syncRendererViewport();
markSceneTexturesNeedsUpdate(scene);
void reloadEarthTextureAfterContextRestore().catch((error) => {
console.warn("[智能星球] 恢复地表贴图失败:", error);
});
void refreshCelestialAfterContextRestore().catch((error) => {
console.warn("[智能星球] 恢复星空贴图失败:", error);
});
recoverBrokenBrandImages(document.getElementById("brand-root"));
clock.getDelta();
if (!desktopMinimized && !animationFrameId) {
animate();
}
showStatusMessage(earthMessage("status.webglRestored"), "success");
};
const handleDesktopGpuProcessGone = (event) => {
console.warn("[智能星球] Desktop GPU process exited", event?.detail);
recoverBrokenBrandImages(document.getElementById("brand-root"));
if (!destroyed && !webglContextLost && renderer?.getContext?.()?.isContextLost?.()) {
handleWebglContextLost(null);
}
};
bindListener(renderer.domElement, "webglcontextlost", handleWebglContextLost);
bindListener(renderer.domElement, "webglcontextrestored", handleWebglContextRestored);
bindListener(window, "planet-desktop:gpu-process-gone", handleDesktopGpuProcessGone);
const container = document.getElementById("container"); const container = document.getElementById("container");
if (container) { if (container) {
container.querySelector("canvas")?.remove(); container.querySelector("canvas")?.remove();
@@ -4599,6 +4722,7 @@ export function init() {
visibleLayers: collectVisibleEarthLayers(), visibleLayers: collectVisibleEarthLayers(),
entityId: options.entityId !== undefined ? options.entityId : (domain === "compute" ? "CN" : null), entityId: options.entityId !== undefined ? options.entityId : (domain === "compute" ? "CN" : null),
initialQuestion: options.initialQuestion || "", initialQuestion: options.initialQuestion || "",
newsContext: options.newsContext || null,
autoAsk: options.autoAsk !== undefined ? Boolean(options.autoAsk) : true, autoAsk: options.autoAsk !== undefined ? Boolean(options.autoAsk) : true,
includeDrill: Boolean(options.includeDrill), includeDrill: Boolean(options.includeDrill),
preserveActiveContext: Boolean(options.preserveActiveContext), preserveActiveContext: Boolean(options.preserveActiveContext),
@@ -4618,6 +4742,7 @@ export function init() {
openWorkbenchForDomain(detail.domain || "global", { openWorkbenchForDomain(detail.domain || "global", {
entityId: detail.entityId ?? null, entityId: detail.entityId ?? null,
initialQuestion: detail.initialQuestion || "", initialQuestion: detail.initialQuestion || "",
newsContext: detail.newsContext || null,
autoAsk: detail.autoAsk !== undefined ? Boolean(detail.autoAsk) : true, autoAsk: detail.autoAsk !== undefined ? Boolean(detail.autoAsk) : true,
includeDrill: Boolean(detail.includeDrill), includeDrill: Boolean(detail.includeDrill),
}); });
@@ -4777,6 +4902,7 @@ export function init() {
backLight: sceneLights?.backLight ?? null, backLight: sceneLights?.backLight ?? null,
pointLight: sceneLights?.pointLight ?? null, pointLight: sceneLights?.pointLight ?? null,
earth: earthObj, earth: earthObj,
deferStarMap: true,
}); });
setCelestialDayNightEnabled(true); setCelestialDayNightEnabled(true);
createGridLines(scene, earthObj); createGridLines(scene, earthObj);
@@ -4812,6 +4938,9 @@ export function init() {
animate(); animate();
requestAnimationFrame(() => setTimeout(() => { requestAnimationFrame(() => setTimeout(() => {
if (destroyed || renderer !== startupRenderer) return; if (destroyed || renderer !== startupRenderer) return;
void loadCelestialStarMap().catch((error) => {
console.warn("[智能星球] 星空背景加载失败:", error);
});
initTVPanel(); initTVPanel();
initNewsPanel(); initNewsPanel();
connectEarthUpdatesRealtime(); connectEarthUpdatesRealtime();
@@ -4827,11 +4956,18 @@ export function init() {
}); });
} }
let activeMotionCameraMode = "";
let activeMotionCameraDeviceId = "";
function setupMotionControl() { function setupMotionControl() {
motionControlAdapter?.stop?.(); motionControlAdapter?.stop?.();
const motionModeActive = getRotationMode() === ROTATION_MODE.MOTION && getAutoRotate(); const motionModeActive = getRotationMode() === ROTATION_MODE.MOTION && getAutoRotate();
const motionDebugEnabled = motionModeActive && getMotionDebugEnabled(); const motionDebugEnabled = motionModeActive && getMotionDebugEnabled();
const motionEnabled = motionModeActive; const motionEnabled = motionModeActive;
const cameraMode = getMotionCameraMode();
const cameraDeviceId = getMotionCameraDeviceId();
activeMotionCameraMode = cameraMode;
activeMotionCameraDeviceId = cameraDeviceId;
setMotionDebugPanelVisible(motionDebugEnabled); setMotionDebugPanelVisible(motionDebugEnabled);
setMotionDebugPanelSkeletonOnly(getMotionDebugSkeletonOnly()); setMotionDebugPanelSkeletonOnly(getMotionDebugSkeletonOnly());
if (!motionEnabled) { if (!motionEnabled) {
@@ -4841,6 +4977,8 @@ function setupMotionControl() {
motionControlAdapter = createMotionControlAdapter({ motionControlAdapter = createMotionControlAdapter({
enabled: motionEnabled, enabled: motionEnabled,
provider: getMotionProvider(), provider: getMotionProvider(),
cameraMode,
cameraDeviceId,
onRotate: applyMotionRotate, onRotate: applyMotionRotate,
onZoom: applyMotionZoom, onZoom: applyMotionZoom,
onConfirm: applyMotionConfirm, onConfirm: applyMotionConfirm,
@@ -5162,7 +5300,7 @@ const EARTH_DATA_LAYER_HANDLERS = {
isVisible: () => satellitesEnabled || getShowSatellites(), isVisible: () => satellitesEnabled || getShowSatellites(),
localCount: () => getSatelliteCount(), localCount: () => getSatelliteCount(),
clear: applySatelliteEmptyState, clear: applySatelliteEmptyState,
refresh: ensureSatellitesEnabled, refresh: () => ensureSatellitesEnabled({ forceNetwork: true }),
refreshOnCountMismatch: true, refreshOnCountMismatch: true,
}, },
vessels: { vessels: {
@@ -5957,6 +6095,9 @@ export async function setSatellitesEnabled(
try { try {
const satelliteCount = await ensureSatellitesEnabled(); const satelliteCount = await ensureSatellitesEnabled();
if (!satellitesEnabled || destroyed) {
return 0;
}
if (!suppressStatus) { if (!suppressStatus) {
showStatusMessage(earthMessage("status.layerVisibility", { layer: "卫星", visible: true }), "info"); showStatusMessage(earthMessage("status.layerVisibility", { layer: "卫星", visible: true }), "info");
} }
@@ -6114,6 +6255,18 @@ function setupEventListeners() {
}; };
const handleMotionDebugModeChange = (event) => { const handleMotionDebugModeChange = (event) => {
const motionModeActive = getRotationMode() === ROTATION_MODE.MOTION && getAutoRotate(); const motionModeActive = getRotationMode() === ROTATION_MODE.MOTION && getAutoRotate();
const nextProvider = event?.detail?.provider;
const nextCameraMode = event?.detail?.cameraMode;
const nextCameraDeviceId = event?.detail?.cameraDeviceId;
const providerChanged =
Boolean(nextProvider) && motionControlAdapter?.getProvider?.() !== nextProvider;
const cameraChanged =
(nextCameraMode !== undefined && nextCameraMode !== activeMotionCameraMode) ||
(nextCameraDeviceId !== undefined && nextCameraDeviceId !== activeMotionCameraDeviceId);
if (motionModeActive && (providerChanged || cameraChanged)) {
setupMotionControl();
return;
}
const nextEnabled = motionModeActive && Boolean(event?.detail?.enabled); const nextEnabled = motionModeActive && Boolean(event?.detail?.enabled);
setMotionDebugPanelVisible(nextEnabled); setMotionDebugPanelVisible(nextEnabled);
setMotionDebugPanelSkeletonOnly(Boolean(event?.detail?.skeletonOnly)); setMotionDebugPanelSkeletonOnly(Boolean(event?.detail?.skeletonOnly));
@@ -6161,7 +6314,7 @@ function setupEventListeners() {
desktopMinimized = false; desktopMinimized = false;
clock.getDelta(); clock.getDelta();
updateSatellitePositions(0, true, { resetTrails: true }); updateSatellitePositions(0, true, { resetTrails: true });
if (!destroyed && !animationFrameId) { if (!destroyed && !webglContextLost && !animationFrameId) {
animate(); animate();
} }
} }
@@ -6901,7 +7054,7 @@ function onClick(event) {
} }
function animate() { function animate() {
if (destroyed || desktopMinimized) return; if (destroyed || desktopMinimized || webglContextLost) return;
animationFrameId = requestAnimationFrame(animate); animationFrameId = requestAnimationFrame(animate);
const frameNow = performance.now(); const frameNow = performance.now();
const stage = (name, update) => { const stage = (name, update) => {
@@ -7074,6 +7227,12 @@ export function destroy() {
if (destroyed) return; if (destroyed) return;
destroyed = true; destroyed = true;
desktopMinimized = false; desktopMinimized = false;
webglContextLost = false;
if (webglRecoveryTimer) {
window.clearTimeout(webglRecoveryTimer);
webglRecoveryTimer = null;
}
delete document.documentElement.dataset.earthWebglContextLost;
cancelPendingHoverMove(); cancelPendingHoverMove();
canvasResizeObserver?.disconnect(); canvasResizeObserver?.disconnect();
canvasResizeObserver = null; canvasResizeObserver = null;
@@ -7130,6 +7289,7 @@ export function destroy() {
clearComputeCenterData(getEarth()); clearComputeCenterData(getEarth());
clearCountryBoundaryData(); clearCountryBoundaryData();
clearEarthTexture(); clearEarthTexture();
abortPendingSatelliteLoad();
resetSatelliteState(); resetSatelliteState();
clearUiState(); clearUiState();
disposeCelestialLayer(); disposeCelestialLayer();
@@ -1,3 +1,9 @@
import {
buildCameraConstraints,
DEFAULT_MOTION_CAMERA_MODE,
inspectCameraTopology,
} from "./motion-camera-topology.js";
const MEDIAPIPE_TASKS_VERSION = "0.10.35"; const MEDIAPIPE_TASKS_VERSION = "0.10.35";
const MEDIAPIPE_TASKS_URLS = [ const MEDIAPIPE_TASKS_URLS = [
`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${MEDIAPIPE_TASKS_VERSION}/vision_bundle.mjs`, `https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${MEDIAPIPE_TASKS_VERSION}/vision_bundle.mjs`,
@@ -49,8 +55,8 @@ const ZOOM_HOLD_ELBOW_OUT_FACTOR = 0.25;
const CAMERA_CONSTRAINTS = { const CAMERA_CONSTRAINTS = {
video: { video: {
facingMode: "user", facingMode: "user",
width: { ideal: 1280 }, width: { ideal: 640 },
height: { ideal: 720 }, height: { ideal: 360 },
}, },
audio: false, audio: false,
}; };
@@ -416,54 +422,111 @@ function recognizeGesture(joints, previousJoints, options = {}) {
return null; return null;
} }
function uniqueStrings(values) {
const result = [];
const seen = new Set();
for (const value of values) {
const trimmed = String(value || "").trim();
if (!trimmed || seen.has(trimmed)) continue;
seen.add(trimmed);
result.push(trimmed);
}
return result;
}
function resolveSameOriginMediaPipeBase() {
if (typeof window === "undefined") return "";
const href = window.location?.href;
if (!href) return "";
try {
return new URL("./vendor/mediapipe", href).href.replace(/\/+$/, "");
} catch {
return "";
}
}
function resolveMediaPipeConfig() { function resolveMediaPipeConfig() {
const runtimeConfig = typeof globalThis !== "undefined" ? globalThis.__PLANET_RUNTIME_CONFIG__ : null; const runtimeConfig = typeof globalThis !== "undefined" ? globalThis.__PLANET_RUNTIME_CONFIG__ : null;
const localBase = typeof runtimeConfig?.localMediaPipeBaseUrl === "string" const localBase = typeof runtimeConfig?.localMediaPipeBaseUrl === "string"
? runtimeConfig.localMediaPipeBaseUrl.replace(/\/+$/, "") ? runtimeConfig.localMediaPipeBaseUrl.replace(/\/+$/, "")
: ""; : "";
const sameOriginBase = resolveSameOriginMediaPipeBase();
const baseUrl = localBase || sameOriginBase;
const localPoseModelUrl = typeof runtimeConfig?.localPoseModelUrl === "string" const localPoseModelUrl = typeof runtimeConfig?.localPoseModelUrl === "string"
? runtimeConfig.localPoseModelUrl.trim() ? runtimeConfig.localPoseModelUrl.trim()
: ""; : "";
const sameOriginModelUrl = baseUrl ? `${baseUrl}/pose_landmarker_lite.task` : "";
const delegates = runtimeConfig?.gpuTarget === "software" ? ["CPU"] : ["GPU", "CPU"];
return { return {
moduleUrls: localBase ? [`${localBase}/vision_bundle.mjs`, ...MEDIAPIPE_TASKS_URLS] : MEDIAPIPE_TASKS_URLS, moduleUrls: uniqueStrings([
wasmUrl: localBase ? `${localBase}/wasm` : MEDIAPIPE_WASM_URL, ...(baseUrl ? [`${baseUrl}/vision_bundle.mjs`] : []),
modelUrl: localPoseModelUrl || POSE_MODEL_URL, ...MEDIAPIPE_TASKS_URLS,
]),
wasmUrls: uniqueStrings([
...(baseUrl ? [`${baseUrl}/wasm`] : []),
MEDIAPIPE_WASM_URL,
]),
modelUrls: uniqueStrings([
localPoseModelUrl,
sameOriginModelUrl,
POSE_MODEL_URL,
]),
delegates,
}; };
} }
async function createDefaultRecognizer() { async function resolveVisionFileset(FilesetResolver, wasmUrls) {
const { moduleUrls, wasmUrl, modelUrl } = resolveMediaPipeConfig(); let lastError = null;
const { FilesetResolver, PoseLandmarker } = await importMediaPipeTasksVision(moduleUrls); for (const wasmUrl of wasmUrls) {
let vision;
try { try {
vision = await FilesetResolver.forVisionTasks(wasmUrl); return await FilesetResolver.forVisionTasks(wasmUrl);
} catch (error) { } catch (error) {
if (wasmUrl === MEDIAPIPE_WASM_URL) throw error; lastError = error;
vision = await FilesetResolver.forVisionTasks(MEDIAPIPE_WASM_URL);
} }
let pose; }
throw lastError || new Error("Unable to initialize MediaPipe WASM fileset");
}
async function createDefaultRecognizer(options = {}) {
const config = resolveMediaPipeConfig();
const importModule = options.importMediaPipe || importMediaPipeTasksVision;
const { FilesetResolver, PoseLandmarker } = await importModule(config.moduleUrls);
const vision = await resolveVisionFileset(FilesetResolver, config.wasmUrls);
let pose = null;
let lastError = null;
let activeDelegate = "GPU";
let activeModelUrl = POSE_MODEL_URL;
for (const modelUrl of config.modelUrls) {
for (const delegate of config.delegates) {
try { try {
pose = await PoseLandmarker.createFromOptions(vision, { pose = await PoseLandmarker.createFromOptions(vision, {
baseOptions: { baseOptions: {
modelAssetPath: modelUrl, modelAssetPath: modelUrl,
delegate: "GPU", delegate,
}, },
runningMode: "VIDEO", runningMode: "VIDEO",
numPoses: 1, numPoses: 1,
}); });
activeDelegate = delegate;
activeModelUrl = modelUrl;
break;
} catch (error) { } catch (error) {
if (modelUrl === POSE_MODEL_URL) throw error; lastError = error;
pose = await PoseLandmarker.createFromOptions(vision, { }
baseOptions: { }
modelAssetPath: POSE_MODEL_URL, if (pose) break;
delegate: "GPU", }
},
runningMode: "VIDEO", if (!pose) {
numPoses: 1, throw lastError || new Error("Unable to create PoseLandmarker");
});
} }
return { return {
delegate: activeDelegate,
modelUrl: activeModelUrl,
recognize(video, timestampMs) { recognize(video, timestampMs) {
const result = pose.detectForVideo(video, timestampMs); const result = pose.detectForVideo(video, timestampMs);
const landmarks = result?.landmarks?.[0] || []; const landmarks = result?.landmarks?.[0] || [];
@@ -496,6 +559,8 @@ async function importMediaPipeTasksVision(moduleUrls = MEDIAPIPE_TASKS_URLS) {
export function createBrowserCameraProvider(options = {}) { export function createBrowserCameraProvider(options = {}) {
const { const {
mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : null, mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : null,
cameraMode = DEFAULT_MOTION_CAMERA_MODE,
cameraDeviceId = "",
recognizerFactory = createDefaultRecognizer, recognizerFactory = createDefaultRecognizer,
requestAnimationFrameFn = requestAnimationFrameFn =
typeof requestAnimationFrame !== "undefined" typeof requestAnimationFrame !== "undefined"
@@ -521,12 +586,15 @@ export function createBrowserCameraProvider(options = {}) {
let lastGestureAt = 0; let lastGestureAt = 0;
let seq = 0; let seq = 0;
let previousJoints = []; let previousJoints = [];
let currentTopology = null;
let deviceChangeBound = false;
const gestureState = {}; const gestureState = {};
function emitState(detail = {}) { function emitState(detail = {}) {
onState({ onState({
provider: "browser_camera", provider: "browser_camera",
connected, connected,
...(currentTopology ? { topology: currentTopology } : {}),
...detail, ...detail,
}); });
} }
@@ -536,6 +604,34 @@ export function createBrowserCameraProvider(options = {}) {
emitState({ message, ...extra }); emitState({ message, ...extra });
} }
async function refreshTopology() {
currentTopology = await inspectCameraTopology(mediaDevices, {
requestedMode: cameraMode,
preferredDeviceId: cameraDeviceId,
});
return currentTopology;
}
function handleDeviceChange() {
if (disposed) return;
void refreshTopology().then((topology) => {
if (disposed) return;
emitState({ topology });
});
}
function bindDeviceChange() {
if (deviceChangeBound || typeof mediaDevices?.addEventListener !== "function") return;
mediaDevices.addEventListener("devicechange", handleDeviceChange);
deviceChangeBound = true;
}
function unbindDeviceChange() {
if (!deviceChangeBound || typeof mediaDevices?.removeEventListener !== "function") return;
mediaDevices.removeEventListener("devicechange", handleDeviceChange);
deviceChangeBound = false;
}
function stopStream() { function stopStream() {
onVideoSource({ onVideoSource({
provider: "browser_camera", provider: "browser_camera",
@@ -559,8 +655,10 @@ export function createBrowserCameraProvider(options = {}) {
type: "skeleton", type: "skeleton",
timestamp_ms: wallClockMs(), timestamp_ms: wallClockMs(),
source: "browser-camera", source: "browser-camera",
mode: "single", mode: currentTopology?.effectiveMode || "single",
camera_id: "browser:getUserMedia", camera_id: currentTopology?.selectedDeviceId
? `browser:${currentTopology.selectedDeviceId}`
: "browser:getUserMedia",
matched_gesture: matchedGesture, matched_gesture: matchedGesture,
confidence, confidence,
joints, joints,
@@ -579,7 +677,7 @@ export function createBrowserCameraProvider(options = {}) {
timestamp_ms: wallClockMs(), timestamp_ms: wallClockMs(),
seq, seq,
source: "browser-camera", source: "browser-camera",
mode: "single", mode: currentTopology?.effectiveMode || "single",
payload: {}, payload: {},
}); });
} }
@@ -623,6 +721,21 @@ export function createBrowserCameraProvider(options = {}) {
scheduleFrame(); scheduleFrame();
} }
async function openCameraStream(selectedDeviceId) {
if (!selectedDeviceId) {
return mediaDevices.getUserMedia(CAMERA_CONSTRAINTS);
}
const targetedConstraints = buildCameraConstraints(selectedDeviceId, CAMERA_CONSTRAINTS);
try {
return await mediaDevices.getUserMedia(targetedConstraints);
} catch (error) {
if (error?.name === "OverconstrainedError" || error?.name === "NotFoundError") {
return mediaDevices.getUserMedia(CAMERA_CONSTRAINTS);
}
throw error;
}
}
async function startCamera() { async function startCamera() {
if (!canUseBrowserCamera(mediaDevices)) { if (!canUseBrowserCamera(mediaDevices)) {
emitStatus("当前浏览器不支持 getUserMedia 摄像头接口", "error", { emitStatus("当前浏览器不支持 getUserMedia 摄像头接口", "error", {
@@ -637,6 +750,8 @@ export function createBrowserCameraProvider(options = {}) {
return false; return false;
} }
await refreshTopology();
try { try {
recognizer = await recognizerFactory(); recognizer = await recognizerFactory();
} catch (error) { } catch (error) {
@@ -648,7 +763,7 @@ export function createBrowserCameraProvider(options = {}) {
} }
try { try {
stream = await mediaDevices.getUserMedia(CAMERA_CONSTRAINTS); stream = await openCameraStream(currentTopology?.selectedDeviceId || "");
video = document.createElement("video"); video = document.createElement("video");
video.muted = true; video.muted = true;
video.playsInline = true; video.playsInline = true;
@@ -674,8 +789,30 @@ export function createBrowserCameraProvider(options = {}) {
return false; return false;
} }
const activeTrackDeviceId = stream?.getVideoTracks?.()?.[0]?.getSettings?.()?.deviceId || "";
if (
currentTopology?.physicalCameras?.some((camera) => !camera.rawLabel) ||
(activeTrackDeviceId && currentTopology?.selectedDeviceId !== activeTrackDeviceId)
) {
await refreshTopology();
if (activeTrackDeviceId && !cameraDeviceId) {
currentTopology = {
...currentTopology,
selectedDeviceId: activeTrackDeviceId,
};
}
}
bindDeviceChange();
connected = true; connected = true;
emitStatus("浏览器摄像头动捕已连接", "info"); emitStatus("本机摄像头动捕已连接", "info", {
topology: currentTopology,
});
if (currentTopology?.dualCameraDetected) {
emitStatus("检测到双摄像头:当前使用单摄 2D 模式(双摄 3D 深度规划中)", "info", {
topology: currentTopology,
});
}
scheduleFrame(); scheduleFrame();
return true; return true;
} }
@@ -688,6 +825,7 @@ export function createBrowserCameraProvider(options = {}) {
}, },
stop() { stop() {
disposed = true; disposed = true;
unbindDeviceChange();
if (rafId) { if (rafId) {
cancelAnimationFrameFn(rafId); cancelAnimationFrameFn(rafId);
rafId = null; rafId = null;
@@ -706,7 +844,9 @@ export function createBrowserCameraProvider(options = {}) {
export { export {
CAMERA_CONSTRAINTS, CAMERA_CONSTRAINTS,
createDefaultRecognizer,
importMediaPipeTasksVision, importMediaPipeTasksVision,
POSE_BONES, POSE_BONES,
recognizeGesture, recognizeGesture,
resolveMediaPipeConfig,
}; };
@@ -0,0 +1,149 @@
export const MOTION_CAMERA_MODE_AUTO = "auto";
export const MOTION_CAMERA_MODE_SINGLE = "single";
export const MOTION_CAMERA_MODE_DUAL_3D = "dual_3d";
export const MOTION_CAMERA_MODES = new Set([
MOTION_CAMERA_MODE_AUTO,
MOTION_CAMERA_MODE_SINGLE,
MOTION_CAMERA_MODE_DUAL_3D,
]);
export const DEFAULT_MOTION_CAMERA_MODE = MOTION_CAMERA_MODE_AUTO;
export const DUAL_3D_PLACEHOLDER_STATUS = "planned";
const DEFAULT_CAMERA_WIDTH = 640;
const DEFAULT_CAMERA_HEIGHT = 360;
const VIRTUAL_OR_IR_KEYWORDS = [
"obs",
"virtual",
"snap camera",
"manycam",
"droidcam",
"iriun",
"epoccam",
"splitcam",
"xsplit",
"youcam",
"infrared",
"windows hello",
"depth",
];
export function normalizeMotionCameraMode(
value,
fallback = DEFAULT_MOTION_CAMERA_MODE,
) {
const normalized = String(value || "").trim().toLowerCase();
if (normalized === "dual" || normalized === "3d" || normalized === "dual-3d") {
return MOTION_CAMERA_MODE_DUAL_3D;
}
return MOTION_CAMERA_MODES.has(normalized) ? normalized : fallback;
}
export function isVirtualOrInfraredCameraLabel(label) {
const normalized = String(label || "").trim().toLowerCase();
if (!normalized) return false;
if (VIRTUAL_OR_IR_KEYWORDS.some((keyword) => normalized.includes(keyword))) {
return true;
}
return /\bir\b/.test(normalized);
}
function normalizeCameraDevice(device, index) {
const deviceId = String(device?.deviceId || "").trim();
const groupId = String(device?.groupId || "").trim();
const label = String(device?.label || "").trim();
return {
deviceId,
groupId,
label: label || `摄像头 ${index + 1}`,
rawLabel: label,
index,
};
}
export function filterPhysicalVideoInputs(devices) {
if (!Array.isArray(devices)) return [];
const videoInputs = devices.filter((device) => device?.kind === "videoinput");
if (videoInputs.length === 0) return [];
const filtered = videoInputs.filter(
(device) => !isVirtualOrInfraredCameraLabel(device?.label),
);
const effectiveList = filtered.length > 0 ? filtered : videoInputs;
return effectiveList.map((device, index) => normalizeCameraDevice(device, index));
}
export async function inspectCameraTopology(
mediaDevices,
{ requestedMode = DEFAULT_MOTION_CAMERA_MODE, preferredDeviceId = "" } = {},
) {
const normalizedMode = normalizeMotionCameraMode(
requestedMode,
DEFAULT_MOTION_CAMERA_MODE,
);
const preferredId = String(preferredDeviceId || "").trim();
if (typeof mediaDevices?.enumerateDevices !== "function") {
return {
requestedMode: normalizedMode,
effectiveMode: MOTION_CAMERA_MODE_SINGLE,
physicalCameras: [],
dualCameraDetected: false,
dual3dStatus: DUAL_3D_PLACEHOLDER_STATUS,
dual3dFallbackReason:
normalizedMode === MOTION_CAMERA_MODE_DUAL_3D
? "dual_3d_not_yet_implemented"
: null,
selectedDeviceId: preferredId || null,
};
}
let devices = [];
try {
devices = await mediaDevices.enumerateDevices();
} catch (_error) {
devices = [];
}
const physicalCameras = filterPhysicalVideoInputs(devices);
const dualCameraDetected = physicalCameras.length >= 2;
const matchedPreferred = preferredId
? physicalCameras.find((camera) => camera.deviceId && camera.deviceId === preferredId)
: null;
const selectedDeviceId =
matchedPreferred?.deviceId || physicalCameras[0]?.deviceId || null;
const dual3dFallbackReason =
normalizedMode === MOTION_CAMERA_MODE_DUAL_3D ||
(normalizedMode === MOTION_CAMERA_MODE_AUTO && dualCameraDetected)
? "dual_3d_not_yet_implemented"
: null;
return {
requestedMode: normalizedMode,
effectiveMode: MOTION_CAMERA_MODE_SINGLE,
physicalCameras,
dualCameraDetected,
dual3dStatus: DUAL_3D_PLACEHOLDER_STATUS,
dual3dFallbackReason,
selectedDeviceId,
};
}
export function buildCameraConstraints(deviceId, baseConstraints = {}) {
const baseVideo =
baseConstraints?.video && typeof baseConstraints.video === "object"
? baseConstraints.video
: {};
const nextVideo = {
width: baseVideo.width || { ideal: DEFAULT_CAMERA_WIDTH },
height: baseVideo.height || { ideal: DEFAULT_CAMERA_HEIGHT },
};
const trimmedDeviceId = String(deviceId || "").trim();
if (trimmedDeviceId) {
nextVideo.deviceId = { exact: trimmedDeviceId };
} else {
nextVideo.facingMode = baseVideo.facingMode || "user";
}
return {
video: nextVideo,
audio: false,
};
}
+10 -1
View File
@@ -3,6 +3,7 @@ import {
DEFAULT_AGENT_URL, DEFAULT_AGENT_URL,
} from "./motion-agent-provider.js"; } from "./motion-agent-provider.js";
import { createBrowserCameraProvider } from "./motion-browser-provider.js"; import { createBrowserCameraProvider } from "./motion-browser-provider.js";
import { DEFAULT_MOTION_CAMERA_MODE } from "./motion-camera-topology.js";
import { import {
DEFAULT_MOTION_PROVIDER, DEFAULT_MOTION_PROVIDER,
MOTION_GESTURES, MOTION_GESTURES,
@@ -88,6 +89,8 @@ export function createMotionControlAdapter(options = {}) {
const { const {
enabled = false, enabled = false,
provider = DEFAULT_MOTION_PROVIDER, provider = DEFAULT_MOTION_PROVIDER,
cameraMode = DEFAULT_MOTION_CAMERA_MODE,
cameraDeviceId = "",
url = getConfiguredAgentUrl(), url = getConfiguredAgentUrl(),
minConfidence = DEFAULT_MIN_CONFIDENCE, minConfidence = DEFAULT_MIN_CONFIDENCE,
cooldownMs = DEFAULT_COOLDOWN_MS, cooldownMs = DEFAULT_COOLDOWN_MS,
@@ -210,6 +213,8 @@ export function createMotionControlAdapter(options = {}) {
if (providerFactories[selectedProvider]) { if (providerFactories[selectedProvider]) {
return providerFactories[selectedProvider]({ return providerFactories[selectedProvider]({
...sharedOptions, ...sharedOptions,
cameraMode,
cameraDeviceId,
url, url,
WebSocketCtor, WebSocketCtor,
}); });
@@ -223,7 +228,11 @@ export function createMotionControlAdapter(options = {}) {
enabledGestures: Array.from(enabledGestureSet), enabledGestures: Array.from(enabledGestureSet),
}); });
} }
return createBrowserCameraProvider(sharedOptions); return createBrowserCameraProvider({
...sharedOptions,
cameraMode,
cameraDeviceId,
});
} }
return { return {
@@ -4,9 +4,18 @@ import {
createMotionControlAdapter, createMotionControlAdapter,
normalizeMotionProvider, normalizeMotionProvider,
} from "./motion-control.js"; } from "./motion-control.js";
import {
buildCameraConstraints,
filterPhysicalVideoInputs,
inspectCameraTopology,
isVirtualOrInfraredCameraLabel,
normalizeMotionCameraMode,
} from "./motion-camera-topology.js";
import { import {
createBrowserCameraProvider, createBrowserCameraProvider,
createDefaultRecognizer,
recognizeGesture, recognizeGesture,
resolveMediaPipeConfig,
} from "./motion-browser-provider.js"; } from "./motion-browser-provider.js";
class TestEventTarget { class TestEventTarget {
@@ -859,4 +868,199 @@ describe("browser camera provider", () => {
type: "error", type: "error",
}); });
}); });
test("uses targeted deviceId constraint and falls back on OverconstrainedError", async () => {
installWindow();
installDocument();
const calls = [];
const states = [];
const provider = createBrowserCameraProvider({
cameraDeviceId: "cam-2",
mediaDevices: {
enumerateDevices: () =>
Promise.resolve([
{ kind: "videoinput", deviceId: "cam-1", label: "Logitech C1000e #1" },
{ kind: "videoinput", deviceId: "cam-2", label: "Logitech C1000e #2" },
]),
getUserMedia: (constraints) => {
calls.push(constraints);
if (calls.length === 1) {
return Promise.reject(Object.assign(new Error("overconstrained"), { name: "OverconstrainedError" }));
}
return Promise.resolve({
getTracks: () => [{ stop() {} }],
getVideoTracks: () => [{ getSettings: () => ({ deviceId: "cam-1" }) }],
});
},
},
recognizerFactory: () =>
Promise.resolve({
recognize: () => [],
close() {},
}),
requestAnimationFrameFn: () => 0,
onState: (state) => states.push(state),
});
const started = await provider.start();
provider.stop();
expect(started).toBe(true);
expect(calls[0].video.deviceId).toEqual({ exact: "cam-2" });
expect(calls[1].video.facingMode).toBe("user");
expect(states.some((state) => state.topology?.dualCameraDetected === true)).toBe(true);
expect(states.some((state) => state.topology?.effectiveMode === "single")).toBe(true);
expect(states.some((state) => state.topology?.dual3dStatus === "planned")).toBe(true);
});
});
describe("camera topology auto-detection", () => {
test("normalizes camera modes including dual_3d aliases", () => {
expect(normalizeMotionCameraMode("auto")).toBe("auto");
expect(normalizeMotionCameraMode("single")).toBe("single");
expect(normalizeMotionCameraMode("dual")).toBe("dual_3d");
expect(normalizeMotionCameraMode("3d")).toBe("dual_3d");
expect(normalizeMotionCameraMode("invalid", "auto")).toBe("auto");
});
test("filters virtual and infrared cameras while keeping physical USB cameras", () => {
expect(isVirtualOrInfraredCameraLabel("OBS Virtual Camera")).toBe(true);
expect(isVirtualOrInfraredCameraLabel("Logitech BRIO IR")).toBe(true);
expect(isVirtualOrInfraredCameraLabel("Logitech BRIO")).toBe(false);
const physical = filterPhysicalVideoInputs([
{ kind: "audioinput", deviceId: "mic-1", label: "Mic" },
{ kind: "videoinput", deviceId: "obs-1", label: "OBS Virtual Camera" },
{ kind: "videoinput", deviceId: "ir-1", label: "Logitech C1000e Windows Hello IR" },
{ kind: "videoinput", deviceId: "usb-1", label: "Logitech C1000e" },
{ kind: "videoinput", deviceId: "usb-2", label: "Logitech C1000e" },
]);
expect(physical.map((cam) => cam.deviceId)).toEqual(["usb-1", "usb-2"]);
});
test("falls back to all video inputs when every camera matches virtual filter", () => {
const physical = filterPhysicalVideoInputs([
{ kind: "videoinput", deviceId: "virt-1", label: "OBS Virtual Camera" },
]);
expect(physical.map((cam) => cam.deviceId)).toEqual(["virt-1"]);
});
test("auto mode reports single 2D active and dual_3d planned when two physical cameras exist", async () => {
const singleTopology = await inspectCameraTopology({
enumerateDevices: () =>
Promise.resolve([
{ kind: "videoinput", deviceId: "usb-1", label: "Logitech C1000e" },
]),
});
expect(singleTopology.dualCameraDetected).toBe(false);
expect(singleTopology.effectiveMode).toBe("single");
expect(singleTopology.dual3dFallbackReason).toBeNull();
const dualTopology = await inspectCameraTopology({
enumerateDevices: () =>
Promise.resolve([
{ kind: "videoinput", deviceId: "usb-1", label: "Logitech C1000e" },
{ kind: "videoinput", deviceId: "usb-2", label: "Logitech C1000e" },
]),
});
expect(dualTopology.dualCameraDetected).toBe(true);
expect(dualTopology.effectiveMode).toBe("single");
expect(dualTopology.dual3dStatus).toBe("planned");
expect(dualTopology.dual3dFallbackReason).toBe("dual_3d_not_yet_implemented");
expect(buildCameraConstraints("usb-2").video).toEqual({
width: { ideal: 640 },
height: { ideal: 360 },
deviceId: { exact: "usb-2" },
});
});
test("handles missing enumerateDevices safely", async () => {
const topology = await inspectCameraTopology(null, { preferredDeviceId: "usb-1" });
expect(topology.effectiveMode).toBe("single");
expect(topology.physicalCameras).toEqual([]);
expect(topology.selectedDeviceId).toBe("usb-1");
});
});
describe("MediaPipe local resolution and GPU-to-CPU fallback", () => {
test("prefers Electron runtime local URLs and same-origin Web URLs ahead of CDNs", () => {
const previousRuntime = globalThis.__PLANET_RUNTIME_CONFIG__;
const previousWindow = globalThis.window;
try {
globalThis.__PLANET_RUNTIME_CONFIG__ = {
localMediaPipeBaseUrl: "planet://earth/earth/vendor/mediapipe",
localPoseModelUrl: "planet://earth/earth/vendor/mediapipe/pose_landmarker_lite.task",
gpuTarget: "software",
};
const electronConfig = resolveMediaPipeConfig();
expect(electronConfig.moduleUrls[0]).toBe("planet://earth/earth/vendor/mediapipe/vision_bundle.mjs");
expect(electronConfig.wasmUrls[0]).toBe("planet://earth/earth/vendor/mediapipe/wasm");
expect(electronConfig.modelUrls[0]).toBe("planet://earth/earth/vendor/mediapipe/pose_landmarker_lite.task");
expect(electronConfig.delegates).toEqual(["CPU"]);
delete globalThis.__PLANET_RUNTIME_CONFIG__;
globalThis.window = {
location: { href: "https://planet.example.com/earth/index.html" },
};
const webConfig = resolveMediaPipeConfig();
expect(webConfig.moduleUrls[0]).toBe("https://planet.example.com/earth/vendor/mediapipe/vision_bundle.mjs");
expect(webConfig.wasmUrls[0]).toBe("https://planet.example.com/earth/vendor/mediapipe/wasm");
expect(webConfig.modelUrls[0]).toBe("https://planet.example.com/earth/vendor/mediapipe/pose_landmarker_lite.task");
expect(webConfig.delegates).toEqual(["GPU", "CPU"]);
} finally {
globalThis.__PLANET_RUNTIME_CONFIG__ = previousRuntime;
globalThis.window = previousWindow;
}
});
test("falls back from GPU delegate to CPU delegate when GPU initialization fails", async () => {
const previousRuntime = globalThis.__PLANET_RUNTIME_CONFIG__;
const previousWindow = globalThis.window;
const attempts = [];
try {
globalThis.__PLANET_RUNTIME_CONFIG__ = {
localMediaPipeBaseUrl: "planet://earth/earth/vendor/mediapipe",
localPoseModelUrl: "planet://earth/earth/vendor/mediapipe/pose_landmarker_lite.task",
};
const recognizer = await createDefaultRecognizer({
importMediaPipe: async () => ({
FilesetResolver: {
forVisionTasks: async () => ({ wasmReady: true }),
},
PoseLandmarker: {
createFromOptions: async (_vision, opts) => {
attempts.push({
modelAssetPath: opts.baseOptions.modelAssetPath,
delegate: opts.baseOptions.delegate,
});
if (opts.baseOptions.delegate === "GPU") {
throw new Error("WebGL unavailable");
}
return {
detectForVideo: () => ({ landmarks: [] }),
close() {},
};
},
},
}),
});
expect(attempts).toEqual([
{
modelAssetPath: "planet://earth/earth/vendor/mediapipe/pose_landmarker_lite.task",
delegate: "GPU",
},
{
modelAssetPath: "planet://earth/earth/vendor/mediapipe/pose_landmarker_lite.task",
delegate: "CPU",
},
]);
expect(recognizer.delegate).toBe("CPU");
recognizer.close();
} finally {
globalThis.__PLANET_RUNTIME_CONFIG__ = previousRuntime;
globalThis.window = previousWindow;
}
});
}); });
@@ -47,7 +47,7 @@ let mobilePlayFlashTimer = null;
let mobileLastTapAt = 0; let mobileLastTapAt = 0;
function getProviderLabel(value) { function getProviderLabel(value) {
return value === "motion_agent" ? "Motion Agent" : "浏览器摄像头"; return value === "motion_agent" ? "Motion Agent" : "本机摄像头";
} }
function createCanvasElement() { function createCanvasElement() {
+34 -4
View File
@@ -58,9 +58,22 @@ export function initNewsRegionCards({ rootParent, spatial }) {
card.animation = card.content.animate([{opacity:0},{opacity:1}], {duration:180,easing:"ease"}); card.animation = card.content.animate([{opacity:0},{opacity:1}], {duration:180,easing:"ease"});
} }
const url = String(snapshot.item?.url || ""); const url = String(snapshot.item?.url || "");
const rawItem = snapshot.item || null;
card.currentStory = rawItem ? {
id: rawItem.id || null,
title: data?.title || rawItem.title || "",
summary: data?.summary || rawItem.summary || "",
source: rawItem.source || rawItem.feed_name || "",
region: getNewsRegionLabel(region.key),
region_key: region.key,
published_at: rawItem.published_at || "",
category: rawItem.category || "",
url,
} : null;
card.source.hidden = !/^https?:\/\//i.test(url); card.source.hidden = !/^https?:\/\//i.test(url);
if (!card.source.hidden) card.source.href = url; else card.source.removeAttribute("href"); if (!card.source.hidden) card.source.href = url; else card.source.removeAttribute("href");
card.source.textContent = text("阅读原文 ↗","Read source ↗"); card.source.textContent = text("阅读原文 ↗","Read source ↗");
if (card.analyze) card.analyze.disabled = !card.currentStory;
} }
card.count.textContent = snapshot.count ? `${snapshot.index+1} / ${snapshot.count}` : "0 / 0"; card.count.textContent = snapshot.count ? `${snapshot.index+1} / ${snapshot.count}` : "0 / 0";
card.previous.disabled = card.next.disabled = snapshot.count < 2; card.previous.disabled = card.next.disabled = snapshot.count < 2;
@@ -75,11 +88,11 @@ export function initNewsRegionCards({ rootParent, spatial }) {
const element=document.createElement("article"); const element=document.createElement("article");
element.className="hud-panel info-card news news-region-card"; element.className="hud-panel info-card news news-region-card";
element.dataset.region=region.key; element.dataset.region=region.key;
element.innerHTML=`<header class="info-card-header hud-panel-drag-handle"><span class="info-card-icon" aria-hidden="true">${NEWS_CARD_ICON}</span><h3></h3><span class="news-region-card__region"></span><div class="hud-panel__actions">${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}</div></header><div class="news-region-card__body hud-panel__body hud-panel__body--collapsible"><div class="info-card-content news-region-card__content hud-scroll-region"></div><footer class="news-region-card__footer">${iconButton("news-prev","chevron_left",text("上一条新闻","Previous story"))}<span class="news-region-card__count"></span>${iconButton("news-next","chevron_right",text("下一条新闻","Next story"))}${iconButton("news-play","pause",text("暂停轮播","Pause rotation"))}<a target="_blank" rel="noopener noreferrer" hidden></a></footer></div>`; element.innerHTML=`<header class="info-card-header hud-panel-drag-handle"><span class="info-card-icon" aria-hidden="true">${NEWS_CARD_ICON}</span><h3 class="news-region-card__headline"></h3><span class="news-region-card__region"></span><div class="hud-panel__actions">${iconButton("news-analyze","forum",text("在 AI 参谋中分析","Analyze in AI Copilot"))}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}</div></header><div class="news-region-card__body hud-panel__body hud-panel__body--collapsible"><div class="info-card-content news-region-card__content hud-scroll-region"></div><footer class="news-region-card__footer">${iconButton("news-prev","chevron_left",text("上一条新闻","Previous story"))}<span class="news-region-card__count"></span>${iconButton("news-next","chevron_right",text("下一条新闻","Next story"))}${iconButton("news-play","pause",text("暂停轮播","Pause rotation"))}<a target="_blank" rel="noopener noreferrer" hidden></a></footer></div>`;
const card={ element, hovered:false, signature:null, typing:false, writer:createTypewriter(), const card={ element, hovered:false, signature:null, typing:false, writer:createTypewriter(), currentStory:null,
title:element.querySelector("h3"), region:element.querySelector(".news-region-card__region"), content:element.querySelector(".news-region-card__content"), title:element.querySelector("h3"), region:element.querySelector(".news-region-card__region"), content:element.querySelector(".news-region-card__content"),
count:element.querySelector(".news-region-card__count"),source:element.querySelector("a"), count:element.querySelector(".news-region-card__count"),source:element.querySelector("a"),
previous:element.querySelector('[data-action="news-prev"]'),next:element.querySelector('[data-action="news-next"]'),play:element.querySelector('[data-action="news-play"]'), previous:element.querySelector('[data-action="news-prev"]'),next:element.querySelector('[data-action="news-next"]'),play:element.querySelector('[data-action="news-play"]'),analyze:element.querySelector('[data-action="news-analyze"]'),
}; };
card.panel=createHUDPanel({panel:element,header:element.querySelector("header"),body:element.querySelector(".news-region-card__body"),collapseBtn:element.querySelector('[data-action="card-collapse"]'),expandLabel:text("展开新闻","Expand news"),collapseLabel:text("折叠新闻","Collapse news")}); card.panel=createHUDPanel({panel:element,header:element.querySelector("header"),body:element.querySelector(".news-region-card__body"),collapseBtn:element.querySelector('[data-action="card-collapse"]'),expandLabel:text("展开新闻","Expand news"),collapseLabel:text("折叠新闻","Collapse news")});
element.addEventListener("pointerenter",()=>{card.hovered=true;}); element.addEventListener("pointerenter",()=>{card.hovered=true;});
@@ -89,6 +102,22 @@ export function initNewsRegionCards({ rootParent, spatial }) {
if(action === "news-prev") model.step(region.key,-1); if(action === "news-prev") model.step(region.key,-1);
else if(action === "news-next") model.step(region.key); else if(action === "news-next") model.step(region.key);
else if(action === "news-play") model.togglePaused(region.key); else if(action === "news-play") model.togglePaused(region.key);
else if(action === "news-analyze") {
if (!card.currentStory) return;
const story = card.currentStory;
window.dispatchEvent(new CustomEvent("earth:open-workbench", {
detail: {
domain: "news",
entityId: story.id || null,
newsContext: story,
initialQuestion: story.title
? text(`请深度分析这条新闻:「${story.title}」`, `Analyze this news story in depth: "${story.title}"`)
: text("请分析这条全球新闻动态与潜在影响。", "Analyze this news development and its potential impact."),
autoAsk: true,
},
}));
return;
}
else if(action === "card-collapse") { else if(action === "card-collapse") {
card.panel.setCollapsed(!card.panel.isCollapsed()); card.panel.setCollapsed(!card.panel.isCollapsed());
spatial.invalidate(); spatial.invalidate();
@@ -146,7 +175,8 @@ export function initNewsRegionCards({ rootParent, spatial }) {
root.setAttribute("aria-label",text("区域新闻卡片","Regional news cards")); root.setAttribute("aria-label",text("区域新闻卡片","Regional news cards"));
for(const region of NEWS_CARD_REGIONS) { for(const region of NEWS_CARD_REGIONS) {
const card=cards.get(region.key); const card=cards.get(region.key);
for(const [button,label] of [[card.previous,text("上一条新闻","Previous story")],[card.next,text("下一条新闻","Next story")]]) { for(const [button,label] of [[card.previous,text("上一条新闻","Previous story")],[card.next,text("下一条新闻","Next story")],[card.analyze,text("在 AI 参谋中分析","Analyze in AI Copilot")]]) {
if(!button) continue;
button.title=label;button.setAttribute("aria-label",label); button.title=label;button.setAttribute("aria-label",label);
} }
renderStory(region,true); renderStory(region,true);
+46 -2
View File
@@ -987,18 +987,25 @@ function renderPayload(nextPayload, { forcePanelRender = false } = {}) {
<span class="news-story-tag">${escapeNewsHtml(statusLabel)}</span> <span class="news-story-tag">${escapeNewsHtml(statusLabel)}</span>
`; `;
return ` return `
<a class="${cardClass}" data-news-id="${item.id}" href="${item.url}" target="_blank" rel="noreferrer noopener" title="${escapeNewsHtml(sourceDescriptor.tooltip)}"> <article class="${cardClass}" data-news-id="${item.id}" title="${escapeNewsHtml(sourceDescriptor.tooltip)}">
<div class="news-story-meta"> <div class="news-story-meta">
<span class="news-story-source">${escapeNewsHtml(sourceDescriptor.sourceName)}</span> <span class="news-story-source">${escapeNewsHtml(sourceDescriptor.sourceName)}</span>
<span class="news-story-meta-right">
<span class="news-story-time">${formatRelativeTime(item.published_at)}</span> <span class="news-story-time">${formatRelativeTime(item.published_at)}</span>
<button type="button" class="hud-panel__action news-story-analyze-btn" data-news-analyze="${escapeNewsHtml(String(item.id || ""))}" aria-label="${escapeNewsHtml(translateText("在 AI 参谋中分析"))}" title="${escapeNewsHtml(translateText("在 AI 参谋中分析"))}">
<span class="material-symbols-rounded" aria-hidden="true">forum</span>
</button>
</span>
</div> </div>
<div class="news-story-origin">${escapeNewsHtml(sourceDescriptor.originLabel)}</div> <div class="news-story-origin">${escapeNewsHtml(sourceDescriptor.originLabel)}</div>
<a class="news-story-link" href="${escapeNewsHtml(item.url || "#")}" target="_blank" rel="noreferrer noopener">
<div class="news-story-title">${escapeNewsHtml(leadText)}</div> <div class="news-story-title">${escapeNewsHtml(leadText)}</div>
${summary} ${summary}
</a>
<div class="news-story-tags"> <div class="news-story-tags">
${tagHtml} ${tagHtml}
</div> </div>
</a> </article>
`; `;
}) })
.join(""); .join("");
@@ -1551,6 +1558,43 @@ export function initNewsPanel() {
document.addEventListener("click", (event) => { document.addEventListener("click", (event) => {
const target = event.target instanceof Element ? event.target : null; const target = event.target instanceof Element ? event.target : null;
if (!target) return; if (!target) return;
const analyzeBtn = target.closest("[data-news-analyze]");
if (analyzeBtn instanceof HTMLElement) {
event.preventDefault();
event.stopPropagation();
const targetId = analyzeBtn.dataset.newsAnalyze || "";
const candidates = [
...(Array.isArray(payload?.items) ? payload.items : []),
...(Array.isArray(payload?.cruise_items) ? payload.cruise_items : []),
];
const matched = candidates.find((item) => String(item?.id || "") === targetId);
if (matched) {
const displayTitle = getNewsDisplayTitle(matched) || getNewsDisplaySummary(matched);
const displaySummary = getNewsDisplaySummary(matched);
window.dispatchEvent(new CustomEvent("earth:open-workbench", {
detail: {
domain: "news",
entityId: matched.id || null,
newsContext: {
id: matched.id || null,
title: displayTitle,
summary: displaySummary && displaySummary !== displayTitle ? displaySummary : (matched.summary || ""),
source: matched.source || matched.feed_name || "",
region: getNewsRegionDisplayLabel(matched.region, matched.display_region),
region_key: matched.region || "",
published_at: matched.published_at || "",
category: matched.category || "",
url: matched.url || "",
},
initialQuestion: displayTitle
? (getEarthLocale() === "en-US" ? `Analyze this news story in depth: "${displayTitle}"` : `请深度分析这条新闻:「${displayTitle}」`)
: translateText("请分析这条全球新闻动态与潜在影响。"),
autoAsk: true,
},
}));
}
return;
}
const filterToggle = target.closest("[data-news-filter-toggle]"); const filterToggle = target.closest("[data-news-filter-toggle]");
if (filterToggle instanceof HTMLElement) { if (filterToggle instanceof HTMLElement) {
const kind = filterToggle.dataset.newsFilterToggle || ""; const kind = filterToggle.dataset.newsFilterToggle || "";
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more