Compare commits

..
3 Commits
Author SHA1 Message Date
linkong 352b34e7c6 release: bump version to 0.79.1
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-24 21:00:42 +08:00
linkong 1e9508f2f1 ci: deploy published Planet releases by image digest
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-24 17:27:54 +08:00
linkong e53c3af355 release: bump version to 0.79.0
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release / images (push) Waiting to run
release / client_release (push) Waiting to run
2026-11-24 15:40:10 +08:00
52 changed files with 6009 additions and 520 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
When remote publication is requested, verify the remote tag points to the
release commit. Check the tag's Gitea Actions run and its release job. A queued
run without an online runner does not publish anything.
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
using the command below. The publisher 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
exact tag. Reuse verified artifacts when available, or build with Bun from the
tag in a clean checkout. Use an asset directory that contains only this release.
```bash
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
```
When verified desktop artifacts for the exact tag already exist, pass their
directory explicitly. A queued Gitea Actions run does not block local publication.
```bash
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run
+14 -20
View File
@@ -4,8 +4,7 @@ on:
push:
branches:
- main
tags:
- "v*"
# Tagged production releases are published on demand from the workstation.
workflow_dispatch:
env:
@@ -17,18 +16,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Resolve image tags
id: meta
run: |
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
else
echo "release_tag=" >> "$GITHUB_OUTPUT"
fi
- name: Login to registry
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
- name: Build and push images
env:
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
- name: Publish immutable production images
if: startsWith(github.ref, 'refs/tags/v')
run: |
export PLANET_RELEASE_DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
python3 scripts/production_release.py "$GITHUB_REF_NAME"
- name: Build and push staging images
if: "!startsWith(github.ref, 'refs/tags/v')"
run: |
for service in frontend admin backend aiprovider; do
extra_build_args=""
@@ -52,18 +51,13 @@ jobs:
;;
esac
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}"
image="$REGISTRY/$IMAGE_NAMESPACE/$service:$GITHUB_SHA"
docker build $extra_build_args -t "$image" -f "$dockerfile" "$context"
docker push "$image"
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
docker tag "$image" "$release_image"
docker push "$release_image"
fi
done
client_release:
needs: images
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
+1 -1
View File
@@ -1 +1 @@
0.78.0
0.79.1
+2
View File
@@ -8,6 +8,7 @@ from app.api.v1 import (
datasources,
docs,
earth,
client_updates,
tasks,
dashboard,
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(docs.router, prefix="/docs", tags=["docs"])
api_router.include_router(earth.router, prefix="/earth", tags=["earth"])
api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"])
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboard"])
api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"])
+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}
+5
View File
@@ -87,6 +87,11 @@ class Settings(BaseSettings):
AI_PROVIDER_RETRY_ATTEMPTS: int = 2
OBSERVABILITY_INGEST_TOKEN: str = ""
CLIENT_UPDATES_DIR: str = ""
CLIENT_UPDATE_PUBLISH_TOKEN: str = ""
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
@property
def is_production(self) -> bool:
return str(self.APP_ENV or "").strip().lower() == "production"
+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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-client",
"version": "0.78.0",
"version": "0.79.1",
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true,
"packageManager": "bun@1",
+50 -1
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 { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs'
import { createTarGz } from '../src/main/tar-gz.ts'
const __dirname = dirname(fileURLToPath(import.meta.url))
const desktopRoot = join(__dirname, '..')
@@ -100,3 +102,50 @@ if (existsSync(mediaPipeWasmDir)) {
}
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 path from 'node:path'
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
export type SplashTheme = 'singularity' | 'off'
export type GpuRenderMode = 'auto' | 'high-performance' | 'low-power' | 'software'
export interface ServerEndpoints {
backendUrl: string
@@ -11,6 +12,23 @@ export interface ServerEndpoints {
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
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 {
@@ -22,18 +40,23 @@ export interface DesktopLaunchFlags {
smokeOutputPath: string | null
deepLinkUrl: string | null
splashThemeOverride?: SplashTheme
gpuModeOverride?: GpuRenderMode
gpuHandoff: boolean
gpuHandoffTarget?: GpuHandoffTarget
}
export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags {
wsUrl: string
splashTheme: SplashTheme
gpuMode: GpuRenderMode
}
const VALID_SPLASH_THEMES: ReadonlySet<SplashTheme> = new Set([
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
'singularity',
'constellation',
'horizon',
'off',
'on',
'default',
])
export function normalizeSplashTheme(
@@ -41,8 +64,38 @@ export function normalizeSplashTheme(
fallback: SplashTheme = 'singularity',
): SplashTheme {
if (typeof raw !== 'string') return fallback
const normalized = raw.trim().toLowerCase() as SplashTheme
return VALID_SPLASH_THEMES.has(normalized) ? normalized : fallback
const normalized = raw.trim().toLowerCase()
if (normalized === 'off') return 'off'
return LEGACY_ACTIVE_THEMES.has(normalized) ? 'singularity' : fallback
}
export function normalizeGpuMode(
raw: unknown,
fallback: GpuRenderMode = 'auto',
): GpuRenderMode {
if (typeof raw !== 'string') return fallback
const normalized = raw.trim().toLowerCase()
if (normalized === 'auto') return 'auto'
if (
normalized === 'high-performance' ||
normalized === 'high' ||
normalized === 'discrete' ||
normalized === 'dgpu'
) {
return 'high-performance'
}
if (
normalized === 'low-power' ||
normalized === 'low' ||
normalized === 'integrated' ||
normalized === 'igpu'
) {
return 'low-power'
}
if (normalized === 'software' || normalized === 'cpu' || normalized === 'swiftshader') {
return 'software'
}
return fallback
}
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
@@ -113,6 +166,7 @@ export function parseLaunchArgs(argv: string[]): {
headlessSmoke: false,
smokeOutputPath: null,
deepLinkUrl: null,
gpuHandoff: false,
}
for (let i = 0; i < argv.length; i += 1) {
@@ -134,6 +188,22 @@ export function parseLaunchArgs(argv: string[]): {
flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length))
} else if (arg === '--splash-theme' && argv[i + 1]) {
flags.splashThemeOverride = normalizeSplashTheme(argv[++i])
} else if (arg.startsWith('--gpu-mode=')) {
flags.gpuModeOverride = normalizeGpuMode(arg.slice('--gpu-mode='.length))
} else if (arg === '--gpu-mode' && argv[i + 1]) {
flags.gpuModeOverride = normalizeGpuMode(argv[++i])
} else if (arg === '--software-gl') {
flags.gpuModeOverride = 'software'
} else if (arg === '--low-power-gpu') {
flags.gpuModeOverride = 'low-power'
} else if (arg === '--high-performance-gpu') {
flags.gpuModeOverride = 'high-performance'
} else if (arg === '--gpu-handoff') {
flags.gpuHandoff = true
} else if (arg.startsWith('--gpu-handoff-target=')) {
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(arg.slice('--gpu-handoff-target='.length))
} else if (arg === '--gpu-handoff-target' && argv[i + 1]) {
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(argv[++i])
} else if (arg === '--fullscreen') {
flags.fullscreen = true
} else if (arg === '--kiosk') {
@@ -155,6 +225,55 @@ export function parseLaunchArgs(argv: string[]): {
return { endpoints, flags }
}
function getPortableConfigPaths(exeDir: string, resourcesDir?: string): string[] {
const candidates: string[] = []
if (exeDir) {
candidates.push(path.join(exeDir, 'planet-earth.json'))
}
if (resourcesDir) {
candidates.push(path.join(resourcesDir, 'planet-earth.json'))
}
return candidates
}
function readFirstPortableConfig(paths: string[]): PersistedUserConfig {
for (const candidate of paths) {
const data = readJsonFileSafe(candidate)
if (Object.keys(data).length > 0) {
return data
}
}
return {}
}
export function readPreReadyGpuMode(options: {
userDataDir: string
exeDir: string
resourcesDir?: string
argv: string[]
env?: NodeJS.ProcessEnv
}): GpuRenderMode {
const env = options.env ?? process.env
const { flags } = parseLaunchArgs(options.argv)
const portable = readFirstPortableConfig(getPortableConfigPaths(options.exeDir, options.resourcesDir))
const userSaved = options.userDataDir ? readJsonFileSafe(path.join(options.userDataDir, 'config.json')) : {}
return normalizeGpuMode(
flags.gpuModeOverride ?? env.PLANET_GPU_MODE ?? portable.gpuMode ?? userSaved.gpuMode,
'auto',
)
}
export function readPreReadyGpuHandoff(argv: string[]): {
gpuHandoff: boolean
gpuHandoffTarget?: GpuHandoffTarget
} {
const { flags } = parseLaunchArgs(argv)
return {
gpuHandoff: flags.gpuHandoff,
gpuHandoffTarget: flags.gpuHandoffTarget,
}
}
export class DesktopConfigStore {
private readonly userConfigPath: string
private readonly portableConfigPaths: string[]
@@ -170,10 +289,7 @@ export class DesktopConfigStore {
env?: NodeJS.ProcessEnv
}) {
this.userConfigPath = path.join(options.userDataDir, 'config.json')
this.portableConfigPaths = [
path.join(options.exeDir, 'planet-earth.json'),
...(options.resourcesDir ? [path.join(options.resourcesDir, 'planet-earth.json')] : []),
]
this.portableConfigPaths = getPortableConfigPaths(options.exeDir, options.resourcesDir)
const parsed = parseLaunchArgs(options.argv)
this.cliEndpoints = parsed.endpoints
this.launchFlags = parsed.flags
@@ -182,14 +298,7 @@ export class DesktopConfigStore {
private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig {
const userSaved = readJsonFileSafe(this.userConfigPath)
let portable: PersistedUserConfig = {}
for (const candidate of this.portableConfigPaths) {
const data = readJsonFileSafe(candidate)
if (Object.keys(data).length > 0) {
portable = data
break
}
}
const portable = readFirstPortableConfig(this.portableConfigPaths)
const backendUrl = normalizeHttpUrl(
this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl,
@@ -210,6 +319,13 @@ export class DesktopConfigStore {
userSaved.splashTheme,
'singularity',
)
const gpuMode = normalizeGpuMode(
this.launchFlags.gpuModeOverride ??
env.PLANET_GPU_MODE ??
portable.gpuMode ??
userSaved.gpuMode,
'auto',
)
return {
backendUrl,
@@ -217,6 +333,7 @@ export class DesktopConfigStore {
motionWsUrl,
wsUrl: deriveBackendWsUrl(backendUrl),
splashTheme,
gpuMode,
...this.launchFlags,
}
}
@@ -258,4 +375,14 @@ export class DesktopConfigStore {
}
return this.get()
}
updateGpuMode(rawMode: unknown): DesktopRuntimeConfig {
const nextMode = normalizeGpuMode(rawMode, this.current.gpuMode)
this.writeUserConfig({ gpuMode: nextMode })
this.current = {
...this.current,
gpuMode: nextMode,
}
return this.get()
}
}
+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
},
}
}
+229 -26
View File
@@ -1,30 +1,73 @@
import fs from 'node:fs'
import path from 'node:path'
import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron'
import { app, BrowserWindow, dialog, ipcMain, Menu, 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 { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy'
import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core'
import { createHotUpdateController } from './hot-updater'
import { buildApplicationMenu } from './menu'
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation } from './window'
import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
registerEarthScheme()
const isHeadlessSmoke = process.argv.includes('--headless-smoke')
if (isHeadlessSmoke) {
app.commandLine.appendSwitch('disable-gpu')
app.commandLine.appendSwitch('use-gl', 'angle')
app.commandLine.appendSwitch('use-angle', 'swiftshader')
app.commandLine.appendSwitch('enable-unsafe-swiftshader')
} else {
// Prioritize discrete/high-performance GPU and avoid throttling visible secondary-screen renders.
app.commandLine.appendSwitch('force_high_performance_gpu')
app.commandLine.appendSwitch('enable-gpu-rasterization')
app.commandLine.appendSwitch('enable-zero-copy')
app.commandLine.appendSwitch('disable-renderer-backgrounding')
if (process.platform === 'linux') {
app.commandLine.appendSwitch('ozone-platform-hint', 'auto')
let preReadyUserDataDir = ''
let preReadyExeDir = process.cwd()
try {
preReadyUserDataDir = app.getPath('userData')
} catch {
preReadyUserDataDir = ''
}
try {
preReadyExeDir = path.dirname(app.getPath('exe'))
} catch {
preReadyExeDir = process.cwd()
}
const requestedGpuMode = readPreReadyGpuMode({
userDataDir: preReadyUserDataDir,
exeDir: preReadyExeDir,
resourcesDir: process.resourcesPath,
argv: process.argv,
})
const preReadyHandoff = readPreReadyGpuHandoff(process.argv)
const preReadyGpuEnv =
!isHeadlessSmoke &&
!preReadyHandoff.gpuHandoffTarget &&
requestedGpuMode === 'auto' &&
process.platform === 'win32'
? probeWindowsGpuEnvironmentSync()
: { vramSample: null, hasIntegratedGpu: false }
const startupGpuDecision = chooseStartupGpuTarget({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
requestedMode: requestedGpuMode,
handoffTarget: preReadyHandoff.gpuHandoffTarget,
vramSample: preReadyGpuEnv.vramSample,
hasIntegratedGpu: preReadyGpuEnv.hasIntegratedGpu,
})
if (startupGpuDecision.reason === 'low-vram-igpu' || startupGpuDecision.reason === 'low-vram-software') {
console.info(
`[planet-client] Adaptive GPU selected ${startupGpuDecision.target} (reason=${startupGpuDecision.reason}, freeMiB=${startupGpuDecision.vramSample?.freeMiB ?? 'unknown'})`,
)
}
for (const sw of resolveChromiumGpuSwitches({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
target: startupGpuDecision.target,
})) {
if (sw.value !== undefined) {
app.commandLine.appendSwitch(sw.name, sw.value)
} else {
app.commandLine.appendSwitch(sw.name)
}
}
@@ -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 () => {
if (!isHeadlessSmoke) {
void registerDesktopLink().catch(error => console.warn('Planet Earth protocol registration failed', error))
@@ -105,11 +162,120 @@ if (!singleInstanceLock) {
})
const earthBundleRoot = resolveEarthBundleRoot()
const relaunchDesktopApp = (relaunchOptions?: {
gpuHandoff?: boolean
gpuHandoffTarget?: ResolvedGpuTarget
}) => {
flushWindowState(mainWindow)
if (singleInstanceLock) {
app.releaseSingleInstanceLock()
}
const rawArgs = process.argv.slice(1)
const args = relaunchOptions?.gpuHandoff
? buildGpuHandoffArgs(rawArgs, relaunchOptions.gpuHandoffTarget)
: stripGpuOverrideArgs(rawArgs)
app.relaunch({ args })
app.exit(0)
}
const hotUpdater = createHotUpdateController({
userDataDir: app.getPath('userData'),
shellVersion: app.getVersion(),
getBackendUrl: () => configStore.get().backendUrl,
getMainWindow: () => mainWindow,
onOverlayChanged: () => {
refreshApplicationMenu()
},
})
const gpuMonitor = createAdaptiveGpuMonitor({
userDataDir: app.getPath('userData'),
startupDecision: startupGpuDecision,
getConfiguredMode: () => configStore.get().gpuMode,
getMainWindow: () => mainWindow,
onAutoSwitch: (nextTarget) => {
relaunchDesktopApp({ gpuHandoff: true, gpuHandoffTarget: nextTarget })
},
onStatusUpdated: () => {
refreshApplicationMenu()
},
})
const sendPendingHandoffToast = () => {
if (isHeadlessSmoke || !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
return
}
const toast = gpuMonitor.consumePendingHandoffToast()
if (toast) {
mainWindow.webContents.send('planet:update-status', toast)
}
}
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, {
earthBundleRoot,
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
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) => {
const cfg = configStore.get()
event.returnValue = {
@@ -119,6 +285,9 @@ if (!singleInstanceLock) {
wsUrl: cfg.wsUrl,
forceShowFps: cfg.forceShowFps,
splashTheme: cfg.splashTheme,
gpuMode: cfg.gpuMode,
gpuTarget: startupGpuDecision.target,
gpuHandoff: cfg.gpuHandoff,
headlessSmoke: cfg.headlessSmoke,
isElectron: true,
platform: process.platform,
@@ -178,9 +347,7 @@ if (!singleInstanceLock) {
ipcMain.handle('planet:set-splash-theme', (_event, rawTheme: unknown) => {
const next = configStore.updateSplashTheme(normalizeSplashTheme(rawTheme, configStore.get().splashTheme))
if (mainWindow && !mainWindow.isDestroyed()) {
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
}
refreshApplicationMenu()
return next.splashTheme
})
@@ -197,11 +364,48 @@ if (!singleInstanceLock) {
configStore,
})
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
refreshApplicationMenu()
if (process.platform !== 'darwin') {
mainWindow.setMenuBarVisibility(false)
}
if (!isHeadlessSmoke) {
let autoUpdateTimer: ReturnType<typeof setTimeout> | null = null
let periodicUpdateTimer: ReturnType<typeof setInterval> | null = null
mainWindow.webContents.on('render-process-gone', () => {
hotUpdater.handleRendererCrash()
})
hotUpdater.startStartupWatchdog()
mainWindow.webContents.once('did-finish-load', () => {
gpuMonitor.start()
autoUpdateTimer = setTimeout(() => {
autoUpdateTimer = null
if (mainWindow && !mainWindow.isDestroyed()) {
void hotUpdater.checkForUpdates({ manual: false })
}
}, 4000)
if (!periodicUpdateTimer) {
periodicUpdateTimer = setInterval(() => {
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.isMinimized()) {
void hotUpdater.checkForUpdates({ manual: false })
}
}, PERIODIC_UPDATE_CHECK_INTERVAL_MS)
}
})
mainWindow.once('closed', () => {
gpuMonitor.stop()
if (autoUpdateTimer) {
clearTimeout(autoUpdateTimer)
autoUpdateTimer = null
}
if (periodicUpdateTimer) {
clearInterval(periodicUpdateTimer)
periodicUpdateTimer = null
}
hotUpdater.stopStartupWatchdog()
})
}
if (isHeadlessSmoke) {
const smokeTimeout = setTimeout(() => {
app.exit(1)
@@ -267,19 +471,18 @@ if (!singleInstanceLock) {
const img = sr?.querySelector('.splash-zju-emblem');
const copy = sr?.querySelector('.splash-presenter-copy')?.textContent || '';
const finishCheck = () => {
window.planetDesktop.replaySplash('constellation');
const firstSwitch = host?.dataset.splashTheme || '';
window.planetDesktop.replaySplash('horizon');
const secondSwitch = host?.dataset.splashTheme || '';
const activeTheme = host?.dataset.splashTheme || '';
const hasNoThemeSwitcher = !sr?.querySelector('.splash-switcher');
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
resolve({
mounted: Boolean(host && sr),
hasPresentedBy: copy.includes('PRESENTED BY'),
hasPresenterZh: copy.includes('临空智能媒体研究院'),
hasPresenterEn: copy.includes('Institute of Intelligent Media'),
hasPresenterEn: copy.includes('Intelligent Media Institute'),
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
emblemWidth: img ? img.naturalWidth : 0,
switchedThemes: [firstSwitch, secondSwitch],
activeTheme,
hasNoThemeSwitcher,
});
};
if (!img || img.complete) {
+93 -24
View File
@@ -1,11 +1,33 @@
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'
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
const targetLabel =
summary.activeTarget === 'low-power'
? '集成核显'
: summary.activeTarget === 'software'
? 'CPU 软渲染'
: summary.activeTarget === 'high-performance' || summary.latestVramSample
? '独立显卡'
: '硬件 GPU'
const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动'
const vramTag = summary.latestVramSample
? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`
: ''
return `当前生效: ${targetLabel} (${modeTag}${vramTag})`
}
export function buildApplicationMenu(options: {
mainWindow: BrowserWindow
configStore: DesktopConfigStore
getVersionInfo?: () => HotUpdateVersionInfo
onCheckForUpdates?: () => void
getGpuStatus?: () => GpuRuntimeSummary
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
}): Menu {
const sendAction = (action: string) => {
if (!options.mainWindow.isDestroyed()) {
@@ -19,6 +41,8 @@ export function buildApplicationMenu(options: {
}
const currentSplashTheme = options.configStore.get().splashTheme
const currentGpuMode = options.configStore.get().gpuMode
const gpuSummary = options.getGpuStatus?.()
const selectSplashTheme = (theme: SplashTheme) => {
options.configStore.updateSplashTheme(theme)
@@ -72,31 +96,13 @@ export function buildApplicationMenu(options: {
},
},
{
label: '启动画面方案 / Splash Screen',
label: '启动画面 / Splash Screen',
submenu: [
{
label: '方案 1:星核奇点展开 / Singularity Burst',
type: 'radio',
checked: currentSplashTheme === 'singularity',
click: () => selectSplashTheme('singularity'),
},
{
label: '方案 2:轨道星座校准 / Orbital Astrolabe',
type: 'radio',
checked: currentSplashTheme === 'constellation',
click: () => selectSplashTheme('constellation'),
},
{
label: '方案 3:晨昏日冕破晓 / Eclipse Horizon',
type: 'radio',
checked: currentSplashTheme === 'horizon',
click: () => selectSplashTheme('horizon'),
},
{
label: '关闭启动画面 / Off',
type: 'radio',
checked: currentSplashTheme === 'off',
click: () => selectSplashTheme('off'),
label: '启用启动画面 / Enable Splash Screen',
type: 'checkbox',
checked: currentSplashTheme !== 'off',
click: () => selectSplashTheme(currentSplashTheme === 'off' ? 'singularity' : 'off'),
},
{ type: 'separator' },
{
@@ -106,6 +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' },
{
label: '打开运维控制台 / Open Admin Console',
@@ -116,6 +168,23 @@ export function buildApplicationMenu(options: {
click: () => openAdminPath('/docs/manual'),
},
{ type: 'separator' },
{
label: '检查更新 / Check for Updates...',
click: () => options.onCheckForUpdates?.(),
},
...(options.getVersionInfo
? [
(() => {
const info = options.getVersionInfo!()
const suffix = info.usingHotfix ? ' (热更 / Hotfix)' : ''
return {
label: `当前版本: Shell v${info.shellVersion} · Earth v${info.activeBundleVersion}${suffix}`,
enabled: false,
}
})(),
]
: []),
{ type: 'separator' },
{ role: 'quit', label: '退出 / Quit' },
],
},
+16
View File
@@ -156,6 +156,7 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade
export function createEarthProtocolHandler(options: {
earthBundleRoot: string
getEarthOverlayRoot?: () => string | null
getBackendUrl: () => string
fetchImpl?: typeof fetch
}): (request: Request) => Promise<Response> {
@@ -209,6 +210,21 @@ export function createEarthProtocolHandler(options: {
if (!staticPath) {
return new Response('Forbidden', { status: 403 })
}
const overlayRoot = options.getEarthOverlayRoot?.()
if (overlayRoot) {
const overlayPath = resolveEarthStaticPath(overlayRoot, parsedUrl.pathname)
if (overlayPath) {
try {
if (fs.statSync(overlayPath).isFile()) {
return createStaticFileResponse(overlayPath, request.headers)
}
} catch {
// Fall back to the built-in shell bundle for non-overlaid static assets.
}
}
}
return createStaticFileResponse(staticPath, request.headers)
}
}
+2
View File
@@ -25,11 +25,13 @@ export function installEarthSessionHandlers(
targetSession: Session,
options: {
earthBundleRoot: string
getEarthOverlayRoot?: () => string | null
getBackendUrl: () => string
},
): void {
const handler = createEarthProtocolHandler({
earthBundleRoot: options.earthBundleRoot,
getEarthOverlayRoot: options.getEarthOverlayRoot,
getBackendUrl: options.getBackendUrl,
fetchImpl: (input, init) => net.fetch(input as string, init),
})
+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,
}
}
+18 -5
View File
@@ -21,6 +21,12 @@ import {
import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol'
const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>()
const windowStateFlushers = new WeakMap<BrowserWindow, () => void>()
export function flushWindowState(win: BrowserWindow | null): void {
if (!win || win.isDestroyed()) return
windowStateFlushers.get(win)?.()
}
interface OrientationWindowState {
lastLandscapeBounds: Rect | null
@@ -296,14 +302,17 @@ export function createMainWindow(options: {
}
}
win.on('resize', captureNormalBounds)
win.on('move', captureNormalBounds)
win.on('close', () => {
const flushCurrentWindowState = () => {
captureNormalBounds()
if (!runtimeConfig.headlessSmoke) {
saveWindowState(statePath, win, lastNormalBounds)
}
})
}
windowStateFlushers.set(win, flushCurrentWindowState)
win.on('resize', captureNormalBounds)
win.on('move', captureNormalBounds)
win.on('close', flushCurrentWindowState)
win.on('minimize', () => {
if (!win.isDestroyed()) {
@@ -346,7 +355,10 @@ export function createMainWindow(options: {
}
const showGate = createWindowShowGate({
requireSplashFirstPaint: !runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off',
requireSplashFirstPaint:
!runtimeConfig.headlessSmoke &&
!runtimeConfig.gpuHandoff &&
runtimeConfig.splashTheme !== 'off',
fallbackDelayMs: 1500,
onReveal: revealMainWindow,
})
@@ -359,6 +371,7 @@ export function createMainWindow(options: {
ipcMain.on('planet:splash-first-paint', onSplashFirstPaint)
win.once('closed', () => {
windowStateFlushers.delete(win)
showGate.dispose()
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)
}
}
+39 -1
View File
@@ -1,5 +1,6 @@
import { contextBridge, ipcRenderer } from 'electron'
import { startDesktopLowFpsWatcher } from './fps-watcher'
import { createDesktopSplashController, type SplashTheme } from './splash'
interface PreloadRuntimeConfig {
@@ -9,6 +10,9 @@ interface PreloadRuntimeConfig {
wsUrl: string
forceShowFps: boolean
splashTheme: SplashTheme
gpuMode?: string
gpuTarget?: string
gpuHandoff?: boolean
headlessSmoke: boolean
isElectron: true
platform: string
@@ -27,7 +31,7 @@ const splashController = createDesktopSplashController({
},
})
if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
if (!runtimeConfig.headlessSmoke && !runtimeConfig.gpuHandoff && runtimeConfig.splashTheme !== 'off') {
let bootStarted = false
const tryStartBoot = () => {
if (bootStarted || !document.documentElement) return false
@@ -54,6 +58,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('planetDesktop', {
@@ -75,6 +92,8 @@ contextBridge.exposeInMainWorld('planetDesktop', {
replaySplash: (theme?: SplashTheme) => {
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) => {
@@ -93,6 +112,25 @@ ipcRenderer.on('planet:replay-splash', (_event, detail?: { theme?: SplashTheme }
splashController.replay(detail?.theme)
})
ipcRenderer.on('planet:gpu-process-gone', (_event, detail) => {
window.dispatchEvent(new CustomEvent('planet-desktop:gpu-process-gone', { detail }))
})
ipcRenderer.on('planet:update-status', (_event, detail) => {
window.dispatchEvent(new CustomEvent('earth:status', { detail }))
})
if (document.documentElement?.dataset?.earthStartupReady === '1') {
ipcRenderer.send('planet:earth-startup-ready')
}
window.addEventListener(
'earth:startup-ready',
() => {
ipcRenderer.send('planet:earth-startup-ready')
},
{ once: true },
)
window.addEventListener(
'pointerdown',
() => {
+200 -364
View File
@@ -1,7 +1,7 @@
import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from './earth-landmask'
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
export type ActiveSplashTheme = Exclude<SplashTheme, 'off'>
export type SplashTheme = 'singularity' | 'off'
export type ActiveSplashTheme = 'singularity'
interface GlobePoint {
lat: number
@@ -32,10 +32,70 @@ interface ArcDef {
const SPLASH_HOST_ID = 'planet-desktop-splash-host'
const DEFAULT_HOST_THEME: ActiveSplashTheme = 'singularity'
const REPLAY_DURATION_MS = 2600
const MIN_BOOT_SHOWCASE_MS = 1800
const REPLAY_DURATION_MS = 3200
const MIN_BOOT_SHOWCASE_MS = 2200
const MAX_BOOT_CAP_MS = 20000
export interface SplashCanvasSize {
dpr: number
width: number
height: number
}
export function computeSplashCanvasSize(
width: number,
height: number,
devicePixelRatio: number,
maxPixels = 1920 * 1080,
maxDpr = 1.5,
): SplashCanvasSize {
const safeW = Math.max(1, Number(width) || 1)
const safeH = Math.max(1, Number(height) || 1)
const rawDpr = Math.min(Math.max(Number(devicePixelRatio) || 1, 0.5), maxDpr)
const totalPixels = safeW * safeH * rawDpr * rawDpr
const dpr =
totalPixels > maxPixels
? Math.min(rawDpr, Math.max(0.75, Math.floor(Math.sqrt(maxPixels / (safeW * safeH)) * 100) / 100))
: rawDpr
return {
dpr,
width: Math.max(1, Math.round(safeW * dpr)),
height: Math.max(1, Math.round(safeH * dpr)),
}
}
export interface SplashMorphPhases {
dawnIntensity: number
coreReveal: number
orbitReveal: number
arcReveal: number
burst: number
fade: number
}
function clamp01(value: number): number {
return Math.max(0, Math.min(1, value))
}
function smoothstep(edge0: number, edge1: number, x: number): number {
if (edge1 <= edge0) return x >= edge1 ? 1 : 0
const t = clamp01((x - edge0) / (edge1 - edge0))
return t * t * (3 - 2 * t)
}
export function computeSplashMorphPhases(progress: number, exitRatio: number): SplashMorphPhases {
const p = clamp01(Number.isFinite(progress) ? progress : 0)
const e = clamp01(Number.isFinite(exitRatio) ? exitRatio : 0)
return {
dawnIntensity: (1 - smoothstep(0.36, 0.78, p)) * (1 - smoothstep(0, 0.35, e)),
coreReveal: smoothstep(0.18, 0.68, p),
orbitReveal: smoothstep(0.38, 0.82, p),
arcReveal: smoothstep(0.56, 0.9, p),
burst: e > 0 ? Math.pow(e, 1.38) : 0,
fade: 1 - Math.pow(e, 2.2),
}
}
export interface BootSplashStateInput {
elapsedMs: number
minDurationMs: number
@@ -84,7 +144,7 @@ const ARC_DEFINITIONS: readonly ArcDef[] = [
]
function isActiveTheme(value: string | undefined | null): value is ActiveSplashTheme {
return value === 'singularity' || value === 'constellation' || value === 'horizon'
return value === 'singularity'
}
function getLocaleIsEn(): boolean {
@@ -225,14 +285,6 @@ const SPLASH_CSS = `
transition: opacity 380ms cubic-bezier(0.22, 1, 0.36, 1);
}
.splash-root[data-theme="horizon"] {
background: radial-gradient(circle at 50% 41%, #091322 0%, #030710 56%, #010308 100%);
}
.splash-root[data-theme="constellation"] {
background: radial-gradient(circle at 50% 41%, #06182c 0%, #030916 55%, #02040a 100%);
}
.splash-root.is-exiting {
pointer-events: none;
}
@@ -309,48 +361,24 @@ const SPLASH_CSS = `
flex-wrap: wrap;
}
.splash-switcher {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px;
border: 1px solid rgba(173, 210, 255, 0.16);
background: rgba(8, 19, 36, 0.62);
backdrop-filter: blur(10px);
}
.splash-pill,
.splash-skip {
appearance: none;
border: 1px solid transparent;
background: transparent;
color: rgba(190, 216, 245, 0.72);
border: 1px solid rgba(173, 210, 255, 0.16);
background: rgba(8, 19, 36, 0.55);
backdrop-filter: blur(10px);
color: rgba(190, 216, 245, 0.78);
font-family: inherit;
font-size: 11px;
font-weight: 500;
letter-spacing: 0.04em;
padding: 4px 9px;
padding: 5px 10px;
cursor: pointer;
transition: color 160ms ease, background-color 160ms ease, border-color 160ms ease;
}
.splash-pill:hover,
.splash-skip:hover {
color: #f3f9ff;
background: rgba(132, 192, 255, 0.12);
}
.splash-pill.is-active {
color: #f5faff;
background: rgba(82, 168, 255, 0.24);
border-color: rgba(136, 206, 255, 0.42);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.16);
}
.splash-skip {
border-color: rgba(173, 210, 255, 0.16);
background: rgba(8, 19, 36, 0.55);
padding: 5px 10px;
background: rgba(132, 192, 255, 0.14);
}
.splash-footer {
@@ -438,21 +466,6 @@ const SPLASH_CSS = `
border: 1px solid rgba(173, 214, 255, 0.12);
}
.splash-root[data-theme="horizon"] .splash-progress-track {
height: 2px;
border: none;
background: rgba(210, 232, 255, 0.14);
}
.splash-root[data-theme="constellation"] .splash-progress-track {
height: 6px;
background: repeating-linear-gradient(
90deg,
rgba(135, 188, 242, 0.18) 0 12px,
rgba(6, 15, 30, 0.7) 12px 16px
);
}
.splash-progress-fill {
position: relative;
height: 100%;
@@ -461,20 +474,6 @@ const SPLASH_CSS = `
box-shadow: 0 0 14px rgba(105, 198, 255, 0.55);
}
.splash-root[data-theme="constellation"] .splash-progress-fill {
background: repeating-linear-gradient(
90deg,
#77cfff 0 12px,
transparent 12px 16px
);
box-shadow: 0 0 12px rgba(105, 206, 255, 0.45);
}
.splash-root[data-theme="horizon"] .splash-progress-fill {
background: linear-gradient(90deg, rgba(84, 165, 255, 0.55) 0%, #c4e4ff 70%, #ffffff 100%);
box-shadow: 0 0 16px rgba(196, 228, 255, 0.72);
}
.splash-progress-fill::after {
content: "";
position: absolute;
@@ -594,7 +593,6 @@ export function createDesktopSplashController(options: {
let progressFillEl: HTMLDivElement | null = null
let stageEl: HTMLSpanElement | null = null
let percentEl: HTMLSpanElement | null = null
let switcherButtons: HTMLButtonElement[] = []
let rafId = 0
let statusObserver: MutationObserver | null = null
@@ -667,7 +665,6 @@ export function createDesktopSplashController(options: {
progressFillEl = null
stageEl = null
percentEl = null
switcherButtons = []
exitStartTime = 0
}
@@ -685,11 +682,6 @@ export function createDesktopSplashController(options: {
if (hostEl) {
hostEl.dataset.splashTheme = nextTheme
}
for (const btn of switcherButtons) {
const match = btn.dataset.splashSwitch === nextTheme
btn.classList.toggle('is-active', match)
btn.setAttribute('aria-pressed', String(match))
}
}
const notifyFirstPaintOnce = () => {
@@ -764,11 +756,6 @@ export function createDesktopSplashController(options: {
<span>PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL</span>
</div>
<div class="splash-controls">
<div class="splash-switcher" role="group" aria-label="启动画面方案">
<button type="button" class="splash-pill" data-splash-switch="singularity">01 星核</button>
<button type="button" class="splash-pill" data-splash-switch="constellation">02 星轨</button>
<button type="button" class="splash-pill" data-splash-switch="horizon">03 破晓</button>
</div>
<button type="button" class="splash-skip" data-splash-skip title="跳过启动动画 (Esc)">ESC 跳过</button>
</div>
</header>
@@ -792,7 +779,7 @@ export function createDesktopSplashController(options: {
<div class="splash-presenter-copy">
<span class="splash-presenter-kicker">PRESENTED BY</span>
<span class="splash-presenter-zh">临空智能媒体研究院</span>
<span class="splash-presenter-en">Institute of Intelligent Media</span>
<span class="splash-presenter-en">Intelligent Media Institute</span>
</div>
</div>
</footer>
@@ -807,23 +794,6 @@ export function createDesktopSplashController(options: {
progressFillEl = root.querySelector('[data-splash-fill]')
stageEl = root.querySelector('[data-splash-stage]')
percentEl = root.querySelector('[data-splash-percent]')
switcherButtons = Array.from(root.querySelectorAll('[data-splash-switch]'))
for (const btn of switcherButtons) {
btn.addEventListener('click', (event) => {
event.stopPropagation()
const picked = btn.dataset.splashSwitch
if (isActiveTheme(picked)) {
preferredTheme = picked
options.onSelectTheme(picked)
if (sessionMode === 'boot' && !startupReady) {
setActiveThemeVisual(picked)
} else {
startSplashSession(picked, 'replay')
}
}
})
}
const skipBtn = root.querySelector('[data-splash-skip]')
skipBtn?.addEventListener('click', (event) => {
@@ -932,7 +902,7 @@ export function createDesktopSplashController(options: {
cx: number,
cy: number,
) => {
const warp = exitRatio > 0 && activeTheme === 'singularity' ? exitRatio * exitRatio : 0
const warp = exitRatio > 0 ? exitRatio * exitRatio : 0
for (const star of stars) {
const sx = star.x * w
const sy = star.y * h
@@ -960,7 +930,7 @@ export function createDesktopSplashController(options: {
}
}
const drawSingularityScene = (
const drawDawnToSingularityScene = (
ctx: CanvasRenderingContext2D,
w: number,
h: number,
@@ -971,57 +941,115 @@ export function createDesktopSplashController(options: {
progress: number,
exitRatio: number,
) => {
const burst = exitRatio > 0 ? Math.pow(exitRatio, 1.4) : 0
const fade = 1 - Math.pow(exitRatio, 2.2)
const { dawnIntensity, coreReveal, orbitReveal, arcReveal, burst, fade } =
computeSplashMorphPhases(progress, exitRatio)
// Deep holographic ambient halo
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * fade).toFixed(3)})`)
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * fade).toFixed(3)})`)
glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
ctx.fillStyle = glow
ctx.beginPath()
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2)
ctx.fill()
const perspD = 3.6
const perspK = 3.25
const tiltX = -0.25
const rollZ = -0.11
const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 2.1)
const eclipseR = radius * 0.955
const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45
// Tilted orbital rings accelerating cleanly toward phase lock
const yaw = (108 * Math.PI) / 180 + elapsed * (0.42 + progress * 0.48 + burst * 2.2)
const ringConfigs = [
{ rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
]
for (let i = 0; i < ringConfigs.length; i += 1) {
const ring = ringConfigs[i]
ctx.save()
ctx.translate(cx, cy)
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * fade).toFixed(3)})`
ctx.lineWidth = 1.15
// Act 1 -> Act 2: Eclipse atmospheric corona cross-dissolves into deep holographic halo
if (dawnIntensity > 0.01) {
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
const coronaAlpha = dawnIntensity * fade
const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 1.4))
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.9 * coronaAlpha).toFixed(3)})`)
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.5 * coronaAlpha).toFixed(3)})`)
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.15 * coronaAlpha).toFixed(3)})`)
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
ctx.fillStyle = corona
ctx.beginPath()
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
ctx.stroke()
// Moving orbital shard beacon along ellipse
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
const sx = Math.cos(a) * ring.rx
const sy = Math.sin(a) * ring.ry
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * fade).toFixed(3)})`
ctx.beginPath()
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
ctx.arc(cx, cy, eclipseR * (1.95 + burst * 1.4), 0, Math.PI * 2)
ctx.fill()
ctx.restore()
}
// 3D Holographic Earth point cloud + burst explosion streaks
const tiltX = -0.26
const rollZ = -0.14
const perspD = 3.1
if (coreReveal > 0.01) {
const haloAlpha = coreReveal * fade
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`)
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * haloAlpha).toFixed(3)})`)
glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
ctx.fillStyle = glow
ctx.beginPath()
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2)
ctx.fill()
}
// Act 1 silhouette & luminous dawn limb hugging the sphere edge cleanly without shadowBlur
if (dawnIntensity > 0.01) {
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
const discAlpha = dawnIntensity * fade
const discGrad = ctx.createRadialGradient(lx, ly, eclipseR * 0.55, cx, cy, eclipseR)
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * discAlpha).toFixed(3)})`)
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * discAlpha).toFixed(3)})`)
ctx.fillStyle = discGrad
ctx.beginPath()
ctx.arc(cx, cy, eclipseR * 0.99, 0, Math.PI * 2)
ctx.fill()
const arcStart = coronaOffsetAngle - 0.88
const arcEnd = coronaOffsetAngle + 0.88
ctx.strokeStyle = `rgba(148, 214, 255, ${(0.24 * discAlpha).toFixed(3)})`
ctx.lineWidth = 7
ctx.beginPath()
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
ctx.stroke()
ctx.strokeStyle = `rgba(226, 246, 255, ${(0.92 * discAlpha).toFixed(3)})`
ctx.lineWidth = 2.3
ctx.beginPath()
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
ctx.stroke()
}
// Act 2: Three tilted orbital rings drawing into full orbits, expanding on Act 3 burst
if (orbitReveal > 0.01) {
const ringConfigs = [
{ rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
]
for (let i = 0; i < ringConfigs.length; i += 1) {
const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8)
if (ringReveal <= 0.005) continue
const ring = ringConfigs[i]
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
ctx.save()
ctx.translate(cx, cy)
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * fade).toFixed(3)})`
ctx.lineWidth = 1.15
ctx.beginPath()
if (ringReveal >= 0.995) {
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
} else {
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, a - ringReveal * Math.PI * 2, a)
}
ctx.stroke()
const sx = Math.cos(a) * ring.rx
const sy = Math.sin(a) * ring.ry
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * fade).toFixed(3)})`
ctx.beginPath()
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
ctx.fill()
ctx.restore()
}
}
// Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> radial scatter
const oceanReveal = clamp01((coreReveal - 0.25) / 0.75)
for (const pt of globePoints) {
const p = projectSpherePoint(pt.lat, pt.lon, yaw, tiltX, rollZ)
if (burst === 0 && p.nz < -0.22) continue
// On explosion, scatter outward radially & toward camera
const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8)
const jitterX = Math.cos(pt.shardAngle) * burst * 0.28
const jitterY = Math.sin(pt.shardAngle) * burst * 0.28
@@ -1030,7 +1058,7 @@ export function createDesktopSplashController(options: {
const pz = p.nz + burst * pt.shardSpeed * 1.1
const depth = Math.max(0.25, perspD - pz)
const screenScale = (radius * (perspD - 0.6)) / depth
const screenScale = (radius * perspK) / depth
const sx = cx + px * screenScale
const sy = cy + py * screenScale
if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) continue
@@ -1038,23 +1066,29 @@ export function createDesktopSplashController(options: {
const depthFade = p.nz >= 0 ? 1 : Math.max(0.14, 1 + p.nz * 2.2)
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.36 : 1
let color = '84, 146, 232'
let baseAlpha = 0.28
let pointGain = 0
let dotR = 1.1
if (pt.kind === 2) {
color = '196, 240, 255'
baseAlpha = 0.94
dotR = 1.75
const dawnShimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
const dawnWeight = p.nz > 0.06 ? dawnIntensity * 0.58 * p.nz * dawnShimmer : 0
const coreWeight = coreReveal * 0.94 * depthFade
pointGain = Math.max(dawnWeight, coreWeight)
dotR = 1.45 + coreReveal * 0.3
} else if (pt.kind === 1) {
color = '106, 188, 255'
baseAlpha = 0.56
pointGain = coreReveal * 0.56 * depthFade
dotR = 1.3
} else {
pointGain = oceanReveal * 0.28 * depthFade
}
const alpha = baseAlpha * depthFade * polarFade * fade
const alpha = pointGain * polarFade * fade
if (alpha <= 0.015) continue
if (burst > 0.03) {
const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst)
const prevScale = (radius * (perspD - 0.6)) / Math.max(0.3, perspD - p.nz)
const prevScale = (radius * perspK) / Math.max(0.3, perspD - p.nz)
const ox = cx + p.nx * prevBoost * prevScale
const oy = cy + p.ny * prevBoost * prevScale
ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})`
@@ -1071,8 +1105,9 @@ export function createDesktopSplashController(options: {
}
}
// Great-circle telemetry arcs across front hemisphere
if (burst < 0.55) {
// Intercontinental telemetry arcs across front hemisphere
if (arcReveal > 0.01 && burst < 0.55) {
const arcAlpha = arcReveal * fade * Math.max(0, 1 - burst * 1.6)
for (const arc of ARC_DEFINITIONS) {
const p1 = projectSpherePoint((arc.lat1 * Math.PI) / 180, (arc.lon1 * Math.PI) / 180, yaw, tiltX, rollZ)
const p2 = projectSpherePoint((arc.lat2 * Math.PI) / 180, (arc.lon2 * Math.PI) / 180, yaw, tiltX, rollZ)
@@ -1088,7 +1123,7 @@ export function createDesktopSplashController(options: {
const cpx = cx + mx * radius * lift
const cpy = cy + my * radius * lift
ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * fade).toFixed(3)})`
ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * arcAlpha).toFixed(3)})`
ctx.lineWidth = 1.25
ctx.beginPath()
ctx.moveTo(x1, y1)
@@ -1099,14 +1134,14 @@ export function createDesktopSplashController(options: {
const inv = 1 - u
const px = inv * inv * x1 + 2 * inv * u * cpx + u * u * x2
const py = inv * inv * y1 + 2 * inv * u * cpy + u * u * y2
ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * fade).toFixed(3)})`
ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * arcAlpha).toFixed(3)})`
ctx.beginPath()
ctx.arc(px, py, 2.2, 0, Math.PI * 2)
ctx.fill()
}
}
// Shockwave ring on climax burst
// Act 3: Climax shockwave ring on scatter burst
if (burst > 0.005) {
const shockR = radius * (0.88 + exitRatio * 5.2)
ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})`
@@ -1117,203 +1152,16 @@ export function createDesktopSplashController(options: {
}
}
const drawConstellationScene = (
ctx: CanvasRenderingContext2D,
_w: number,
_h: number,
cx: number,
cy: number,
radius: number,
elapsed: number,
progress: number,
exitRatio: number,
) => {
const irisScale = 1 + Math.pow(exitRatio, 1.55) * 2.1
const fade = 1 - Math.pow(exitRatio, 1.8)
const yaw = (108 * Math.PI) / 180 + elapsed * 0.34
// Outer calibrated compass reticle rings
ctx.save()
ctx.translate(cx, cy)
ctx.scale(irisScale, irisScale)
const outerR = radius * 1.42
const midR = radius * 1.2
ctx.strokeStyle = `rgba(130, 198, 255, ${(0.22 * fade).toFixed(3)})`
ctx.lineWidth = 1
ctx.beginPath()
ctx.arc(0, 0, outerR, 0, Math.PI * 2)
ctx.stroke()
ctx.strokeStyle = `rgba(154, 214, 255, ${(0.36 * fade).toFixed(3)})`
ctx.setLineDash([4, 6])
ctx.beginPath()
ctx.arc(0, 0, midR, -elapsed * 0.25, -elapsed * 0.25 + Math.PI * 1.65)
ctx.stroke()
ctx.setLineDash([])
// Progress calibration arc
const sweepAngle = Math.max(0.08, progress * Math.PI * 2)
ctx.strokeStyle = `rgba(126, 222, 255, ${(0.88 * fade).toFixed(3)})`
ctx.lineWidth = 2.1
ctx.beginPath()
ctx.arc(0, 0, radius * 1.29, -Math.PI / 2, -Math.PI / 2 + sweepAngle)
ctx.stroke()
// 72 degree graduation ticks
for (let deg = 0; deg < 360; deg += 5) {
const rad = (deg * Math.PI) / 180 + elapsed * 0.05
const major = deg % 30 === 0
const len = major ? 9 : 4
ctx.strokeStyle = `rgba(170, 216, 255, ${((major ? 0.55 : 0.22) * fade).toFixed(3)})`
ctx.lineWidth = major ? 1.3 : 0.85
ctx.beginPath()
ctx.moveTo(Math.cos(rad) * (outerR - len), Math.sin(rad) * (outerR - len))
ctx.lineTo(Math.cos(rad) * outerR, Math.sin(rad) * outerR)
ctx.stroke()
}
// Precision meridian & equator CAD wireframe + continental points
ctx.strokeStyle = `rgba(104, 178, 245, ${(0.22 * fade).toFixed(3)})`
ctx.lineWidth = 0.9
ctx.beginPath()
ctx.arc(0, 0, radius, 0, Math.PI * 2)
ctx.stroke()
for (const tilt of [-0.55, 0, 0.55]) {
ctx.beginPath()
ctx.ellipse(0, 0, radius * Math.abs(Math.cos(tilt)), radius, 0, 0, Math.PI * 2)
ctx.stroke()
}
for (const pt of globePoints) {
if (pt.kind === 0) continue
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, 0)
if (p.nz < 0) continue
const sx = p.nx * radius
const sy = p.ny * radius
const isCoast = pt.kind === 2
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
ctx.fillStyle = isCoast
? `rgba(216, 246, 255, ${(0.92 * polarFade * fade).toFixed(3)})`
: `rgba(106, 186, 255, ${(0.42 * polarFade * fade).toFixed(3)})`
ctx.fillRect(sx - (isCoast ? 1 : 0.7), sy - (isCoast ? 1 : 0.7), isCoast ? 2 : 1.4, isCoast ? 2 : 1.4)
}
// Hangzhou target crosshair lock when front-facing
const hz = projectSpherePoint((30.27 * Math.PI) / 180, (120.15 * Math.PI) / 180, yaw, -0.24, 0)
if (hz.nz > 0.1) {
const hx = hz.nx * radius
const hy = hz.ny * radius
ctx.strokeStyle = `rgba(255, 255, 255, ${(0.88 * fade).toFixed(3)})`
ctx.lineWidth = 1.2
ctx.strokeRect(hx - 6, hy - 6, 12, 12)
ctx.beginPath()
ctx.moveTo(hx - 12, hy)
ctx.lineTo(hx + 12, hy)
ctx.moveTo(hx, hy - 12)
ctx.lineTo(hx, hy + 12)
ctx.stroke()
}
// Keplerian satellites
for (let i = 0; i < 3; i += 1) {
ctx.save()
ctx.rotate(-0.5 + i * 0.55)
const rx = radius * 1.48
const ry = radius * 0.42
ctx.strokeStyle = `rgba(136, 206, 255, ${(0.24 * fade).toFixed(3)})`
ctx.lineWidth = 0.9
ctx.beginPath()
ctx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2)
ctx.stroke()
const theta = elapsed * (0.9 + i * 0.35) + i * 1.9
const sx = Math.cos(theta) * rx
const sy = Math.sin(theta) * ry
ctx.fillStyle = `rgba(232, 249, 255, ${(0.95 * fade).toFixed(3)})`
ctx.beginPath()
ctx.arc(sx, sy, 3, 0, Math.PI * 2)
ctx.fill()
ctx.restore()
}
ctx.restore()
}
const drawHorizonScene = (
ctx: CanvasRenderingContext2D,
_w: number,
_h: number,
cx: number,
cy: number,
radius: number,
elapsed: number,
progress: number,
exitRatio: number,
) => {
const fade = 1 - Math.pow(exitRatio, 2.0)
const bloom = 1 + exitRatio * 0.55
const yaw = (108 * Math.PI) / 180 + elapsed * 0.24
const r = radius * 1.06 * bloom
// Volumetric atmospheric crescent corona behind dark planet
const coronaOffsetAngle = -Math.PI * 0.65 + progress * Math.PI * 0.38
const lx = cx + Math.cos(coronaOffsetAngle) * r * 0.72
const ly = cy + Math.sin(coronaOffsetAngle) * r * 0.72
const corona = ctx.createRadialGradient(lx, ly, r * 0.15, cx, cy, r * (1.85 + exitRatio * 1.4))
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.92 * fade).toFixed(3)})`)
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.52 * fade).toFixed(3)})`)
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.16 * fade).toFixed(3)})`)
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
ctx.fillStyle = corona
ctx.beginPath()
ctx.arc(cx, cy, r * (1.9 + exitRatio * 1.4), 0, Math.PI * 2)
ctx.fill()
// Planetary shadow disc eclipsing the sun
const discGrad = ctx.createRadialGradient(lx, ly, r * 0.55, cx, cy, r)
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * fade).toFixed(3)})`)
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * fade).toFixed(3)})`)
ctx.fillStyle = discGrad
ctx.beginPath()
ctx.arc(cx, cy, r * 0.99, 0, Math.PI * 2)
ctx.fill()
// Crisp luminous terminator limb sweep following progress
ctx.save()
ctx.strokeStyle = `rgba(222, 245, 255, ${(0.92 * fade).toFixed(3)})`
ctx.lineWidth = 2.4
ctx.shadowColor = 'rgba(148, 214, 255, 0.95)'
ctx.shadowBlur = 18
ctx.beginPath()
ctx.arc(cx, cy, r, coronaOffsetAngle - 0.85, coronaOffsetAngle + 0.85)
ctx.stroke()
ctx.restore()
// Subtle night-side coastline lights glimmering across the shadowed face
for (const pt of globePoints) {
if (pt.kind !== 2) continue
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, -0.08)
if (p.nz < 0.08) continue
const shimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
const alpha = 0.56 * p.nz * shimmer * polarFade * fade
if (alpha <= 0.02) continue
ctx.fillStyle = `rgba(176, 224, 255, ${alpha.toFixed(3)})`
ctx.beginPath()
ctx.arc(cx + p.nx * r * 0.96, cy + p.ny * r * 0.96, 1.4, 0, Math.PI * 2)
ctx.fill()
}
}
const renderSceneFrame = (now: number, clampedProgress: number, exitRatio: number) => {
if (!canvasEl || !rootEl) return
const dpr = Math.min(window.devicePixelRatio || 1, 2)
const width = window.innerWidth || 1280
const height = window.innerHeight || 800
const targetCanvasW = Math.max(1, Math.round(width * dpr))
const targetCanvasH = Math.max(1, Math.round(height * dpr))
const { dpr, width: targetCanvasW, height: targetCanvasH } = computeSplashCanvasSize(
width,
height,
window.devicePixelRatio || 1,
)
if (canvasEl.width !== targetCanvasW || canvasEl.height !== targetCanvasH) {
canvasEl.width = targetCanvasW
canvasEl.height = targetCanvasH
@@ -1347,7 +1195,7 @@ export function createDesktopSplashController(options: {
const radius = Math.max(82, Math.min(width * 0.24, height * 0.21, 196))
if (exitRatio > 0) {
if (reducedMotion || activeTheme === 'horizon') {
if (reducedMotion) {
rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(exitRatio, 1.35)).toFixed(3)}`
} else {
// Portal cutout expands from center while particle bursts continue radiating over edges
@@ -1365,13 +1213,7 @@ export function createDesktopSplashController(options: {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
ctx.clearRect(0, 0, width, height)
drawStars(ctx, width, height, elapsedSec, exitRatio, cx, cy)
if (activeTheme === 'singularity') {
drawSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
} else if (activeTheme === 'constellation') {
drawConstellationScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
} else {
drawHorizonScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
}
drawDawnToSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
}
}
@@ -1463,13 +1305,7 @@ export function createDesktopSplashController(options: {
}
const clampedProgress = Math.max(0, Math.min(1, displayProgress))
const exitDuration = reducedMotion
? 300
: activeTheme === 'singularity'
? 920
: activeTheme === 'constellation'
? 860
: 900
const exitDuration = reducedMotion ? 300 : 940
const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0
renderSceneFrame(now, clampedProgress, exitRatio)
+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()
})
})
+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 { createWindowShowGate } from '../src/main/show-gate'
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 = ''
@@ -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('CONSTELLATION')).toBe('constellation')
expect(normalizeSplashTheme('horizon')).toBe('horizon')
expect(normalizeSplashTheme('HORIZON')).toBe('singularity')
expect(normalizeSplashTheme('constellation')).toBe('singularity')
expect(normalizeSplashTheme('off')).toBe('off')
expect(normalizeSplashTheme('invalid', 'singularity')).toBe('singularity')
expect(normalizeSplashTheme(undefined)).toBe('singularity')
})
test('parses --splash-theme CLI flag and persists splashTheme without clobbering endpoints', () => {
const parsed = parseLaunchArgs(['--splash-theme=constellation'])
expect(parsed.flags.splashThemeOverride).toBe('constellation')
const parsed = parseLaunchArgs(['--splash-theme=off'])
expect(parsed.flags.splashThemeOverride).toBe('off')
const userDataDir = path.join(tempRoot, 'user-data')
const exeDir = path.join(tempRoot, 'exe-dir')
@@ -56,18 +56,48 @@ describe('splash theme configuration and landmask', () => {
expect(store.get().splashTheme).toBe('singularity')
store.updateEndpoints({ backendUrl: 'https://api.planet.test:8443' })
store.updateSplashTheme('horizon')
store.updateSplashTheme('off')
const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
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' })
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')
})
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', () => {
const grid = unpackEarthLandMask()
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"
volumes:
- earth_brand_data:/app/backend/data/earth-brand
- client_updates_data:/app/backend/data/client-updates
- collector_cache:/root/.cache/planet/downloads
mem_limit: ${PLANET_BACKEND_MEM_LIMIT:-2g}
logging: *default-logging
@@ -207,6 +208,7 @@ volumes:
postgres_data:
redis_data:
earth_brand_data:
client_updates_data:
collector_cache:
secrets:
+33
View File
@@ -8,6 +8,39 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [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
Released: 2026-11-23
+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.
- **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`.
- **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.
+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.
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
- [planet.sh Startup Mechanism](/home/ray/dev/linkong/planet/docs/technical/en/ops-planet-sh-startup.md)
+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。
- **跨进程实时同步**:由于 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` 暂停空转渲染。
- **多方案桌面端启动画面与无闪烁就绪门控**:[桌面端启动画面控制器](/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 与桌面端。
+38
View File
@@ -473,6 +473,44 @@ uv run pytest backend/tests/test_otp_service.py
5. 部署后打开智能星球,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover 和边界口径。
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)
+3 -1
View File
@@ -16,12 +16,14 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.78.0`
- `dev` 当前开发分支历史推导到:`0.79.1`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `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.77.0` | feature | `dev` | `v0.77.0` | 新增原生 Electron Earth 桌面客户端(多方案 3D 启动页/横竖屏/离线协议/Gitea 自动发布)、轻量 Admin 独立容器、全球综合态势工作台与算力对比增强 |
| `0.76.20` | improvement | `dev` | `v0.76.20` | 统一 Earth 卡片布局仲裁与连接线,修复悬停展开和固定深度,并优化卫星分批查询与连接测试反馈 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.78.0",
"version": "0.79.1",
"private": true,
"packageManager": "bun@1",
"dependencies": {
+93 -1
View File
@@ -114,15 +114,105 @@ function normalizeBrandConfig(config = {}, variant = DEFAULT_BRAND_LANGUAGE) {
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 =
typeof configOrVariant === "string"
? configOrVariant
: configOrVariant.variant ?? DEFAULT_BRAND_LANGUAGE;
const defaults = getDefaultBrandConfig(variant);
const config =
typeof configOrVariant === "string"
? normalizeBrandConfig({}, 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
? `
<img
@@ -158,7 +248,9 @@ export function renderBrand(configOrVariant = DEFAULT_BRAND_LANGUAGE) {
export function mountBrand(target, configOrVariant = DEFAULT_BRAND_LANGUAGE) {
if (!target) return;
const { defaults } = resolveBrandMountInputs(configOrVariant);
target.innerHTML = renderBrand(configOrVariant);
attachBrandImageResilience(target, defaults);
}
export async function fetchEarthBrandConfig() {
+139 -14
View File
@@ -8,6 +8,10 @@ import {
} from "./constants.js";
import { latLonToVector3 } from "./utils.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 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 skySphere = null;
let skyStarMapRequested = false;
let skyStarMapLoadPromise = null;
let skyBrightness = CELESTIAL_CONFIG.skyBrightness;
export function getSkyBrightness() { return skyBrightness; }
export function setSkyBrightness(value) {
@@ -192,7 +198,87 @@ function createSprite({ texture, scale, opacity = 1, name, color = 0xffffff }) {
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(
CELESTIAL_CONFIG.skyRadius,
64,
@@ -221,18 +307,9 @@ function createSkySphere() {
mesh.renderOrder = -1000;
mesh.raycast = () => {};
textureLoader.load(
CELESTIAL_CONFIG.starMapUrl,
(texture) => {
configureColorTexture(texture);
material.map = texture;
material.needsUpdate = true;
},
undefined,
() => {
console.warn("Failed to load celestial star map texture");
},
);
if (!deferStarMap) {
void loadSkyStarMapTexture(material).catch(() => {});
}
return mesh;
}
@@ -458,6 +535,7 @@ export function initCelestialLayer(
ambientLight = null,
pointLight = null,
earth = null,
deferStarMap = false,
} = {},
) {
if (!scene || !CELESTIAL_CONFIG.enabled) return null;
@@ -477,7 +555,7 @@ export function initCelestialLayer(
refreshCelestialOrientation();
skySphere = createSkySphere();
skySphere = createSkySphere({ deferStarMap });
brightStarsGroup = createBrightStarsGroup();
const sunTexture = createDiscTexture([
@@ -609,6 +687,51 @@ export function setCelestialDayNightEnabled(enabled) {
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() {
if (celestialRoot?.parent) {
celestialRoot.parent.remove(celestialRoot);
@@ -624,6 +747,8 @@ export function disposeCelestialLayer() {
});
skySphere = null;
skyStarMapRequested = false;
skyStarMapLoadPromise = null;
brightStarsGroup = null;
sunSprite = null;
moonSprite = null;
+34
View File
@@ -15,6 +15,7 @@ import { configureColorTexture, preserveTextureOutput, shaderOutputMarker } from
import { createEarthMapController } from './earth-map-sources.js';
import { earthTextureImages } from './earth-texture-image.js';
import { createEarthAtmosphereMaterial, createEarthSurfaceMaterial } from './earth-surface-material.js';
import { isDetachedImageBitmap } from './webgl-recovery.js';
export let earth = null;
export let clouds = null;
@@ -434,3 +435,36 @@ export function setEarthTextureVisible(visible) {
export function getEarthTextureVisible() {
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);
}
+18 -2
View File
@@ -354,6 +354,22 @@ const EARTH_MESSAGE_TEMPLATES = {
zh: "巡航已暂停,按空格恢复",
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 = {
@@ -855,7 +871,7 @@ const EXACT_TRANSLATIONS = {
"出品方": "Producer",
"策划人": "Planners",
"产品兼开发者": "Product & Development",
"浙江大学临空智能媒体研究院": "Zhejiang University Linkong Institute of Intelligent Media",
"浙江大学临空智能媒体研究院": "Zhejiang University Linkong Intelligent Media Institute",
"方兴东、黄柳青": "Fang Xingdong, Huang Liuqing",
"钱坤、张鸽、齐鹏": "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.",
@@ -965,7 +981,7 @@ const EXACT_TRANSLATIONS = {
"搜索结果": "Search results",
"调整地球默认大小": "Adjust default Earth size",
"调整地形透明度": "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 页面发生未处理 Promise 错误": "Earth page unhandled Promise error",
"等待动捕数据": "Waiting for motion data",
+95 -4
View File
@@ -75,6 +75,7 @@ import {
getEarthSurfacePickTarget,
loadCloudTexture,
loadEarthTexture,
reloadEarthTextureAfterContextRestore,
isEarthTextureReady,
clearEarthTexture,
setEarthSunDirection,
@@ -86,6 +87,8 @@ import {
import { registerTerrainMesh, clearTerrainData, sampleElevationAt } from "./terrain.js";
import {
initCelestialLayer,
loadCelestialStarMap,
refreshCelestialAfterContextRestore,
updateCelestialLayer,
disposeCelestialLayer,
getCelestialDebugState,
@@ -94,6 +97,11 @@ import {
setCelestialFollow,
setCelestialDayNightEnabled,
} from "./celestial.js";
import {
computeEffectivePixelRatio,
createWebglRecoveryGuard,
markSceneTexturesNeedsUpdate,
} from "./webgl-recovery.js";
import {
clearCountryBoundaryData,
clearCountryBoundaryHover,
@@ -322,7 +330,7 @@ import {
refreshLegend,
setLegendItems,
} from "./legend.js";
import { fetchEarthBrandConfig, mountBrand } from "./brand.js";
import { fetchEarthBrandConfig, mountBrand, recoverBrokenBrandImages } from "./brand.js";
import { runEarthStartup } from "./earth-startup.js";
import { initEarthAbout } from "./about.js";
import { initEarthOobe } from "./oobe.js";
@@ -485,6 +493,9 @@ let canvasResizeObserver = null;
let pendingHoverEvent = null;
let pendingHoverFrameId = null;
let desktopMinimized = false;
let webglContextLost = false;
let webglRecoveryTimer = null;
const webglRecoveryGuard = createWebglRecoveryGuard();
const EARTH_UPDATES_CHANNEL = "earth_updates";
const EARTH_UPDATES_RECONNECT_DELAY_MS = 5000;
@@ -635,7 +646,11 @@ function syncRendererViewport() {
if (!camera || !renderer) return;
camera.aspect = getViewportAspect();
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);
renderer.setSize(window.innerWidth, window.innerHeight);
updateCachedCanvasRect();
@@ -4461,6 +4476,72 @@ export function init() {
renderer.setClearColor(0x02040a, 1);
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");
if (container) {
container.querySelector("canvas")?.remove();
@@ -4777,6 +4858,7 @@ export function init() {
backLight: sceneLights?.backLight ?? null,
pointLight: sceneLights?.pointLight ?? null,
earth: earthObj,
deferStarMap: true,
});
setCelestialDayNightEnabled(true);
createGridLines(scene, earthObj);
@@ -4812,6 +4894,9 @@ export function init() {
animate();
requestAnimationFrame(() => setTimeout(() => {
if (destroyed || renderer !== startupRenderer) return;
void loadCelestialStarMap().catch((error) => {
console.warn("[智能星球] 星空背景加载失败:", error);
});
initTVPanel();
initNewsPanel();
connectEarthUpdatesRealtime();
@@ -6161,7 +6246,7 @@ function setupEventListeners() {
desktopMinimized = false;
clock.getDelta();
updateSatellitePositions(0, true, { resetTrails: true });
if (!destroyed && !animationFrameId) {
if (!destroyed && !webglContextLost && !animationFrameId) {
animate();
}
}
@@ -6901,7 +6986,7 @@ function onClick(event) {
}
function animate() {
if (destroyed || desktopMinimized) return;
if (destroyed || desktopMinimized || webglContextLost) return;
animationFrameId = requestAnimationFrame(animate);
const frameNow = performance.now();
const stage = (name, update) => {
@@ -7074,6 +7159,12 @@ export function destroy() {
if (destroyed) return;
destroyed = true;
desktopMinimized = false;
webglContextLost = false;
if (webglRecoveryTimer) {
window.clearTimeout(webglRecoveryTimer);
webglRecoveryTimer = null;
}
delete document.documentElement.dataset.earthWebglContextLost;
cancelPendingHoverMove();
canvasResizeObserver?.disconnect();
canvasResizeObserver = null;
+130
View File
@@ -0,0 +1,130 @@
export const DEFAULT_MAX_WEBGL_BACKING_PIXELS = 2560 * 1440;
const STANDARD_TEXTURE_SLOTS = [
"map",
"alphaMap",
"aoMap",
"bumpMap",
"displacementMap",
"emissiveMap",
"envMap",
"lightMap",
"metalnessMap",
"normalMap",
"roughnessMap",
"specularMap",
];
/**
* Cap WebGL backing-store pixel count on 4K/high-DPI displays to prevent
* oversized MSAA render targets from exhausting GPU VRAM on startup.
*/
export function computeEffectivePixelRatio(
width,
height,
devicePixelRatio = 1,
options = {},
) {
const maxDpr = options.maxDpr ?? 2;
const minDpr = options.minDpr ?? 0.75;
const maxBackingPixels = options.maxBackingPixels ?? DEFAULT_MAX_WEBGL_BACKING_PIXELS;
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);
if (safeW * safeH * rawDpr * rawDpr <= maxBackingPixels) {
return rawDpr;
}
const capped = Math.floor(Math.sqrt(maxBackingPixels / (safeW * safeH)) * 100) / 100;
return Math.min(rawDpr, Math.max(minDpr, capped));
}
export function isDetachedImageBitmap(image) {
return Boolean(
image &&
typeof image.close === "function" &&
(image.width === 0 || image.height === 0),
);
}
/**
* Mark active Three.js textures for re-upload after a WebGL context restore
* while flagging any detached ImageBitmap textures that need full reloading.
*/
export function markSceneTexturesNeedsUpdate(root) {
if (!root || typeof root.traverse !== "function") {
return { updatedCount: 0, detachedTextures: [] };
}
const seen = new Set();
const detachedTextures = [];
let updatedCount = 0;
const touchTexture = (texture) => {
if (!texture || seen.has(texture)) return;
seen.add(texture);
if (isDetachedImageBitmap(texture.image)) {
detachedTextures.push(texture);
return;
}
texture.needsUpdate = true;
updatedCount += 1;
};
const inspectMaterial = (material) => {
if (!material) return;
if (Array.isArray(material)) {
material.forEach(inspectMaterial);
return;
}
for (const slot of STANDARD_TEXTURE_SLOTS) {
if (material[slot]) touchTexture(material[slot]);
}
if (material.uniforms && typeof material.uniforms === "object") {
for (const uniform of Object.values(material.uniforms)) {
const value = uniform?.value;
if (value && (value.isTexture || typeof value.dispose === "function" && "needsUpdate" in value)) {
touchTexture(value);
}
}
}
};
root.traverse((object) => {
if (object?.material) {
inspectMaterial(object.material);
}
});
return { updatedCount, detachedTextures };
}
/**
* Rate-limit automatic page reloads after unrecovered WebGL context loss
* so a persistent driver issue never triggers an infinite reload loop.
*/
export function createWebglRecoveryGuard({
cooldownMs = 30_000,
storageKey = "planet-earth-gpu-auto-reload-at",
now = () => Date.now(),
storage = typeof globalThis !== "undefined" ? globalThis.sessionStorage : undefined,
} = {}) {
return {
canAutoReload() {
try {
const raw = storage?.getItem?.(storageKey);
if (!raw) return true;
const lastTs = Number(raw);
if (!Number.isFinite(lastTs) || lastTs <= 0) return true;
return now() - lastTs >= cooldownMs;
} catch {
return true;
}
},
recordAutoReload() {
try {
storage?.setItem?.(storageKey, String(now()));
} catch {
// Ignore private-mode / sandboxed storage failures.
}
},
};
}
@@ -0,0 +1,154 @@
import { expect, test } from "bun:test";
import {
DEFAULT_MAX_WEBGL_BACKING_PIXELS,
computeEffectivePixelRatio,
createWebglRecoveryGuard,
isDetachedImageBitmap,
markSceneTexturesNeedsUpdate,
} from "./webgl-recovery.js";
import {
appendBrandRetryParam,
attachBrandImageResilience,
recoverBrokenBrandImages,
} from "./brand.js";
test("computeEffectivePixelRatio keeps 1080p/mobile crisp and caps 4K MSAA VRAM budget", () => {
expect(computeEffectivePixelRatio(1920, 1080, 1)).toBe(1);
expect(computeEffectivePixelRatio(1536, 864, 1.25)).toBe(1.25);
expect(computeEffectivePixelRatio(460, 820, 2)).toBe(2);
// 4K screen at 150% Windows DPI scaling -> logical 2560x1440
const dpi150 = computeEffectivePixelRatio(2560, 1440, 1.5);
expect(dpi150).toBe(1);
expect(2560 * 1440 * dpi150 * dpi150).toBeLessThanOrEqual(DEFAULT_MAX_WEBGL_BACKING_PIXELS);
// Native 4K at 100% scaling -> clamps smoothly to 0.75 floor (44% pixel savings)
expect(computeEffectivePixelRatio(3840, 2160, 1)).toBe(0.75);
});
test("markSceneTexturesNeedsUpdate refreshes valid textures and isolates detached ImageBitmaps", () => {
const dayMap = { isTexture: true, needsUpdate: false, image: { width: 8192, height: 4096 } };
const detachedCloudMap = {
isTexture: true,
needsUpdate: false,
image: { width: 0, height: 0, close() {} },
};
const sharedSkyMap = { isTexture: true, needsUpdate: false, image: { width: 4096, height: 2048 } };
const fakeScene = {
traverse(visit) {
visit({ material: { map: sharedSkyMap } });
visit({
material: [
{ map: detachedCloudMap },
{ uniforms: { uDayMap: { value: dayMap }, uSky: { value: sharedSkyMap } } },
],
});
},
};
expect(isDetachedImageBitmap(detachedCloudMap.image)).toBe(true);
expect(isDetachedImageBitmap(dayMap.image)).toBe(false);
const summary = markSceneTexturesNeedsUpdate(fakeScene);
expect(summary.updatedCount).toBe(2);
expect(summary.detachedTextures).toEqual([detachedCloudMap]);
expect(dayMap.needsUpdate).toBe(true);
expect(sharedSkyMap.needsUpdate).toBe(true);
expect(detachedCloudMap.needsUpdate).toBe(false);
});
test("createWebglRecoveryGuard enforces cooldown between automatic reloads", () => {
let clockMs = 100_000;
const store = new Map();
const guard = createWebglRecoveryGuard({
cooldownMs: 30_000,
now: () => clockMs,
storage: {
getItem: (k) => store.get(k) ?? null,
setItem: (k, v) => store.set(k, v),
},
});
expect(guard.canAutoReload()).toBe(true);
guard.recordAutoReload();
clockMs += 5_000;
expect(guard.canAutoReload()).toBe(false);
clockMs += 30_000;
expect(guard.canAutoReload()).toBe(true);
});
function createMockBrandImg(src) {
let currentSrc = src;
const listeners = new Map();
return {
dataset: {},
isConnected: true,
complete: true,
naturalWidth: 0,
getAttribute(name) {
return name === "src" ? currentSrc : null;
},
setAttribute(name, value) {
if (name === "src") currentSrc = value;
},
addEventListener(eventName, handler) {
listeners.set(eventName, [...(listeners.get(eventName) || []), handler]);
},
trigger(eventName) {
for (const handler of listeners.get(eventName) || []) {
handler();
}
},
};
}
test("brand image resilience retries transient errors and recovers broken images up to limit", () => {
expect(appendBrandRetryParam("/earth/assets/brand/earth-logo.png", 1)).toBe(
"/earth/assets/brand/earth-logo.png?brand_retry=1",
);
expect(appendBrandRetryParam("/custom/logo.png?v=2#icon", 2)).toBe(
"/custom/logo.png?v=2&brand_retry=2#icon",
);
const logoImg = createMockBrandImg("/custom/logo.png");
const titleImg = createMockBrandImg("/earth/assets/brand/title-zh.png");
titleImg.naturalWidth = 720;
const timers = [];
const root = {
querySelector: (selector) => (selector === ".earth-brand__logo" ? logoImg : titleImg),
querySelectorAll: () => [logoImg, titleImg],
};
attachBrandImageResilience(
root,
{
logoSrc: "/earth/assets/brand/earth-logo.png",
titleSrc: "/earth/assets/brand/title-zh.png",
},
(fn) => {
timers.push(fn);
},
);
logoImg.trigger("error");
expect(timers).toHaveLength(1);
timers.shift()();
expect(logoImg.getAttribute("src")).toBe("/custom/logo.png?brand_retry=1");
logoImg.trigger("error");
expect(timers).toHaveLength(1);
timers.shift()();
expect(logoImg.getAttribute("src")).toBe("/earth/assets/brand/earth-logo.png?brand_retry=2");
// Third failure does not loop indefinitely.
logoImg.trigger("error");
expect(timers).toHaveLength(0);
// Explicit recovery (e.g. after GPU restart) refreshes only broken imgs.
const recovered = recoverBrokenBrandImages(root, 999);
expect(recovered).toBe(1);
expect(logoImg.getAttribute("src")).toBe("/custom/logo.png?brand_retry=999");
expect(titleImg.getAttribute("src")).toBe("/earth/assets/brand/title-zh.png");
});
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.78.0"
version = "0.79.1"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+2 -2
View File
@@ -169,8 +169,8 @@ function checkElectronHeadlessSmoke() {
`expected transparent ZJU emblem (283px) loaded in splash, got ${JSON.stringify(report.splashCheck)}`,
)
assert(
report.splashCheck?.switchedThemes?.join(',') === 'constellation,horizon',
`expected splash scheme switching to update active theme, got ${JSON.stringify(report.splashCheck)}`,
report.splashCheck?.activeTheme === 'singularity' && report.splashCheck?.hasNoThemeSwitcher === true,
`expected unified singularity splash without theme switcher, got ${JSON.stringify(report.splashCheck)}`,
)
console.log(`ok: Electron headless smoke passed (${jsonLine})`)
}
+1
View File
@@ -24,6 +24,7 @@ main() {
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_proxy.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_mirror.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_database_startup.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_production_release.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_windows_restart.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_error_diagnostics.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_tool_resolution.py
+239
View File
@@ -0,0 +1,239 @@
import hashlib
import io
import json
import sys
import tarfile
import tempfile
import unittest
from contextlib import ExitStack
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import production_deploy as deploy
import production_registry as registry
import production_release as publisher
def hotfix(tag):
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as archive:
for name, data in {
"bundle-meta.json": json.dumps({"version": tag[1:], "shellVersion": tag[1:]}).encode(),
"index.html": b"<html>release test</html>",
}.items():
member = tarfile.TarInfo(name)
member.size = len(data)
archive.addfile(member, io.BytesIO(data))
return buf.getvalue()
class TransactionTests(unittest.TestCase):
old, tag = "v1.0.0", "v1.1.0"
def setUp(self):
self.stack = ExitStack()
self.addCleanup(self.stack.close)
base = Path(self.stack.enter_context(tempfile.TemporaryDirectory()))
self.host = deploy.Host(base / "host", base / "settings", base / "state")
self.host.state.mkdir()
folder = self.host.directory(self.old)
folder.mkdir(parents=True)
for name in deploy.HOST_FILES:
(folder / name).write_text("host-managed")
deploy.point_current(self.host, self.old)
self.old_refs = {key: "previous-" + key for key in registry.SERVICES}
self.new_refs = {key: "candidate-" + key for key in registry.SERVICES}
lines = [f"{key}={self.old_refs[name]}" for name, key in registry.SERVICES.items()]
self.host.env.write_text(
"\n".join(lines + ["LIMIT=500m", "CLIENT_UPDATE_PUBLISH_TOKEN=fixture"]) + "\n"
)
self.running = self.old_refs.copy()
self.manifest = base / "manifest.json"
self.original = b'{"bundle":{"version":"1.0.0","sha256":"previous"}}'
self.manifest.write_bytes(self.original)
self.calls = []
self.data = hotfix(self.tag)
self.sha = hashlib.sha256(self.data).hexdigest()
self.release = {"tag_name": self.tag, "draft": False, "prerelease": False}
self.mock("read_url", return_value=json.dumps(self.release).encode())
self.mock("tag_commit", return_value="f" * 40)
self.images = self.mock("resolved_images", return_value=self.new_refs)
self.mock("release_bundle", return_value=("bundle.tar.gz", self.data, self.sha))
self.mock("inspect", side_effect=lambda name: {"Config": {"Image": self.running[name]}})
self.mock("data_containers", return_value={"postgres": "same-db", "redis": "same-redis"})
self.mock("live_manifest_path", return_value=self.manifest)
self.mock("docker", side_effect=lambda *args: self.calls.append(args[0]))
self.mock("backup_database", side_effect=lambda p: p.write_bytes(b"verified backup"))
self.mock("check_routes", side_effect=lambda: self.calls.append("health"))
self.service = self.mock("rollout_services", side_effect=self.roll)
self.publish = self.mock("publish_hotfix_bundle", side_effect=self.publish_data)
self.verify = self.mock("check_hotfix", side_effect=self.verify_data)
def mock(self, name, **kwargs):
return self.stack.enter_context(patch.object(deploy, name, **kwargs))
def roll(self, host, tag, refs):
self.calls.append(tag)
self.running.update(refs)
def publish_data(self, **kwargs):
self.calls.append("hotfix")
archive, digest = kwargs["assets"][0]
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), digest)
self.manifest.write_text(
json.dumps({"bundle": {"version": kwargs["tag"][1:], "sha256": digest}})
)
def verify_data(self, tag, digest, shell_version=None):
self.assertEqual(
json.loads(self.manifest.read_bytes())["bundle"], {"version": tag[1:], "sha256": digest}
)
def test_new_release_and_duplicate_tick(self):
deploy.reconcile(self.host)
self.assertEqual(self.calls, ["pull"] * 3 + [self.tag, "health", "hotfix"])
self.assertEqual(self.host.current(), self.tag)
self.assertEqual(self.running, self.new_refs)
self.assertIn("LIMIT=500m\n", self.host.env.read_text())
self.assertTrue((self.host.state / "last-success/database.dump").is_file())
deploy.reconcile(self.host)
self.assertEqual(self.service.call_count, 1)
def test_manifest_failure_restores_previous_release_and_parks_it(self):
def verify(tag, sha, shell_version=None):
if tag == self.tag:
raise RuntimeError("independent public download failed")
self.verify_data(tag, sha)
self.verify.side_effect = verify
with self.assertRaisesRegex(RuntimeError, "download failed"):
deploy.reconcile(self.host)
self.assertEqual(self.host.current(), self.old)
self.assertEqual(self.running, self.old_refs)
self.assertEqual(self.manifest.read_bytes(), self.original)
self.assertTrue((self.host.state / "last-failed/database.dump").is_file())
deploy.reconcile(self.host)
self.assertEqual(self.service.call_count, 2)
self.verify.side_effect = self.verify_data
deploy.reconcile(self.host, retry=True)
self.assertEqual(self.host.current(), self.tag)
def test_interrupted_rollout_recovers_before_processing_latest(self):
self.service.side_effect = KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt):
deploy.reconcile(self.host)
self.assertTrue((self.host.state / "pending/release.json").is_file())
self.service.side_effect = self.roll
deploy.reconcile(self.host)
self.assertFalse((self.host.state / "pending").exists())
self.assertEqual(self.host.current(), self.old)
self.assertEqual(self.running, self.old_refs)
self.assertEqual(self.calls.count(self.old), 1)
self.publish.assert_not_called()
def test_incomplete_publication_does_not_change_production(self):
self.images.side_effect = RuntimeError("image is missing")
env = self.host.env.read_bytes()
with self.assertRaisesRegex(RuntimeError, "image is missing"):
deploy.reconcile(self.host)
self.assertEqual(self.host.env.read_bytes(), env)
self.assertFalse((self.host.state / "pending").exists())
self.service.assert_not_called()
def test_drafts_prereleases_and_older_versions_never_roll_out(self):
for tag, draft, pre in [
(self.tag, True, False),
(self.tag, False, True),
("v0.9.9", False, False),
]:
data = json.dumps({"tag_name": tag, "draft": draft, "prerelease": pre}).encode()
with patch.object(deploy, "read_url", return_value=data):
deploy.reconcile(self.host)
self.images.assert_not_called()
class ImageTests(unittest.TestCase):
def test_interrupted_upload_reuses_identical_local_artifacts(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
supplied = root / "supplied"
supplied.mkdir()
cache = root / "cache"
tag = "v1.2.3"
for name in (
"Planet Earth-1.2.3-win.zip",
"Planet Earth-1.2.3-mac.zip",
"planet_1.2.3.deb",
):
(supplied / name).write_bytes(b"original")
(supplied / "planet-earth-bundle-1.2.3.tar.gz").write_bytes(hotfix(tag))
suffixes = (".zip", ".deb", ".tar.gz")
publisher.cached_packages(root, supplied, cache, tag, suffixes)
original = "Planet Earth-1.2.3-win.zip"
(supplied / original).write_bytes(b"later build")
publisher.cached_packages(root, supplied, cache, tag, suffixes)
self.assertEqual((cache / original).read_bytes(), b"original")
(cache / original).write_bytes(b"corrupt cache")
with self.assertRaisesRegex(ValueError, "differ"):
publisher.cached_packages(root, supplied, cache, tag, suffixes)
def test_builds_only_missing_service_from_tag_and_verifies_after_push(self):
with (
tempfile.TemporaryDirectory() as temp,
patch.object(publisher, "resolve_image") as resolve,
patch.object(publisher.subprocess, "run") as run,
):
resolve.side_effect = ["provider-pin", "backend-pin", None, "admin-pin"]
publisher.ensure_images(Path(temp), "v1.2.3", "a" * 40)
args = run.call_args.args[0]
self.assertIn("linux/amd64", args)
self.assertIn("PLANET_FRONTEND_TARGET=admin", args)
self.assertIn("org.opencontainers.image.revision=" + "a" * 40, args)
self.assertTrue(any("push=true" in x and "admin:v1.2.3" in x for x in args))
run.assert_called_once()
def test_registry_verifies_actual_config_and_commit_before_accepting_digest(self):
commit = "a" * 40
cfg = json.dumps(
{
"os": "linux",
"architecture": "amd64",
"config": {
"Labels": {
"org.opencontainers.image.revision": commit,
"planet.frontend.target": "admin",
}
},
}
).encode()
raw = json.dumps({"config": {"digest": registry.digest(cfg)}}).encode()
with patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, cfg]):
pin = registry.resolve_image("admin", "v1.2.3", commit)
self.assertTrue(pin.endswith("@" + registry.digest(raw)))
for bad_commit, bad_cfg in [("b" * 40, cfg), (commit, cfg + b" ")]:
with (
patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, bad_cfg]),
self.assertRaises(ValueError),
):
registry.resolve_image("admin", "v1.2.3", bad_commit)
def test_corrupt_bundle_and_duplicate_checksum_are_rejected(self):
tag = "v1.2.3"
name = "planet-earth-bundle-1.2.3.tar.gz"
data = hotfix(tag)
expected = f"{hashlib.sha256(data).hexdigest()} {name}\n".encode()
release = {
"tag_name": tag,
"assets": [{"name": name, "size": len(data)}, {"name": "SHA256SUMS.txt", "size": 99}],
}
for sums, content in [(expected + expected, data), (expected, b"x" * len(data))]:
with (
patch.object(registry, "read_url", side_effect=[sums, content]),
self.assertRaises(ValueError),
):
registry.release_bundle(release, tag)
if __name__ == "__main__":
unittest.main()
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env python3
"""Reconcile published Planet releases with the existing lightweight production Compose stack."""
from __future__ import annotations
import argparse
import fcntl
import hashlib
import io
import json
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
if __package__:
from .production_registry import (
API,
REPO,
SERVER,
SERVICES,
read_url,
release_bundle,
resolve_image,
tag_commit,
version,
)
from .release_publish import publish_hotfix_bundle
else:
from production_registry import (
API,
REPO,
SERVER,
SERVICES,
read_url,
release_bundle,
resolve_image,
tag_commit,
version,
)
from release_publish import publish_hotfix_bundle
PUBLIC = "https://rclaw.top"
ADMIN = "https://admin.rclaw.top"
PROJECT = "planet-production"
HOST_FILES = (
"compose.yaml",
"compose.pilot.yaml",
"planet-https.conf",
"planet-api-locations.conf",
)
@dataclass(frozen=True)
class Host:
root: Path = Path("/opt/planet")
env: Path = Path("/etc/planet/deploy.env")
state: Path = Path("/var/lib/planet-release-deploy")
def directory(self, tag):
version(tag)
path = self.root / "releases" / tag
if path.is_symlink():
raise ValueError("Release directories must not be symbolic links")
return path
def current(self):
path = (self.root / "current").resolve(strict=True)
if path != self.directory(path.name):
raise ValueError("Unexpected active release directory")
return path.name
def sync_directory(path):
fd = os.open(path, os.O_DIRECTORY | os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def atomic_file(path, data, mode=0o600):
fd, name = tempfile.mkstemp(prefix="." + path.name, dir=path.parent)
try:
with os.fdopen(fd, "wb") as out:
os.fchmod(out.fileno(), mode)
out.write(data)
out.flush()
os.fsync(out.fileno())
os.replace(name, path)
sync_directory(path.parent)
finally:
Path(name).unlink(missing_ok=True)
def point_current(host, tag):
link = host.root / "current"
with tempfile.TemporaryDirectory(dir=host.root) as temp:
candidate = Path(temp) / "current"
candidate.symlink_to(host.directory(tag))
os.replace(candidate, link)
sync_directory(host.root)
def env_settings(host):
return dict(
line.split("=", 1)
for line in host.env.read_text().splitlines()
if "=" in line and not line.lstrip().startswith("#")
)
def set_images(host, images):
values = {SERVICES[service]: images[service] for service in SERVICES}
found = set()
lines = host.env.read_text().splitlines(keepends=True)
for index, line in enumerate(lines):
key = line.partition("=")[0]
if key in values:
found.add(key)
lines[index] = f"{key}={values[key]}\n"
if missing := values.keys() - found:
raise ValueError("Missing production image settings: " + ", ".join(sorted(missing)))
atomic_file(host.env, "".join(lines).encode())
def docker(*args):
return subprocess.check_output(["docker", *map(str, args)], text=True).strip()
def container_name(service):
return "planet_deploy_" + service
def inspect(service):
return json.loads(docker("inspect", container_name(service)))[0]
def data_containers():
return {name: inspect(name)["Id"] for name in ("postgres", "redis")}
def live_manifest_path():
mounts = inspect("backend")["Mounts"]
[mount] = [m for m in mounts if m["Destination"] == "/app/backend/data/client-updates"]
if mount.get("Name") != PROJECT + "_client_updates_data" or mount["Type"] != "volume":
raise RuntimeError("Expected the persistent production client update volume")
return Path(mount["Source"]) / "manifest.json"
def stage_config(host, previous, tag):
source, target = host.directory(previous), host.directory(tag)
target.mkdir(exist_ok=True)
sync_directory(target.parent)
for name in HOST_FILES:
original, dest = source / name, target / name
if dest.exists():
if dest.is_symlink() or dest.read_bytes() != original.read_bytes():
raise RuntimeError(f"Existing host configuration differs: {dest}")
else:
atomic_file(dest, original.read_bytes(), original.stat().st_mode & 0o777)
return target
def rollout_services(host, tag, images):
directory = host.directory(tag)
for name in SERVICES:
print(f"Starting {name} from {images[name]}", flush=True)
docker(
"compose",
"--project-name",
PROJECT,
"--env-file",
host.env,
"-f",
directory / "compose.yaml",
"-f",
directory / "compose.pilot.yaml",
"up",
"-d",
"--no-deps",
"--no-build",
"--pull",
"never",
name,
)
deadline = time.monotonic() + 100
while True:
container = inspect(name)
state = container["State"]
if (
container["Config"]["Image"] == images[name]
and state["Status"] == "running"
and state.get("Health", {}).get("Status") == "healthy"
):
break
if (
state["Status"] in ("exited", "dead")
or state.get("OOMKilled")
or time.monotonic() >= deadline
):
raise RuntimeError(f"{name} did not become healthy")
time.sleep(2)
def check_routes():
for url in (PUBLIC + "/health/ready", PUBLIC + "/api/v1/visualization/geo/summary"):
if not isinstance(json.loads(read_url(url)), dict):
raise RuntimeError(f"Unexpected response from {url}")
if b"<html" not in read_url(ADMIN + "/earth").lower():
raise RuntimeError("Admin Earth entry did not return HTML")
def check_hotfix(tag, sha, shell_version=None):
manifest = json.loads(read_url(PUBLIC + "/api/v1/client/update-manifest"))
bundle = manifest.get("bundle") or {}
path = f"/api/v1/client/updates/files/planet-earth-bundle-{tag[1:]}.tar.gz"
if (
manifest.get("shell", {}).get("version") != (shell_version or tag[1:])
or bundle.get("version") != tag[1:]
or bundle.get("sha256") != sha
or bundle.get("url") != path
):
raise RuntimeError("Live hotfix manifest does not match the release")
if hashlib.sha256(read_url(PUBLIC + path, limit=32 * 1024 * 1024)).hexdigest() != sha:
raise RuntimeError("Live hotfix download failed SHA-256 verification")
def minimum_shell(data, tag):
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 8192:
raise ValueError("Invalid hotfix metadata")
meta = json.load(archive.extractfile(member))
if meta.get("version") != tag[1:]:
raise ValueError("Hotfix metadata version differs from the release")
minimum = meta.get("minShellVersion") or meta["shellVersion"]
if version("v" + minimum) > version(tag):
raise ValueError("Hotfix requires a newer shell than the release")
return minimum
def backup_database(target):
with target.open("xb") as out:
subprocess.run(
[
"docker",
"exec",
container_name("postgres"),
"sh",
"-ec",
'exec pg_dump -Fc -Z 1 -U "$POSTGRES_USER" "$POSTGRES_DB"',
],
stdout=out,
check=True,
)
os.fsync(out.fileno())
with target.open("rb") as source:
catalog = subprocess.check_output(
["docker", "exec", "-i", container_name("postgres"), "pg_restore", "-l"], stdin=source
)
if b"TABLE DATA" not in catalog:
raise RuntimeError("Pre-deployment database backup failed verification")
def save_journal(host, journal, manifest):
with tempfile.TemporaryDirectory(dir=host.state) as scratch:
directory = Path(scratch) / "transaction"
directory.mkdir()
atomic_file(directory / "release.json", json.dumps(journal).encode())
if manifest.exists():
atomic_file(directory / "previous-manifest.json", manifest.read_bytes())
backup_database(directory / "database.dump")
sync_directory(directory)
os.rename(directory, host.state / "pending")
sync_directory(host.state)
def finish_journal(host, name):
previous = host.state / name
if previous.exists():
shutil.rmtree(previous)
os.rename(host.state / "pending", previous)
sync_directory(host.state)
def rollback(host):
pending = host.state / "pending"
journal = json.loads((pending / "release.json").read_text())
previous = journal["previous"]
print(f"Restoring {previous} after interrupted or unsuccessful {journal['tag']}", flush=True)
manifest = Path(journal["manifest"])
old = pending / "previous-manifest.json"
before = old.read_bytes() if old.exists() else None
current = manifest.read_bytes() if manifest.exists() else None
if current != before:
bundle = json.loads(current or b"{}").get("bundle") or {}
if bundle.get("version") != journal["tag"][1:] or bundle.get("sha256") != journal["sha"]:
raise RuntimeError(
"Hotfix manifest changed independently; preserved the transaction for review"
)
if before is None:
manifest.unlink()
sync_directory(manifest.parent)
else:
atomic_file(manifest, before, 0o644)
set_images(host, journal["old_images"])
rollout_services(host, previous, journal["old_images"])
point_current(host, previous)
check_routes()
if before:
old_manifest = json.loads(before)
bundle = old_manifest.get("bundle")
if bundle:
check_hotfix(
"v" + bundle["version"],
bundle["sha256"],
old_manifest.get("shell", {}).get("version"),
)
finish_journal(host, "last-failed")
print(f"Rollback to {previous} verified", flush=True)
def resolved_images(tag, commit):
images = {}
for service in SERVICES:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
images[service] = ref
return images
def deploy(host, release, previous, tag, images, commit):
name, data, sha = release_bundle(release, tag)
minimum = minimum_shell(data, tag)
settings = env_settings(host)
token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022")
if not token:
raise RuntimeError("Production hotfix publisher credential is missing")
old_images = {n: settings[k].strip("'\u0022") for n, k in SERVICES.items()}
for service, ref in images.items():
docker("pull", "--platform", "linux/amd64", ref)
if inspect(service)["Config"]["Image"] != old_images[service]:
raise RuntimeError("Running image differs from the host configuration: " + service)
stage_config(host, previous, tag)
manifest = live_manifest_path()
bundle_path = manifest.parent / name
if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha:
raise RuntimeError("Existing versioned hotfix file has different contents")
original_stores = data_containers()
save_journal(
host,
dict(
tag=tag,
previous=previous,
old_images=old_images,
manifest=str(manifest),
sha=sha,
commit=commit,
),
manifest,
)
try:
set_images(host, images)
rollout_services(host, tag, images)
check_routes()
if data_containers() != original_stores:
raise RuntimeError("PostgreSQL or Redis container identity changed")
with tempfile.TemporaryDirectory(dir=host.state) as tmp:
archive = Path(tmp) / name
archive.write_bytes(data)
publish_hotfix_bundle(
publish_url=PUBLIC,
publish_token=token,
tag=tag,
notes=release.get("body") or "",
release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}",
assets=[(archive, sha)],
min_shell_version=minimum,
)
check_hotfix(tag, sha)
point_current(host, tag)
finish_journal(host, "last-success")
except Exception as exc:
print(f"Deploying {tag} failed: {exc}", file=sys.stderr, flush=True)
rollback(host)
raise
print(f"Deployed {tag} at {commit}", flush=True)
def reconcile(host, *, check=False, retry=False):
if (host.state / "pending").exists():
if check:
raise RuntimeError("A previous rollout is pending recovery")
rollback(host)
previous = host.current()
release = json.loads(read_url(API + "/releases/latest"))
tag = release["tag_name"]
if release.get("draft") or release.get("prerelease"):
return
try:
candidate_version = version(tag)
except ValueError:
print(f"Ignoring release with a non-production tag: {tag!r}")
return
if candidate_version < version(previous):
return
if tag == previous and not check:
print(f"{tag} is already active")
return
commit = tag_commit(tag)
failed = host.state / "last-failed/release.json"
if (
tag != previous
and failed.is_file()
and json.loads(failed.read_text())["tag"] == tag
and not retry
):
print(f"{tag} previously rolled back; waiting for a new release or --retry", flush=True)
return
images = resolved_images(tag, commit)
if check:
_, data, sha = release_bundle(release, tag)
minimum_shell(data, tag)
if tag == previous:
for name, ref in images.items():
container = inspect(name)
if (
container["Config"]["Image"] != ref
or container["State"]["Health"]["Status"] != "healthy"
):
raise RuntimeError("Active service differs from the release: " + name)
check_routes()
check_hotfix(tag, sha)
print(f"Verified {tag} at {commit}; active release {previous}", flush=True)
return
deploy(host, release, previous, tag, images, commit)
def main():
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--check", action="store_true", help="Verify the release without switching production"
)
group.add_argument(
"--retry", action="store_true", help="Retry the latest release after a verified rollback"
)
args = parser.parse_args()
os.umask(0o077)
host = Host()
host.state.mkdir(mode=0o700, parents=True, exist_ok=True)
with (host.state / "lock").open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print("Another production release check is running")
return
reconcile(host, check=args.check, retry=args.retry)
if __name__ == "__main__":
try:
main()
except (
RuntimeError,
ValueError,
KeyError,
OSError,
tarfile.TarError,
subprocess.SubprocessError,
) as exc:
sys.exit(f"Production release check failed: {exc}")
+155
View File
@@ -0,0 +1,155 @@
"""Read the public Planet release and immutable linux/amd64 images from Gitea."""
from __future__ import annotations
import hashlib
import json
import re
import time
import urllib.error
import urllib.parse
import urllib.request
SERVER = "https://gitea.rclaw.top"
REPO = "linkong/planet"
REGISTRY = urllib.parse.urlsplit(SERVER).netloc
API = f"{SERVER}/api/v1/repos/{REPO}"
SERVICES = {
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
"backend": "BACKEND_IMAGE_NAME",
"admin": "ADMIN_IMAGE_NAME",
}
MANIFEST_TYPES = ", ".join(
(
"application/vnd.oci.image.index.v1+json",
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.docker.distribution.manifest.v2+json",
)
)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args):
return None
def read_url(url, *, headers=None, limit=2 * 1024 * 1024):
"""Bound a release download and keep authorization on its original HTTPS endpoint."""
request = urllib.request.Request(url, headers=headers or {})
for attempt in range(3):
try:
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
data = response.read(limit + 1)
if len(data) > limit:
raise ValueError(f"Release response exceeds {limit} bytes")
return data
except urllib.error.HTTPError as exc:
if exc.code not in (502, 503, 504) or attempt == 2:
raise
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
if attempt == 2:
raise RuntimeError(f"Could not read release metadata from {url}") from exc
time.sleep(1 + attempt)
def version(tag):
if not isinstance(tag, str) or not re.fullmatch(
r"v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)", tag
):
raise ValueError(f"Expected a stable version tag, got {tag!r}")
return tuple(int(part) for part in tag[1:].split("."))
def tag_commit(tag):
version(tag)
commit = json.loads(read_url(f"{API}/tags/{tag}"))["commit"]["sha"]
if not re.fullmatch("[0-9a-f]{40,64}", commit):
raise ValueError("Invalid Gitea commit ID")
return commit
def release_bundle(release, tag):
"""Read the published hotfix and check it against the release checksum file."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
assets = release.get("assets") or []
sizes = {entry["name"]: entry["size"] for entry in assets}
if len(assets) != len(sizes):
raise ValueError("Duplicate release attachment names")
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
base = f"{SERVER}/{REPO}/releases/download/{tag}"
if not 0 < sizes.get(name, 0) <= 32 * 1024 * 1024 or "SHA256SUMS.txt" not in sizes:
raise ValueError("Release has no complete Earth bundle and checksum list")
sums = read_url(f"{base}/SHA256SUMS.txt", limit=128 * 1024).decode().splitlines()
hashes = [line.split(" ", 1)[0] for line in sums if line.endswith(" " + name)]
data = read_url(f"{base}/{name}", limit=sizes[name])
sha = hashlib.sha256(data).hexdigest()
if hashes != [sha] or len(data) != sizes[name]:
raise ValueError("Earth bundle failed release SHA-256 or size verification")
return name, data, sha
def image_name(service):
if service not in SERVICES:
raise ValueError(f"Unexpected production service: {service}")
return f"{REGISTRY}/{REPO}/{service}"
def digest(data):
return "sha256:" + hashlib.sha256(data).hexdigest()
def descriptor_digest(desc):
value = desc["digest"]
if not re.fullmatch(r"sha256:[a-f0-9]{64}", value):
raise ValueError("Registry returned an invalid digest")
return value
def resolve_image(service, tag, commit):
"""Return the immutable platform image; only an absent tag returns None."""
version(tag)
name = image_name(service)
repository = f"{REPO}/{service}"
query = urllib.parse.urlencode(
{"service": "container_registry", "scope": f"repository:{repository}:pull"}
)
token = json.loads(read_url(f"{SERVER}/v2/token?{query}"))["token"]
headers = {"Authorization": "Bearer " + token, "Accept": MANIFEST_TYPES}
base = f"{SERVER}/v2/{repository}"
try:
raw = read_url(f"{base}/manifests/{tag}", headers=headers)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
raise
manifest = json.loads(raw)
if "manifests" in manifest:
candidates = [
entry
for entry in manifest["manifests"]
if entry.get("platform", {}).get("os") == "linux"
and entry["platform"].get("architecture") == "amd64"
]
if len(candidates) != 1:
raise ValueError(f"{name}:{tag} must contain one linux/amd64 image")
selected = descriptor_digest(candidates[0])
raw = read_url(f"{base}/manifests/{selected}", headers=headers)
if digest(raw) != selected:
raise ValueError("Registry platform manifest failed digest verification")
manifest = json.loads(raw)
config_digest = descriptor_digest(manifest["config"])
config_raw = read_url(f"{base}/blobs/{config_digest}", headers=headers)
if digest(config_raw) != config_digest:
raise ValueError("Registry image configuration failed digest verification")
config = json.loads(config_raw)
labels = config.get("config", {}).get("Labels") or {}
if (config.get("os"), config.get("architecture")) != ("linux", "amd64"):
raise ValueError(f"{name}:{tag} is not a linux/amd64 image")
if labels.get("org.opencontainers.image.revision") != commit:
raise ValueError(f"{name}:{tag} belongs to a different commit")
if service == "admin" and labels.get("planet.frontend.target") != "admin":
raise ValueError("The production Admin image must be built with the admin-only target")
return f"{name}:{tag}@{digest(raw)}"
+223
View File
@@ -0,0 +1,223 @@
"""Prepare a tagged Planet release on the publishing workstation."""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from contextlib import contextmanager
from pathlib import Path
if __package__:
from .production_registry import (
REPO,
SERVER,
SERVICES,
image_name,
resolve_image,
tag_commit,
version,
)
else:
from production_registry import (
REPO,
SERVER,
SERVICES,
image_name,
resolve_image,
tag_commit,
version,
)
def git(*args, cwd=None):
return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
def verified_tag(tag):
commit = tag_commit(tag)
if git("rev-parse", "--verify", f"{commit}^{{commit}}") != commit:
raise RuntimeError("The remote release commit is not available locally")
if git("show", f"{commit}:VERSION") != tag[1:]:
raise ValueError("Tagged VERSION differs from the published tag")
return commit
def docker_config():
config = os.environ.get("PLANET_RELEASE_DOCKER_CONFIG")
if config:
return Path(config).expanduser()
return (
Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "planet" / "registry"
)
def ensure_images(source, tag, commit):
for service in SERVICES:
pin = resolve_image(service, tag, commit)
if not pin:
context = source / "frontend" if service == "admin" else source
dockerfile = (
context / "Dockerfile" if service == "admin" else source / service / "Dockerfile"
)
cmd = [
"docker",
"--config",
str(docker_config()),
"buildx",
"build",
"--platform",
"linux/amd64",
"--provenance=false",
"--file",
str(dockerfile),
"--label",
f"org.opencontainers.image.revision={commit}",
"--label",
f"org.opencontainers.image.version={tag[1:]}",
"--label",
f"org.opencontainers.image.source={SERVER}/{REPO}",
]
if service == "admin":
cmd += [
"--build-arg",
"PLANET_FRONTEND_TARGET=admin",
"--label",
"planet.frontend.target=admin",
]
uv_config = Path.home() / ".config/uv/uv.toml"
if service != "admin" and uv_config.is_file():
cmd += ["--secret", f"id=planet_uv_config,src={uv_config}"]
cmd += [
"--output",
f"type=image,name={image_name(service)}:{tag},push=true,compression=gzip,force-compression=true",
str(context),
]
subprocess.run(cmd, check=True)
pin = resolve_image(service, tag, commit)
if not pin:
raise RuntimeError(f"Pushed image is not visible: {service}:{tag}")
print(f"Verified {pin}", flush=True)
def select_packages(directory, tag, suffixes):
number = re.compile(rf"(?<![\d.]){re.escape(tag[1:])}(?!\d|\.\d)")
paths = (
[
p
for p in directory.iterdir()
if p.is_file() and number.search(p.name) and p.name.lower().endswith(suffixes)
]
if directory.is_dir()
else []
)
names = [p.name.lower() for p in paths]
if not (
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
and any(n.endswith((".appimage", ".deb")) for n in names)
and f"planet-earth-bundle-{tag[1:]}.tar.gz" in names
):
return []
bundle = directory / f"planet-earth-bundle-{tag[1:]}.tar.gz"
with tarfile.open(bundle, "r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 8192:
raise ValueError("Invalid hotfix package metadata")
if json.load(archive.extractfile(member)).get("version") != tag[1:]:
raise ValueError("Hotfix contents do not match the release tag")
return paths
@contextmanager
def local_release_lock(path):
with path.open("a+b") as lock:
if os.name == "nt":
import msvcrt
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def package_hash(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def cached_packages(source, supplied, cache, tag, suffixes):
if not cache.exists():
if supplied is None:
subprocess.run(["./planet.sh", "bundle", "--all"], cwd=source, check=True)
supplied = source / "client/release"
packages = select_packages(supplied, tag, suffixes)
if not packages:
raise RuntimeError(f"Missing tagged desktop clients or Earth hotfix in {supplied}")
with tempfile.TemporaryDirectory(dir=cache.parent) as tmp:
stage = Path(tmp) / "assets"
stage.mkdir()
for package in packages:
shutil.copy2(package, stage / package.name)
sums = {p.name: package_hash(p) for p in stage.iterdir()}
(stage / "checksums.json").write_text(json.dumps(sums))
os.rename(stage, cache)
packages = select_packages(cache, tag, suffixes)
expected = json.loads((cache / "checksums.json").read_text())
if not packages or {p.name: package_hash(p) for p in packages} != expected:
raise ValueError("The saved release artifacts differ from the original build")
return packages
@contextmanager
def prepare(tag, assets_dir, suffixes, *, already_published=False):
version(tag)
commit = verified_tag(tag)
state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
state = state / "planet-releases" / tag / "publisher"
state.mkdir(mode=0o700, parents=True, exist_ok=True)
cache = state / commit
with (
local_release_lock(state / "lock"),
tempfile.TemporaryDirectory(prefix="planet-publish-") as tmp,
):
worktree = Path(tmp) / "src"
subprocess.run(
["git", "worktree", "add", "--quiet", "--detach", str(worktree), commit], check=True
)
try:
ensure_images(worktree, tag, commit)
stage = Path(tmp) / "assets"
stage.mkdir()
if not already_published:
for package in cached_packages(worktree, assets_dir, cache, tag, suffixes):
try:
os.link(package, stage / package.name)
except OSError:
shutil.copy2(package, stage / package.name)
yield stage, worktree / "docs/CHANGELOG.md"
# The verified public release now holds these bytes. Keep the cache on upload failure.
if cache.exists():
shutil.rmtree(cache)
finally:
# This detached checkout and its generated build files are private to this invocation.
subprocess.run(["git", "worktree", "remove", "--force", str(worktree)], check=True)
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("Usage: production_release.py vX.Y.Z")
release_tag = sys.argv[1]
revision = verified_tag(release_tag)
if git("rev-parse", "HEAD") != revision or git("status", "--porcelain", "--untracked-files=no"):
sys.exit("Image-only CI jobs require a clean checkout at the tagged commit")
ensure_images(Path.cwd(), release_tag, revision)
+164 -17
View File
@@ -11,12 +11,14 @@ import os
import re
import subprocess
import sys
import tarfile
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ASSET_SUFFIXES = (".zip", ".appimage", ".deb", ".exe", ".dmg")
ASSET_SUFFIXES = (".zip", ".appimage", ".deb", ".exe", ".dmg", ".tar.gz")
class RejectRedirects(urllib.request.HTTPRedirectHandler):
@@ -24,6 +26,10 @@ class RejectRedirects(urllib.request.HTTPRedirectHandler):
return None
class RetryableUploadError(RuntimeError):
"""The server may already have received the attachment."""
API_OPENER = urllib.request.build_opener(RejectRedirects())
@@ -226,7 +232,8 @@ def upload_asset_with_curl(
capture_output=True,
)
if proc.returncode != 0:
raise RuntimeError(
error = RetryableUploadError if proc.returncode in (6, 7, 18, 28, 52, 55, 56, 92) else RuntimeError
raise error(
f"curl upload failed for {file_path.name} (exit={proc.returncode}): {proc.stderr.strip()}"
)
@@ -243,7 +250,8 @@ def upload_asset_with_curl(
"Check Gitea app.ini [attachment] MAX_SIZE and Nginx/Ingress client_max_body_size (>= 300M)."
)
if status_code != 201:
raise RuntimeError(f"Upload failed for {file_path.name} (HTTP {status_code})")
error = RetryableUploadError if status_code in (408, 409, 429, 502, 503, 504) else RuntimeError
raise error(f"Upload failed for {file_path.name} (HTTP {status_code})")
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
@@ -251,7 +259,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser.add_argument("--tag", required=True, help="Git release tag, e.g. v0.77.0")
parser.add_argument(
"--assets-dir",
default="client/release",
default=None,
help="Directory containing packaged client binaries (default: client/release)",
)
parser.add_argument(
@@ -279,6 +287,16 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
action="store_true",
help="Verify release notes and asset checksums without calling remote Gitea APIs",
)
parser.add_argument(
"--hotfix-publish-url",
default="",
help="Optional backend base URL (e.g. https://rclaw.top) to publish L1 hotfix bundle",
)
parser.add_argument(
"--hotfix-publish-token",
default="",
help="Optional X-Client-Update-Token matching CLIENT_UPDATE_PUBLISH_TOKEN on backend",
)
return parser.parse_args(argv)
@@ -377,17 +395,30 @@ def publish_release(
if path.name in existing:
verify_existing_asset(existing[path.name], path, sha, server, authorization)
print(f"verified existing {path.name}", flush=True)
for path, _sha in assets:
for path, sha in assets:
if path.name in existing:
continue
name = urllib.parse.quote(path.name, safe="")
print(f"uploading {path.name}...", flush=True)
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
for attempt in range(3):
try:
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
break
except RetryableUploadError:
received = list_assets(release_url, authorization).get(path.name)
if received:
verify_existing_asset(received, path, sha, server, authorization)
break
if attempt == 2:
raise
time.sleep(2 ** attempt)
uploaded = list_assets(release_url, authorization)
for path, _sha in assets:
for path, sha in assets:
if uploaded.get(path.name, {}).get("size") != path.stat().st_size:
raise RuntimeError(f"Missing or incomplete attachment: {path.name}")
if path.name not in existing or uploaded[path.name].get("id") != existing[path.name].get("id"):
verify_existing_asset(uploaded[path.name], path, sha, server, authorization)
status, published = api_request(
"PATCH", release_url, authorization, {"name": tag, "body": notes, "draft": False}
@@ -395,6 +426,83 @@ def publish_release(
if status != 200 or not isinstance(published, dict) or published.get("draft") is not False:
raise RuntimeError(f"Could not publish release {tag} (HTTP {status})")
print(f"published release {tag} with {len(assets)} asset(s)", flush=True)
return str(published.get("html_url") or f"{server}/{repo}/releases/tag/{tag}")
def publish_hotfix_bundle(
*,
publish_url: str,
publish_token: str,
tag: str,
notes: str,
release_html_url: str,
assets: list[tuple[Path, str]],
min_shell_version: str | None = None,
) -> None:
hotfix_tar = next(
(
path
for path, _sha in assets
if path.name.startswith("planet-earth-bundle-") and path.name.endswith(".tar.gz")
),
None,
)
if hotfix_tar is None:
print("skipping L1 hotfix publish: no planet-earth-bundle-*.tar.gz found in assets", flush=True)
return
version = tag.lstrip("vV")
endpoint = f"{publish_url.rstrip('/')}/api/v1/client/updates/bundle"
proc = subprocess.run(
[
"curl",
"--disable",
"-sS",
"--connect-timeout",
"15",
"--max-time",
"120",
"-w",
"\n%{http_code}",
"-X",
"POST",
"--header",
"@-",
"-F",
f"file=@{hotfix_tar}",
"--form-string",
f"version={version}",
"--form-string",
f"min_shell_version={min_shell_version or version}",
"--form-string",
f"shell_version={version}",
"--form-string",
f"shell_download_url={release_html_url}",
"--form-string",
f"release_notes={notes[:2000]}",
endpoint,
],
input=f"X-Client-Update-Token: {publish_token}\n",
text=True,
capture_output=True,
)
if proc.returncode != 0:
raise RuntimeError(
f"Hotfix upload failed for {hotfix_tar.name} (exit={proc.returncode}): {proc.stderr.strip()}"
)
lines = proc.stdout.splitlines()
status_str = lines[-1].strip() if lines else ""
try:
status_code = int(status_str)
except ValueError as exc:
raise RuntimeError(f"Unexpected response publishing hotfix {hotfix_tar.name}: {proc.stdout}") from exc
if status_code not in (200, 201):
body_preview = "\n".join(lines[:-1])[:300]
raise RuntimeError(
f"Hotfix publish rejected for {hotfix_tar.name} (HTTP {status_code}): {body_preview}"
)
print(f"published L1 hotfix bundle {hotfix_tar.name} -> {endpoint}", flush=True)
def main(argv: list[str] | None = None) -> int:
@@ -409,14 +517,14 @@ def main(argv: list[str] | None = None) -> int:
print("error: unable to resolve Gitea server URL or owner/repo slug", file=sys.stderr)
return 1
notes = extract_release_notes(Path(args.changelog), args.tag)
assets_dir = Path(args.assets_dir)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
assets_dir = Path(args.assets_dir or "client/release")
if args.dry_run:
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
print(f"server: {server}")
print(f"repo: {repo}")
print(f"tag: {args.tag}")
@@ -428,15 +536,54 @@ def main(argv: list[str] | None = None) -> int:
return 0
try:
if args.use_git_credential:
if __package__:
from .production_registry import API, REPO, SERVER, release_bundle
from .production_release import prepare
else:
from production_registry import API, REPO, SERVER, release_bundle
from production_release import prepare
production = (server, repo) == (SERVER, REPO) and re.fullmatch(r"v\d+\.\d+\.\d+", args.tag)
token = os.environ.get("GITEA_TOKEN")
if not token and (not production or os.environ.get("GITHUB_SERVER_URL", "").rstrip("/") == server):
token = os.environ.get("GITHUB_TOKEN")
if args.use_git_credential or (production and not token):
authorization = git_credential_authorization(origin, server, repo)
else:
token = os.environ.get("GITEA_TOKEN") or os.environ.get("GITHUB_TOKEN")
if not token:
raise RuntimeError("Set GITEA_TOKEN or use the saved HTTPS Git credential")
authorization = f"token {token}"
publish_release(server, repo, args.tag, notes, assets, authorization)
except (RuntimeError, urllib.error.URLError, TimeoutError) as exc:
if production:
status, public = api_request("GET", f"{API}/releases/tags/{args.tag}", authorization)
if status not in (200, 404):
raise RuntimeError(f"Cannot inspect the release (HTTP {status})")
published = status == 200 and isinstance(public, dict) and public.get("draft") is False
supplied = assets_dir if args.assets_dir else None
with prepare(args.tag, supplied, ASSET_SUFFIXES, already_published=published) as (stage, changelog):
if published:
release_bundle(public, args.tag)
print(f"Verified published release {args.tag}; production follows stable releases")
else:
notes = extract_release_notes(changelog, args.tag)
publish_release(server, repo, args.tag, notes, collect_release_assets(stage), authorization)
return 0
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
raise RuntimeError(f"No distributable assets found in {assets_dir}")
release_html_url = publish_release(server, repo, args.tag, notes, assets, authorization)
hotfix_url = str(args.hotfix_publish_url or "").strip()
hotfix_token = str(args.hotfix_publish_token or "").strip()
if hotfix_url and hotfix_token:
publish_hotfix_bundle(
publish_url=hotfix_url,
publish_token=hotfix_token,
tag=args.tag,
notes=notes,
release_html_url=release_html_url,
assets=assets,
)
except (RuntimeError, ValueError, KeyError, OSError, subprocess.SubprocessError, tarfile.TarError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
return 0
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.78.0"
version = "0.79.1"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },