From e53c3af355ff466a5ba0ae09295c929457c125c9 Mon Sep 17 00:00:00 2001 From: linkong Date: Tue, 24 Nov 2026 15:40:10 +0800 Subject: [PATCH] release: bump version to 0.79.0 --- .gitea/workflows/release.yaml | 6 +- VERSION | 2 +- backend/app/api/main.py | 2 + backend/app/api/v1/client_updates.py | 317 ++++++++++ backend/app/core/config.py | 5 + backend/tests/test_client_updates.py | 174 ++++++ client/package.json | 2 +- client/scripts/build-earth-bundle.mjs | 51 +- client/src/main/config.ts | 12 +- client/src/main/gpu-policy.ts | 35 ++ client/src/main/hot-update-core.ts | 504 ++++++++++++++++ client/src/main/hot-updater.ts | 313 ++++++++++ client/src/main/index.ts | 127 +++- client/src/main/menu.ts | 49 +- client/src/main/protocol-core.ts | 16 + client/src/main/protocol.ts | 2 + client/src/main/tar-gz.ts | 233 ++++++++ client/src/preload/index.ts | 21 + client/src/preload/splash.ts | 562 +++++++----------- client/tests/gpu-policy.test.ts | 72 +++ client/tests/hot-update.test.ts | 303 ++++++++++ client/tests/splash-config.test.ts | 48 +- docker-compose.deploy.yml | 2 + docs/CHANGELOG.md | 21 + docs/version-history.md | 3 +- frontend/package.json | 2 +- frontend/public/earth/js/brand.js | 94 ++- frontend/public/earth/js/celestial.js | 153 ++++- frontend/public/earth/js/earth.js | 34 ++ frontend/public/earth/js/i18n.js | 16 + frontend/public/earth/js/main.js | 99 ++- frontend/public/earth/js/webgl-recovery.js | 130 ++++ .../public/earth/js/webgl-recovery.test.js | 154 +++++ pyproject.toml | 2 +- scripts/harness/client-smoke.mjs | 4 +- scripts/release_publish.py | 101 +++- uv.lock | 2 +- 37 files changed, 3220 insertions(+), 453 deletions(-) create mode 100644 backend/app/api/v1/client_updates.py create mode 100644 backend/tests/test_client_updates.py create mode 100644 client/src/main/gpu-policy.ts create mode 100644 client/src/main/hot-update-core.ts create mode 100644 client/src/main/hot-updater.ts create mode 100644 client/src/main/tar-gz.ts create mode 100644 client/tests/gpu-policy.test.ts create mode 100644 client/tests/hot-update.test.ts create mode 100644 frontend/public/earth/js/webgl-recovery.js create mode 100644 frontend/public/earth/js/webgl-recovery.test.js diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml index eddb2793..981c0560 100644 --- a/.gitea/workflows/release.yaml +++ b/.gitea/workflows/release.yaml @@ -82,8 +82,12 @@ jobs: - name: Publish Gitea Release with client packages env: GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }} + CLIENT_UPDATE_PUBLISH_URL: ${{ secrets.CLIENT_UPDATE_PUBLISH_URL }} + CLIENT_UPDATE_PUBLISH_TOKEN: ${{ secrets.CLIENT_UPDATE_PUBLISH_TOKEN }} run: | python3 scripts/release_publish.py \ --tag "${GITHUB_REF_NAME}" \ --assets-dir client/release \ - --changelog docs/CHANGELOG.md + --changelog docs/CHANGELOG.md \ + --hotfix-publish-url "${CLIENT_UPDATE_PUBLISH_URL}" \ + --hotfix-publish-token "${CLIENT_UPDATE_PUBLISH_TOKEN}" diff --git a/VERSION b/VERSION index bd14e853..870aec4a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.78.0 +0.79.0 diff --git a/backend/app/api/main.py b/backend/app/api/main.py index 43abc551..bf1d209c 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -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"]) diff --git a/backend/app/api/v1/client_updates.py b/backend/app/api/v1/client_updates.py new file mode 100644 index 00000000..cf5d3d5d --- /dev/null +++ b/backend/app/api/v1/client_updates.py @@ -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} diff --git a/backend/app/core/config.py b/backend/app/core/config.py index cf3231ab..84033e6f 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -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" diff --git a/backend/tests/test_client_updates.py b/backend/tests/test_client_updates.py new file mode 100644 index 00000000..4a1f477c --- /dev/null +++ b/backend/tests/test_client_updates.py @@ -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"updated", + "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 diff --git a/client/package.json b/client/package.json index c060ac67..e659c75d 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "planet-client", - "version": "0.78.0", + "version": "0.79.0", "description": "Intelligent Planet Program - Native Electron Earth Viewer", "private": true, "packageManager": "bun@1", diff --git a/client/scripts/build-earth-bundle.mjs b/client/scripts/build-earth-bundle.mjs index 49569104..21073d57 100644 --- a/client/scripts/build-earth-bundle.mjs +++ b/client/scripts/build-earth-bundle.mjs @@ -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})`, +) diff --git a/client/src/main/config.ts b/client/src/main/config.ts index 37f5fa7d..53cb939e 100644 --- a/client/src/main/config.ts +++ b/client/src/main/config.ts @@ -1,7 +1,7 @@ import fs from 'node:fs' import path from 'node:path' -export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off' +export type SplashTheme = 'singularity' | 'off' export interface ServerEndpoints { backendUrl: string @@ -29,11 +29,12 @@ export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlag splashTheme: SplashTheme } -const VALID_SPLASH_THEMES: ReadonlySet = new Set([ +const LEGACY_ACTIVE_THEMES: ReadonlySet = new Set([ 'singularity', 'constellation', 'horizon', - 'off', + 'on', + 'default', ]) export function normalizeSplashTheme( @@ -41,8 +42,9 @@ 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 const DEFAULT_ENDPOINTS: Readonly = { diff --git a/client/src/main/gpu-policy.ts b/client/src/main/gpu-policy.ts new file mode 100644 index 00000000..a61f81ba --- /dev/null +++ b/client/src/main/gpu-policy.ts @@ -0,0 +1,35 @@ +export interface ChromiumSwitch { + name: string + value?: string +} + +export interface GpuPolicyInput { + platform: NodeJS.Platform + headlessSmoke: boolean + softwareGl: boolean +} + +export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitch[] { + if (input.headlessSmoke || input.softwareGl) { + 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 / force_high_performance_gpu: + // on Windows dual-GPU setups with high baseline VRAM usage they can provoke driver TDRs. + const switches: ChromiumSwitch[] = [{ name: 'disable-renderer-backgrounding' }] + if (input.platform === 'linux') { + switches.push({ name: 'ozone-platform-hint', value: 'auto' }) + } + return switches +} + +export function isGpuProcessCrash( + details: { type?: string; reason?: string } | null | undefined, +): boolean { + return Boolean(details && details.type === 'GPU' && details.reason !== 'clean-exit') +} diff --git a/client/src/main/hot-update-core.ts b/client/src/main/hot-update-core.ts new file mode 100644 index 00000000..483d55fe --- /dev/null +++ b/client/src/main/hot-update-core.ts @@ -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 + 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): 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([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 }, +): 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 + } +} diff --git a/client/src/main/hot-updater.ts b/client/src/main/hot-updater.ts new file mode 100644 index 00000000..705f66e2 --- /dev/null +++ b/client/src/main/hot-updater.ts @@ -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 +} + +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 { + 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 | null = null + let inFlightCheck: Promise | null = null + const dismissedPromptKeys = new Set() + + 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 => { + 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 + }, + } +} diff --git a/client/src/main/index.ts b/client/src/main/index.ts index d8754b0f..876c5fcd 100644 --- a/client/src/main/index.ts +++ b/client/src/main/index.ts @@ -5,6 +5,9 @@ import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron' import { DesktopConfigStore, normalizeSplashTheme, type ServerEndpoints } from './config' import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link' +import { isGpuProcessCrash, resolveChromiumGpuSwitches } 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' @@ -12,19 +15,16 @@ import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation 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') +const isSoftwareGl = process.argv.includes('--software-gl') +for (const sw of resolveChromiumGpuSwitches({ + platform: process.platform, + headlessSmoke: isHeadlessSmoke, + softwareGl: isSoftwareGl, +})) { + if (sw.value !== undefined) { + app.commandLine.appendSwitch(sw.name, sw.value) + } else { + app.commandLine.appendSwitch(sw.name) } } @@ -93,6 +93,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 +119,48 @@ if (!singleInstanceLock) { }) const earthBundleRoot = resolveEarthBundleRoot() + const hotUpdater = createHotUpdateController({ + userDataDir: app.getPath('userData'), + shellVersion: app.getVersion(), + getBackendUrl: () => configStore.get().backendUrl, + getMainWindow: () => mainWindow, + onOverlayChanged: () => { + refreshApplicationMenu() + }, + }) + + const refreshApplicationMenu = () => { + if (!mainWindow || mainWindow.isDestroyed()) return + Menu.setApplicationMenu( + buildApplicationMenu({ + mainWindow, + configStore, + getVersionInfo: () => hotUpdater.getVersionInfo(), + onCheckForUpdates: () => { + void hotUpdater.checkForUpdates({ manual: true }) + }, + }), + ) + } + installEarthSessionHandlers(session.defaultSession, { earthBundleRoot, + getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(), getBackendUrl: () => configStore.get().backendUrl, }) + ipcMain.on('planet:earth-startup-ready', () => { + if (!isHeadlessSmoke) { + hotUpdater.markStartupReady() + } + }) + + 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 = { @@ -178,9 +229,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 +246,46 @@ if (!singleInstanceLock) { configStore, }) - Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore })) + refreshApplicationMenu() if (process.platform !== 'darwin') { mainWindow.setMenuBarVisibility(false) } + if (!isHeadlessSmoke) { + let autoUpdateTimer: ReturnType | null = null + let periodicUpdateTimer: ReturnType | null = null + mainWindow.webContents.on('render-process-gone', () => { + hotUpdater.handleRendererCrash() + }) + hotUpdater.startStartupWatchdog() + mainWindow.webContents.once('did-finish-load', () => { + 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', () => { + if (autoUpdateTimer) { + clearTimeout(autoUpdateTimer) + autoUpdateTimer = null + } + if (periodicUpdateTimer) { + clearInterval(periodicUpdateTimer) + periodicUpdateTimer = null + } + hotUpdater.stopStartupWatchdog() + }) + } + if (isHeadlessSmoke) { const smokeTimeout = setTimeout(() => { app.exit(1) @@ -267,10 +351,8 @@ 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), @@ -279,7 +361,8 @@ if (!singleInstanceLock) { hasPresenterEn: copy.includes('Institute of Intelligent Media'), emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0), emblemWidth: img ? img.naturalWidth : 0, - switchedThemes: [firstSwitch, secondSwitch], + activeTheme, + hasNoThemeSwitcher, }); }; if (!img || img.complete) { diff --git a/client/src/main/menu.ts b/client/src/main/menu.ts index 72a71612..7d5f04d5 100644 --- a/client/src/main/menu.ts +++ b/client/src/main/menu.ts @@ -3,9 +3,13 @@ import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } import type { DesktopConfigStore, SplashTheme } from './config' import { openServerSettingsDialog, toggleWindowOrientation } from './window' +import type { HotUpdateVersionInfo } from './hot-updater' + export function buildApplicationMenu(options: { mainWindow: BrowserWindow configStore: DesktopConfigStore + getVersionInfo?: () => HotUpdateVersionInfo + onCheckForUpdates?: () => void }): Menu { const sendAction = (action: string) => { if (!options.mainWindow.isDestroyed()) { @@ -72,31 +76,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' }, { @@ -116,6 +102,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' }, ], }, diff --git a/client/src/main/protocol-core.ts b/client/src/main/protocol-core.ts index df410b7b..cc6d4cc5 100644 --- a/client/src/main/protocol-core.ts +++ b/client/src/main/protocol-core.ts @@ -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 { @@ -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) } } diff --git a/client/src/main/protocol.ts b/client/src/main/protocol.ts index 3ff2ba5b..141a77e0 100644 --- a/client/src/main/protocol.ts +++ b/client/src/main/protocol.ts @@ -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), }) diff --git a/client/src/main/tar-gz.ts b/client/src/main/tar-gz.ts new file mode 100644 index 00000000..8242e441 --- /dev/null +++ b/client/src/main/tar-gz.ts @@ -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, + } +} diff --git a/client/src/preload/index.ts b/client/src/preload/index.ts index aca8df0b..cf2c1cf5 100644 --- a/client/src/preload/index.ts +++ b/client/src/preload/index.ts @@ -75,6 +75,8 @@ contextBridge.exposeInMainWorld('planetDesktop', { replaySplash: (theme?: SplashTheme) => { splashController.replay(theme) }, + checkForUpdates: () => ipcRenderer.invoke('planet:check-for-updates') as Promise, + getVersionInfo: () => ipcRenderer.invoke('planet:get-version-info'), }) ipcRenderer.on('planet:visibility', (_event, detail) => { @@ -93,6 +95,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', () => { diff --git a/client/src/preload/splash.ts b/client/src/preload/splash.ts index f2061436..932638b9 100644 --- a/client/src/preload/splash.ts +++ b/client/src/preload/splash.ts @@ -1,7 +1,7 @@ import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from './earth-landmask' -export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off' -export type ActiveSplashTheme = Exclude +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: { PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL
-
- - - -
@@ -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) diff --git a/client/tests/gpu-policy.test.ts b/client/tests/gpu-policy.test.ts new file mode 100644 index 00000000..69c700cd --- /dev/null +++ b/client/tests/gpu-policy.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, test } from 'bun:test' + +import { isGpuProcessCrash, resolveChromiumGpuSwitches } from '../src/main/gpu-policy' +import { computeSplashCanvasSize } from '../src/preload/splash' + +describe('chromium GPU switch policy and splash pixel budget', () => { + test('win32 hardware mode avoids risky zero-copy and forced GPU switches', () => { + 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).toContain('disable-renderer-backgrounding') + expect(names).not.toContain('ozone-platform-hint') + }) + + 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 and explicit software-gl select SwiftShader safely', () => { + for (const flags of [ + { headlessSmoke: true, softwareGl: false }, + { headlessSmoke: false, softwareGl: true }, + ]) { + 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) + }) +}) diff --git a/client/tests/hot-update.test.ts b/client/tests/hot-update.test.ts new file mode 100644 index 00000000..b2b82d38 --- /dev/null +++ b/client/tests/hot-update.test.ts @@ -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('ok') }, + { 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('ok') + 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('v1') }, + { 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('broken v2') }, + ]) + 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'), 'shell') + 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'), 'hotfix') + 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('hotfix') + + 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('shell') + }) + + 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() + 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() + }) +}) diff --git a/client/tests/splash-config.test.ts b/client/tests/splash-config.test.ts index 5a3c0bfd..2bf99bb5 100644 --- a/client/tests/splash-config.test.ts +++ b/client/tests/splash-config.test.ts @@ -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) diff --git a/docker-compose.deploy.yml b/docker-compose.deploy.yml index d10c69ba..6b533f99 100644 --- a/docker-compose.deploy.yml +++ b/docker-compose.deploy.yml @@ -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: diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3d3302bf..0f44eede 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,27 @@ This project follows the repository versioning rule: - `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `bugfix` -> `+0.0.1` +## [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 diff --git a/docs/version-history.md b/docs/version-history.md index 3be52b90..4c918992 100644 --- a/docs/version-history.md +++ b/docs/version-history.md @@ -16,12 +16,13 @@ ## Current Version - `main` 当前主线历史推导到:`0.16.5` -- `dev` 当前开发分支历史推导到:`0.78.0` +- `dev` 当前开发分支历史推导到:`0.79.0` ## Timeline | Version | Type | Branch | Commit | Summary | | --- | --- | --- | --- | --- | +| `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 卡片布局仲裁与连接线,修复悬停展开和固定深度,并优化卫星分批查询与连接测试反馈 | diff --git a/frontend/package.json b/frontend/package.json index acb67db2..31f56d8a 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "planet-frontend", - "version": "0.78.0", + "version": "0.79.0", "private": true, "packageManager": "bun@1", "dependencies": { diff --git a/frontend/public/earth/js/brand.js b/frontend/public/earth/js/brand.js index 0391811a..a14ff505 100644 --- a/frontend/public/earth/js/brand.js +++ b/frontend/public/earth/js/brand.js @@ -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 ? ` { + 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; diff --git a/frontend/public/earth/js/earth.js b/frontend/public/earth/js/earth.js index 87d41ec6..75cde341 100644 --- a/frontend/public/earth/js/earth.js +++ b/frontend/public/earth/js/earth.js @@ -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); +} diff --git a/frontend/public/earth/js/i18n.js b/frontend/public/earth/js/i18n.js index ea8a90ef..b89f0877 100644 --- a/frontend/public/earth/js/i18n.js +++ b/frontend/public/earth/js/i18n.js @@ -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 = { diff --git a/frontend/public/earth/js/main.js b/frontend/public/earth/js/main.js index dddfb0a6..be4e3cc5 100644 --- a/frontend/public/earth/js/main.js +++ b/frontend/public/earth/js/main.js @@ -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; diff --git a/frontend/public/earth/js/webgl-recovery.js b/frontend/public/earth/js/webgl-recovery.js new file mode 100644 index 00000000..e32cc073 --- /dev/null +++ b/frontend/public/earth/js/webgl-recovery.js @@ -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. + } + }, + }; +} diff --git a/frontend/public/earth/js/webgl-recovery.test.js b/frontend/public/earth/js/webgl-recovery.test.js new file mode 100644 index 00000000..7c2f89bc --- /dev/null +++ b/frontend/public/earth/js/webgl-recovery.test.js @@ -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"); +}); diff --git a/pyproject.toml b/pyproject.toml index 5a49e0f5..6cdb7214 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "planet" -version = "0.78.0" +version = "0.79.0" description = "智能星球计划 - 态势感知系统" requires-python = ">=3.14" dependencies = [ diff --git a/scripts/harness/client-smoke.mjs b/scripts/harness/client-smoke.mjs index 7a782d69..b76d4d1e 100644 --- a/scripts/harness/client-smoke.mjs +++ b/scripts/harness/client-smoke.mjs @@ -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})`) } diff --git a/scripts/release_publish.py b/scripts/release_publish.py index d8617830..4c1594b6 100644 --- a/scripts/release_publish.py +++ b/scripts/release_publish.py @@ -16,7 +16,7 @@ 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): @@ -279,6 +279,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) @@ -395,6 +405,82 @@ 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]], +) -> 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}", + "-F", + f"version={version}", + "-F", + f"min_shell_version={version}", + "-F", + f"shell_version={version}", + "-F", + f"shell_download_url={release_html_url}", + "-F", + 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: @@ -435,7 +521,18 @@ def main(argv: list[str] | None = None) -> int: 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) + 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, urllib.error.URLError, TimeoutError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 diff --git a/uv.lock b/uv.lock index 8ab309c4..573075aa 100644 --- a/uv.lock +++ b/uv.lock @@ -757,7 +757,7 @@ wheels = [ [[package]] name = "planet" -version = "0.78.0" +version = "0.79.0" source = { virtual = "." } dependencies = [ { name = "aiofiles" },