Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2025dbfe0 | ||
|
|
003b316d42 | ||
|
|
0c40764c58 |
@@ -113,6 +113,9 @@ behavior and document the compatibility note in `docs/harness-audit.md` or
|
||||
## Operating Mode
|
||||
|
||||
- Default to acting directly when the user gives a clear task.
|
||||
- For authorized multi-agent work, follow the Coding Agent Model Strategy in
|
||||
`rules.md` workflow: Sol for implementation, Luna for bounded supporting work,
|
||||
and Astra for complex reasoning; the main agent owns final verification.
|
||||
- Ask before acting only when the missing decision is risky, cannot be
|
||||
discovered from repository context, and no conservative assumption is safe.
|
||||
- Read relevant files before editing.
|
||||
|
||||
@@ -17,6 +17,7 @@ are the source of detail for specific subsystems.
|
||||
| `deploy/helm/planet/` | Helm chart for staging/deployment smoke paths | CI runs helm lint/template when delivery checks are available. |
|
||||
| `.gitea/workflows/` | CI, release image build, staging deploy workflows | This repository uses Gitea workflow files, not `.github/workflows/`. |
|
||||
| `planet.sh` | Main local lifecycle script | Owns init/start/restart/stop/health/log/createuser/destroy. |
|
||||
| `planet.cmd` and `scripts/windows/` | Portable Windows entry, bound desktop launcher generation, and WSL restart bridge | Delegates service lifecycle to `planet.sh`; Windows and isolated WSL regression tests live under `scripts/harness/`. |
|
||||
|
||||
## Runtime Entry Points
|
||||
|
||||
|
||||
@@ -1,25 +1,38 @@
|
||||
"""Read-only compute topic: independent macro observations and facility samples."""
|
||||
"""Compute observations, administrator configuration and independent facility samples."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import and_, case, func, or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.visualization import convert_compute_centers_to_geojson
|
||||
from app.core.earth_geography_policy import display_country
|
||||
from app.core.enums import UserRole
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.services.compute_center_locations import refresh_compute_center_location_cache
|
||||
from app.models.user import User
|
||||
from app.schemas.compute_configuration import (
|
||||
ComputeConfiguration,
|
||||
ComputeConfigurationReset,
|
||||
ComputeConfigurationWrite,
|
||||
)
|
||||
from app.services.compute_catalog import (
|
||||
PARTICIPANTS,
|
||||
participant_members,
|
||||
source_country_names,
|
||||
source_country_participants,
|
||||
)
|
||||
from app.services.compute_center_locations import refresh_compute_center_location_cache
|
||||
from app.services.compute_configuration import (
|
||||
DEFAULT_CONFIGURATION,
|
||||
configuration_response,
|
||||
publish_configuration,
|
||||
read_configuration,
|
||||
)
|
||||
from app.services.compute_history import compute_history
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from sqlalchemy import and_, case, func, or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
router = APIRouter()
|
||||
SOURCES = ("top500", "epoch_ai_gpu")
|
||||
@@ -38,10 +51,60 @@ def selected_countries(countries: str) -> list[str]:
|
||||
|
||||
@router.get("/series")
|
||||
async def get_series(
|
||||
response: Response,
|
||||
countries: str = "CN,US",
|
||||
mode: Literal["global_share", "bilateral_share", "absolute"] = "global_share",
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return compute_history(selected_countries(countries), mode)
|
||||
codes = selected_countries(countries)
|
||||
envelope = await read_configuration(db)
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
result = compute_history(codes, mode, ComputeConfiguration.model_validate(envelope["config"]))
|
||||
result.update(
|
||||
version=envelope["revision"],
|
||||
provenance="bundled_reports" if envelope["is_default"] else "admin_curated_reports",
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
async def configuration_admin(user: User = Depends(get_current_user)) -> User:
|
||||
if user.role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
raise HTTPException(403, "Administrator access required")
|
||||
return user
|
||||
|
||||
|
||||
@router.get("/configuration")
|
||||
async def get_configuration(
|
||||
response: Response,
|
||||
_actor: User = Depends(configuration_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return configuration_response(await read_configuration(db))
|
||||
|
||||
|
||||
@router.put("/configuration")
|
||||
async def update_configuration(
|
||||
payload: ComputeConfigurationWrite,
|
||||
actor: User = Depends(configuration_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
envelope = await publish_configuration(
|
||||
db, revision=payload.revision, config=payload.config, actor=actor,
|
||||
)
|
||||
return configuration_response(envelope)
|
||||
|
||||
|
||||
@router.post("/configuration/reset")
|
||||
async def reset_configuration(
|
||||
payload: ComputeConfigurationReset,
|
||||
actor: User = Depends(configuration_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
envelope = await publish_configuration(
|
||||
db, revision=payload.revision, config=DEFAULT_CONFIGURATION, actor=actor, reset=True,
|
||||
)
|
||||
return configuration_response(envelope)
|
||||
|
||||
|
||||
async def sample_query(db: AsyncSession, countries: list[str], year: int | None):
|
||||
|
||||
94
backend/app/schemas/compute_configuration.py
Normal file
94
backend/app/schemas/compute_configuration.py
Normal file
@@ -0,0 +1,94 @@
|
||||
"""Validated, source-backed observations for the compute comparison cards."""
|
||||
|
||||
from datetime import date
|
||||
from typing import Annotated, Literal, Self
|
||||
|
||||
from app.services.compute_catalog import COUNTRY_PARTICIPANTS
|
||||
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_validator, model_validator
|
||||
|
||||
Year = Annotated[int, Field(strict=True, ge=2000, le=2100)]
|
||||
Value = Annotated[float, Field(strict=True, allow_inf_nan=False, ge=0, le=1e12)]
|
||||
Identifier = Annotated[str, Field(min_length=1, max_length=80, pattern=r"^[a-zA-Z0-9_-]+$")]
|
||||
Text = Annotated[str, Field(min_length=1, max_length=500)]
|
||||
|
||||
|
||||
class ConfigurationModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
|
||||
class ComputeSource(ConfigurationModel):
|
||||
id: Identifier
|
||||
title: Text
|
||||
url: HttpUrl
|
||||
publisher: Text
|
||||
report_year: Year
|
||||
published_at: date | None = None
|
||||
locator: Text
|
||||
|
||||
@field_validator("url")
|
||||
@classmethod
|
||||
def public_reference(cls, value: HttpUrl) -> HttpUrl:
|
||||
if value.username or value.password or len(str(value)) > 2000:
|
||||
raise ValueError("Use a report URL without credentials (maximum 2000 characters)")
|
||||
return value
|
||||
|
||||
|
||||
class ComputeObservation(ConfigurationModel):
|
||||
year: Year
|
||||
metric: Literal["global_share", "absolute"]
|
||||
source_id: Identifier
|
||||
values: dict[str, Value] = Field(min_length=1, max_length=250)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def comparable_values(self) -> Self:
|
||||
if any(code not in COUNTRY_PARTICIPANTS for code in self.values):
|
||||
raise ValueError(
|
||||
"Use countries from the canonical compute catalog, not regional totals"
|
||||
)
|
||||
if self.metric == "global_share" and sum(self.values.values()) > 100.000001:
|
||||
raise ValueError("Global shares for one year must total at most 100 percent")
|
||||
return self
|
||||
|
||||
|
||||
class InnovationObservation(ConfigurationModel):
|
||||
year: Year
|
||||
value: Annotated[float, Field(strict=True, allow_inf_nan=False, ge=-100, le=100)]
|
||||
source_id: Identifier
|
||||
|
||||
|
||||
class ComputeConfiguration(ConfigurationModel):
|
||||
reviewed_at: date
|
||||
sources: list[ComputeSource] = Field(max_length=200)
|
||||
observations: list[ComputeObservation] = Field(max_length=202)
|
||||
innovation: list[InnovationObservation] = Field(max_length=101)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def consistent_evidence(self) -> Self:
|
||||
ids = [source.id for source in self.sources]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError("Report source IDs must be unique")
|
||||
keys = [(row.metric, row.year) for row in self.observations]
|
||||
if len(keys) != len(set(keys)):
|
||||
raise ValueError("Each metric/year may have only one observation")
|
||||
years = [row.year for row in self.innovation]
|
||||
if len(years) != len(set(years)):
|
||||
raise ValueError("Innovation observation years must be unique")
|
||||
sources = {source.id: source for source in self.sources}
|
||||
for row in [*self.observations, *self.innovation]:
|
||||
source = sources.get(row.source_id)
|
||||
if source is None:
|
||||
raise ValueError(f"Missing report source: {row.source_id}")
|
||||
if row.year > source.report_year:
|
||||
raise ValueError("Observation year must not be after its report year")
|
||||
if self.reviewed_at > date.today():
|
||||
raise ValueError("Review date must not be in the future")
|
||||
return self
|
||||
|
||||
|
||||
class ComputeConfigurationWrite(ConfigurationModel):
|
||||
revision: str = Field(min_length=1, max_length=80)
|
||||
config: ComputeConfiguration
|
||||
|
||||
|
||||
class ComputeConfigurationReset(ConfigurationModel):
|
||||
revision: str = Field(min_length=1, max_length=80)
|
||||
99
backend/app/services/compute_configuration.py
Normal file
99
backend/app/services/compute_configuration.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""Database overrides with bundled defaults and atomic, revision-checked publishing."""
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from app.core.request_context import get_request_id
|
||||
from app.models.system_log import AuditLog
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.user import User
|
||||
from app.schemas.compute_configuration import ComputeConfiguration
|
||||
from app.services.compute_catalog import COUNTRY_CATALOG
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
CATEGORY = "compute_comparison"
|
||||
DEFAULT_PATH = Path(__file__).with_name("compute_history_defaults.json")
|
||||
DEFAULT_CONFIGURATION = ComputeConfiguration.model_validate_json(DEFAULT_PATH.read_text())
|
||||
DEFAULT_REVISION = hashlib.sha256(DEFAULT_PATH.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def default_envelope() -> dict:
|
||||
return {
|
||||
"config": DEFAULT_CONFIGURATION.model_dump(mode="json"),
|
||||
"revision": DEFAULT_REVISION,
|
||||
"is_default": True,
|
||||
}
|
||||
|
||||
|
||||
async def read_configuration(db: AsyncSession) -> dict:
|
||||
record = (
|
||||
await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY))
|
||||
).scalar_one_or_none()
|
||||
return dict(record.payload) if record else default_envelope()
|
||||
|
||||
|
||||
def configuration_response(envelope: dict) -> dict:
|
||||
return {
|
||||
**envelope,
|
||||
"countries": [
|
||||
{key: country[key] for key in ("code", "name", "name_en")}
|
||||
for country in COUNTRY_CATALOG
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def publish_configuration(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
revision: str,
|
||||
config: ComputeConfiguration,
|
||||
actor: User,
|
||||
reset: bool = False,
|
||||
) -> dict:
|
||||
# The unique category plus row lock also serializes concurrent first writes.
|
||||
await db.execute(
|
||||
insert(SystemSetting)
|
||||
.values(category=CATEGORY, payload=default_envelope())
|
||||
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
|
||||
)
|
||||
record = (
|
||||
await db.execute(
|
||||
select(SystemSetting).where(SystemSetting.category == CATEGORY).with_for_update()
|
||||
)
|
||||
).scalar_one()
|
||||
if record.payload["revision"] != revision:
|
||||
await db.rollback()
|
||||
raise HTTPException(409, "Configuration changed. Reload before saving your edits.")
|
||||
envelope = (
|
||||
default_envelope()
|
||||
if reset
|
||||
else {
|
||||
"config": config.model_dump(mode="json"),
|
||||
"revision": uuid4().hex,
|
||||
"is_default": reset,
|
||||
}
|
||||
)
|
||||
before = record.payload
|
||||
if reset:
|
||||
await db.delete(record)
|
||||
else:
|
||||
record.payload = envelope
|
||||
# Audit and configuration commit together: a published edit must be attributable.
|
||||
db.add(
|
||||
AuditLog(
|
||||
actor_id=actor.id,
|
||||
actor_name=actor.username,
|
||||
action="compute_comparison.reset" if reset else "compute_comparison.update",
|
||||
target_type="system_setting",
|
||||
target_id=CATEGORY,
|
||||
result="success",
|
||||
request_id=get_request_id(),
|
||||
details={"before": before, "after": envelope},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
return envelope
|
||||
@@ -1,74 +1,16 @@
|
||||
"""Versioned, source-backed annual observations for compute comparisons."""
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import date
|
||||
|
||||
from app.schemas.compute_configuration import ComputeConfiguration
|
||||
from app.services.compute_catalog import (
|
||||
CATALOG,
|
||||
DEFAULT_PARTICIPANTS,
|
||||
PARTICIPANTS,
|
||||
participant_members,
|
||||
)
|
||||
|
||||
HISTORY_VERSION = "compute-history-2026-09-22"
|
||||
HISTORY_YEARS = tuple(range(2020, 2027))
|
||||
REPORTS = {
|
||||
"caict-2021": {
|
||||
"title": "中国算力发展指数白皮书(2021)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202109/P020210918521091309950.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2021,
|
||||
"published_at": None,
|
||||
"locator": "正文 11 页图 4(2020 年全球份额)",
|
||||
},
|
||||
"caict-2022": {
|
||||
"title": "中国算力发展指数白皮书(2022)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202211/P020221105727522653499.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2022,
|
||||
"published_at": None,
|
||||
"locator": "正文 13 页图 5(2021 年全球份额)",
|
||||
},
|
||||
"caict-2023": {
|
||||
"title": "中国算力发展指数白皮书(2023)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202309/P020240326630458153765.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2023,
|
||||
"published_at": None,
|
||||
"locator": "正文 13 页图 5(2022 年全球份额);16 页(中国总规模)",
|
||||
},
|
||||
"caict-2024": {
|
||||
"title": "先进计算暨算力发展指数蓝皮书(2024年)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202501/P020250117503621662777.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2024,
|
||||
"published_at": None,
|
||||
"locator": "正文 10 页图 3(2023 年全球份额);12 页(中国总规模)",
|
||||
},
|
||||
"innovation-2026": {
|
||||
"title": "全球人工智能创新指数报告 2026:科技日报报道",
|
||||
"url": "https://finance.sina.com.cn/tech/roll/2026-07-17/doc-iniickaz8224252.shtml",
|
||||
"publisher": "科技日报(新浪转载)",
|
||||
"published_at": "2026-07-17",
|
||||
"publication_year": 2026,
|
||||
"locator": "2023–2025 年美国减中国的指数分差",
|
||||
},
|
||||
}
|
||||
GLOBAL_SHARES = {
|
||||
year: {"US": us, "CN": cn, "JP": jp}
|
||||
for year, (us, cn, jp) in {
|
||||
2020: (36, 31, 6), 2021: (34, 33, 5),
|
||||
2022: (34, 33, 4), 2023: (41, 31, 4),
|
||||
}.items()
|
||||
}
|
||||
|
||||
ABSOLUTE_COMPUTE = {2022: {"CN": 302}, 2023: {"CN": 435}}
|
||||
GAPS = {2023: 22.02, 2024: 19.96, 2025: 17.95}
|
||||
|
||||
|
||||
def _observations(mode: str, year: int) -> dict[str, float | int]:
|
||||
return (GLOBAL_SHARES if mode in {"global_share", "bilateral_share"} else ABSOLUTE_COMPUTE).get(
|
||||
year, {}
|
||||
)
|
||||
from app.services.compute_configuration import DEFAULT_CONFIGURATION
|
||||
|
||||
|
||||
def _participant_value(
|
||||
@@ -85,7 +27,11 @@ def _participant_value(
|
||||
if missing:
|
||||
return None, coverage
|
||||
if mode == "bilateral_share":
|
||||
if not set(members).issubset({"CN", "US"}) or not {"CN", "US"}.issubset(observations):
|
||||
if (
|
||||
not set(members).issubset({"CN", "US"})
|
||||
or not {"CN", "US"}.issubset(observations)
|
||||
or observations["US"] + observations["CN"] <= 0
|
||||
):
|
||||
coverage.update(
|
||||
{
|
||||
"status": "incompatible",
|
||||
@@ -96,7 +42,8 @@ def _participant_value(
|
||||
return (
|
||||
round(
|
||||
sum(observations[member] for member in members)
|
||||
/ (observations["US"] + observations["CN"]) * 100,
|
||||
/ (observations["US"] + observations["CN"])
|
||||
* 100,
|
||||
2,
|
||||
),
|
||||
coverage,
|
||||
@@ -104,16 +51,32 @@ def _participant_value(
|
||||
return sum(observations[member] for member in members), coverage
|
||||
|
||||
|
||||
def compute_history(countries: list[str], mode: str = "global_share") -> dict:
|
||||
def compute_history(
|
||||
countries: list[str],
|
||||
mode: str = "global_share",
|
||||
config: ComputeConfiguration | None = None,
|
||||
) -> dict:
|
||||
"""Aggregate only fully covered, same-year compatible observations."""
|
||||
config = config if config is not None else DEFAULT_CONFIGURATION
|
||||
metric = "global_share" if mode == "bilateral_share" else mode
|
||||
annual = {row.year: row for row in config.observations if row.metric == metric}
|
||||
gaps = {row.year: row for row in config.innovation}
|
||||
observed_years = [row.year for row in config.observations] + list(gaps)
|
||||
years = tuple(
|
||||
range(
|
||||
min(observed_years, default=date.today().year),
|
||||
max([date.today().year, *observed_years]) + 1,
|
||||
)
|
||||
)
|
||||
members_by_participant = participant_members(countries)
|
||||
rows = []
|
||||
for year in HISTORY_YEARS:
|
||||
observations = _observations(mode, year)
|
||||
for year in years:
|
||||
record = annual.get(year)
|
||||
observations = record.values if record else {}
|
||||
values, coverage = {}, {}
|
||||
for code, members in members_by_participant.items():
|
||||
values[code], coverage[code] = _participant_value(members, observations, mode)
|
||||
evidence_id = f"caict-{year + 1}" if observations else None
|
||||
evidence_id = record.source_id if record else None
|
||||
rows.append(
|
||||
{"year": year, "values": values, "coverage": coverage, "evidence_id": evidence_id}
|
||||
)
|
||||
@@ -121,11 +84,11 @@ def compute_history(countries: list[str], mode: str = "global_share") -> dict:
|
||||
selected_members = {member for members in members_by_participant.values() for member in members}
|
||||
has_innovation_scope = {"CN", "US"}.issubset(selected_members)
|
||||
return {
|
||||
"version": HISTORY_VERSION,
|
||||
"provenance": "reviewed_official_reports",
|
||||
"reviewed_at": "2026-09-22",
|
||||
"version": f"compute-history-{config.reviewed_at}",
|
||||
"provenance": "curated_reports",
|
||||
"reviewed_at": config.reviewed_at.isoformat(),
|
||||
"time_basis": "retrospective",
|
||||
"years": HISTORY_YEARS,
|
||||
"years": years,
|
||||
"mode": mode,
|
||||
"unit": "EFlop/s (FP32)" if mode == "absolute" else "%",
|
||||
"denominator": {"global_share": "global", "bilateral_share": "US+CN", "absolute": None}[
|
||||
@@ -138,18 +101,22 @@ def compute_history(countries: list[str], mode: str = "global_share") -> dict:
|
||||
"innovation": [
|
||||
{
|
||||
"year": year,
|
||||
"value": GAPS.get(year) if has_innovation_scope else None,
|
||||
"evidence_id": "innovation-2026" if year in GAPS and has_innovation_scope else None,
|
||||
"value": gaps[year].value if year in gaps and has_innovation_scope else None,
|
||||
"evidence_id": gaps[year].source_id
|
||||
if year in gaps and has_innovation_scope
|
||||
else None,
|
||||
}
|
||||
for year in HISTORY_YEARS
|
||||
for year in years
|
||||
],
|
||||
"evidence": deepcopy(REPORTS),
|
||||
"evidence": {
|
||||
source.id: source.model_dump(mode="json", exclude={"id"}) for source in config.sources
|
||||
},
|
||||
"innovation_scope": ["US", "CN"],
|
||||
"limitations": [
|
||||
"公开设施样本不代表全国总算力;FP64、FP16 与 FP32 不可直接相加。",
|
||||
"区域值只在全部成员有同年、同指标、可比较观测时汇总;缺失成员时返回 null。",
|
||||
"全球份额不从中美或其他局部成员反推剩余地区。",
|
||||
"年度资料来自信通院官方报告,观测年与报告年份分列;跨年方法可比性仍需核验。",
|
||||
"年度资料按已配置报告引用展示,观测年与报告年份分列;跨年方法可比性仍需核验。",
|
||||
"创新分差为美国减中国;只有分差,不反推单国得分,不证明算力与创新的因果关系。",
|
||||
],
|
||||
}
|
||||
|
||||
125
backend/app/services/compute_history_defaults.json
Normal file
125
backend/app/services/compute_history_defaults.json
Normal file
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"reviewed_at": "2026-09-22",
|
||||
"sources": [
|
||||
{
|
||||
"id": "caict-2021",
|
||||
"title": "中国算力发展指数白皮书(2021)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202109/P020210918521091309950.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2021,
|
||||
"published_at": null,
|
||||
"locator": "正文 11 页图 4(2020 年全球份额)"
|
||||
},
|
||||
{
|
||||
"id": "caict-2022",
|
||||
"title": "中国算力发展指数白皮书(2022)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202211/P020221105727522653499.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2022,
|
||||
"published_at": null,
|
||||
"locator": "正文 13 页图 5(2021 年全球份额)"
|
||||
},
|
||||
{
|
||||
"id": "caict-2023",
|
||||
"title": "中国算力发展指数白皮书(2023)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202309/P020240326630458153765.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2023,
|
||||
"published_at": null,
|
||||
"locator": "正文 13 页图 5(2022 年全球份额);16 页(中国总规模)"
|
||||
},
|
||||
{
|
||||
"id": "caict-2024",
|
||||
"title": "先进计算暨算力发展指数蓝皮书(2024年)",
|
||||
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202501/P020250117503621662777.pdf",
|
||||
"publisher": "中国信息通信研究院",
|
||||
"report_year": 2024,
|
||||
"published_at": null,
|
||||
"locator": "正文 10 页图 3(2023 年全球份额);12 页(中国总规模)"
|
||||
},
|
||||
{
|
||||
"id": "innovation-2026",
|
||||
"title": "全球人工智能创新指数报告 2026:科技日报报道",
|
||||
"url": "https://finance.sina.com.cn/tech/roll/2026-07-17/doc-iniickaz8224252.shtml",
|
||||
"publisher": "科技日报(新浪转载)",
|
||||
"report_year": 2026,
|
||||
"published_at": "2026-07-17",
|
||||
"locator": "2023–2025 年美国减中国的指数分差"
|
||||
}
|
||||
],
|
||||
"observations": [
|
||||
{
|
||||
"year": 2020,
|
||||
"metric": "global_share",
|
||||
"source_id": "caict-2021",
|
||||
"values": {
|
||||
"US": 36,
|
||||
"CN": 31,
|
||||
"JP": 6
|
||||
}
|
||||
},
|
||||
{
|
||||
"year": 2021,
|
||||
"metric": "global_share",
|
||||
"source_id": "caict-2022",
|
||||
"values": {
|
||||
"US": 34,
|
||||
"CN": 33,
|
||||
"JP": 5
|
||||
}
|
||||
},
|
||||
{
|
||||
"year": 2022,
|
||||
"metric": "global_share",
|
||||
"source_id": "caict-2023",
|
||||
"values": {
|
||||
"US": 34,
|
||||
"CN": 33,
|
||||
"JP": 4
|
||||
}
|
||||
},
|
||||
{
|
||||
"year": 2023,
|
||||
"metric": "global_share",
|
||||
"source_id": "caict-2024",
|
||||
"values": {
|
||||
"US": 41,
|
||||
"CN": 31,
|
||||
"JP": 4
|
||||
}
|
||||
},
|
||||
{
|
||||
"year": 2022,
|
||||
"metric": "absolute",
|
||||
"source_id": "caict-2023",
|
||||
"values": {
|
||||
"CN": 302
|
||||
}
|
||||
},
|
||||
{
|
||||
"year": 2023,
|
||||
"metric": "absolute",
|
||||
"source_id": "caict-2024",
|
||||
"values": {
|
||||
"CN": 435
|
||||
}
|
||||
}
|
||||
],
|
||||
"innovation": [
|
||||
{
|
||||
"year": 2023,
|
||||
"value": 22.02,
|
||||
"source_id": "innovation-2026"
|
||||
},
|
||||
{
|
||||
"year": 2024,
|
||||
"value": 19.96,
|
||||
"source_id": "innovation-2026"
|
||||
},
|
||||
{
|
||||
"year": 2025,
|
||||
"value": 17.95,
|
||||
"source_id": "innovation-2026"
|
||||
}
|
||||
]
|
||||
}
|
||||
222
backend/tests/test_compute_configuration.py
Normal file
222
backend/tests/test_compute_configuration.py
Normal file
@@ -0,0 +1,222 @@
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from app.api.v1.compute_intelligence import configuration_admin, get_series, router
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.models.system_log import AuditLog
|
||||
from app.schemas.compute_configuration import ComputeConfiguration
|
||||
from app.services.compute_configuration import (
|
||||
DEFAULT_CONFIGURATION,
|
||||
default_envelope,
|
||||
publish_configuration,
|
||||
read_configuration,
|
||||
)
|
||||
from app.services.compute_history import compute_history
|
||||
from fastapi import FastAPI, HTTPException, Response
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from pydantic import ValidationError
|
||||
|
||||
|
||||
def default_config():
|
||||
return DEFAULT_CONFIGURATION.model_dump(mode="json")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
[
|
||||
lambda value: value["observations"][0]["values"].update(CN=101),
|
||||
lambda value: value["observations"][0]["values"].update(CN=-1),
|
||||
lambda value: value["observations"][0]["values"].update(CN=float("nan")),
|
||||
lambda value: value["observations"][0]["values"].update(CN=True),
|
||||
lambda value: value["observations"][0]["values"].update(EUROPE=10),
|
||||
lambda value: value["observations"][0].update(source_id="unknown"),
|
||||
lambda value: value["observations"][0].update(year=2026),
|
||||
lambda value: value["observations"].append(value["observations"][0]),
|
||||
lambda value: value["sources"].append(value["sources"][0]),
|
||||
lambda value: value["innovation"].append(value["innovation"][0]),
|
||||
lambda value: value["sources"][0].update(url="javascript:alert(1)"),
|
||||
lambda value: value["sources"][0].update(url="https://user:pass@example.com/report"),
|
||||
],
|
||||
)
|
||||
def test_rejects_invalid_or_ambiguous_evidence(mutation):
|
||||
payload = default_config()
|
||||
mutation(payload)
|
||||
with pytest.raises(ValidationError):
|
||||
ComputeConfiguration.model_validate(payload)
|
||||
|
||||
|
||||
def test_arbitrary_report_updates_values_sources_and_years_without_code_changes():
|
||||
payload = default_config()
|
||||
payload["sources"].append(
|
||||
{
|
||||
"id": "new-report",
|
||||
"title": "New report",
|
||||
"url": "https://example.com/report",
|
||||
"publisher": "Research group",
|
||||
"report_year": 2026,
|
||||
"locator": "Figure 2",
|
||||
}
|
||||
)
|
||||
payload["observations"].append(
|
||||
{
|
||||
"year": 2025,
|
||||
"metric": "global_share",
|
||||
"source_id": "new-report",
|
||||
"values": {"CN": 25, "US": 50, "JP": 0},
|
||||
}
|
||||
)
|
||||
config = ComputeConfiguration.model_validate(payload)
|
||||
result = compute_history(["CN", "US", "JP", "EUROPE"], config=config)
|
||||
row = next(row for row in result["compute"] if row["year"] == 2025)
|
||||
assert row["values"] == {"CN": 25, "US": 50, "JP": 0, "EUROPE": None}
|
||||
assert result["evidence"][row["evidence_id"]]["title"] == "New report"
|
||||
assert DEFAULT_CONFIGURATION.model_dump(mode="json") == default_config()
|
||||
|
||||
|
||||
def test_zero_bilateral_denominator_is_missing_and_empty_override_stays_empty():
|
||||
payload = default_config()
|
||||
payload["observations"][0]["values"] = {"CN": 0, "US": 0}
|
||||
result = compute_history(
|
||||
["CN", "US"], "bilateral_share", ComputeConfiguration.model_validate(payload)
|
||||
)
|
||||
assert result["compute"][0]["values"] == {"CN": None, "US": None}
|
||||
payload.update(sources=[], observations=[], innovation=[])
|
||||
result = compute_history(["CN"], config=ComputeConfiguration.model_validate(payload))
|
||||
assert all(row["values"]["CN"] is None for row in result["compute"])
|
||||
assert result["evidence"] == {}
|
||||
|
||||
|
||||
def fake_db(record=None):
|
||||
db = AsyncMock()
|
||||
db.add = MagicMock()
|
||||
result = MagicMock()
|
||||
result.scalar_one_or_none.return_value = record
|
||||
result.scalar_one.return_value = record
|
||||
db.execute.return_value = result
|
||||
return db
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fresh_install_uses_defaults_without_writing_database():
|
||||
db = fake_db()
|
||||
assert await read_configuration(db) == default_envelope()
|
||||
db.add.assert_not_called()
|
||||
db.commit.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_series_reads_persisted_override_and_disables_http_cache():
|
||||
envelope = default_envelope()
|
||||
envelope["is_default"] = False
|
||||
envelope["revision"] = "custom"
|
||||
envelope["config"]["observations"][3]["values"]["CN"] = 30
|
||||
response = Response()
|
||||
data = await get_series(
|
||||
response, "CN,US", "global_share", fake_db(SimpleNamespace(payload=envelope))
|
||||
)
|
||||
assert data["compute"][3]["values"]["CN"] == 30
|
||||
assert data["version"] == "custom"
|
||||
assert data["provenance"] == "admin_curated_reports"
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_and_audit_are_one_transaction_and_conflicts_do_not_overwrite():
|
||||
record = SimpleNamespace(payload=default_envelope())
|
||||
db = fake_db(record)
|
||||
actor = SimpleNamespace(id=1, username="admin")
|
||||
old = deepcopy(record.payload)
|
||||
result = await publish_configuration(
|
||||
db,
|
||||
revision=old["revision"],
|
||||
config=DEFAULT_CONFIGURATION,
|
||||
actor=actor,
|
||||
)
|
||||
assert result["revision"] != old["revision"]
|
||||
audit = db.add.call_args.args[0]
|
||||
assert isinstance(audit, AuditLog)
|
||||
assert audit.details == {"before": old, "after": result}
|
||||
assert audit.actor_id == actor.id
|
||||
db.commit.assert_awaited_once()
|
||||
with pytest.raises(HTTPException) as failure:
|
||||
await publish_configuration(
|
||||
db, revision=old["revision"], config=DEFAULT_CONFIGURATION, actor=actor
|
||||
)
|
||||
assert failure.value.status_code == 409
|
||||
assert record.payload == result
|
||||
db.rollback.assert_awaited_once()
|
||||
db.commit.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_changes_revision_and_restores_bundled_data():
|
||||
record = SimpleNamespace(
|
||||
payload={**default_envelope(), "revision": "custom", "is_default": False}
|
||||
)
|
||||
result = await publish_configuration(
|
||||
fake_db(record),
|
||||
revision="custom",
|
||||
config=DEFAULT_CONFIGURATION,
|
||||
actor=SimpleNamespace(id=1, username="admin"),
|
||||
reset=True,
|
||||
)
|
||||
assert result["is_default"] is True
|
||||
assert result["config"] == default_config()
|
||||
assert result["revision"] != "custom"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("role", ["user", "viewer", "operator"])
|
||||
async def test_non_admin_cannot_configure(role):
|
||||
with pytest.raises(HTTPException) as failure:
|
||||
await configuration_admin(SimpleNamespace(role=role))
|
||||
assert failure.value.status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_http_configuration_auth_validation_and_public_series():
|
||||
app = FastAPI()
|
||||
app.include_router(router)
|
||||
record = SimpleNamespace(payload=default_envelope())
|
||||
db = fake_db(record)
|
||||
app.dependency_overrides[get_db] = lambda: db
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
assert (await client.get("/configuration")).status_code == 401
|
||||
assert (await client.get("/series")).status_code == 200
|
||||
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
|
||||
id=1,
|
||||
username="admin",
|
||||
role="admin",
|
||||
)
|
||||
loaded = (await client.get("/configuration")).json()
|
||||
invalid = deepcopy(loaded["config"])
|
||||
invalid["observations"][0]["values"]["CN"] = 200
|
||||
response = await client.put(
|
||||
"/configuration",
|
||||
json={
|
||||
"revision": loaded["revision"],
|
||||
"config": invalid,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 422
|
||||
db.commit.assert_not_awaited()
|
||||
response = await client.put(
|
||||
"/configuration",
|
||||
json={
|
||||
"revision": loaded["revision"],
|
||||
"config": loaded["config"],
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["revision"] != loaded["revision"]
|
||||
assert (
|
||||
await client.post(
|
||||
"/configuration/reset",
|
||||
json={
|
||||
"revision": loaded["revision"],
|
||||
},
|
||||
)
|
||||
).status_code == 409
|
||||
@@ -262,6 +262,7 @@ def test_absolute_report_year_mapping_and_bilateral_denominator_ignore_other_cou
|
||||
bilateral = compute_history(["CN", "US", "JP"], "bilateral_share")
|
||||
values = next(row["values"] for row in bilateral["compute"] if row["year"] == 2023)
|
||||
assert values == {"CN": 43.06, "US": 56.94, "JP": None}
|
||||
for report in absolute["evidence"].values():
|
||||
if report.get("report_year"):
|
||||
for row in absolute["compute"]:
|
||||
if row["evidence_id"]:
|
||||
report = absolute["evidence"][row["evidence_id"]]
|
||||
assert report["url"].startswith("https://www.caict.ac.cn/")
|
||||
|
||||
@@ -8,6 +8,36 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [0.75.2] — 2026-09-25
|
||||
|
||||
Released: 2026-09-25
|
||||
|
||||
### Highlights
|
||||
- 修复 Windows 启动器固定使用旧版 PowerShell 的问题,优先在 Windows Terminal 新窗口中运行 PowerShell 7。
|
||||
|
||||
### Fixed
|
||||
- 仓库与桌面 CMD 引导优先使用 `pwsh.exe`,缺少新版 PowerShell 或 Terminal 时保留可用环境回退。
|
||||
- 已以管理员运行的入口同样进入首选终端,子窗口校验权限后直接衔接 WSL,避免重复提权和递归开窗。
|
||||
- 补齐终端选择、含空格路径、提权分支回归和中英文说明,保持 WSL 重启参数及默认端口不变。
|
||||
|
||||
---
|
||||
|
||||
## [0.75.1] — 2026-09-25
|
||||
|
||||
Released: 2026-09-25
|
||||
|
||||
### Highlights
|
||||
- Windows 启动器从当前项目位置识别 WSL 发行版与目录,首次生成本机桌面 CMD,后续沿用标准重启流程。
|
||||
- 算力对比数据可由后台维护;小球恢复惯性拖动,大幅放大后保留球面跟手,修复移出球面后的反向旋转。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 桌面入口兼容两种 WSL UNC 路径和 Windows 本地磁盘映射,保留原有文件,支持只安装检查;默认端口仍为 3000 / 8000 / 8010。
|
||||
- 算力报告来源、年度观测与创新分差使用数据库配置,提供数值校验、版本冲突保护、事务审计、恢复默认和地球自动刷新。
|
||||
- 根据相机视锥在按下时固定拖动模式;小球使用旧版位移平滑与惯性,大球不再用球外最近点生成反向旋转。
|
||||
- 更新开发 agent 的 Sol / Luna / Astra 分工规则,补齐中英文运维说明、启动故障编号与隔离回归测试。
|
||||
|
||||
---
|
||||
|
||||
## [0.75.0] — 2026-09-23
|
||||
|
||||
Released: 2026-09-23
|
||||
|
||||
@@ -79,6 +79,16 @@ git diff --unified=0 HEAD -- <path>
|
||||
|
||||
## Harness Commands
|
||||
|
||||
Windows desktop launcher tests run separately on Windows with
|
||||
`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\harness\test_windows_launcher.ps1`.
|
||||
They use temporary desktop folders and mocked restart commands; no UAC prompt
|
||||
or real service restart is triggered. The WSL bridge regression suite,
|
||||
`scripts/harness/test_windows_restart.py`, is included in quick-check and uses
|
||||
disposable command substitutes. For a real entry-point check without restarting,
|
||||
run the repository `planet.cmd --install-only`, then the generated desktop
|
||||
launcher with the same flag. Installation and mocked checks do not prove a live
|
||||
elevated restart; report that separately when it has not been exercised.
|
||||
|
||||
| Tier | Command | What It Does |
|
||||
| --- | --- | --- |
|
||||
| Doctor | `scripts/harness/doctor.sh` | Checks required files, required tools, optional delivery tools, and forbidden frontend lockfiles. |
|
||||
|
||||
@@ -467,6 +467,8 @@ Epoch uses its official public CSV, retaining theoretical FP16 performance, orig
|
||||
|
||||
Neither collector returns sample data on failure. Empty fetches or transformed results, schema errors, and losses exceeding 40% of the previous snapshot fail while retaining prior data. Incomplete writes are rolled back. TOP500 location migration copies only a unique exact name and canonical-country match to the new system ID, retaining the historical key; rank is never a migration key.
|
||||
|
||||
`compute_history.py` stores controlled imports from the reviewed research plan, including annual observations, sources, and a version. Reference periods and publication dates are distinct; unknown publication days remain unspecified. `/api/v1/data-products/compute/series` offers global share, fixed US + China bilateral share, and available FP32 absolute observations. Innovation gaps are independent and never expanded into inferred national scores.
|
||||
`compute_history_defaults.json` ships the original report data. `compute_configuration.py` reads a complete override from the `compute_comparison` category in `system_settings`; absent records use bundled defaults without migrations or manual initialization. `compute_history.py` performs same-year aggregation. Reference periods and publication dates remain distinct, and unknown publication days remain unspecified. `/api/v1/data-products/compute/series` reads configuration on each request with `Cache-Control: no-store`, offering global share, fixed US + China bilateral share and FP32 absolute observations. Innovation gaps remain independent. An empty override stays empty instead of silently restoring observations.
|
||||
|
||||
Under the same prefix, `GET/PUT /configuration` and `POST /configuration/reset` require admin/super_admin. Writes accept `{revision, config}` and reset accepts `revision`. Pydantic validates canonical countries, finite values, share totals, duplicate metric/year pairs and report references; each metric/year has one report basis. PostgreSQL category uniqueness and row locking serialize first writes and updates; stale revisions return 409. Configuration and before/after audit records commit in one transaction. Reset removes the override so subsequent reads use the current bundled defaults. `version` is a configuration revision, while `reviewed_at` is the supplied review date. Admin-curated data is not automatically labeled official. Source URLs are references, not scrape instructions.
|
||||
|
||||
`/api/v1/data-products/compute/facilities` reads successful snapshots with `compute_contract=v1`, applying country filters and per-source counts in SQL. Epoch excludes planned, decommissioned, superseded, and suspected duplicate records; TOP500 means list observations. Cross-source deduplication remains pending. Historical cutoffs use collection time, never pretending a recently fetched old source was available earlier. Geographic results are bounded and report truncation; total record counts are independent of this limit. Official site helpers are keyed by exact `source` + `source_id`; their access-map centers are site-level references only and retain their official URL in `source_note`.
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# Earth Frontend Context
|
||||
|
||||
## Configurable compute observations
|
||||
|
||||
Compute cards read annual observations from `/api/v1/data-products/compute/series`; the admin Compute comparison section is the maintenance entry point. `compute-topic.js` fetches with no-store, listens for same-origin `planet-compute-configuration` notifications, and checks every 60 seconds while visible and enabled, plus when the page becomes visible. Observation refresh does not reload facility layers. `destroy()` releases the timer, channel and visibility listener. Country membership, full regional coverage and missing-value semantics remain backend-owned.
|
||||
|
||||
## Surface texture provenance
|
||||
|
||||
On 2026-09-21, `assets/8k_earth_daymap.jpg` was replaced with an 8192×4096 Web derivative of the paired Natural Earth I raster. Its loading path and rendering code remain unchanged. The source is a 16200×8100 EPSG:4326 image; the previous JPEG is preserved byte-for-byte under `resources/earth/archive/2026-09-21/`. Source/license records, the catalogue versus embedded-version discrepancy, SHA256 hashes, JPEG parameters, and recalculated world-file metadata live in `resources/earth/natural-earth-1/`. Large originals remain in Git-ignored `downloads/earth/`, outside the frontend release bundle.
|
||||
@@ -365,7 +369,7 @@ If future cable, satellite, or news cruise is added, do not copy a new set of `m
|
||||
|
||||
[controls.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/controls.js) owns the Earth zoom state, and every zoom entry point must ultimately call `setZoomLevel()` to write the camera distance. Do not write `camera.position.z` from other modules, or the zoom percentage, drag sensitivity, and Interactable clustering thresholds will diverge again.
|
||||
|
||||
`globe-navigation.js` maps zoom to `sqrt(R² + (D₀² - R²) / zoom²)` with minimum surface clearance and the matching inverse. The 100% camera pose remains unchanged; 500% stays outside the globe. Mouse and single-touch dragging use ray/sphere intersections and quaternion rotation to keep the grabbed surface under the pointer, without an empirical sensitivity multiplier or frame-by-frame catch-up. Auto-rotation is suspended during dragging and pinching. Release inertia follows the measured axis; paused releases and cancellation do not fling. Returning from a pinch to one finger rebases the grab point. Click suppression uses displacement from pointer-down, including slow drags.
|
||||
`globe-navigation.js` maps zoom to `sqrt(R² + (D₀² - R²) / zoom²)` with minimum surface clearance and the matching inverse. The 100% camera pose remains unchanged; 500% stays outside the globe. Mouse and single-touch drags choose a mode on pointer-down from the actual camera frustum. A fully visible globe retains legacy screen-delta sensitivity, 0.18 smoothing and release inertia, including movement outside its silhouette. A viewport-clipped globe uses pixel-aligned ray/sphere grabbing only when the initial pointer hits its surface. Subsequent missed intersections pause surface updates and clear fling speed instead of using a closest-point substitute that can reverse rotation. Grabs starting in space use screen deltas. The mode stays fixed throughout the drag; auto-rotation is suspended during dragging and pinching. Returning from a pinch to one finger reselects the mode and rebases the anchor. Click suppression uses displacement from pointer-down, and cancellation clears inertia.
|
||||
|
||||
|
||||
Interactable clustering is selected per layer through `cluster.strategy`. `stable-spherical` uses discrete zoom bands and local 3D bucket clustering, so BGP, compute centers, and Earth interactables do not regroup while the globe rotates inside the same band. `dynamic-screen` keeps projection-based clustering, and `none` disables it. Vessels explicitly disable clustering and avoidance so incremental updates do not rebuild cluster topology. Stable cluster dots stay rigidly aligned to their 3D centroid projection and do not participate in 2D avoidance. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md) for strategy configuration and tuning.
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# Admin Frontend Context
|
||||
|
||||
## Compute comparison configuration
|
||||
|
||||
The Earth content `compute_comparison` section mounts `ComputeComparisonSettings.tsx`. Structured forms maintain report sources, annual country observations and innovation gaps using the shared Panel, Input, Select, Button and confirmation dialog; operators do not edit JSON. Drafts survive section switches, full-page unload warns about unsaved work, and discarding a draft or restoring defaults requires confirmation. Management data loads on activation. Publishing sends the backend revision to prevent overwriting concurrent edits, and failures preserve the draft. The content area scrolls internally while the heading and publish controls stay in the first viewport. `compute-comparison-model.ts` owns types and same-origin update notifications; `compute-comparison.css` only owns this section's layout.
|
||||
|
||||
This document describes the current real structure of the console frontend. The goal is to help future page development, table refactoring, layout governance, and state consolidation quickly find the right entry points.
|
||||
|
||||
Related references:
|
||||
|
||||
@@ -412,11 +412,15 @@ Docs supports: category navigation, Markdown rendering, tables and code blocks,
|
||||
|
||||
## Compute intelligence
|
||||
|
||||
Administrators maintain card data in **Earth content → Compute comparison**. Add a report title, URL, publisher, report year and page/figure locator under Sources, then add country values by observation year, metric and source under Observations. Save and publish applies the complete configuration. Global shares use the world denominator; absolute values use FP32 EFlop/s. Bilateral shares are derived from same-year US and China observations, and regions require every member. Do not mix FP16/FP64 capacity, regional estimates or facility counts. Omit missing countries; enter zero only when the source explicitly reports zero.
|
||||
|
||||
Innovation gap observations remain independent US-minus-China values. Referenced reports cannot be removed until their observations are removed or reassigned. Duplicate metric/year rows, missing sources and global shares totaling over 100% are rejected. Concurrent edits return a conflict while preserving the local draft. Restore defaults requires confirmation and restores the bundled report data. Publishing and restoring are audited. Same-origin Earth pages receive a refresh notification; other visible pages check once per minute and hidden pages check when visible again. Reports must still be reviewed manually; configuring a URL does not scrape a report.
|
||||
|
||||
Open the analysis icon beside Compute Centers, then enable Show region cards. Connectors draw to their target positions before the cards fade in; subsequent globe motion does not replay entrance. Closing the configuration window or pressing Escape leaves the cards enabled; the analysis icon reopens configuration, while the switch disables the cards. Anchors rotate with Earth while cards remain readable. Dragging or expanding grants reading time; after a substantial change in geographic direction, cards can move together when that materially reduces crossing or detours. Active interaction prevents movement, while manual positions remain preferences rather than permanent pins. Rear regions retain their state without a connector drawn through the globe. Existing layer, news, and media windows remain available.
|
||||
|
||||
The picker groups the canonical comparison catalog as China, US, Europe, APAC excluding China, and Other; the groups are display buckets, not statistical denominators. It offers period and metric selection. Bilateral share still uses US + China as its fixed denominator; unavailable measures stay missing for other participants. Regional anchors are label positions, never facility locations. Source buttons open report evidence and facility buttons reuse the existing detail card. Mobile uses a compact regional overview in the drawer. Each row is an accordion: tapping the same header collapses it, tapping another collapses the old row, and at most one long card is open. The expanded card keeps trends, region members, facilities, media, and sources; there is no region subpage. Settings remain a separate on-demand page.
|
||||
|
||||
The default national metric is global compute-device scale, covering basic, intelligent, and supercomputer capacity with observations from 2020–2023. The reviewed absolute observations are 302 for 2022 (`caict2023` evidence) and 435 for 2023 (`caict2024` evidence). Japan's global-share observations are 6%/5%/4%/4% for 2020/2021/2022/2023. Product groups APAC and OTHER do not mean the report's Japan or “other” categories, and EUROPE remains missing until its membership matches the report. Bilateral share always uses US + China as its denominator. A missing primary value may show the latest reported year (currently 2023); explicitly selecting 2026 still shows missing and does not backfill. Unconfirmed comparability does not produce year-over-year change. National report metrics remain separate from public facility samples; coverage counts remain auxiliary evidence, never computed capacity or a global coverage rate. TOP500 and Epoch may overlap, so source-record counts are not a global census. API review metadata is `reviewed_at=2026-09-22` with the matching version date. An independent Epoch share mode is not implemented.
|
||||
The default national metric is global compute-device scale, covering basic, intelligent, and supercomputer capacity with observations from 2020–2023. The reviewed absolute observations are 302 for 2022 (`caict2023` evidence) and 435 for 2023 (`caict2024` evidence). Japan's global-share observations are 6%/5%/4%/4% for 2020/2021/2022/2023. Product groups APAC and OTHER do not mean the report's Japan or “other” categories, and EUROPE remains missing until its membership matches the report. Bilateral share always uses US + China as its denominator. A missing primary value may show the latest reported year (currently 2023); explicitly selecting 2026 still shows missing and does not backfill. Unconfirmed comparability does not produce year-over-year change. National report metrics remain separate from public facility samples; coverage counts remain auxiliary evidence, never computed capacity or a global coverage rate. TOP500 and Epoch may overlap, so source-record counts are not a global census. The bundled reports were reviewed on 2026-09-22; published overrides use their maintained review date and observations. An independent Epoch share mode is not implemented.
|
||||
|
||||
This prototype shows up to six content cards. The main card centers on the selected compute metric: a large share percentage or absolute value with its unit, observation year, historical context, and source entry. Missing comparable data is shown as “No comparable data yet”; a trend is omitted when there are no observations rather than rendered as an empty chart. Facility records and coverage metadata remain complete but move to the expanded auxiliary area; sample counts are evidence context, never a compute value or global coverage rate. Region previews may show member counts, and long lists open only when needed. Desktop compact cards are about 268px wide with content-driven height; expanded cards support user resizing up to 480px. Mobile keeps the same single metric meaning in the one-card accordion rather than promoting facility counts. Local card position and size are saved, with a reset-to-auto action. The content layout leaves room for later image and video integration, but those media data are not connected yet. When outside space is insufficient, cards can travel through the globe's foreground instead of teleporting or shrinking to labels.
|
||||
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
# `planet.sh` Startup Performance Optimization
|
||||
|
||||
## Background
|
||||
## Windows desktop launcher
|
||||
|
||||
The launcher prefers a new Windows Terminal window and explicitly runs PowerShell 7 (`pwsh.exe`), independently of the default Terminal profile. Without PowerShell 7 it falls back to Windows PowerShell; without Terminal it starts the available PowerShell directly. The CMD bootstrap also prefers PowerShell 7. Ordinary entries request elevation; entries already running as administrator still dispatch to the preferred terminal without another elevation request. The child validates its privileges and enters WSL directly, preventing recursive windows. The existing post-restart WSL shell is retained.
|
||||
|
||||
On first use, open the actual project folder in Windows Explorer and double-click the repository's `planet.cmd`. It derives the WSL distribution and Linux project directory from its own location, creates `Planet.cmd` on the current user's actual Windows desktop, then follows the normal restart flow. Both `\\wsl$\distribution\...` and `\\wsl.localhost\distribution\...` work. Local Windows-drive checkouts use the default WSL distribution and `wslpath`. Windows resolves the desktop location, including redirected desktops such as OneDrive; WSL, zsh and project dependencies must already be installed.
|
||||
|
||||
Subsequent desktop launches use the bound target, request the existing administrator elevation and call `planet.sh restart --allow-lan`. No test ports are embedded: defaults remain frontend 3000, backend 8000 and AI Provider 8010, subject to explicit `DEFAULT_*_PORT` environment overrides. Successful restarts open Earth using the actual `ports.env` values and retain the WSL shell; failures display their error without opening a success page. `scripts/windows/planet-launcher.ps1` owns path resolution, desktop installation and elevation; `scripts/windows/restart.zsh` only bridges to the existing lifecycle script.
|
||||
|
||||
Use `planet.cmd --install-only` on Windows to generate or validate a launcher without restarting services. Re-running the repository entry updates the same target's launcher. Other projects and unmanaged files are preserved by choosing a target-specific filename. After moving a checkout, regenerate from its new location; old launchers never guess another directory. Desktop launchers require the scripts in the checkout and are not standalone installation packages.
|
||||
|
||||
Do not copy the raw repository `planet.cmd` to the desktop by itself: first installation needs the adjacent `scripts/windows/` directory. On another computer, generate a new launcher from that computer's checkout instead of reusing an old desktop copy. Server paths such as `/home/linkong/planet` and personal workstation paths both work without machine-specific Git edits. Run under the Windows account that owns the WSL distribution; elevating under a different account may expose a different set of registered distributions. Installation itself does not require administrator privileges; elevation is requested for the actual restart.
|
||||
|
||||
Run Windows regression checks with `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\harness\test_windows_launcher.ps1`. They cover target resolution, special characters, generated launchers and name collisions. `scripts/harness/test_windows_restart.py` uses disposable command substitutes to check restart arguments, browser opening after success and shell retention after failure. The latter runs in quick-check without starting real services.
|
||||
|
||||
## Startup background
|
||||
|
||||
Use `zsh ./planet.sh start --non-motion-agent` for daily startup; use `init` when preparing a new environment. When investigating latency, distinguish initial dependency downloads, container readiness, and application initialization using the stage timestamps.
|
||||
|
||||
|
||||
@@ -311,6 +311,7 @@ For each newly confirmed cause, update both language tables with a stable code,
|
||||
<!-- planet-error-catalog:start -->
|
||||
| Error code | Matching fragments (semicolon-separated) | Cause / established failure | Remedy |
|
||||
| --- | --- | --- | --- |
|
||||
| P_WINDOWS_LAUNCHER_TARGET_MISSING | P_WINDOWS_LAUNCHER_TARGET_MISSING | The bound WSL project is unavailable or lacks launcher scripts, commonly after moving a checkout, losing access to a distribution or copying another machine's desktop launcher. | Run the repository planet.cmd from the current checkout to regenerate this machine's desktop launcher and verify the WSL distribution; do not hardcode another machine's path. |
|
||||
| P_PROXY_EXTERNAL | PLANET_PROXY_EXTERNAL | Docker proxy settings belong to another configuration source or have been edited manually. | Inspect daemon.json, systemd proxy settings and the Planet ownership record before changing ownership; existing settings are preserved. |
|
||||
| P_AUTH_BOOTSTRAP_MISSING | DEFAULT_LOGIN_USER_MISSING | The active backend database is confirmed to lack default accounts, often in an isolated preview that skipped initialization. | Verify database ownership and run the existing account initializer without resetting existing passwords or clearing data. |
|
||||
| P_AUTH_PROFILE_INVALID | AUTH_IDENTITY_RESPONSE_INVALID | Login succeeds but the identity response lacks required fields or incorrectly rejects a stored local email address. | Load the complete persisted identity, separate response serialization from registration validation, and run default-account identity regressions. |
|
||||
|
||||
@@ -74,4 +74,6 @@ Open `/forgot-password`, enter your email, receive a code, then enter the code p
|
||||
|
||||
## Try compute intelligence
|
||||
|
||||
To maintain card values, an administrator opens **Earth content → Compute comparison**, adds report sources, enters comparable annual country observations, then chooses **Save and publish**. Omit missing countries; facility counts never replace compute shares. Bundled defaults can be restored and Earth cards automatically check published configuration.
|
||||
|
||||
Open the analysis icon beside Compute Centers and enable Show region cards. Closing configuration keeps the cards active; the switch controls their visibility. Resize or collapse desktop cards and inspect observed history, sources, and facility details. On mobile, use the Compute drawer tab. National indicators and facility samples are separate. “—” means missing evidence, not zero capacity.
|
||||
|
||||
@@ -498,6 +498,8 @@ Epoch 改用官方公开 CSV,保留 FP16 理论性能、原始日期、状态
|
||||
|
||||
两个采集器不再生成示例回退。空原文、转换后空结果、结构错误或相对上次快照减少超过 40% 会失败并保留旧快照;写入失败回滚不完整记录。TOP500 身份切换仅在旧位置名称、规范国家完全一致且唯一时复制位置到新系统 ID,旧位置保留用于历史查询,绝不按名次迁移。
|
||||
|
||||
`compute_history.py` 保存从已核对研究计划受控导入的年度数值、来源和版本,参考期与发表时间分开;未知具体发表日保持未提供。`/api/v1/data-products/compute/series` 支持全球份额、固定中美分母的双边份额及已知 FP32 绝对量。创新分差独立返回,不反推单国指数。
|
||||
`compute_history_defaults.json` 提供原有报告数据,`compute_configuration.py` 从 `system_settings` 的 `compute_comparison` 分类读取完整数据库覆盖;没有记录时使用默认值,不需要迁移或人工初始化。`compute_history.py` 只处理同年聚合,参考期与发表时间分开;未知具体发表日保持未提供。`/api/v1/data-products/compute/series` 支持全球份额、固定中美分母的双边份额及 FP32 绝对量,逐次读取配置并返回 `Cache-Control: no-store`。创新分差独立返回,不反推单国指数。空配置保留缺失,不回填默认观测。
|
||||
|
||||
同前缀的 `GET/PUT /configuration` 和 `POST /configuration/reset` 仅允许 admin/super_admin。写入体为 `{revision, config}`,重置只需要 `revision`。Pydantic 校验国家目录、有限数值、比例总和、重复指标年份和报告引用;每个指标年份只允许一个报告口径。PostgreSQL 唯一分类与行锁串行化首次写入和更新,旧版本返回 409。审计记录和配置在同一事务提交;重置移除覆盖,下次读取随版本默认值。`version` 为配置修订标识,`reviewed_at` 为录入的核验日期,不能将管理员配置一概称为官方报告。来源链接只作引用,不触发抓取。
|
||||
|
||||
`/api/v1/data-products/compute/facilities` 仅读取 `compute_contract=v1` 的成功快照,数据库执行国家过滤和按来源计数。Epoch 默认排除规划、退役、已被替代和疑似重复记录;TOP500 表示榜单观测,跨源仍未合并。历史选择按采集时间截止,不将最近抓到的旧资料冒充过去已知的快照。地理结果有返回上限与截断标记,记录统计不受该上限影响。官方 site helper 按精确 `source` + `source_id` 匹配;access map 中心只表示 site 级参考点,并在 `source_note` 保留官方 URL。
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
## 当前目标
|
||||
|
||||
算力卡片的年度观测由 `/api/v1/data-products/compute/series` 返回,后台“算力对比”配置为唯一维护入口。`compute-topic.js` 以 no-store 请求读取数据,接收同源 `planet-compute-configuration` 发布通知,并在可见且专题启用时每 60 秒及页面恢复可见时检查更新;刷新观测不重拉设施图层。`destroy()` 释放计时器、通知通道和可见性监听。国家目录、区域完整覆盖条件与缺失语义仍由后端统一处理。
|
||||
|
||||
Earth 前端不是普通管理页,它是独立的大屏展示前端。当前产品目标是:
|
||||
|
||||
- 维持地球视图的空间感和可读性
|
||||
@@ -445,7 +447,7 @@ asset 图标大小由 `Interactable` 的 `icon.fitSize` 控制。SVG / 图片文
|
||||
|
||||
`globe-navigation.js` 统一投影缩放与表面拖动。相机距离采用 `sqrt(R² + (D₀² - R²) / zoom²)`,并保留最小地表净空;100% 视角不变,500% 仍在球外,反向换算也使用同一公式。滚轮、按钮、捏合、搜索与巡航继续共用 `setZoomLevel()`。
|
||||
|
||||
鼠标和单指通过相机射线取得球面抓点,以四元数将同一地表点旋转到当前接触位置;按住期间不使用经验倍率或追赶平滑,自转也不叠加。松手后沿实际旋转轴衰减惯性,停住再松手或取消手势不触发甩动。双指进入缩放时清除拖动惯性,回到单指时重建抓点。拖动阈值按起点至当前位置的累计位移判断,避免慢拖被当作点击。
|
||||
鼠标和单指在按下时按实际相机视锥选择并固定拖动模式:球体完整放入视口时,使用旧版屏幕位移、缩放灵敏度、0.18 追赶平滑和松手衰减惯性,指针移出球面仍保持原方向;球体放大到被视口裁切且按下命中球面时,才用射线抓点与四元数逐像素跟手。大球拖动移出球面后暂停更新并清除甩动速度,不再用可能反向的最近点代替真实交点;从球外开始则使用屏幕位移拖动。一趟拖动中不切换模式,自转不叠加。双指进入缩放时清除惯性,回到单指时重新判断模式并建立抓点。拖动阈值仍按起点累计位移判断,取消手势不产生惯性。
|
||||
|
||||
### `data-status-target`
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# 控制台前端结构
|
||||
|
||||
## 算力对比配置
|
||||
|
||||
“智能星球内容”的 `compute_comparison` 分区挂载独立 `ComputeComparisonSettings.tsx`,通过结构化表单维护来源、年度国家观测及创新分差,复用现有 Panel、Input、Select、Button 和确认弹窗,不让运营人员编辑 JSON。草稿在同页切换分区时保留,整页离开提示未保存内容;手动重新加载和恢复默认需确认。组件仅激活时读取管理接口,保存使用后端 revision 防止覆盖其他编辑者,失败保留草稿。表单内容区负责内部滚动,标题和发布操作留在首屏。`compute-comparison-model.ts` 集中类型与同源更新通知,`compute-comparison.css` 只负责该分区布局。
|
||||
|
||||
本文件描述当前控制台前端的真实结构,目标是帮助后续页面开发、表格改造、布局治理和状态收口时快速找到正确入口。
|
||||
|
||||
相关规则建议一起参考:
|
||||
|
||||
@@ -411,11 +411,15 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军
|
||||
|
||||
## 算力与资源态势
|
||||
|
||||
管理员可在控制台“智能星球内容 → 算力对比”维护卡片数据。先在“报告来源”录入报告标题、链接、发布机构、报告年份与页码,再在“年度观测”按年份选择指标、来源和国家数值,最后“保存并发布”。占比以全球为分母,绝对量统一为 FP32 EFlop/s;中美双边份额由同年全球份额计算,区域仅在成员数据完整时汇总。不要混入 FP16/FP64、地区估计值或设施记录数;空缺国家应不录入,明确的零值才填 0。
|
||||
|
||||
“创新指数分差”独立维护美国减中国的观测,不反推单国指数。来源被观测引用时不能直接移除;重复指标年份、无效来源、占比总和超过 100% 等内容会拒绝发布。多人同时编辑时,后保存者收到冲突提示,草稿保留以便核对。“恢复默认”需要确认,会恢复随版本提供的报告数据;保存和恢复均有操作审计。同源页面收到发布通知后更新,其他正在展示的地球页每分钟检查一次,后台标签页恢复可见时也会检查。数值仍需人工核验报告,配置链接不会自动抓取报告。
|
||||
|
||||
点击算力中心图层行的“算力态势分析”打开配置窗,再开启“显示区域卡片”,地球周围会先绘制到目标位置的连接线,随后数据卡平滑出现;再次转动时不会重播入场。关闭配置窗或按 Escape 仅收起配置,卡片继续显示;再次点击分析按钮可重开配置,关闭显示开关才会停用卡片。区域锚点随地球旋转,卡片保持朝向读者;背面区域有状态提示,不绘制穿过地球的连线。其他图层、新闻和媒体窗口保持可用。
|
||||
|
||||
选择器按规范目录分为中国、美国、欧洲、不含中国的亚太和其他五组;这些分组只用于展示,不参与统计分母,可改变参考期与指标口径。双边份额的分母仍固定为美国加中国,其他参与方没有该口径时显示缺失。区域中心只用于卡片定位,不代表设施位置。点击来源查看报告,点击设施按钮使用原有详情卡。手机通过底部抽屉的“算力”页查看紧凑地区概览:同一列表中的短卡采用手风琴,重复点击卡头收起,点击另一张先收起旧卡,最多同时展开一张长卡。展开详情保留趋势、区域成员、设施、媒体和来源,不设地区二级页面;设置仍是单独按需页。
|
||||
|
||||
默认主指标为全球计算设备总规模,拆分基础计算、智能计算和超级计算,观察期为 2020—2023。已核对的绝对量为 2022 年 302(证据 `caict2023`)和 2023 年 435(证据 `caict2024`)。日本全球份额为 2020/2021/2022/2023 = 6%/5%/4%/4%。产品分组 APAC、OTHER 不能直接等同报告里的日本或“其他”;EUROPE 成员集合尚未与报告对齐,仍显示缺失。双边份额分母固定为美国加中国,不受日本加入影响。主指标缺失时可显示最近有报告的年份(当前到 2023),明确选择 2026 仍显示缺失,不回填最近值。不可比性未确认时不展示同比变化。国家报告指标与公开设施样本独立,覆盖 count 只保留在辅助证据区,不能当作算力值或全球覆盖率。TOP500 与 Epoch 可能重复收录,来源记录数不代表全球设施总数。API 审计字段为 `reviewed_at=2026-09-22`,版本与该日期一致。独立 Epoch 份额模式尚未实现。
|
||||
默认主指标为全球计算设备总规模,拆分基础计算、智能计算和超级计算,观察期为 2020—2023。已核对的绝对量为 2022 年 302(证据 `caict2023`)和 2023 年 435(证据 `caict2024`)。日本全球份额为 2020/2021/2022/2023 = 6%/5%/4%/4%。产品分组 APAC、OTHER 不能直接等同报告里的日本或“其他”;EUROPE 成员集合尚未与报告对齐,仍显示缺失。双边份额分母固定为美国加中国,不受日本加入影响。主指标缺失时可显示最近有报告的年份(当前到 2023),明确选择 2026 仍显示缺失,不回填最近值。不可比性未确认时不展示同比变化。国家报告指标与公开设施样本独立,覆盖 count 只保留在辅助证据区,不能当作算力值或全球覆盖率。TOP500 与 Epoch 可能重复收录,来源记录数不代表全球设施总数。默认报告核验日期为 2026-09-22;后台发布后以维护的核验日期和实际观测为准。独立 Epoch 份额模式尚未实现。
|
||||
|
||||
当前原型最多同时显示六张内容卡。主卡围绕当前选择的算力指标:大号百分比或带单位的绝对量、观测年份、历史上下文和来源入口。缺少可比数据时明确显示“暂无可比数据”;没有观测值时不绘制空趋势图。设施记录和覆盖信息仍完整保留,但移到展开后的辅助区;样本数只是证据上下文,不能当作算力值或全球覆盖率。区域预览可以显示成员数,长列表仅在需要时展开。桌面卡片约宽 268 像素,高度随内容自适应;展开卡片支持用户调整至最高 480 像素。手机手风琴单卡也保持同一占比/绝对量语义,不把设施条数提升为主数字。位置和尺寸保存于本地,并可恢复自动布局。拖动或展开后先留出阅读时间;地区随地球明显转到另一侧或上下方后,卡片才会在能减少连线交叉、绕行的情况下成组平滑换位。鼠标正在卡片上操作时不移动,手动位置不会被立即抢回,也不会永久阻止必要调整。图片、视频等内容可以沿用内容区布局,当前尚未接入这些媒体数据。空间不足时卡片可以经过球体前景移动,不再靠瞬移避让或缩成小标签。
|
||||
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
# planet.sh 启动性能优化
|
||||
|
||||
## 背景
|
||||
## Windows 桌面启动器
|
||||
|
||||
启动窗口优先使用 Windows Terminal,并显式运行 PowerShell 7(`pwsh.exe`),不依赖 Terminal 默认配置文件。未安装 PowerShell 7 时回退到 Windows PowerShell;未安装 Terminal 时直接启动可用的 PowerShell。CMD 初始引导同样优先 PowerShell 7。普通入口请求提权,已经以管理员运行的入口也会进入新 Terminal 窗口,但不会再次请求提权;子窗口校验权限后直接执行 WSL,避免递归打开窗口。重启完成后仍保留原有 WSL shell。
|
||||
|
||||
首次在 Windows 文件资源管理器中打开实际项目目录,双击仓库根目录的 `planet.cmd`。它从自身位置识别 WSL 发行版和 Linux 项目目录,在 Windows 当前用户的实际桌面生成 `Planet.cmd`,随后进入正常重启流程。支持 `\\wsl$\发行版\...` 与 `\\wsl.localhost\发行版\...`;仓库位于 Windows 本地磁盘时,使用默认 WSL 发行版及 `wslpath` 映射。系统桌面位置由 Windows 获取,兼容不同用户名和 OneDrive 等桌面重定向;WSL、zsh 及项目依赖仍须先准备好。
|
||||
|
||||
后续双击桌面副本,使用已绑定的发行版与目录,申请原有管理员权限,并调用 `planet.sh restart --allow-lan`。不写入测试端口;默认前端 3000、后端 8000、AI Provider 8010,显式 `DEFAULT_*_PORT` 环境配置仍有效。成功后按实际 `ports.env` 端口打开 Earth,终端保留 WSL shell;失败只显示错误,不打开成功页面。源文件负责生成入口,`scripts/windows/planet-launcher.ps1` 负责 Windows 路径、桌面安装与提权,`scripts/windows/restart.zsh` 只衔接现有重启流程。
|
||||
|
||||
只生成或检查副本而不重启服务,可在 Windows 中运行 `planet.cmd --install-only`。从仓库再次运行会刷新同一目标的副本;已有其他项目或非托管 `Planet.cmd` 时另存带目标标识的文件,不覆盖。目录移动后从新位置重新运行仓库入口,旧副本不会猜测新目录。桌面副本依赖项目中的脚本,不是可脱离仓库运行的安装包。
|
||||
|
||||
不要把仓库原始 `planet.cmd` 单独复制到桌面,它需要相邻的 `scripts/windows/` 才能完成首次生成。换电脑时应从新电脑的项目目录重新生成,不能直接沿用旧电脑的桌面副本。服务器的 `/home/linkong/planet` 与个人电脑的其他路径均可使用,不必修改提交到 Git 的路径。应在拥有目标 WSL 发行版的 Windows 账号下运行;若提权时改用其他账号,其 WSL 发行版注册可能不同。首次生成不要求管理员权限,真正重启时才申请提权。
|
||||
|
||||
Windows 回归命令为 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\harness\test_windows_launcher.ps1`,覆盖路径识别、特殊字符、生成副本及名称冲突。`scripts/harness/test_windows_restart.py` 用临时替身验证重启参数、成功打开页面和失败保留 shell,已接入 quick-check,不启动实际服务。
|
||||
|
||||
## 启动背景
|
||||
|
||||
日常启动使用 `zsh ./planet.sh start --non-motion-agent`;新环境首次准备才需要 `init`。排查耗时时,应区分首次依赖下载、容器就绪和应用初始化,结合阶段日志时间判断。
|
||||
|
||||
|
||||
@@ -311,6 +311,7 @@ OTP 一次性验证码走 Redis,key 格式 `otp:{purpose}:{email}`,TTL 600
|
||||
<!-- planet-error-catalog:start -->
|
||||
| 错误编号 | 匹配片段(分号分隔) | 原因/已确认的故障现象 | 处理建议 |
|
||||
| --- | --- | --- | --- |
|
||||
| P_WINDOWS_LAUNCHER_TARGET_MISSING | P_WINDOWS_LAUNCHER_TARGET_MISSING | 桌面启动器绑定的 WSL 项目目录不可访问或缺少启动脚本,常见于项目移动、发行版不可用或复制旧机器的副本。 | 从当前项目目录运行仓库 planet.cmd 重新生成本机桌面副本,检查 WSL 发行版;不修改成其他电脑的固定路径。 |
|
||||
| P_PROXY_EXTERNAL | PLANET_PROXY_EXTERNAL | 当前 Docker 代理由其他配置管理,或已被人工修改,不能安全自动覆盖。 | 检查 daemon.json、systemd 代理及 Planet 管理记录,确认归属后再调整;脚本保留现有配置。 |
|
||||
| P_AUTH_BOOTSTRAP_MISSING | DEFAULT_LOGIN_USER_MISSING | 已确认当前后端数据库缺少默认账户,常见于跳过初始化的隔离预览。 | 核对数据库归属后运行现有默认账户初始化,不重置已有账户或清空数据库。 |
|
||||
| P_AUTH_PROFILE_INVALID | AUTH_IDENTITY_RESPONSE_INVALID | 已确认登录成功但身份响应字段缺失,或响应错误拒绝既有本地邮箱。 | 从真实用户记录加载完整身份,区分响应序列化与注册输入校验;运行默认账户身份回归。 |
|
||||
|
||||
@@ -74,4 +74,6 @@
|
||||
|
||||
## 试用算力专题
|
||||
|
||||
维护卡片数值:管理员打开“智能星球内容 → 算力对比”,先维护报告来源,再填写年度国家观测并“保存并发布”。只录入同年同口径数据,缺失国家不填,设施数量不会替代算力份额。可恢复内置默认值,地球卡片自动检查已发布配置。
|
||||
|
||||
在算力中心旁打开“算力态势分析”,开启“显示区域卡片”,选择地区并旋转地球。关闭配置窗会保留卡片,显示开关才控制启停。桌面卡片可调整大小、收起并查看真实历史图;点击来源或设施进入详情。手机使用底部“算力”页。国家指标与设施样本分开,“—”表示缺数据,不代表算力为零。
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.75.0`
|
||||
- `dev` 当前开发分支历史推导到:`0.75.2`
|
||||
|
||||
## Timeline
|
||||
|
||||
| Version | Type | Branch | Commit | Summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `0.75.2` | bugfix | `dev` | `v0.75.2` | Windows 启动器优先 Terminal 与 PowerShell 7,修复管理员入口分流,补齐兼容回退与提权测试 |
|
||||
| `0.75.1` | improvement | `dev` | `v0.75.1` | Windows 启动器自动生成本机桌面入口,后台维护算力比较数据,恢复小球惯性与大球跟手分流并更新 agent 策略 |
|
||||
| `0.75.0` | feature | `dev` | `v0.75.0` | 四图切换默认原始底图,新增算力区域态势卡片,统一空间连线与重排,优化启动和缩放拖动并补齐地理规则交付 |
|
||||
| `0.74.7` | improvement | `dev` | `v0.74.7` | Docker 镜像网络故障临时回退,精简副行进度与失败显示,修复数据库端口冲突及启动重试并补齐实际验证 |
|
||||
| `0.74.6` | improvement | `dev` | `v0.74.6` | 自动检测 Docker 构建代理与直连,统一运维错误诊断,支持跳过 AI Provider 构建并修复 Compose 回退与失败退出状态 |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-frontend",
|
||||
"version": "0.75.0",
|
||||
"version": "0.75.2",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { createSpatialCallouts } from "./spatial-callouts.js";
|
||||
|
||||
const API = "/api/v1/data-products/compute";
|
||||
const MAX_VISIBLE_REGIONS = 6;
|
||||
const CONFIGURATION_REFRESH_MS = 60_000;
|
||||
const LOCAL_FLAG_CODES = new Set([
|
||||
"af", "ao", "au", "br", "ca", "ch", "cn", "co", "cr", "de", "do", "eg",
|
||||
"es", "fi", "fr", "gb", "hu", "id", "ie", "in", "it", "jp", "ke", "kr",
|
||||
@@ -740,7 +741,7 @@ export function initComputeTopic({
|
||||
if (refreshMap && cardsEnabled) refreshFacilities();
|
||||
try {
|
||||
const params = new URLSearchParams({ countries: countries.join(","), mode });
|
||||
const response = await fetch(`${API}/series?${params}`, { signal: request.signal });
|
||||
const response = await fetch(`${API}/series?${params}`, { signal: request.signal, cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const payload = await response.json();
|
||||
if (token !== serial || (!configVisible && !cardsEnabled)) return;
|
||||
@@ -1004,6 +1005,14 @@ export function initComputeTopic({
|
||||
};
|
||||
window.addEventListener("resize", resize);
|
||||
window.addEventListener("earth:locale-change", locale);
|
||||
const refreshConfiguration = () => {
|
||||
if (!document.hidden && (configVisible || cardsEnabled)) load({ refreshMap: false });
|
||||
};
|
||||
const configurationChannel = typeof BroadcastChannel === "undefined" ? null
|
||||
: new BroadcastChannel("planet-compute-configuration");
|
||||
if (configurationChannel) configurationChannel.onmessage = refreshConfiguration;
|
||||
const configurationTimer = setInterval(refreshConfiguration, CONFIGURATION_REFRESH_MS);
|
||||
document.addEventListener("visibilitychange", refreshConfiguration);
|
||||
renderPicker();
|
||||
renderMobile();
|
||||
return {
|
||||
@@ -1026,6 +1035,9 @@ export function initComputeTopic({
|
||||
cardsEnabled = false;
|
||||
serial++;
|
||||
request?.abort();
|
||||
clearInterval(configurationTimer);
|
||||
configurationChannel?.close();
|
||||
document.removeEventListener("visibilitychange", refreshConfiguration);
|
||||
document.body.classList.remove("compute-topic-open");
|
||||
for (const controller of cardPanels.values()) controller.destroy();
|
||||
cardPanels.clear();
|
||||
|
||||
@@ -9,6 +9,10 @@ export const CONFIG = {
|
||||
earthRadius: 100,
|
||||
rotationSpeed: 0.0005,
|
||||
minimumCameraAltitude: 10,
|
||||
dragRotationFactorBase: 0.005,
|
||||
dragRotationZoomExponent: 1.8,
|
||||
dragRotationScaleMin: 0.12,
|
||||
dragRotationScaleMax: 1.65,
|
||||
};
|
||||
|
||||
export const ROTATION_MODE = {
|
||||
|
||||
@@ -23,6 +23,20 @@ export function globeZoomForDistance(distance, radius, defaultDistance) {
|
||||
Math.max(0.0001, distance ** 2 - radius ** 2));
|
||||
}
|
||||
|
||||
// Use the actual camera frustum so portrait screens switch by their width,
|
||||
// while landscape screens switch by their height. Decide only on pointer-down.
|
||||
export function isGlobeClippedByViewport(earth, camera, radius) {
|
||||
camera.updateMatrixWorld();
|
||||
const center = earth.getWorldPosition(new THREE.Vector3());
|
||||
const scale = earth.getWorldScale(new THREE.Vector3());
|
||||
const worldRadius = radius * Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
|
||||
const viewProjection = new THREE.Matrix4().multiplyMatrices(
|
||||
camera.projectionMatrix, camera.matrixWorldInverse,
|
||||
);
|
||||
const frustum = new THREE.Frustum().setFromProjectionMatrix(viewProjection);
|
||||
return frustum.planes.slice(0, 4).some(plane => plane.distanceToPoint(center) < worldRadius);
|
||||
}
|
||||
|
||||
export function createSurfaceDrag(radius) {
|
||||
const raycaster = new THREE.Raycaster();
|
||||
const pointer = new THREE.Vector2();
|
||||
@@ -46,11 +60,12 @@ export function createSurfaceDrag(radius) {
|
||||
1 - (point.y - viewport.top) / viewport.height * 2,
|
||||
), camera);
|
||||
if (!raycaster.ray.intersectSphere(sphere, hit)) {
|
||||
// Outside the silhouette there is no grabbed surface; continue smoothly
|
||||
// around its rim instead of producing a jump or an invalid intersection.
|
||||
raycaster.ray.closestPointToPoint(center, hit);
|
||||
// No real surface point exists here. A closest-point substitute folds
|
||||
// back toward the camera as the pointer moves away, reversing rotation.
|
||||
return false;
|
||||
}
|
||||
output.copy(hit).sub(center).normalize().applyQuaternion(parentInverse);
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -58,12 +73,17 @@ export function createSurfaceDrag(radius) {
|
||||
speed = 0; active = true; lastMoveAt = now;
|
||||
parentInverse.identity();
|
||||
if (earth.parent) earth.parent.getWorldQuaternion(parentInverse).invert();
|
||||
pointerNormal(earth, camera, point, viewport, anchor);
|
||||
active = pointerNormal(earth, camera, point, viewport, anchor);
|
||||
initial.copy(earth.quaternion);
|
||||
return active;
|
||||
},
|
||||
move(earth, camera, point, viewport, now) {
|
||||
if (!active) return;
|
||||
pointerNormal(earth, camera, point, viewport, current);
|
||||
if (!pointerNormal(earth, camera, point, viewport, current)) {
|
||||
speed = 0;
|
||||
lastMoveAt = now;
|
||||
return;
|
||||
}
|
||||
previous.copy(earth.quaternion);
|
||||
change.setFromUnitVectors(anchor, current);
|
||||
earth.quaternion.copy(initial).premultiply(change);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import * as THREE from "three";
|
||||
import { CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET } from "./constants.js";
|
||||
import { createSurfaceDrag, distanceForGlobeZoom, globeZoomForDistance } from "./globe-navigation.js";
|
||||
import { createSurfaceDrag, distanceForGlobeZoom, globeZoomForDistance, isGlobeClippedByViewport } from "./globe-navigation.js";
|
||||
|
||||
const radius = CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET;
|
||||
const distance = zoom => distanceForGlobeZoom(zoom, CONFIG.earthRadius,
|
||||
@@ -37,6 +37,41 @@ function scene(zoom, width, height) {
|
||||
return { camera, earth, viewport, project, grabbed };
|
||||
}
|
||||
|
||||
for (const [zoom, width, height, clipped] of [
|
||||
[0.5, 1440, 900, false], [1, 1440, 900, false], [2, 1440, 900, false],
|
||||
[3, 1440, 900, true], [5, 1440, 900, true],
|
||||
[0.5, 390, 844, false], [0.9, 390, 844, false], [1, 390, 844, true], [2, 390, 844, true],
|
||||
]) {
|
||||
test(`${zoom * 100}% at ${width}x${height}: choose surface drag only when the globe is clipped`, () => {
|
||||
const f = scene(zoom, width, height);
|
||||
expect(isGlobeClippedByViewport(f.earth, f.camera, radius)).toBe(clipped);
|
||||
});
|
||||
}
|
||||
|
||||
test("a grab outside the globe is rejected so screen-space dragging can handle it", () => {
|
||||
const f = scene(1, 1440, 900);
|
||||
const drag = createSurfaceDrag(radius);
|
||||
expect(drag.begin(f.earth, f.camera, { x: 20, y: 30 }, f.viewport, 0)).toBe(false);
|
||||
const before = f.earth.quaternion.clone();
|
||||
drag.move(f.earth, f.camera, { x: 150, y: 30 }, f.viewport, 16);
|
||||
expect(f.earth.quaternion.angleTo(before)).toBeCloseTo(0, 7);
|
||||
});
|
||||
|
||||
test("moving a large-globe grab beyond its limb never reverses or generates inertia", () => {
|
||||
const f = scene(3, 1440, 900);
|
||||
const drag = createSurfaceDrag(radius), start = f.project(f.grabbed);
|
||||
expect(drag.begin(f.earth, f.camera, start, f.viewport, 0)).toBe(true);
|
||||
let previous = f.earth.quaternion.clone();
|
||||
for (let step = 1; step <= 100; step++) {
|
||||
drag.move(f.earth, f.camera, { x: start.x + step * 10, y: start.y }, f.viewport, step * 16);
|
||||
const delta = f.earth.quaternion.clone().multiply(previous.clone().invert());
|
||||
expect(delta.y).toBeGreaterThanOrEqual(-1e-10);
|
||||
previous.copy(f.earth.quaternion);
|
||||
}
|
||||
drag.end(1601);
|
||||
expect(drag.hasInertia()).toBe(false);
|
||||
});
|
||||
|
||||
for (const zoom of [0.5, 1, 2, 3, 5]) for (const [width, height] of [[1440, 900], [390, 844]]) {
|
||||
test(`${zoom * 100}% at ${width}px: the grabbed surface follows the pointer pixel for pixel`, () => {
|
||||
const f = scene(zoom, width, height);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createSurfaceDrag } from "./globe-navigation.js";
|
||||
import { createSurfaceDrag, isGlobeClippedByViewport } from "./globe-navigation.js";
|
||||
import * as THREE from "three";
|
||||
|
||||
import {
|
||||
@@ -346,6 +346,7 @@ let previousMousePosition = { x: 0, y: 0 };
|
||||
let targetRotation = { x: 0, y: 0 };
|
||||
let inertialVelocity = { x: 0, y: 0 };
|
||||
const surfaceDrag = createSurfaceDrag(CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET);
|
||||
let surfaceDragging = false;
|
||||
let hoveredCable = null;
|
||||
let hoveredBGP = null;
|
||||
let hoveredComputeCenter = null;
|
||||
@@ -583,6 +584,16 @@ function hasActiveGlobeInertia() {
|
||||
);
|
||||
}
|
||||
|
||||
function getDragRotationFactor() {
|
||||
const zoom = Math.max(getZoomLevel(), 0.01);
|
||||
const scale = THREE.MathUtils.clamp(
|
||||
Math.pow(zoom, -CONFIG.dragRotationZoomExponent),
|
||||
CONFIG.dragRotationScaleMin,
|
||||
CONFIG.dragRotationScaleMax,
|
||||
);
|
||||
return CONFIG.dragRotationFactorBase * scale;
|
||||
}
|
||||
|
||||
function getTargetSwitchZoomOptions(requestedZoom) {
|
||||
const currentZoom = getZoomLevel();
|
||||
const defaultZoom = getDefaultEarthZoomLevel();
|
||||
@@ -5753,9 +5764,18 @@ function onMouseMove(event) {
|
||||
isLongDrag = true;
|
||||
}
|
||||
|
||||
surfaceDrag.move(earth, camera, { x: event.clientX, y: event.clientY },
|
||||
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
|
||||
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
|
||||
if (surfaceDragging) {
|
||||
surfaceDrag.move(earth, camera, { x: event.clientX, y: event.clientY },
|
||||
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
|
||||
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
|
||||
} else {
|
||||
const factor = getDragRotationFactor();
|
||||
const deltaX = (event.clientX - previousMousePosition.x) * factor;
|
||||
const deltaY = (event.clientY - previousMousePosition.y) * factor;
|
||||
targetRotation.x += deltaY;
|
||||
targetRotation.y += deltaX;
|
||||
inertialVelocity = { x: deltaY, y: deltaX };
|
||||
}
|
||||
previousMousePosition = { x: event.clientX, y: event.clientY };
|
||||
if (!document.body.classList.contains("layout-mode-mobile")) {
|
||||
clearCountryBoundaryHover();
|
||||
@@ -6047,10 +6067,14 @@ function onMouseDown(event) {
|
||||
previousMousePosition = { x: event.clientX, y: event.clientY };
|
||||
dragStartPointer = { ...previousMousePosition };
|
||||
inertialVelocity = { x: 0, y: 0 };
|
||||
surfaceDrag.stop();
|
||||
surfaceDragging = false;
|
||||
if (earth) {
|
||||
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
|
||||
surfaceDrag.begin(earth, camera, { x: event.clientX, y: event.clientY },
|
||||
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
|
||||
surfaceDragging = isGlobeClippedByViewport(earth, camera,
|
||||
CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET) &&
|
||||
surfaceDrag.begin(earth, camera, { x: event.clientX, y: event.clientY },
|
||||
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
|
||||
}
|
||||
clearDocumentSelection();
|
||||
setGlobeDraggingUiState(true);
|
||||
@@ -6059,7 +6083,10 @@ function onMouseDown(event) {
|
||||
}
|
||||
|
||||
function onMouseUp(event = {}, cancelInertia = false) {
|
||||
surfaceDrag.end(event.timeStamp || performance.now(), cancelInertia || event.type === "pointercancel");
|
||||
const cancelled = cancelInertia || event.type === "pointercancel";
|
||||
surfaceDrag.end(event.timeStamp || performance.now(), cancelled);
|
||||
if (cancelled) inertialVelocity = { x: 0, y: 0 };
|
||||
surfaceDragging = false;
|
||||
isDragging = false;
|
||||
setGlobeDraggingUiState(false);
|
||||
clearDocumentSelection();
|
||||
@@ -6435,10 +6462,13 @@ function animate() {
|
||||
}
|
||||
|
||||
if (earth) {
|
||||
if (isDragging || surfaceDrag.advance(earth, deltaTime)) {
|
||||
if ((isDragging && surfaceDragging) || surfaceDrag.advance(earth, deltaTime)) {
|
||||
// Pointer movement has already placed the grabbed surface point exactly.
|
||||
targetRotation.x = earth.rotation.x;
|
||||
targetRotation.y = earth.rotation.y;
|
||||
} else if (isDragging) {
|
||||
earth.rotation.x += (targetRotation.x - earth.rotation.x) * DRAG_SMOOTHING_FACTOR;
|
||||
earth.rotation.y += (targetRotation.y - earth.rotation.y) * DRAG_SMOOTHING_FACTOR;
|
||||
} else if (
|
||||
Math.abs(inertialVelocity.x) > INERTIA_MIN_VELOCITY ||
|
||||
Math.abs(inertialVelocity.y) > INERTIA_MIN_VELOCITY
|
||||
|
||||
240
frontend/src/admin/pages/ComputeComparisonSettings.tsx
Normal file
240
frontend/src/admin/pages/ComputeComparisonSettings.tsx
Normal file
@@ -0,0 +1,240 @@
|
||||
import axios from 'axios'
|
||||
import { Plus, RefreshCw, RotateCcw, Save, Trash2 } from 'lucide-react'
|
||||
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { useLocale } from '../../i18n/locale'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { ConfirmDialog } from '../components/ui/dialog'
|
||||
import { Input } from '../components/ui/input'
|
||||
import { Select } from '../components/ui/select'
|
||||
import { Panel } from '../patterns/patterns'
|
||||
import {
|
||||
notifyComputeConfigurationChanged, reportIsUsed,
|
||||
type ComputeConfiguration, type ComputeConfigurationResponse, type ComputeObservation,
|
||||
} from './compute-comparison-model'
|
||||
import './compute-comparison.css'
|
||||
|
||||
const ENDPOINT = `${import.meta.env.VITE_API_URL || '/api/v1'}/data-products/compute/configuration`
|
||||
type View = 'observations' | 'sources' | 'innovation'
|
||||
|
||||
function Field({ title, children }: { title: string; children: ReactNode }) {
|
||||
return <label className="an-compute-field"><span>{title}</span>{children}</label>
|
||||
}
|
||||
|
||||
function validationMessage(message: string, english: boolean) {
|
||||
const normalized = message.replace(/^Value error, /, '')
|
||||
if (english) return normalized
|
||||
const translations: Record<string, string> = {
|
||||
'Global shares for one year must total at most 100 percent': '同年各国全球算力占比之和不能超过 100%。',
|
||||
'Each metric/year may have only one observation': '同一指标、同一年只能保留一条年度观测。',
|
||||
'Report source IDs must be unique': '报告来源不能重复。',
|
||||
'Innovation observation years must be unique': '创新指数分差的年份不能重复。',
|
||||
'Observation year must not be after its report year': '观测年份不能晚于所选报告的年份。',
|
||||
'Review date must not be in the future': '核验日期不能晚于今天。',
|
||||
'Use countries from the canonical compute catalog, not regional totals': '请使用国家观测,不能直接录入区域合计。',
|
||||
'Use a report URL without credentials (maximum 2000 characters)': '报告链接不能包含账号密码,长度不能超过 2000 字符。',
|
||||
}
|
||||
if (normalized.startsWith('Missing report source:')) return '请为观测选择有效的报告来源。'
|
||||
return translations[normalized] || '字段内容无效,请检查必填项、数值范围和报告链接。'
|
||||
}
|
||||
|
||||
function requestError(error: unknown, english: boolean) {
|
||||
if (!axios.isAxiosError(error)) return english ? 'Request failed.' : '请求失败。'
|
||||
if (error.response?.status === 409) return english
|
||||
? 'Someone updated this configuration. Your draft is preserved. Reload and reconcile before saving.'
|
||||
: '配置已被其他人更新。当前草稿已保留,请核对后重新加载再保存。'
|
||||
const detail: unknown = error.response?.data?.detail
|
||||
if (Array.isArray(detail)) return detail.map((item: { loc?: Array<string | number>; msg?: string }) => {
|
||||
const section = item.loc?.find(value => ['sources', 'observations', 'innovation'].includes(String(value)))
|
||||
const index = item.loc?.find(value => typeof value === 'number')
|
||||
const labels: Record<string, string> = { sources: '报告来源', observations: '年度观测', innovation: '创新指数分差' }
|
||||
const location = section ? english ? String(section) : labels[String(section)] : ''
|
||||
const row = typeof index === 'number' ? english ? ` #${index + 1}` : ` 第 ${index + 1} 条` : ''
|
||||
return `${location}${row}${location ? ':' : ''}${validationMessage(item.msg || '', english)}`
|
||||
}).join(';')
|
||||
if (error.response?.status === 403) return english ? 'Administrator access required.' : '仅管理员可以维护算力对比数据。'
|
||||
return typeof detail === 'string' ? detail : error.message
|
||||
}
|
||||
|
||||
export function ComputeComparisonSettings({ active }: { active: boolean }) {
|
||||
const { locale } = useLocale()
|
||||
const english = locale === 'en-US'
|
||||
const t = (zh: string, en: string) => english ? en : zh
|
||||
const [saved, setSaved] = useState<ComputeConfigurationResponse | null>(null)
|
||||
const [draft, setDraft] = useState<ComputeConfiguration | null>(null)
|
||||
const [view, setView] = useState<View>('observations')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [message, setMessage] = useState('')
|
||||
const [confirmation, setConfirmation] = useState<'reset' | 'reload' | null>(null)
|
||||
const [loadRevision, setLoadRevision] = useState(0)
|
||||
const viewportRef = useRef<HTMLDivElement>(null)
|
||||
const dirty = Boolean(draft && saved && JSON.stringify(draft) !== JSON.stringify(saved.config))
|
||||
|
||||
useEffect(() => {
|
||||
viewportRef.current?.scrollTo({ top: 0 })
|
||||
}, [view])
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || saved) return
|
||||
const controller = new AbortController()
|
||||
setBusy(true)
|
||||
axios.get<ComputeConfigurationResponse>(ENDPOINT, { signal: controller.signal })
|
||||
.then(({ data }) => { setSaved(data); setDraft(data.config); setError('') })
|
||||
.catch(failure => { if (!controller.signal.aborted) setError(requestError(failure, english)) })
|
||||
.finally(() => { if (!controller.signal.aborted) setBusy(false) })
|
||||
return () => controller.abort()
|
||||
}, [active, saved, loadRevision, english])
|
||||
|
||||
useEffect(() => {
|
||||
if (!dirty) return
|
||||
const preventLoss = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
|
||||
window.addEventListener('beforeunload', preventLoss)
|
||||
return () => window.removeEventListener('beforeunload', preventLoss)
|
||||
}, [dirty])
|
||||
|
||||
const edit = (next: ComputeConfiguration) => { setDraft(next); setMessage(''); setError('') }
|
||||
const reload = () => { setSaved(null); setLoadRevision(value => value + 1); setMessage('') }
|
||||
const metricLabel = (metric: string) => metric === 'global_share'
|
||||
? t('全球算力占比 (%)', 'Global compute share (%)')
|
||||
: t('计算设备总规模 · FP32 (EFlop/s)', 'Total compute · FP32 (EFlop/s)')
|
||||
|
||||
async function publish(reset = false) {
|
||||
if (!saved || !draft) return
|
||||
setBusy(true); setError(''); setMessage('')
|
||||
try {
|
||||
const { data } = reset
|
||||
? await axios.post<ComputeConfigurationResponse>(`${ENDPOINT}/reset`, { revision: saved.revision })
|
||||
: await axios.put<ComputeConfigurationResponse>(ENDPOINT, { revision: saved.revision, config: draft })
|
||||
setSaved(data); setDraft(data.config); setConfirmation(null)
|
||||
setMessage(t('已发布,地球卡片将自动更新。', 'Published. Earth cards will refresh automatically.'))
|
||||
notifyComputeConfigurationChanged()
|
||||
} catch (failure) { setError(requestError(failure, english)); setConfirmation(null) }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
|
||||
function save(event: FormEvent) { event.preventDefault(); void publish() }
|
||||
if (!active && !saved) return null
|
||||
const sources = draft?.sources.map(source => ({ value: source.id, label: source.title || source.id })) || []
|
||||
const sourceSelect = (value: string, onChange: (value: string) => void) => (
|
||||
<Field title={t('报告来源', 'Report source')}><Select value={value} onValueChange={onChange}
|
||||
options={sources} placeholder={t('选择报告', 'Select a report')} /></Field>
|
||||
)
|
||||
const removeButton = (label: string, onClick: () => void, disabled = false) => (
|
||||
<Button type="button" size="icon" variant="subtle" title={label} aria-label={label}
|
||||
disabled={disabled || busy} onClick={onClick}><Trash2 size={15} /></Button>
|
||||
)
|
||||
const updateObservation = (index: number, row: ComputeObservation) => {
|
||||
if (draft) edit({ ...draft, observations: draft.observations.map((item, i) => i === index ? row : item) })
|
||||
}
|
||||
|
||||
return (
|
||||
<Panel className="an-compute-settings" hidden={!active}>
|
||||
<form className="an-compute-form" onSubmit={save} onInvalidCapture={event => {
|
||||
const details = (event.target as HTMLElement).closest('details')
|
||||
if (details) details.open = true
|
||||
}}>
|
||||
<div className="an-panel-heading an-compute-heading">
|
||||
<div><h2>{t('算力对比数据', 'Compute comparison data')}</h2>
|
||||
<p>{t('同年、同口径的国家观测;未录入的数值保持缺失。', 'Comparable country observations by year. Omitted values stay unavailable.')}</p></div>
|
||||
<div className="an-compute-actions">
|
||||
<Button type="button" size="icon" variant="subtle" title={t('重新加载', 'Reload')} aria-label={t('重新加载', 'Reload')} disabled={busy} onClick={() => dirty ? setConfirmation('reload') : reload()}>
|
||||
<RefreshCw size={15} /></Button>
|
||||
<Button type="button" size="icon" variant="subtle" title={t('恢复默认', 'Restore defaults')} aria-label={t('恢复默认', 'Restore defaults')} disabled={busy || !saved} onClick={() => setConfirmation('reset')}>
|
||||
<RotateCcw size={15} /></Button>
|
||||
<Button type="submit" disabled={busy || !dirty} loading={busy}>
|
||||
<Save size={15} />{t('保存并发布', 'Save and publish')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="an-compute-status" role="status">
|
||||
{message || (error && !saved ? t('配置读取失败', 'Configuration unavailable') : dirty ? t('有未发布修改', 'Unpublished changes') : saved?.is_default ? t('当前使用内置报告数据', 'Using bundled report data') : saved ? t('当前使用后台配置', 'Using published configuration') : t('正在读取配置…', 'Loading configuration…'))}
|
||||
</div>
|
||||
{error ? <p className="an-compute-error" role="alert">{error}</p> : null}
|
||||
{draft && saved ? <>
|
||||
<div className="an-compute-toolbar">
|
||||
<div className="an-compute-actions" role="group" aria-label={t('数据分类', 'Data categories')}>
|
||||
{([['observations', t('年度观测', 'Observations')], ['sources', t('报告来源', 'Sources')], ['innovation', t('创新指数分差', 'Innovation gap')]] as const).map(([key, label]) => (
|
||||
<Button key={key} type="button" variant={view === key ? 'primary' : 'subtle'} aria-pressed={view === key} onClick={() => setView(key)}>{label}</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Scrollbar className="an-compute-scroll" viewportRef={viewportRef}>
|
||||
<fieldset className="an-compute-content" disabled={busy}>
|
||||
<Field title={t('核验日期', 'Review date')}><Input type="date" required disabled={busy} value={draft.reviewed_at}
|
||||
onChange={event => edit({ ...draft, reviewed_at: event.target.value })} /></Field>
|
||||
{view === 'observations' ? <>
|
||||
<p>{t('占比以全球为分母;绝对量统一为 FP32 EFlop/s。区域只在全部成员都有同年数据时汇总。', 'Shares use the global denominator. Absolute values use FP32 EFlop/s. Regions require every member in the same year.')}</p>
|
||||
{draft.observations.map((row, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
|
||||
<summary>{row.year} · {metricLabel(row.metric)} · {Object.keys(row.values).length} {t('个国家', 'countries')}</summary>
|
||||
<div className="an-compute-fields">
|
||||
<Field title={t('观测年份', 'Observation year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(row.year) ? row.year : ''}
|
||||
onChange={event => updateObservation(index, { ...row, year: event.target.valueAsNumber })} /></Field>
|
||||
<Field title={t('指标', 'Metric')}><Select value={row.metric} options={(['global_share', 'absolute'] as const).map(metric => ({ value: metric, label: metricLabel(metric) }))}
|
||||
onValueChange={value => updateObservation(index, { ...row, metric: value as ComputeObservation['metric'] })} /></Field>
|
||||
{sourceSelect(row.source_id, value => updateObservation(index, { ...row, source_id: value }))}
|
||||
</div>
|
||||
<div className="an-compute-values">
|
||||
{Object.entries(row.values).map(([code, value]) => <div className="an-compute-value" key={code}>
|
||||
<Field title={saved.countries.find(country => country.code === code)?.[english ? 'name_en' : 'name'] || code}>
|
||||
<Input type="number" required min={0} max={row.metric === 'global_share' ? 100 : 1e12} step="any" value={Number.isFinite(value) ? value : ''}
|
||||
onChange={event => updateObservation(index, { ...row, values: { ...row.values, [code]: event.target.valueAsNumber } })} />
|
||||
</Field>
|
||||
{removeButton(t(`移除 ${code} 观测`, `Remove ${code} observation`), () => {
|
||||
const values = { ...row.values }; delete values[code]; updateObservation(index, { ...row, values })
|
||||
})}
|
||||
</div>)}
|
||||
</div>
|
||||
<div className="an-compute-row-actions">
|
||||
<Select value="" placeholder={t('添加国家观测', 'Add country observation')}
|
||||
options={saved.countries.filter(country => !(country.code in row.values)).map(country => ({ value: country.code, label: english ? country.name_en : country.name }))}
|
||||
onValueChange={code => updateObservation(index, { ...row, values: { ...row.values, [code]: Number.NaN } })} />
|
||||
{removeButton(t('移除年度观测', 'Remove annual observation'), () => edit({ ...draft, observations: draft.observations.filter((_, i) => i !== index) }))}
|
||||
</div>
|
||||
</details>)}
|
||||
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, observations: [...draft.observations, { year: new Date().getFullYear(), metric: 'global_share', source_id: sources[0]?.value || '', values: {} }] })}>
|
||||
<Plus size={15} />{t('添加年度观测', 'Add annual observation')}</Button>
|
||||
</> : view === 'sources' ? <>
|
||||
{draft.sources.map((source, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
|
||||
<summary>{source.title || t('新报告', 'New report')} · {source.report_year}</summary>
|
||||
<div className="an-compute-fields">
|
||||
{(['title', 'publisher', 'url', 'locator'] as const).map((key, fieldIndex) => <Field key={key} title={[
|
||||
t('报告标题', 'Report title'), t('发布机构', 'Publisher'), t('报告链接', 'Report URL'), t('页码 / 图表位置', 'Page / figure locator'),
|
||||
][fieldIndex]}><Input required type={key === 'url' ? 'url' : 'text'} maxLength={key === 'url' ? 2000 : 500}
|
||||
value={source[key]}
|
||||
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, [key]: event.target.value } : item) })} /></Field>)}
|
||||
<Field title={t('报告年份', 'Report year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(source.report_year) ? source.report_year : ''}
|
||||
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, report_year: event.target.valueAsNumber } : item) })} /></Field>
|
||||
<Field title={t('发布日期(可选)', 'Publication date (optional)')}><Input type="date" value={source.published_at || ''}
|
||||
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, published_at: event.target.value || null } : item) })} /></Field>
|
||||
</div>
|
||||
{removeButton(reportIsUsed(draft, source.id) ? t('该来源仍被观测引用', 'Source is referenced by observations') : t('移除报告', 'Remove report'),
|
||||
() => edit({ ...draft, sources: draft.sources.filter((_, i) => i !== index) }), reportIsUsed(draft, source.id))}
|
||||
</details>)}
|
||||
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, sources: [...draft.sources, { id: `report-${crypto.randomUUID()}`, title: '', publisher: '', url: '', locator: '', report_year: new Date().getFullYear(), published_at: null }] })}>
|
||||
<Plus size={15} />{t('添加报告来源', 'Add report source')}</Button>
|
||||
</> : <>
|
||||
<p>{t('美国减中国的创新指数分差,与算力占比独立,不反推单国得分。', 'US minus China innovation index gap. Independent of compute shares; individual scores are not inferred.')}</p>
|
||||
{draft.innovation.map((row, index) => <div className="an-compute-row" key={index}>
|
||||
<div className="an-compute-fields">
|
||||
<Field title={t('观测年份', 'Observation year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(row.year) ? row.year : ''}
|
||||
onChange={event => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, year: event.target.valueAsNumber } : item) })} /></Field>
|
||||
<Field title={t('指数分差', 'Index gap')}><Input type="number" required min={-100} max={100} step="any" value={Number.isFinite(row.value) ? row.value : ''}
|
||||
onChange={event => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, value: event.target.valueAsNumber } : item) })} /></Field>
|
||||
{sourceSelect(row.source_id, value => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, source_id: value } : item) }))}
|
||||
</div>
|
||||
{removeButton(t('移除创新观测', 'Remove innovation observation'), () => edit({ ...draft, innovation: draft.innovation.filter((_, i) => i !== index) }))}
|
||||
</div>)}
|
||||
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, innovation: [...draft.innovation, { year: new Date().getFullYear(), value: Number.NaN, source_id: sources[0]?.value || '' }] })}>
|
||||
<Plus size={15} />{t('添加创新观测', 'Add innovation observation')}</Button>
|
||||
</>}
|
||||
</fieldset>
|
||||
</Scrollbar>
|
||||
</> : null}
|
||||
</form>
|
||||
<ConfirmDialog open={confirmation !== null} onOpenChange={open => !open && setConfirmation(null)} loading={busy}
|
||||
title={confirmation === 'reset' ? t('恢复内置报告数据?', 'Restore bundled report data?') : t('放弃草稿并重新加载?', 'Discard draft and reload?')}
|
||||
description={t('当前未发布修改将被替换。恢复默认会记录在操作审计中。', 'Unpublished edits will be replaced. Restoring defaults is audited.')}
|
||||
onConfirm={() => { if (confirmation === 'reset') void publish(true); else { setConfirmation(null); reload() } }} />
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
@@ -44,6 +44,7 @@ import { AdminSwitch } from '../components/ui/switch'
|
||||
import { ControlGroup as TactileControlGroup } from '../../components/tactile-ui'
|
||||
import { useToast } from '../components/ui/toast'
|
||||
import { DetailPanel, EmptyState, PageFrame, Panel, StatCell, StatusText, SummaryStrip } from '../patterns/patterns'
|
||||
import { ComputeComparisonSettings } from './ComputeComparisonSettings'
|
||||
|
||||
type AnyRecord = Record<string, unknown>
|
||||
type Tone = 'success' | 'warning' | 'danger' | 'info' | 'neutral' | 'running' | 'ai'
|
||||
@@ -3486,6 +3487,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
|
||||
const activeSection = useMemo(() => config.sections.find((section) => section.key === activeSectionKey) ?? config.sections[0], [activeSectionKey, config.sections])
|
||||
const activeState = useMemo(() => states.find((state) => state.section.key === activeSection?.key), [activeSection?.key, states])
|
||||
const isComputeConfigSection = config === configs.earthContent && activeSection?.key === 'compute_comparison'
|
||||
const rows = activeState?.rows ?? []
|
||||
const isDatasourceBuiltinSection = config === configs.datasources && activeSection?.key === 'builtin'
|
||||
const selectedDatasourceRows = useMemo(
|
||||
@@ -7142,9 +7144,9 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
className="an-resource-page"
|
||||
actions={(
|
||||
<>
|
||||
<Button size="icon" variant="subtle" onClick={() => void load()} loading={loading} title={localizeAdminText('刷新', locale)} aria-label={localizeAdminText('刷新', locale)}><RefreshCw size={15} /></Button>
|
||||
{!isComputeConfigSection ? <Button size="icon" variant="subtle" onClick={() => void load()} loading={loading} title={localizeAdminText('刷新', locale)} aria-label={localizeAdminText('刷新', locale)}><RefreshCw size={15} /></Button> : null}
|
||||
{renderCollectionQueueAction()}
|
||||
{moduleActions}
|
||||
{!isComputeConfigSection ? moduleActions : null}
|
||||
{config.actions.map((action) => (
|
||||
<Button key={action.label} asChild size="icon" variant="subtle" title={localizeAdminText(action.label, locale)} aria-label={localizeAdminText(action.label, locale)}>
|
||||
<Link to={action.to}>{action.icon}</Link>
|
||||
@@ -7154,17 +7156,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
)}
|
||||
>
|
||||
<div className="an-page-grid">
|
||||
<SummaryStrip>
|
||||
{!isComputeConfigSection ? <SummaryStrip>
|
||||
<StatCell label={localizeAdminText('接口在线', locale)} value={`${summary.online}/${states.length || 1}`} hint={localizeAdminText('已加载分区', locale)} />
|
||||
<StatCell label={localizeAdminText('记录数', locale)} value={summary.rows} hint={localizeAdminText('已加载分区汇总', locale)} />
|
||||
<StatCell label={localizeAdminText('异常接口', locale)} value={summary.failing} hint={localizeAdminText('失败时页面仍可操作', locale)} />
|
||||
</SummaryStrip>
|
||||
</SummaryStrip> : null}
|
||||
|
||||
<SectionTabs sections={config.sections} states={states} activeKey={activeSection?.key || ''} onChange={handleSectionChange} />
|
||||
{renderDatasourceFilters()}
|
||||
</div>
|
||||
|
||||
{isPlaygroundSection ? (
|
||||
{config === configs.earthContent ? <ComputeComparisonSettings active={isComputeConfigSection} /> : null}
|
||||
{isComputeConfigSection ? null : isPlaygroundSection ? (
|
||||
<PlaygroundLite />
|
||||
) : isHierarchySection ? (
|
||||
config === configs.ai ? renderAIHierarchy() : renderConfigHierarchy()
|
||||
@@ -7501,12 +7504,13 @@ const configs = {
|
||||
},
|
||||
earthContent: {
|
||||
title: '智能星球内容',
|
||||
description: '管理智能星球品牌、边界、电视内容和内容资产。',
|
||||
description: '管理智能星球品牌、算力对比、边界、电视内容和内容资产。',
|
||||
listTitle: '智能星球内容配置',
|
||||
listDescription: '只展示智能星球品牌、边界构建和电视内容配置。',
|
||||
listDescription: '选择内容分区,维护展示配置与报告数据。',
|
||||
viewMode: 'management',
|
||||
sections: [
|
||||
{ key: 'brand', label: '品牌标识', url: '/earth/brand', map: (payload) => singleRow(payload, 'brand', { __title: '品牌配置', __module: '品牌' }).map((row) => ({ ...row, __title: '品牌配置', __module: '品牌', __status: '已读取' })) },
|
||||
{ key: 'compute_comparison', label: '算力对比', map: emptyRows },
|
||||
{ key: 'about', label: '关于', url: '/earth/about', map: (payload) => singleRow(payload, 'about', { __title: '关于配置', __module: '关于' }).map((row) => ({ ...row, __title: '关于配置', __module: '关于', __status: '已读取' })) },
|
||||
{
|
||||
key: 'earth_assets',
|
||||
|
||||
47
frontend/src/admin/pages/compute-comparison-model.ts
Normal file
47
frontend/src/admin/pages/compute-comparison-model.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
export interface ComputeSource {
|
||||
id: string
|
||||
title: string
|
||||
url: string
|
||||
publisher: string
|
||||
report_year: number
|
||||
published_at: string | null
|
||||
locator: string
|
||||
}
|
||||
|
||||
export interface ComputeObservation {
|
||||
year: number
|
||||
metric: 'global_share' | 'absolute'
|
||||
source_id: string
|
||||
values: Record<string, number>
|
||||
}
|
||||
|
||||
export interface InnovationObservation {
|
||||
year: number
|
||||
value: number
|
||||
source_id: string
|
||||
}
|
||||
|
||||
export interface ComputeConfiguration {
|
||||
reviewed_at: string
|
||||
sources: ComputeSource[]
|
||||
observations: ComputeObservation[]
|
||||
innovation: InnovationObservation[]
|
||||
}
|
||||
|
||||
export interface ComputeConfigurationResponse {
|
||||
config: ComputeConfiguration
|
||||
revision: string
|
||||
is_default: boolean
|
||||
countries: Array<{ code: string; name: string; name_en: string }>
|
||||
}
|
||||
|
||||
export function reportIsUsed(config: ComputeConfiguration, id: string) {
|
||||
return [...config.observations, ...config.innovation].some(row => row.source_id === id)
|
||||
}
|
||||
|
||||
export function notifyComputeConfigurationChanged() {
|
||||
if (typeof BroadcastChannel === 'undefined') return
|
||||
const channel = new BroadcastChannel('planet-compute-configuration')
|
||||
channel.postMessage({ type: 'updated' })
|
||||
channel.close()
|
||||
}
|
||||
28
frontend/src/admin/pages/compute-comparison.css
Normal file
28
frontend/src/admin/pages/compute-comparison.css
Normal file
@@ -0,0 +1,28 @@
|
||||
.an-compute-settings {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.an-compute-settings[hidden] { display: none; }
|
||||
.an-compute-form { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
||||
.an-compute-heading { flex-wrap: wrap; gap: 12px; }
|
||||
.an-compute-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.an-compute-toolbar { display: flex; flex-wrap: wrap; gap: 12px; justify-content: space-between; padding: 12px 16px; }
|
||||
.an-compute-status, .an-compute-error { padding: 8px 16px; margin: 0; overflow-wrap: anywhere; }
|
||||
.an-compute-error { color: var(--an-danger, #b42318); max-height: 100px; overflow: auto; }
|
||||
.an-compute-scroll { flex: 1; min-height: 0; min-width: 0; }
|
||||
.an-compute-content { min-width: 0; margin: 0; padding: 0 16px 16px; border: 0; }
|
||||
.an-compute-row { border-bottom: 1px solid var(--an-border); padding: 12px 0; }
|
||||
.an-compute-row summary { cursor: pointer; padding: 8px 0; overflow-wrap: anywhere; }
|
||||
.an-compute-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 12px 0; }
|
||||
.an-compute-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; font-size: 13px; }
|
||||
.an-compute-field .an-input, .an-compute-field .an-select { width: 100%; min-width: 0; }
|
||||
.an-compute-values { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
||||
.an-compute-value { display: flex; align-items: end; gap: 4px; min-width: 0; }
|
||||
.an-compute-value .an-compute-field { flex: 1; }
|
||||
.an-compute-row-actions { display: flex; align-items: center; gap: 12px; margin: 12px 0; }
|
||||
.an-compute-row-actions .an-select { flex: 1; min-width: 0; }
|
||||
@media (max-width: 680px) {
|
||||
.an-compute-fields, .an-compute-values { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
export const legacyUiTextEnUS: Record<string, string> = {
|
||||
'算力对比': 'Compute comparison',
|
||||
'管理智能星球品牌、算力对比、边界、电视内容和内容资产。': 'Manage Intelligent Planet branding, compute comparison, boundaries, TV and content assets.',
|
||||
'选择内容分区,维护展示配置与报告数据。': 'Choose a section to maintain display configuration and report data.',
|
||||
'OpenAI Chat Completions': 'OpenAI Chat Completions',
|
||||
'OpenAI Responses': 'OpenAI Responses',
|
||||
'AI Provider连通性正常': 'AI Provider connectivity OK',
|
||||
|
||||
28
planet.cmd
28
planet.cmd
@@ -1,18 +1,12 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
|
||||
net session >nul 2>&1
|
||||
if not "%errorlevel%"=="0" (
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$script = '%~f0'; $arg = '-NoExit -NoProfile -ExecutionPolicy Bypass -Command ""& { & ''' + $script + ''' --elevated }""'; if (Get-Command wt.exe -ErrorAction SilentlyContinue) { Start-Process wt.exe -Verb RunAs -ArgumentList @('powershell.exe', $arg) } else { Start-Process powershell.exe -Verb RunAs -ArgumentList $arg }"
|
||||
exit /b
|
||||
)
|
||||
|
||||
if /i "%~1"=="--elevated" shift
|
||||
|
||||
echo Starting Planet in WSL as Administrator...
|
||||
echo This window will stay inside WSL after startup. Close it manually when you are done.
|
||||
echo.
|
||||
|
||||
wsl.exe -d Ubuntu --cd /home/linkong/planet -- zsh -lic "./planet.sh restart --allow-lan; planet_exit=\$?; echo; if [ \$planet_exit -eq 0 ]; then echo 'Planet restart finished successfully.'; powershell.exe -NoProfile -Command 'Start-Process "http://localhost:3000/earth"'; else echo \"Planet restart failed with exit code \$planet_exit.\"; fi; echo; echo 'Staying in WSL. Close this terminal manually when you are done.'; exec zsh -l"
|
||||
|
||||
exit /b %errorlevel%
|
||||
setlocal EnableExtensions DisableDelayedExpansion
|
||||
set "PLANET_LAUNCHER_SOURCE=%~f0"
|
||||
set "PLANET_LAUNCHER_INSTALL_ONLY="
|
||||
if /i "%~1"=="--install-only" set "PLANET_LAUNCHER_INSTALL_ONLY=1"
|
||||
set "PLANET_POWERSHELL=powershell.exe"
|
||||
where.exe pwsh.exe >nul 2>&1
|
||||
if not errorlevel 1 set "PLANET_POWERSHELL=pwsh.exe"
|
||||
%PLANET_POWERSHELL% -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "& (Join-Path (Split-Path -LiteralPath $env:PLANET_LAUNCHER_SOURCE) 'scripts\windows\planet-launcher.ps1') -InstallOnly:($env:PLANET_LAUNCHER_INSTALL_ONLY -eq '1')"
|
||||
set "planet_launcher_exit=%errorlevel%"
|
||||
if not "%planet_launcher_exit%"=="0" pause
|
||||
exit /b %planet_launcher_exit%
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "planet"
|
||||
version = "0.75.0"
|
||||
version = "0.75.2"
|
||||
description = "智能星球计划 - 态势感知系统"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
|
||||
35
rules.md
35
rules.md
@@ -169,6 +169,41 @@ Always.
|
||||
- Keep confirmed operational failure causes in the error catalog in `docs/technical/{zh,en}/ops-runbook.md`. `planet.sh` diagnostics must read causes and remedies from this catalog. Add a stable error code, matching evidence, and a regression case when fixing a previously unclassified cause; unknown failures must remain explicitly unclassified until verified.
|
||||
- If a harness rule is no longer true for the current toolchain, update or delete it in the same cleanup pass.
|
||||
|
||||
### Coding Agent Model Strategy
|
||||
|
||||
This policy applies to repository development agents, not the product's
|
||||
`aiprovider` model settings. Preserve the user's selected main-agent model;
|
||||
these preferences do not switch a running task or change global Codex settings.
|
||||
|
||||
When delegation is explicitly authorized by the user or an applicable skill,
|
||||
select workers by task scope and verification difficulty:
|
||||
|
||||
| Work | Preferred model | Initial reasoning effort |
|
||||
| --- | --- | --- |
|
||||
| Bounded implementation, ordinary bug fixes, focused tests, code review | `gpt-6-sol` | `medium`; `high` for interacting modules |
|
||||
| Narrow file discovery, evidence extraction, mechanical docs updates, small deterministic edits | `gpt-6-luna` | `low` or `medium` |
|
||||
| Architecture, ambiguous requirements, difficult rendering/performance bugs, security-sensitive reasoning, repeated failed fixes | `gpt-6-astra` | `high`; increase only when evidence justifies it |
|
||||
|
||||
- These are project routing preferences, not measured Planet benchmarks.
|
||||
Model roles follow [OpenAI model guidance](https://developers.openai.com/api/docs/models),
|
||||
checked on 2026-09-23. Use the actual host/tool model and effort catalog;
|
||||
API-supported settings do not automatically imply Codex tool support.
|
||||
- Keep small or tightly coupled tasks with the main agent. Delegate only bounded,
|
||||
independent work that can progress alongside useful main-agent work; avoid
|
||||
parallel edits to the same files and do not create agents merely to fill slots.
|
||||
- Give each worker its objective, owned paths, constraints, relevant evidence,
|
||||
and acceptance checks. Prefer a concise handoff over copying the entire history.
|
||||
- Start directly with the model appropriate to the risk. Escalate Luna to Sol,
|
||||
or Sol to Astra, when scope exceeds the assigned task or a failed verification
|
||||
remains unresolved after one focused correction. Pass the reproduction,
|
||||
attempted fixes, and remaining uncertainty; do not repeat blind retries.
|
||||
- The main agent owns integration and final verification. Luna findings are
|
||||
evidence inputs, not sole sign-off for security, migrations, releases, or
|
||||
complex Earth rendering. All tiers retain the same test and visual gates.
|
||||
- If the preferred model is unavailable, use the current capable model and
|
||||
disclose the fallback. Do not silently downgrade or assume older model names
|
||||
are aliases. Record actual validation outcomes rather than promising savings.
|
||||
|
||||
### Git
|
||||
|
||||
- Do not revert user changes unless explicitly requested.
|
||||
|
||||
@@ -913,6 +913,16 @@ function apiPayloadFor(requestUrl, method) {
|
||||
if (path === '/ai/playground/thread') return jsonResponse({ messages: [], session: { state: {} } })
|
||||
|
||||
if (path === '/earth/brand') return jsonResponse({ brand: { title: '智能星球', subtitle: 'Smoke', logo_alt: 'Planet' } })
|
||||
if (path === '/data-products/compute/configuration') return jsonResponse({
|
||||
config: JSON.parse(readRepoText('backend/app/services/compute_history_defaults.json')),
|
||||
revision: 'compute-configuration-smoke',
|
||||
is_default: true,
|
||||
countries: [
|
||||
{ code: 'CN', name: '中国', name_en: 'China' },
|
||||
{ code: 'US', name: '美国', name_en: 'United States' },
|
||||
{ code: 'JP', name: '日本', name_en: 'Japan' },
|
||||
],
|
||||
})
|
||||
if (path === '/earth/about') return jsonResponse({ about: { title: '智能星球', version: 'smoke', description: 'Harness smoke.' } })
|
||||
if (path === '/earth/boundaries/status') return jsonResponse({ status: 'ready', provider: 'low', updated_at: now })
|
||||
if (path === '/earth/boundaries/build/status') return jsonResponse({ status: 'idle', progress: 0 })
|
||||
|
||||
@@ -17,11 +17,13 @@ main() {
|
||||
harness_run zsh -n scripts/lib/docker-proxy.zsh
|
||||
harness_run zsh -n scripts/lib/docker-mirror.zsh
|
||||
harness_run zsh -n scripts/lib/error-diagnostics.zsh
|
||||
harness_run zsh -n scripts/windows/restart.zsh
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_bootstrap.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_command.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_proxy.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_mirror.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_database_startup.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_windows_restart.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_error_diagnostics.py
|
||||
harness_run bash -n scripts/bootstrap-dev.sh
|
||||
harness_run bash -n scripts/harness/lib.sh
|
||||
|
||||
127
scripts/harness/test_windows_launcher.ps1
Normal file
127
scripts/harness/test_windows_launcher.ps1
Normal file
@@ -0,0 +1,127 @@
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PSScriptRoot '..\windows\planet-launcher.ps1')
|
||||
|
||||
function Assert-Equal($Expected, $Actual, $Label) {
|
||||
if ($Expected -cne $Actual) { throw "$Label expected [$Expected], got [$Actual]" }
|
||||
}
|
||||
|
||||
foreach ($prefix in @('\\wsl$\', '\\wsl.localhost\')) {
|
||||
$target = Get-PlanetTarget ($prefix + 'Ubuntu-24.04\home\alice\planet app')
|
||||
Assert-Equal 'Ubuntu-24.04' $target.Distro 'UNC distribution'
|
||||
Assert-Equal '/home/alice/planet app' $target.LinuxProjectRoot 'UNC Linux path'
|
||||
}
|
||||
$specialRoot = '/home/alice/planet ' + [char]0x5730 + [char]0x7403 + " ' & % ! `$ (demo)"
|
||||
$target = Get-PlanetTarget ('\\wsl$\Debian' + $specialRoot.Replace('/', '\'))
|
||||
Assert-Equal $specialRoot $target.LinuxProjectRoot 'Special characters'
|
||||
|
||||
function Invoke-WslText {
|
||||
param([string[]]$Arguments)
|
||||
if ($Arguments[1] -eq 'printenv') { return 'Ubuntu' }
|
||||
Assert-Equal 'C:\Projects\Planet Space' $Arguments[-1] 'Windows path remains one argument'
|
||||
return '/mnt/c/Projects/Planet Space'
|
||||
}
|
||||
$driveTarget = Get-PlanetTarget 'C:\Projects\Planet Space'
|
||||
Assert-Equal 'Ubuntu' $driveTarget.Distro 'Default distribution'
|
||||
Assert-Equal '/mnt/c/Projects/Planet Space' $driveTarget.LinuxProjectRoot 'Mounted drive'
|
||||
|
||||
foreach ($elevated in @($false, $true)) {
|
||||
$bootstrap = Get-PlanetBootstrap $target -RunElevated:$elevated
|
||||
$tokens = $null; $errors = $null
|
||||
[void][Management.Automation.Language.Parser]::ParseInput($bootstrap, [ref]$tokens, [ref]$errors)
|
||||
if ($errors.Count) { throw ($errors | Out-String) }
|
||||
$encoded = ConvertTo-PlanetEncodedCommand $bootstrap
|
||||
Assert-Equal $bootstrap ([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encoded))) 'Encoded command roundtrip'
|
||||
if ($bootstrap.Contains($specialRoot)) { throw 'Project path must remain encoded data' }
|
||||
$match = [regex]::Match($bootstrap, "FromBase64String\('([A-Za-z0-9+/=]+)'\)")
|
||||
$decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($match.Groups[1].Value)) | ConvertFrom-Json
|
||||
Assert-Equal $specialRoot $decoded.LinuxProjectRoot 'Bound target roundtrip'
|
||||
}
|
||||
|
||||
function Test-PlanetAdministrator { return $true }
|
||||
function wsl.exe {
|
||||
$script:CapturedWslArguments = $args
|
||||
$global:LASTEXITCODE = 17
|
||||
Write-Output 'live-wsl-output'
|
||||
}
|
||||
$liveOutput = Start-PlanetRestart $target -AlreadyElevated
|
||||
Assert-Equal 'live-wsl-output' $liveOutput 'WSL output is streamed, not returned as an exit-code array'
|
||||
Assert-Equal 17 $script:PlanetLauncherExitCode 'WSL exit status preserved'
|
||||
Assert-Equal $specialRoot $script:CapturedWslArguments[3] 'Working directory is one native argument'
|
||||
Assert-Equal ($specialRoot + '/scripts/windows/restart.zsh') $script:CapturedWslArguments[8] 'Bridge path is one native argument'
|
||||
|
||||
$testDirectory = Join-Path ([IO.Path]::GetTempPath()) ('planet-launcher-tests-' + [guid]::NewGuid().ToString('N'))
|
||||
[void][IO.Directory]::CreateDirectory($testDirectory)
|
||||
try {
|
||||
$launcher = Install-PlanetDesktopLauncher $target -Desktop $testDirectory
|
||||
Assert-Equal 'Planet.cmd' ([IO.Path]::GetFileName($launcher)) 'First install'
|
||||
$content = [IO.File]::ReadAllText($launcher)
|
||||
if ($content -notmatch 'DisableDelayedExpansion' -or $content -notmatch '--install-only') {
|
||||
throw 'Generated launcher lacks safe CMD mode or install-only option'
|
||||
}
|
||||
Assert-Equal $launcher (Install-PlanetDesktopLauncher $target -Desktop $testDirectory) 'Repeat install'
|
||||
$other = Install-PlanetDesktopLauncher $driveTarget -Desktop $testDirectory
|
||||
if ($other -eq $launcher) { throw 'Different projects must not overwrite each other' }
|
||||
Assert-Equal $content ([IO.File]::ReadAllText($launcher)) 'Original target preserved'
|
||||
[IO.File]::WriteAllText($launcher, 'unrelated user file')
|
||||
$alternate = Install-PlanetDesktopLauncher $target -Desktop $testDirectory
|
||||
if ($alternate -eq $launcher) { throw 'Unrelated file overwritten' }
|
||||
Assert-Equal 'unrelated user file' ([IO.File]::ReadAllText($launcher)) 'User file preserved'
|
||||
$missing = @{ Distro = 'Ubuntu'; LinuxProjectRoot = '/missing/planet-launcher-test-' + [guid]::NewGuid() }
|
||||
try { Assert-PlanetTarget $missing; throw 'Missing project accepted' }
|
||||
catch { if ($_.Exception.Message -notmatch 'P_WINDOWS_LAUNCHER_TARGET_MISSING') { throw } }
|
||||
Write-Host 'PASS: UNC aliases, drive mapping, special paths, encoding, repeat installation, collisions, missing project'
|
||||
} finally {
|
||||
$resolved = [IO.Path]::GetFullPath($testDirectory)
|
||||
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
|
||||
if (-not $resolved.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -or
|
||||
[IO.Path]::GetFileName($resolved) -notlike 'planet-launcher-tests-*') { throw 'Unsafe cleanup path' }
|
||||
Remove-Item -LiteralPath $resolved -Recurse -Force
|
||||
}
|
||||
|
||||
function Get-Command {
|
||||
param([string]$Name, [string]$CommandType, [string]$ErrorAction)
|
||||
if ($script:AvailableLaunchCommands.ContainsKey($Name)) {
|
||||
return [pscustomobject]@{ Source = $script:AvailableLaunchCommands[$Name] }
|
||||
}
|
||||
}
|
||||
$pwshPath = 'C:\Program Files\PowerShell\7\pwsh.exe'
|
||||
$terminalPath = 'C:\Users\Test\AppData\Local\Microsoft\WindowsApps\wt.exe'
|
||||
$legacyPath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
|
||||
foreach ($hasTerminal in @($true, $false)) {
|
||||
foreach ($hasPwsh in @($true, $false)) {
|
||||
$script:AvailableLaunchCommands = @{ 'powershell.exe' = $legacyPath }
|
||||
if ($hasTerminal) { $script:AvailableLaunchCommands['wt.exe'] = $terminalPath }
|
||||
if ($hasPwsh) { $script:AvailableLaunchCommands['pwsh.exe'] = $pwshPath }
|
||||
$launch = Get-PlanetTerminalLaunch 'TESTPAYLOAD'
|
||||
$expectedShell = if ($hasPwsh) { $pwshPath } else { $legacyPath }
|
||||
$expectedExecutable = if ($hasTerminal) { $terminalPath } else { $expectedShell }
|
||||
Assert-Equal $expectedExecutable $launch.FilePath 'Terminal/shell priority'
|
||||
if ($hasTerminal -and -not $launch.ArgumentList.Contains('"' + $expectedShell + '"')) {
|
||||
throw 'Terminal shell path must be quoted, including Program Files paths'
|
||||
}
|
||||
if ($launch.ArgumentList -notmatch '-EncodedCommand TESTPAYLOAD$') {
|
||||
throw 'Encoded bootstrap was not preserved'
|
||||
}
|
||||
}
|
||||
}
|
||||
function Test-PlanetAdministrator { return $script:IsTestAdministrator }
|
||||
function Start-Process {
|
||||
param($FilePath, $ArgumentList, $WindowStyle, $Verb)
|
||||
$script:CapturedLaunch = @{ FilePath = $FilePath; ArgumentList = $ArgumentList; Verb = $Verb }
|
||||
$script:LaunchCount++
|
||||
}
|
||||
$script:AvailableLaunchCommands = @{ 'pwsh.exe' = $pwshPath; 'wt.exe' = $terminalPath }
|
||||
$script:LaunchCount = 0
|
||||
foreach ($isAdmin in @($false, $true)) {
|
||||
$script:IsTestAdministrator = $isAdmin
|
||||
Start-PlanetRestart $target
|
||||
Assert-Equal $terminalPath $script:CapturedLaunch.FilePath 'Admin and ordinary entry both use Terminal'
|
||||
if ($isAdmin -and $script:CapturedLaunch.Verb) { throw 'Already elevated entry must not request UAC again' }
|
||||
if (-not $isAdmin) { Assert-Equal 'RunAs' $script:CapturedLaunch.Verb 'Ordinary entry requires elevation' }
|
||||
}
|
||||
$script:IsTestAdministrator = $false
|
||||
try { Start-PlanetRestart $target -AlreadyElevated; throw 'Unelevated child accepted' }
|
||||
catch { if ($_.Exception.Message -ne 'Administrator elevation was not granted.') { throw } }
|
||||
Assert-Equal 2 $script:LaunchCount 'Child must not recursively launch more windows'
|
||||
Write-Host 'PASS: Terminal/PowerShell priority, quoted paths, elevation and no recursive dispatch'
|
||||
72
scripts/harness/test_windows_restart.py
Normal file
72
scripts/harness/test_windows_restart.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""Exercise the WSL bridge using disposable commands, never real services."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class WindowsRestartTests(unittest.TestCase):
|
||||
def run_bridge(self, exit_code, port_state):
|
||||
with tempfile.TemporaryDirectory(prefix="planet-windows-restart-") as temporary:
|
||||
root = Path(temporary) / "project space ' 地球"
|
||||
bridge = root / "scripts/windows/restart.zsh"
|
||||
bridge.parent.mkdir(parents=True)
|
||||
shutil.copyfile(ROOT / "scripts/windows/restart.zsh", bridge)
|
||||
commands = root / "bin"
|
||||
commands.mkdir()
|
||||
log = root / "calls.log"
|
||||
state = root / "state"
|
||||
state.mkdir()
|
||||
(state / "ports.env").write_text(port_state)
|
||||
scripts = {
|
||||
root
|
||||
/ "planet.sh": '#!/bin/sh\nprintf "restart:%s:%s\\n" "$PWD" "$*" >> "$TEST_LOG"\nexit '
|
||||
+ str(exit_code),
|
||||
commands
|
||||
/ "powershell.exe": '#!/bin/sh\nprintf "browser:%s\\n" "$PLANET_LAUNCH_URL" >> "$TEST_LOG"',
|
||||
commands / "zsh": '#!/bin/sh\nprintf "shell:%s\\n" "$*" >> "$TEST_LOG"',
|
||||
}
|
||||
for path, body in scripts.items():
|
||||
path.write_text(body + "\n")
|
||||
path.chmod(0o755)
|
||||
result = subprocess.run(
|
||||
["/usr/bin/zsh", str(bridge)],
|
||||
cwd="/tmp",
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env={
|
||||
**os.environ,
|
||||
"PATH": str(commands) + ":/usr/bin:/bin",
|
||||
"TEST_LOG": str(log),
|
||||
"PLANET_STATE_DIR": str(state),
|
||||
},
|
||||
timeout=15,
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
calls = log.read_text()
|
||||
self.assertIn(f"restart:{root}:restart --allow-lan", calls)
|
||||
self.assertIn("shell:-l", calls)
|
||||
return calls, result.stdout
|
||||
|
||||
def test_success_uses_actual_frontend_port_and_scheme(self):
|
||||
calls, output = self.run_bridge(0, "FRONTEND_PORT=4177\nFRONTEND_SCHEME=https\n")
|
||||
self.assertIn("browser:https://localhost:4177/earth", calls)
|
||||
self.assertIn("successfully", output)
|
||||
|
||||
def test_failure_keeps_shell_without_opening_browser(self):
|
||||
calls, output = self.run_bridge(7, "FRONTEND_PORT=4177\n")
|
||||
self.assertNotIn("browser:", calls)
|
||||
self.assertIn("failed with exit code 7", output)
|
||||
|
||||
def test_port_state_is_not_executed_as_shell_code(self):
|
||||
calls, _ = self.run_bridge(0, "FRONTEND_PORT=$(exit 91)\nFRONTEND_SCHEME=javascript\n")
|
||||
self.assertIn("browser:http://localhost:3000/earth", calls)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
196
scripts/windows/planet-launcher.ps1
Normal file
196
scripts/windows/planet-launcher.ps1
Normal file
@@ -0,0 +1,196 @@
|
||||
param(
|
||||
[string]$Distro,
|
||||
[string]$LinuxProjectRoot,
|
||||
[switch]$FromDesktop,
|
||||
[switch]$InstallOnly,
|
||||
[switch]$Elevated
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
$script:PlanetTargetFingerprintLength = 12
|
||||
|
||||
function Invoke-WslText {
|
||||
param([string[]]$Arguments)
|
||||
$output = & wsl.exe @Arguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL command failed (exit $LASTEXITCODE). Check the distribution and project directory."
|
||||
}
|
||||
return ($output -join "`n").Trim()
|
||||
}
|
||||
|
||||
function Get-PlanetTarget {
|
||||
param([string]$WindowsRoot)
|
||||
if ($WindowsRoot -match '^\\\\(?:wsl\$|wsl\.localhost)\\([^\\]+)(\\.*)?$') {
|
||||
$root = if ($Matches[2]) { $Matches[2].Replace('\', '/') } else { '/' }
|
||||
return @{ Distro = $Matches[1]; LinuxProjectRoot = $root.TrimEnd('/') }
|
||||
}
|
||||
if ($WindowsRoot -notmatch '^[a-zA-Z]:\\') {
|
||||
throw 'Run planet.cmd from a WSL project folder or a local Windows drive.'
|
||||
}
|
||||
$distribution = Invoke-WslText -Arguments @('--exec', 'printenv', 'WSL_DISTRO_NAME')
|
||||
$root = Invoke-WslText -Arguments @('-d', $distribution, '--exec', 'wslpath', '-a', '-u', $WindowsRoot)
|
||||
return @{ Distro = $distribution; LinuxProjectRoot = $root.TrimEnd('/') }
|
||||
}
|
||||
|
||||
function Get-PlanetWindowsRoot {
|
||||
param([hashtable]$Target)
|
||||
if ([string]::IsNullOrWhiteSpace($Target.Distro) -or
|
||||
$Target.Distro -match '[\\/\r\n]' -or
|
||||
$Target.LinuxProjectRoot -notmatch '^/' -or
|
||||
$Target.LinuxProjectRoot -match '[\r\n]') {
|
||||
throw 'Invalid WSL distribution or absolute project path.'
|
||||
}
|
||||
return '\\wsl$\' + $Target.Distro + $Target.LinuxProjectRoot.Replace('/', '\')
|
||||
}
|
||||
|
||||
function Assert-PlanetTarget {
|
||||
param([hashtable]$Target)
|
||||
$windowsRoot = Get-PlanetWindowsRoot $Target
|
||||
foreach ($relative in @('planet.sh', 'scripts\windows\planet-launcher.ps1', 'scripts\windows\restart.zsh')) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $windowsRoot $relative) -PathType Leaf)) {
|
||||
throw "P_WINDOWS_LAUNCHER_TARGET_MISSING: $windowsRoot\$relative. Run planet.cmd from the current project folder to regenerate the desktop launcher."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-PlanetBootstrap {
|
||||
param([hashtable]$Target, [switch]$RunElevated)
|
||||
# Only base64 crosses CMD/PowerShell command-line parsing; paths are data.
|
||||
$json = $Target | ConvertTo-Json -Compress
|
||||
$payload = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json))
|
||||
$elevatedFlag = if ($RunElevated) { '$true' } else { '$false' }
|
||||
return @"
|
||||
`$ErrorActionPreference = 'Stop'
|
||||
`$ProgressPreference = 'SilentlyContinue'
|
||||
try {
|
||||
`$target = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('$payload')) | ConvertFrom-Json
|
||||
`$root = '\\wsl$\' + `$target.Distro + `$target.LinuxProjectRoot.Replace('/', '\')
|
||||
`$helper = Join-Path `$root 'scripts\windows\planet-launcher.ps1'
|
||||
if (-not (Test-Path -LiteralPath `$helper -PathType Leaf)) {
|
||||
throw 'P_WINDOWS_LAUNCHER_TARGET_MISSING: Project moved or unavailable. Run planet.cmd from the current project folder again.'
|
||||
}
|
||||
& `$helper -Distro `$target.Distro -LinuxProjectRoot `$target.LinuxProjectRoot -FromDesktop -Elevated:$elevatedFlag -InstallOnly:(`$env:PLANET_LAUNCHER_INSTALL_ONLY -eq '1')
|
||||
exit `$LASTEXITCODE
|
||||
} catch {
|
||||
Write-Host `$_.Exception.Message -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
"@
|
||||
}
|
||||
|
||||
function ConvertTo-PlanetEncodedCommand {
|
||||
param([string]$Command)
|
||||
return [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($Command))
|
||||
}
|
||||
|
||||
function Install-PlanetDesktopLauncher {
|
||||
param([hashtable]$Target, [string]$Desktop = [Environment]::GetFolderPath('DesktopDirectory'))
|
||||
if (-not $Desktop -or -not (Test-Path -LiteralPath $Desktop -PathType Container)) {
|
||||
throw 'Windows Desktop folder is unavailable.'
|
||||
}
|
||||
$identity = $Target.Distro + "`n" + $Target.LinuxProjectRoot
|
||||
$sha256 = [Security.Cryptography.SHA256]::Create()
|
||||
try {
|
||||
$identityBytes = [Text.Encoding]::UTF8.GetBytes($identity)
|
||||
$fingerprint = [BitConverter]::ToString($sha256.ComputeHash($identityBytes)).Replace('-', '')
|
||||
$hash = $fingerprint.Substring(0, $script:PlanetTargetFingerprintLength)
|
||||
} finally {
|
||||
$sha256.Dispose()
|
||||
}
|
||||
$marker = "rem Planet managed launcher v1 target=$hash"
|
||||
$destination = Join-Path $Desktop 'Planet.cmd'
|
||||
if ((Test-Path -LiteralPath $destination) -and
|
||||
-not ([IO.File]::ReadAllText($destination).Contains($marker))) {
|
||||
$destination = Join-Path $Desktop "Planet-$hash.cmd"
|
||||
}
|
||||
if ((Test-Path -LiteralPath $destination) -and
|
||||
-not ([IO.File]::ReadAllText($destination).Contains($marker))) {
|
||||
throw "Refusing to overwrite an unrelated file: $destination"
|
||||
}
|
||||
$encoded = ConvertTo-PlanetEncodedCommand (Get-PlanetBootstrap $Target)
|
||||
$lines = @(
|
||||
'@echo off', 'setlocal EnableExtensions DisableDelayedExpansion', $marker,
|
||||
'set "PLANET_LAUNCHER_INSTALL_ONLY="',
|
||||
'if /i "%~1"=="--install-only" set "PLANET_LAUNCHER_INSTALL_ONLY=1"',
|
||||
'set "PLANET_POWERSHELL=powershell.exe"',
|
||||
'where.exe pwsh.exe >nul 2>&1',
|
||||
'if not errorlevel 1 set "PLANET_POWERSHELL=pwsh.exe"',
|
||||
"%PLANET_POWERSHELL% -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encoded",
|
||||
'set "planet_launcher_exit=%errorlevel%"',
|
||||
'if not "%planet_launcher_exit%"=="0" pause',
|
||||
'exit /b %planet_launcher_exit%'
|
||||
)
|
||||
[IO.File]::WriteAllText($destination, ($lines -join "`r`n") + "`r`n", [Text.Encoding]::ASCII)
|
||||
return $destination
|
||||
}
|
||||
|
||||
function Test-PlanetAdministrator {
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
|
||||
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||
}
|
||||
|
||||
function Get-PlanetTerminalLaunch {
|
||||
param([string]$EncodedCommand)
|
||||
$shell = Get-Command pwsh.exe -CommandType Application -ErrorAction SilentlyContinue |
|
||||
Select-Object -First 1
|
||||
if (-not $shell) {
|
||||
$shell = Get-Command powershell.exe -CommandType Application -ErrorAction Stop |
|
||||
Select-Object -First 1
|
||||
}
|
||||
$shellArguments = "-NoLogo -NoProfile -NoExit -ExecutionPolicy Bypass -EncodedCommand $EncodedCommand"
|
||||
$launch = @{ FilePath = $shell.Source; ArgumentList = $shellArguments; WindowStyle = 'Normal' }
|
||||
$terminal = Get-Command wt.exe -CommandType Application -ErrorAction SilentlyContinue |
|
||||
Select-Object -First 1
|
||||
if ($terminal) {
|
||||
$launch.FilePath = $terminal.Source
|
||||
# Start-Process joins arguments: quote the executable path explicitly.
|
||||
$launch.ArgumentList = '-w new new-tab --title Planet "' + $shell.Source + '" ' + $shellArguments
|
||||
}
|
||||
return $launch
|
||||
}
|
||||
|
||||
function Start-PlanetRestart {
|
||||
param([hashtable]$Target, [switch]$AlreadyElevated)
|
||||
$script:PlanetLauncherExitCode = 0
|
||||
$isAdministrator = Test-PlanetAdministrator
|
||||
if (-not $AlreadyElevated) {
|
||||
$encoded = ConvertTo-PlanetEncodedCommand (Get-PlanetBootstrap $Target -RunElevated)
|
||||
$launch = Get-PlanetTerminalLaunch $encoded
|
||||
if (-not $isAdministrator) { $launch.Verb = 'RunAs' }
|
||||
# An interactive terminal is intentional: startup logs and the WSL shell stay visible.
|
||||
Start-Process @launch | Out-Null
|
||||
return
|
||||
}
|
||||
if (-not $isAdministrator) { throw 'Administrator elevation was not granted.' }
|
||||
Write-Host "Restarting Planet in $($Target.Distro):$($Target.LinuxProjectRoot)"
|
||||
& wsl.exe -d $Target.Distro --cd $Target.LinuxProjectRoot --exec zsh -l -i ($Target.LinuxProjectRoot + '/scripts/windows/restart.zsh')
|
||||
$script:PlanetLauncherExitCode = $LASTEXITCODE
|
||||
}
|
||||
|
||||
if ($MyInvocation.InvocationName -ne '.') {
|
||||
try {
|
||||
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
||||
$OutputEncoding = [Console]::OutputEncoding
|
||||
if ($FromDesktop) {
|
||||
$target = @{ Distro = $Distro; LinuxProjectRoot = $LinuxProjectRoot }
|
||||
} else {
|
||||
$root = (Get-Item -LiteralPath (Join-Path $PSScriptRoot '..\..')).FullName
|
||||
$target = Get-PlanetTarget $root
|
||||
}
|
||||
Assert-PlanetTarget $target
|
||||
if (-not $FromDesktop) {
|
||||
$desktopLauncher = Install-PlanetDesktopLauncher $target
|
||||
Write-Host "Desktop launcher ready: $desktopLauncher"
|
||||
}
|
||||
if ($InstallOnly) { exit 0 }
|
||||
# Do not capture the WSL output: the interactive terminal must stream live.
|
||||
Start-PlanetRestart $target -AlreadyElevated:$Elevated
|
||||
exit $script:PlanetLauncherExitCode
|
||||
} catch {
|
||||
Write-Host $_.Exception.Message -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
30
scripts/windows/restart.zsh
Normal file
30
scripts/windows/restart.zsh
Normal file
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env zsh
|
||||
|
||||
# Locate the repository from this file, independent of Windows/WSL working directories.
|
||||
project_root="${0:A:h:h:h}"
|
||||
cd -- "$project_root" || exit 1
|
||||
./planet.sh restart --allow-lan
|
||||
planet_exit=$?
|
||||
print
|
||||
if (( planet_exit == 0 )); then
|
||||
print 'Planet restart finished successfully.'
|
||||
frontend_port=3000
|
||||
frontend_scheme=http
|
||||
port_state="${PLANET_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/planet}/ports.env"
|
||||
if [[ -f "$port_state" ]]; then
|
||||
while IFS='=' read -r key value; do
|
||||
case "$key" in
|
||||
FRONTEND_PORT) [[ "$value" == <1-65535> ]] && frontend_port="$value" ;;
|
||||
FRONTEND_SCHEME) [[ "$value" == http || "$value" == https ]] && frontend_scheme="$value" ;;
|
||||
esac
|
||||
done < "$port_state"
|
||||
fi
|
||||
WSLENV="${WSLENV:+$WSLENV:}PLANET_LAUNCH_URL" \
|
||||
PLANET_LAUNCH_URL="${frontend_scheme}://localhost:${frontend_port}/earth" \
|
||||
powershell.exe -NoProfile -Command 'Start-Process $env:PLANET_LAUNCH_URL'
|
||||
else
|
||||
print "Planet restart failed with exit code $planet_exit."
|
||||
fi
|
||||
print
|
||||
print 'Staying in WSL. Close this terminal manually when you are done.'
|
||||
exec zsh -l
|
||||
Reference in New Issue
Block a user