Compare commits

...
1 Commits
Author SHA1 Message Date
rayd1o 30b44ec00d release: bump version to 0.84.2
ci / frontend (push) Waiting to run
ci / backend (push) Waiting to run
2026-12-05 01:56:03 +08:00
77 changed files with 3312 additions and 1039 deletions

No files matched your search

+3 -1
View File
@@ -187,7 +187,9 @@ and builds/uploads **only** the affected targets:
service image(s) + OCI `release-manifest:<tag>`, **skips creating a Gitea Release**,
skips desktop packaging and client hotfix updates, and deploys only the changed container(s) on production.
- `frontend/public/earth/**`-only changes (`client.mode == "hotfix"`): emits only the L1 Earth hotfix bundle
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, and creates a Gitea Release with `release-manifest.json` + hotfix bundle.
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, embeds the hotfix bundle and
release notes into OCI `release-manifest:<tag>` (`bundle_storage: "oci"`), and **skips creating a Gitea Release**
so `/releases/latest` always preserves full desktop installers while production auto-publishes the L1 hotfix.
- `client/**` changes (`client.mode == "full"`): builds cross-platform desktop installers (`--all`) plus the
L1 hotfix bundle, and creates a Gitea Release with installers + `release-manifest.json`.
+7 -5
View File
@@ -127,11 +127,13 @@ the user's login interactive shell instead of assuming a specific dotfile.
committed files.
- Backend service code must use structured logging instead of `print()` or
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
- **Client-Only Gitea Releases**: Releases without client updates
(`client.mode == "none"`) push only changed container images plus OCI
`release-manifest:<tag>` and must **not** create a Gitea Release; only
`hotfix` or `full` client releases create a Gitea Release, and production
`planet-release-deploy` reconciles from Git tags + OCI `release-manifest:<tag>`.
- **Client-Only Gitea Releases**: Releases without desktop shell updates
(`client.mode == "none"` or `"hotfix"`) push changed container images plus OCI
`release-manifest:<tag>` (embedding L1 hotfix bundles in OCI for `hotfix`)
and must **not** create a Gitea Release; only `full` desktop client releases
create a Gitea Release so `/releases/latest` always carries installers, and
production `planet-release-deploy` reconciles from Git tags + OCI
`release-manifest:<tag>`.
- **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**:
`scripts/release_publish.py` only publishes container images, OCI
`release-manifest:<tag>`, and optional Gitea Releases; it never updates
+1 -1
View File
@@ -1 +1 @@
0.84.1
0.84.2
+3 -1
View File
@@ -90,7 +90,9 @@ async def lifespan(app: FastAPI):
if settings.should_run_scheduler:
if await acquire_scheduler_leader_lock():
leader_lock_acquired = True
await cleanup_stale_running_tasks()
await cleanup_stale_running_tasks(
include_all_running=(settings.normalized_role == "all")
)
start_scheduler()
scheduler_started = True
await sync_scheduler_with_datasources()
+148 -104
View File
@@ -3,14 +3,15 @@
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import gc
import hashlib
import io
import json
import math
import os
from pathlib import Path
import re
from datetime import UTC, datetime
from pathlib import Path
from time import perf_counter
from typing import Any
from urllib.parse import urlparse
@@ -43,6 +44,7 @@ CLOUD_CONFIG_CATEGORY = "earth_cloud_map"
DEFAULT_STATIC_CLOUD_URL = "./assets/earth_clouds_2048.png"
ANALYSIS_GRID_WIDTH = 720
ANALYSIS_GRID_HEIGHT = 360
LOW_MEMORY_CGROUP_THRESHOLD_MB = 1024
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$")
NASA_GIBS_WMS_URL = "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
@@ -377,6 +379,49 @@ def parse_resolution(resolution: str) -> tuple[int, int]:
return (4096, 2048) if resolution == "4096x2048" else (2048, 1024)
def detect_container_memory_limit_mb() -> int | None:
"""Return cgroup memory limit in MiB when bounded inside a container, else None."""
for path in (
Path("/sys/fs/cgroup/memory.max"),
Path("/sys/fs/cgroup/memory/memory.limit_in_bytes"),
):
try:
raw = path.read_text(encoding="utf-8").strip()
except OSError:
continue
if not raw or raw == "max":
continue
try:
limit_bytes = int(raw)
except ValueError:
continue
if limit_bytes <= 0 or limit_bytes >= (1 << 50):
continue
return int(limit_bytes // (1024 * 1024))
return None
def resolve_effective_cloud_config(config: CloudMapConfig) -> CloudMapConfig:
"""Clamp working resolution to 2048x1024 in bounded low-memory containers."""
env_max = str(os.environ.get("PLANET_CLOUD_MAX_RESOLUTION") or "").strip().lower()
mem_limit_mb = detect_container_memory_limit_mb()
if config.resolution == "4096x2048" and (
env_max == "2048x1024"
or (mem_limit_mb is not None and mem_limit_mb <= LOW_MEMORY_CGROUP_THRESHOLD_MB)
):
logger.warning_event(
"Clamped cloud map working resolution to 2048x1024 for low-memory environment",
event="earth.cloud_map.resolution_clamped_low_memory",
context={
"configured_resolution": config.resolution,
"effective_resolution": "2048x1024",
"container_memory_limit_mb": mem_limit_mb,
},
)
return config.model_copy(update={"resolution": "2048x1024"})
return config
def _get_gibs_3d_lut() -> np.ndarray:
"""Build a quantized 5-bit/channel RGB -> Brightness Temperature (°C) lookup table."""
global _GIBS_3D_LUT
@@ -460,29 +505,33 @@ def _disambiguate_dvorak_cold_gray(
if np.any(ultra_wrap):
result[ultra_wrap] = -91.5
del not_ring, labels, stats
return result, updated_valid
def decode_gibs_band13_to_temp_and_valid(rgba_arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Invert GIBS Band13 Clean IR RGBA pixels into Brightness Temperature (°C) and valid mask."""
rgb = rgba_arr[:, :, :3].astype(np.int32)
r_u8 = rgba_arr[:, :, 0]
g_u8 = rgba_arr[:, :, 1]
b_u8 = rgba_arr[:, :, 2]
alpha = rgba_arr[:, :, 3]
valid = alpha > 12
r_ch = rgb[:, :, 0]
g_ch = rgb[:, :, 1]
b_ch = rgb[:, :, 2]
chroma = np.maximum(np.maximum(r_ch, g_ch), b_ch) - np.minimum(np.minimum(r_ch, g_ch), b_ch)
gray = ((r_ch + g_ch + b_ch) // 3).astype(np.float32)
chroma = np.maximum(np.maximum(r_u8, g_u8), b_u8) - np.minimum(np.minimum(r_u8, g_u8), b_u8)
gray_sum = r_u8.astype(np.uint16)
gray_sum += g_u8
gray_sum += b_u8
gray = (gray_sum // 3).astype(np.float32)
del gray_sum
temp_c = 57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4
temp_c = (57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4).astype(np.float32)
color_mask = valid & (chroma >= 12)
if np.any(color_mask):
lut = _get_gibs_3d_lut()
temp_c[color_mask] = lut[
r_ch[color_mask] >> 3,
g_ch[color_mask] >> 3,
b_ch[color_mask] >> 3,
r_u8[color_mask] >> 3,
g_u8[color_mask] >> 3,
b_u8[color_mask] >> 3,
]
temp_c, valid = _disambiguate_dvorak_cold_gray(valid, gray, chroma, temp_c)
@@ -599,6 +648,7 @@ def synthesize_multi_sat_ir(
temp_accum += safe_temp * pixel_weight
weight_accum += pixel_weight
active_satellites.append(str(sat["id"]))
del rgba_arr, sat_temp, valid, pixel_weight, safe_temp
if not active_satellites or not np.any(weight_accum > 0.0):
raise RuntimeError("No valid geostationary IR satellite frames could be decoded")
@@ -1190,6 +1240,7 @@ async def collect_latest_cloud_frame(
envelope = await read_cloud_map_configuration(db)
merged_cfg = {**envelope["config"], **(override_config or {})}
config = CloudMapConfig.model_validate(merged_cfg)
effective_config = resolve_effective_cloud_config(config)
manifest = _read_manifest()
prev_frames = manifest.get("frames", [])
@@ -1207,42 +1258,43 @@ async def collect_latest_cloud_frame(
density: np.ndarray | None = None
temp_c: np.ndarray | None = None
visual_payloads: list[tuple[dict[str, Any], bytes]] = []
source_used = config.primary_source
source_used = effective_config.primary_source
satellites: list[str] = []
degraded = False
if config.primary_source == "multi_sat_ir":
if config.geocolor_enabled:
payloads, visual_payloads = await asyncio.gather(
_fetch_multi_sat_payloads(config, layer_field="layer"),
_fetch_multi_sat_payloads(config, layer_field="visual_layer"),
)
else:
payloads = await _fetch_multi_sat_payloads(config, layer_field="layer")
if effective_config.primary_source == "multi_sat_ir":
payloads = await _fetch_multi_sat_payloads(effective_config, layer_field="layer")
if payloads:
density, temp_c, satellites = await asyncio.to_thread(
synthesize_multi_sat_ir,
payloads,
config=config,
config=effective_config,
)
payloads.clear()
del payloads
if len(satellites) < len(SATELLITE_SOURCES):
degraded = True
elif config.fallback_source == "matteason_live":
raw = await _fetch_matteason_bytes(config)
if effective_config.geocolor_enabled:
visual_payloads = await _fetch_multi_sat_payloads(
effective_config,
layer_field="visual_layer",
)
elif effective_config.fallback_source == "matteason_live":
raw = await _fetch_matteason_bytes(effective_config)
density, temp_c = await asyncio.to_thread(
decode_matteason_cloud_bytes,
raw,
config=config,
config=effective_config,
)
source_used = "matteason_live"
satellites = ["eumetsat_nasa_mosaic"]
degraded = True
else:
raw = await _fetch_matteason_bytes(config)
raw = await _fetch_matteason_bytes(effective_config)
density, temp_c = await asyncio.to_thread(
decode_matteason_cloud_bytes,
raw,
config=config,
config=effective_config,
)
source_used = "matteason_live"
satellites = ["eumetsat_nasa_mosaic"]
@@ -1257,88 +1309,80 @@ async def collect_latest_cloud_frame(
def _finalize() -> tuple[dict[str, Any], dict[str, Any]]:
from app.services.earth_clouds_fx import (
compute_dis_optical_flow_webp,
decode_visual_payloads,
fuse_daytime_visible_into_density,
synthesize_geocolor_visual_webp,
fuse_and_synthesize_visual_layers,
)
width, height = parse_resolution(config.resolution)
decoded_visuals = (
decode_visual_payloads(visual_payloads, width, height)
if (config.geocolor_enabled and visual_payloads)
else []
)
fused_density = (
fuse_daytime_visible_into_density(
density,
temp_c,
decoded_visuals,
width=width,
height=height,
now_utc=now_utc,
)
if decoded_visuals
else density
)
try:
width, height = parse_resolution(effective_config.resolution)
if effective_config.geocolor_enabled and visual_payloads:
fused_density, visual_webp_bytes = fuse_and_synthesize_visual_layers(
density,
temp_c,
visual_payloads,
width=width,
height=height,
now_utc=now_utc,
)
else:
fused_density, visual_webp_bytes = density, None
visual_payloads.clear()
analysis = analyze_cloud_density_grid(
fused_density,
temp_c,
config=config,
previous_snapshot=prev_snapshot,
previous_regions=prev_regions,
)
webp_bytes = _encode_cloud_webp(fused_density)
visual_webp_bytes = (
synthesize_geocolor_visual_webp(
decoded_visuals,
analysis = analyze_cloud_density_grid(
fused_density,
width=width,
height=height,
temp_c,
config=effective_config,
previous_snapshot=prev_snapshot,
previous_regions=prev_regions,
)
if decoded_visuals
else None
)
flow_webp_bytes: bytes | None = None
flow_prev_version: str | None = None
flow_max_uv = 0.0
if config.optical_flow_enabled and isinstance(prev_entry, dict) and prev_entry.get("version"):
prev_ver = str(prev_entry["version"])
prev_frame_file = _frames_dir() / f"{prev_ver}.webp"
if prev_ver != version and prev_frame_file.exists():
try:
prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height)
prev_density = prev_rgba[:, :, 3]
flow_res = compute_dis_optical_flow_webp(prev_density, fused_density)
if flow_res is not None:
flow_webp_bytes, flow_max_uv = flow_res
flow_prev_version = prev_ver
except Exception as exc:
logger.warning_event(
"Cloud optical flow calculation failed",
event="earth.cloud_map.optical_flow_failed",
context={"prev_version": prev_ver, "error": str(exc)},
)
webp_bytes = _encode_cloud_webp(fused_density)
flow_webp_bytes: bytes | None = None
flow_prev_version: str | None = None
flow_max_uv = 0.0
if (
effective_config.optical_flow_enabled
and isinstance(prev_entry, dict)
and prev_entry.get("version")
):
prev_ver = str(prev_entry["version"])
prev_frame_file = _frames_dir() / f"{prev_ver}.webp"
if prev_ver != version and prev_frame_file.exists():
try:
prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height)
prev_density = prev_rgba[:, :, 3]
flow_res = compute_dis_optical_flow_webp(prev_density, fused_density)
del prev_rgba, prev_density
if flow_res is not None:
flow_webp_bytes, flow_max_uv = flow_res
flow_prev_version = prev_ver
except Exception as exc:
logger.warning_event(
"Cloud optical flow calculation failed",
event="earth.cloud_map.optical_flow_failed",
context={"prev_version": prev_ver, "error": str(exc)},
)
entry = _save_frame_artifacts_sync(
version=version,
captured_at=captured_at,
source_used=source_used,
satellites=satellites,
degraded=degraded,
config=config,
webp_bytes=webp_bytes,
visual_webp_bytes=visual_webp_bytes,
flow_webp_bytes=flow_webp_bytes,
flow_prev_version=flow_prev_version,
flow_max_uv=flow_max_uv,
grid_density=analysis["grid_density"],
grid_temp_i8=analysis["grid_temp_i8"],
global_summary=analysis["global_summary"],
regions=analysis["regions"],
clusters=analysis["convective_clusters"],
)
return entry, analysis
entry = _save_frame_artifacts_sync(
version=version,
captured_at=captured_at,
source_used=source_used,
satellites=satellites,
degraded=degraded,
config=effective_config,
webp_bytes=webp_bytes,
visual_webp_bytes=visual_webp_bytes,
flow_webp_bytes=flow_webp_bytes,
flow_prev_version=flow_prev_version,
flow_max_uv=flow_max_uv,
grid_density=analysis["grid_density"],
grid_temp_i8=analysis["grid_temp_i8"],
global_summary=analysis["global_summary"],
regions=analysis["regions"],
clusters=analysis["convective_clusters"],
)
return entry, analysis
finally:
visual_payloads.clear()
gc.collect()
async with _CLOUD_WRITE_LOCK:
frame_entry, analysis = await asyncio.to_thread(_finalize)
@@ -1348,7 +1392,7 @@ async def collect_latest_cloud_frame(
"global_summary": analysis["global_summary"],
"regions": analysis["regions"],
"convective_clusters": analysis["convective_clusters"],
"config": config.model_dump(mode="json"),
"config": effective_config.model_dump(mode="json"),
}
+80 -34
View File
@@ -2,10 +2,11 @@
from __future__ import annotations
from datetime import UTC, datetime
import gc
import io
import math
from typing import Any, Sequence
from datetime import UTC, datetime
from typing import Any, Iterator, Sequence
import cv2
import numpy as np
@@ -35,18 +36,40 @@ def decode_visual_payloads(
height: int,
) -> list[tuple[dict[str, Any], np.ndarray]]:
"""Decode and resize visible satellite payloads once so density & GeoColor share buffers."""
decoded: list[tuple[dict[str, Any], np.ndarray]] = []
return list(_iter_decoded_visuals(visual_payloads, width, height))
def _iter_decoded_visuals(
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
width: int,
height: int,
) -> Iterator[tuple[dict[str, Any], np.ndarray]]:
"""Yield one decoded RGBA visual frame at a time to bound peak heap usage."""
for sat, payload in visual_payloads:
if isinstance(payload, np.ndarray):
if payload.shape[:2] == (height, width) and payload.shape[2] == 4:
decoded.append((sat, payload))
yield sat, payload
continue
try:
rgba = _decode_rgba_resized(payload, width, height)
decoded.append((sat, rgba))
yield sat, rgba
except Exception:
continue
return decoded
def _rgba_channels_and_luma(
rgba: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
red = rgba[:, :, 0]
green = rgba[:, :, 1]
blue = rgba[:, :, 2]
alpha = rgba[:, :, 3]
luma = (
0.299 * red.astype(np.float32)
+ 0.587 * green.astype(np.float32)
+ 0.114 * blue.astype(np.float32)
)
return red, green, blue, alpha, luma
def _solar_cosine_grid(width: int, height: int, now_utc: datetime) -> tuple[np.ndarray, np.ndarray]:
@@ -87,10 +110,6 @@ def fuse_daytime_visible_into_density(
if not np.any(day_weight > 0.01):
return density_u8
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
if not decoded_visuals:
return density_u8
cos_safe = np.clip(cos_sza, 0.30, 1.0)
safe_temp = np.where(np.isfinite(temp_c), temp_c, 15.0).astype(np.float32)
# Band-pass gate: peaks on -2C..+16C warm low clouds while suppressing hot deserts (>+24C) and sub-zero snow (<-8C).
@@ -102,25 +121,24 @@ def fuse_daytime_visible_into_density(
vis_accum = np.zeros((height, width), dtype=np.float32)
weight_accum = np.zeros((height, width), dtype=np.float32)
for sat, rgba in decoded_visuals:
rgb = rgba[:, :, :3].astype(np.float32)
alpha = rgba[:, :, 3].astype(np.float32)
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
not_clipped = ~(
(rgb[:, :, 0] >= 254.0)
& (rgb[:, :, 1] >= 254.0)
& (rgb[:, :, 2] >= 254.0)
(r_u8 >= 254)
& (g_u8 >= 254)
& (b_u8 >= 254)
& (safe_temp > -10.0)
)
valid = (alpha > 12.0) & (luma > 8.0) & not_clipped
valid = (alpha_u8 > 12) & (luma > 8.0) & not_clipped
if not np.any(valid):
continue
chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0
max_u8 = np.maximum(np.maximum(r_u8, g_u8), b_u8)
min_u8 = np.minimum(np.minimum(r_u8, g_u8), b_u8)
chroma = (max_u8 - min_u8).astype(np.float32) / 255.0
is_color = float(np.nanpercentile(chroma[valid], 95)) > 0.08
if is_color:
min_rgb = np.min(rgb, axis=2)
albedo = min_rgb / cos_safe
albedo = min_u8.astype(np.float32) / cos_safe
whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0)
sat_cloud = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * warm_low_cloud_gate
else:
@@ -131,6 +149,7 @@ def fuse_daytime_visible_into_density(
pix_w = np.where(valid, lon_w[None, :], 0.0)
vis_accum += sat_cloud * pix_w
weight_accum += pix_w
del rgba, luma, chroma, sat_cloud, pix_w
covered = weight_accum > 0.0
if not np.any(covered):
@@ -156,37 +175,33 @@ def synthesize_geocolor_visual_webp(
if not visual_payloads or density_u8.shape != (height, width):
return None
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
if not decoded_visuals:
return None
rgb_accum = np.zeros((height, width, 3), dtype=np.float32)
weight_accum = np.zeros((height, width), dtype=np.float32)
valid_sources = 0
for sat, rgba in decoded_visuals:
rgb = rgba[:, :, :3].astype(np.float32)
alpha = rgba[:, :, 3].astype(np.float32)
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
# EUMETView/GIBS return opaque black over night hemispheres or pure-white clipped wedges.
# Mask out dark night pixels and non-dense pure-white [255,255,255] fill artifacts.
not_clipped = ~(
(rgb[:, :, 0] >= 254.0)
& (rgb[:, :, 1] >= 254.0)
& (rgb[:, :, 2] >= 254.0)
(r_u8 >= 254)
& (g_u8 >= 254)
& (b_u8 >= 254)
& (density_u8 < 180)
)
valid = (alpha > 12.0) & (luma > 22.0) & not_clipped
valid = (alpha_u8 > 12) & (luma > 22.0) & not_clipped
if not np.any(valid):
continue
lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0)))
# Emphasize cloud-rich pixels from daytime channels so dark ocean reflectance doesn't darken clouds.
pix_w = np.where(valid, lon_w[None, :], 0.0)
rgb_accum += rgb * pix_w[:, :, None]
for ch in range(3):
rgb_accum[:, :, ch] += rgba[:, :, ch].astype(np.float32) * pix_w
weight_accum += pix_w
valid_sources += 1
del rgba, luma, pix_w
if valid_sources == 0 or not np.any(weight_accum > 0.0):
return None
@@ -274,3 +289,34 @@ def compute_dis_optical_flow_webp(
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=92, method=1)
return buf.getvalue(), round(float(max_uv), 6)
def fuse_and_synthesize_visual_layers(
density_u8: np.ndarray,
temp_c: np.ndarray,
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
*,
width: int,
height: int,
now_utc: datetime | None = None,
) -> tuple[np.ndarray, bytes | None]:
"""Stream visible payloads one at a time for low-cloud density fusion and GeoColor WebP."""
if not visual_payloads:
return density_u8, None
fused_density = fuse_daytime_visible_into_density(
density_u8,
temp_c,
visual_payloads,
width=width,
height=height,
now_utc=now_utc,
)
gc.collect()
visual_webp_bytes = synthesize_geocolor_visual_webp(
visual_payloads,
fused_density,
width=width,
height=height,
)
gc.collect()
return fused_density, visual_webp_bytes
+102 -39
View File
@@ -3,13 +3,14 @@
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import hashlib
import io
import math
import os
from pathlib import Path
import time
import weakref
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from uuid import uuid4
@@ -57,6 +58,41 @@ BASEMAP_TILE_SOURCES: tuple[str, ...] = (
"earth_imagery_viirs_daily",
)
# A contended semaphore holds its event loop, so the cache also keeps values weakly.
_TILE_ENCODE_SEMAPHORES: weakref.WeakKeyDictionary[
asyncio.AbstractEventLoop, weakref.ReferenceType[asyncio.Semaphore]
] = weakref.WeakKeyDictionary()
_INFLIGHT_TILE_FETCHES: weakref.WeakKeyDictionary[
asyncio.AbstractEventLoop, dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]
] = weakref.WeakKeyDictionary()
def _tile_encode_concurrency() -> int:
raw = str(os.environ.get("PLANET_TILE_ENCODE_CONCURRENCY") or "2").strip()
try:
return max(1, min(8, int(raw)))
except ValueError:
return 2
def _get_tile_encode_semaphore() -> asyncio.Semaphore:
loop = asyncio.get_running_loop()
semaphore_ref = _TILE_ENCODE_SEMAPHORES.get(loop)
semaphore = semaphore_ref() if semaphore_ref is not None else None
if semaphore is None:
semaphore = asyncio.Semaphore(_tile_encode_concurrency())
_TILE_ENCODE_SEMAPHORES[loop] = weakref.ref(semaphore)
return semaphore
def _get_inflight_tile_fetches() -> dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]:
loop = asyncio.get_running_loop()
inflight = _INFLIGHT_TILE_FETCHES.get(loop)
if inflight is None:
inflight = {}
_INFLIGHT_TILE_FETCHES[loop] = inflight
return inflight
DEFAULT_TILE_TEMPLATES: dict[str, str] = {
"cloud_hd_tiles": (
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
@@ -589,29 +625,31 @@ async def _fetch_and_encode_tile(
)
ir_bytes = ir_res.content if _is_valid_image_response(ir_res) else None
if _is_valid_image_response(primary_res):
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
primary_res.content,
provider=provider,
ir_bytes=ir_bytes,
ir_provider=ir_provider,
cos_sza=cos_sza,
z=z,
x=x,
y=y,
ir_z_src=ir_z_src,
)
async with _get_tile_encode_semaphore():
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
primary_res.content,
provider=provider,
ir_bytes=ir_bytes,
ir_provider=ir_provider,
cos_sza=cos_sza,
z=z,
x=x,
y=y,
ir_z_src=ir_z_src,
)
if ir_bytes is not None:
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
ir_bytes,
provider=ir_provider,
z=z,
x=x,
y=y,
)
async with _get_tile_encode_semaphore():
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
ir_bytes,
provider=ir_provider,
z=z,
x=x,
y=y,
)
if isinstance(primary_res, Exception) and raise_on_error:
raise primary_res
if isinstance(primary_res, httpx.Response) and primary_res.status_code not in (200, 404) and raise_on_error:
@@ -632,15 +670,16 @@ async def _fetch_and_encode_tile(
response.raise_for_status()
if not _is_valid_image_response(response):
return None
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
response.content,
provider=provider,
z=z,
x=x,
y=y,
)
async with _get_tile_encode_semaphore():
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
response.content,
provider=provider,
z=z,
x=x,
y=y,
)
async def get_or_fetch_tile(
@@ -667,15 +706,39 @@ async def get_or_fetch_tile(
pass
return target.read_bytes(), True
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
webp_bytes = await _fetch_and_encode_tile(client, source_key, template, z, x, y)
tile_key = (source_key, int(z), int(x), int(y))
inflight = _get_inflight_tile_fetches()
existing_task = inflight.get(tile_key)
if existing_task is None or existing_task.done():
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
async def _load_and_persist() -> bytes | None:
async with httpx.AsyncClient(
timeout=timeout,
follow_redirects=True,
headers=headers,
) as client:
loaded = await _fetch_and_encode_tile(
client, source_key, template, z, x, y
)
if loaded is not None:
await asyncio.to_thread(_atomic_write_bytes, target, loaded)
return loaded
existing_task = asyncio.create_task(_load_and_persist())
inflight[tile_key] = existing_task
existing_task.add_done_callback(
lambda done_task: (
inflight.pop(tile_key, None)
if inflight.get(tile_key) is done_task
else None
)
)
webp_bytes = await asyncio.shield(existing_task)
if webp_bytes is None:
return None, True
await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes)
return webp_bytes, True
+22 -9
View File
@@ -444,26 +444,36 @@ async def run_collector_task(collector_name: str):
)
async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
async def cleanup_stale_running_tasks(
max_age_hours: int = 2,
*,
include_all_running: bool = False,
) -> int:
"""Mark stale running tasks as failed after restarts or collector hangs."""
cutoff = datetime.now(UTC) - timedelta(hours=max_age_hours)
async with async_session_factory() as db:
result = await db.execute(
select(CollectionTask).where(
CollectionTask.status == JobStatus.RUNNING.value,
conditions = [CollectionTask.status == JobStatus.RUNNING.value]
if not include_all_running:
conditions.extend(
[
CollectionTask.started_at.is_not(None),
CollectionTask.started_at < cutoff,
)
]
)
async with async_session_factory() as db:
result = await db.execute(select(CollectionTask).where(*conditions))
stale_tasks = result.scalars().all()
cleanup_error = (
"Marked failed automatically after backend restart"
if include_all_running
else "Marked failed automatically after stale running task cleanup"
)
for task in stale_tasks:
task.status = JobStatus.FAILED.value
task.phase = "failed"
task.completed_at = datetime.now(UTC)
existing_error = (task.error_message or "").strip()
cleanup_error = "Marked failed automatically after stale running task cleanup"
task.error_message = (
f"{existing_error}\n{cleanup_error}".strip() if existing_error else cleanup_error
)
@@ -473,7 +483,10 @@ async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
logger.warning_event(
"Cleaned up stale running collection tasks",
event="collector.cleanup.stale_tasks_cleaned",
context={"count": len(stale_tasks)},
context={
"count": len(stale_tasks),
"include_all_running": include_all_running,
},
)
return len(stale_tasks)
+37
View File
@@ -434,3 +434,40 @@ async def test_cloud_apis_rbac_optimistic_lock_and_analytics(monkeypatch):
assert r_clear.json()["meta"]["mode"] == "fallback_static"
finally:
app.dependency_overrides.clear()
def test_resolve_effective_cloud_config_clamps_on_low_memory(monkeypatch):
cfg = earth_clouds.CloudMapConfig(resolution="4096x2048")
monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: 500)
clamped = earth_clouds.resolve_effective_cloud_config(cfg)
assert clamped.resolution == "2048x1024"
monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: 2048)
assert earth_clouds.resolve_effective_cloud_config(cfg).resolution == "4096x2048"
monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: None)
assert earth_clouds.resolve_effective_cloud_config(cfg).resolution == "4096x2048"
def test_fuse_and_synthesize_visual_layers_streams_png_payloads():
from datetime import UTC, datetime
from app.services.earth_clouds_fx import fuse_and_synthesize_visual_layers
ir_zero = np.zeros((32, 64), dtype=np.uint8)
temp_grid = np.full((32, 64), 16.0, dtype=np.float32)
temp_grid[9:13, 50:56] = 8.0
vis_arr = np.zeros((32, 64, 4), dtype=np.uint8)
vis_arr[:, :, 3] = 255
vis_arr[9:13, 50:56, :3] = [215, 215, 215]
fused, webp = fuse_and_synthesize_visual_layers(
ir_zero,
temp_grid,
[({"id": "himawari", "sub_lon": 140.7}, _make_png_bytes(vis_arr))],
width=64,
height=32,
now_utc=datetime(2026, 12, 3, 5, 0, 0, tzinfo=UTC),
)
assert int(fused[11, 53]) >= 120
assert webp is not None and len(webp) > 20
+101
View File
@@ -2,7 +2,10 @@
from __future__ import annotations
import asyncio
import gc
import io
import weakref
from unittest.mock import AsyncMock
import httpx
@@ -367,3 +370,101 @@ async def test_tile_proxy_gating_cache_lru_and_basemap_api(tmp_path, monkeypatch
assert wind_tool["domain"] == "wind"
finally:
app.dependency_overrides.clear()
@pytest.mark.asyncio
async def test_get_or_fetch_tile_coalesces_concurrent_requests(tmp_path, monkeypatch):
monkeypatch.setattr(earth_tiles, "TILES_DATA_DIR", tmp_path / "tiles")
monkeypatch.setattr(
earth_tiles,
"_get_source_runtime_settings",
AsyncMock(
return_value=(
True,
earth_tiles.DEFAULT_TILE_TEMPLATES["earth_imagery_sentinel2"],
{"max_zoom": 8, "request_timeout_seconds": 10},
)
),
)
calls = 0
async def slow_fetch(*_args, **_kwargs):
nonlocal calls
calls += 1
await asyncio.sleep(0.05)
return b"RIFFcoalescedWEBP"
monkeypatch.setattr(earth_tiles, "_fetch_and_encode_tile", slow_fetch)
results = await asyncio.gather(
*(
earth_tiles.get_or_fetch_tile("earth_imagery_sentinel2", 2, 1, 1)
for _ in range(4)
)
)
assert calls == 1
assert results == [(b"RIFFcoalescedWEBP", True)] * 4
def test_tile_encode_semaphore_limits_concurrency_without_retaining_closed_loop(monkeypatch):
monkeypatch.setenv("PLANET_TILE_ENCODE_CONCURRENCY", "1")
async def contend_for_semaphore():
waiting = asyncio.Event()
entered = asyncio.Event()
async def acquire():
waiting.set()
async with earth_tiles._get_tile_encode_semaphore():
entered.set()
async with earth_tiles._get_tile_encode_semaphore():
contender = asyncio.create_task(acquire())
await waiting.wait()
assert not entered.is_set()
await contender
assert entered.is_set()
return weakref.ref(asyncio.get_running_loop())
loop_ref = asyncio.run(contend_for_semaphore())
gc.collect()
assert loop_ref() is None
@pytest.mark.asyncio
async def test_cleanup_stale_running_tasks_include_all_running(monkeypatch):
from datetime import UTC, datetime
from types import SimpleNamespace
from contextlib import asynccontextmanager
from app.services import scheduler
fresh_task = SimpleNamespace(
id=111,
status="running",
phase="fetching",
started_at=datetime.now(UTC),
completed_at=None,
error_message="",
)
committed = False
class _FakeDb:
async def execute(self, _stmt):
return SimpleNamespace(scalars=lambda: SimpleNamespace(all=lambda: [fresh_task]))
async def commit(self):
nonlocal committed
committed = True
@asynccontextmanager
async def _fake_session_factory():
yield _FakeDb()
monkeypatch.setattr(scheduler, "async_session_factory", _fake_session_factory)
cleaned = await scheduler.cleanup_stale_running_tasks(include_all_running=True)
assert cleaned == 1
assert committed is True
assert fresh_task.status == "failed"
assert fresh_task.phase == "failed"
assert fresh_task.completed_at is not None
assert "backend restart" in fresh_task.error_message
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-client",
"version": "0.84.1",
"version": "0.84.2",
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true,
"packageManager": "bun@1",
+3 -2
View File
@@ -306,11 +306,12 @@ function runWinBuild() {
}
function runMacBuild() {
const architectures = ['--x64', '--arm64']
if (process.platform === 'darwin') {
runBuilder(['--mac', 'dmg', 'zip'])
runBuilder(['--mac', 'dmg', 'zip', ...architectures])
} else {
console.warn('Non-macOS host detected: building macOS zip bundle without dmg/codesign.')
runBuilder(['--mac', 'zip'])
runBuilder(['--mac', 'zip', ...architectures])
}
}
+17
View File
@@ -8,6 +8,23 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [0.84.2] — 2026-12-05
Released: 2026-12-05
### Highlights
- 发布 Windows、Linux 和 macOS 桌面客户端安装包及 Earth 热更新包。
### Improved / Fixed
- 后台优化仪表盘、工作流和数据台账的布局与控件,补齐数据台账的英文界面,并显示实际运行版本。
- Earth 统一按钮与来源链接的图标对齐,卫星目录刷新后保留仍有效的选中目标和轨道。
- 降低云图合成与高清底图瓦片的内存压力,减少并发请求造成的重复加载。
- 轻量 Earth 热更新改由 OCI 发布清单分发,保留下载页的完整客户端安装包。前端冒烟补齐地形瓦片模拟。
---
## [0.84.1] — 2026-12-04
Released: 2026-12-04
+8 -7
View File
@@ -332,13 +332,14 @@ Use `.codex/skills/release/SKILL.md`, `scripts/release_scope.py`,
`scripts/release_publish.py`, and `.gitea/workflows/` files. Tagged releases
classify changed paths into scoped images (`admin`, `backend`, `aiprovider`)
and client modes (`none`, `hotfix`, `full`) recorded in OCI
`release-manifest:<tag>` (and `release-manifest.json` when a client Release is
created). Releases with `client.mode == "none"` push only changed service
images + OCI `release-manifest:<tag>` without creating a Gitea Release or
rebuilding desktop clients; only `hotfix` / `full` client releases create a
Gitea Release. Harness validation can smoke-check Helm and Docker locally,
and `scripts/harness/test_production_release.py` covers scoped release/deploy
logic without replacing the release process.
`release-manifest:<tag>` (and `release-manifest.json` when a full desktop
Release is created). Releases with `client.mode == "none"` or `"hotfix"` push
changed service images + OCI `release-manifest:<tag>` (embedding the L1 hotfix
bundle in OCI for `hotfix`) without creating a Gitea Release or rebuilding
desktop installers; only `full` client releases create a Gitea Release so
`/releases/latest` always holds full desktop packages. Harness validation can
smoke-check Helm and Docker locally, and `scripts/harness/test_production_release.py`
covers scoped release/deploy logic without replacing the release process.
## Implementation Notes
+2 -2
View File
@@ -487,9 +487,9 @@ Run the following command from the tagged commit.
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
The publisher classifies changed files from the tag commit (`scripts/release_scope.py`), builds Linux amd64 images only for changed services, and pushes OCI `release-manifest:<tag>` as the canonical deployment manifest. When a release contains no client or Earth hotfix update (`client.mode == "none"`), it skips desktop packaging and **does not create a Gitea Release**; Gitea Releases are created only for releases with L1 hotfixes (`hotfix`) or full desktop packages (`full`). Pass `--assets-dir client/release` to reuse complete packages and a hotfix built for that tag. Repeat the same command after an interrupted upload to reuse the original build and verified attachments. The workstation can go offline once publication succeeds.
The publisher classifies changed files from the tag commit (`scripts/release_scope.py`), builds Linux amd64 images only for changed services, and pushes OCI `release-manifest:<tag>` as the canonical deployment manifest. When a release contains no desktop shell update (`client.mode == "none"` or `"hotfix"`), it **does not create a Gitea Release** (for `hotfix`, the L1 Earth hotfix bundle and release notes are embedded directly inside OCI `release-manifest:<tag>` so Gitea `/releases/latest` always preserves full desktop installers); Gitea Releases are created only for full desktop client updates (`client.mode == "full"`). Pass `--assets-dir client/release` to reuse complete packages and a hotfix built for that tag. Repeat the same command after an interrupted upload to reuse the original build and verified attachments. The workstation can go offline once publication succeeds.
The production host checks the latest stable Git tags and OCI `release-manifest:<tag>` (plus Gitea Releases when client updates exist) approximately every two minutes using `planet-release-deploy.timer`. Once the manifest and digests are verified, it pulls only changed images by digest, backs up PostgreSQL, rolls out changed services, verifies endpoints, and publishes/verifies the Earth hotfix only when `client.mode != "none"`. The host retains its Compose configuration, memory limits, and data volumes. Apply the release-specific infrastructure migration first when a release requires new mounts, services, or incompatible database changes.
The production host checks the latest stable Git tags and OCI `release-manifest:<tag>` (plus Gitea Releases for full-shell or legacy releases) approximately every two minutes using `planet-release-deploy.timer`. Once the manifest and digests are verified, it pulls only changed images by digest, backs up PostgreSQL, rolls out changed services, verifies endpoints, and publishes/verifies the Earth hotfix from OCI or Gitea Release whenever `client.mode != "none"`. The host retains its Compose configuration, memory limits, and data volumes. Apply the release-specific infrastructure migration first when a release requires new mounts, services, or incompatible database changes.
A failed rollout restores the previous application images and hotfix manifest while preserving database writes. An interrupted rollout resumes recovery on the next check. A failed version waits for an explicit retry or a newer release. The most recent pre-change database backups and version records are under `/var/lib/planet-release-deploy/last-success/` and `last-failed/`. Retry after resolving the underlying error.
+2 -2
View File
@@ -487,9 +487,9 @@ docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
发布器从标签提交识别改动范围(`scripts/release_scope.py`),仅构建变更服务的 Linux amd64 镜像,并把完整部署清单写入 OCI `release-manifest:<tag>`。当版本不包含客户端或 Earth 热更变更(`client.mode == "none"`)时,不构建桌面客户端且**不创建新的 Gitea Release**;仅当包含 L1 热更或桌面客户端更新(`hotfix` / `full`)时才创建 Gitea Release 并附带 `release-manifest.json` 与对应安装包/热更包。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。
发布器从标签提交识别改动范围(`scripts/release_scope.py`),仅构建变更服务的 Linux amd64 镜像,并把完整部署清单写入 OCI `release-manifest:<tag>`。当版本不包含桌面客户端壳包更新(`client.mode == "none"` 或 `"hotfix"`)时,**不创建新的 Gitea Release**(其中 `hotfix` 会把 L1 Earth 热更包与变更说明直接打入 OCI `release-manifest:<tag>`,从而让 Gitea `/releases/latest` 始终保留全平台桌面安装包);仅当包含全平台桌面客户端更新(`client.mode == "full"`)时才创建 Gitea Release 并附带 `release-manifest.json` 与对应安装包/热更包。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。
生产机的 `planet-release-deploy.timer` 约每两分钟检查 Gitea 最新正式标签、OCI `release-manifest:<tag>`(及客户端更新版本对应的 Gitea Release)。确认清单与摘要齐全后,服务按不可变摘要仅拉取并滚动更新有变动的容器,备份 PostgreSQL,验证健康接口;仅在 `client.mode != "none"` 时发布并回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。
生产机的 `planet-release-deploy.timer` 约每两分钟检查 Gitea 最新正式标签、OCI `release-manifest:<tag>`(及客户端全量/历史版本对应的 Gitea Release)。确认清单与摘要齐全后,服务按不可变摘要仅拉取并滚动更新有变动的容器,备份 PostgreSQL,验证健康接口;当 `client.mode != "none"` 时自动从 OCI 或 Release 读取并发布、回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。
上线失败时,服务恢复上一版的镜像摘要和热更新清单,保留数据库里的业务写入。事务记录在重启后仍可恢复。失败的版本会暂停自动重试,较新的正式版仍可上线。`/var/lib/planet-release-deploy/last-success/` 和 `last-failed/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。
+2 -1
View File
@@ -16,12 +16,13 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.84.1`
- `dev` 当前开发分支历史推导到:`0.84.2`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `0.84.2` | improvement | `dev` | `v0.84.2` | 后台数据台账英文和控件改进、Earth 图标对齐与卫星刷新、云图和底图内存优化、OCI 热更新与全平台客户端发布 |
| `0.84.1` | bugfix | `dev` | `v0.84.1` | 在 backend/Dockerfile 补齐 OpenCV 运行时共享库(libxcb1/libgl1/libglib2.0-0 等),修复生产容器启动导入 cv2 失败并完成 v0.84 线上发布与 L1 热更上线 |
| `0.84.0` | feature | `dev` | `v0.84.0` | 算力台账不可变修订/双时间轴/只读血缘、全球实时云图与风场/高清底图瓦片、高精度中国 POV 边界 PMTiles 与 3D 城市分级标注、图层数据台账与 9 节点位置 DAG 统一、修复线上独立 Admin 默认品牌/云图预览裂图及文档清理 |
| `0.83.0` | feature | `dev` | `v0.83.0` | Earth Phase 1–4 贴地影响范围与三维视觉升级、聚合分色环与优先一折连线、AI 参谋自进化加固与数据源连通性修复、桌面客户端启动与资源包更新及代码文档清理 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.84.1",
"version": "0.84.2",
"private": true,
"packageManager": "bun@1",
"dependencies": {
+39 -1
View File
@@ -1304,6 +1304,23 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
color: var(--hud-accent-strong);
}
.compute-source-link.earth-mobile-action-btn {
gap: var(--hud-gap-xs);
}
.compute-source-link > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(13px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
/* Stage Narrative Player HUD Bar (F-12, F-14, F-15, F-17 — Pinned Always-On-Top) */
.stage-narrative-bar {
position: absolute;
@@ -2621,9 +2638,26 @@ body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidd
}
.copilot-source-card__link {
display: inline-flex;
align-items: center;
gap: calc(3px * var(--hud-scale));
color: var(--hud-accent-strong);
text-decoration: none;
font-weight: 600;
line-height: 1.2;
}
.copilot-source-card__link > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(12.5px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.copilot-source-card__link:hover {
@@ -2786,11 +2820,12 @@ body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidd
font: inherit;
font-size: calc(11.5px * var(--hud-scale));
font-weight: 600;
white-space: nowrap;
cursor: pointer;
transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease, transform 0.18s ease;
}
.situational-copilot__send .material-symbols-rounded {
.situational-copilot__send > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
@@ -2801,6 +2836,8 @@ body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidd
font-size: calc(14px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
/* The send and stop glyphs sit above the label's visible center in their font boxes. */
translate: 0 calc(1px * var(--hud-scale));
user-select: none;
pointer-events: none;
}
@@ -4274,6 +4311,7 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
+24 -5
View File
@@ -405,8 +405,23 @@
white-space: nowrap;
}
.hud-select-trigger > .material-symbols-rounded {
.hud-select-trigger > .material-symbols-rounded,
.hud-select-menu__option > .material-symbols-rounded,
.earth-mobile-layer-card-icon.material-symbols-rounded,
.earth-mobile-search-chip > .material-symbols-rounded,
.earth-mobile-details-media-credit > .material-symbols-rounded,
.earth-mobile-details-actions .earth-mobile-action-btn > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.hud-select-trigger > .material-symbols-rounded {
color: var(--hud-text-soft);
font-size: calc(16px * var(--hud-scale));
}
@@ -510,7 +525,6 @@
}
.hud-select-menu__option > .material-symbols-rounded {
flex: 0 0 auto;
font-size: calc(14px * var(--hud-scale));
}
@@ -1241,7 +1255,7 @@
opacity: 0.46;
}
.earth-mobile-layer-card-icon {
.earth-mobile-layer-card-icon.material-symbols-rounded {
font-size: 22px;
color: var(--hud-accent-strong);
}
@@ -1347,6 +1361,7 @@
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
padding: 5px 12px;
border-radius: 18px;
border: 1px solid rgba(255, 255, 255, 0.1);
@@ -1360,6 +1375,10 @@
white-space: nowrap;
}
.earth-mobile-search-chip > .material-symbols-rounded {
font-size: 13px;
}
.earth-mobile-search-chip:active {
transform: scale(0.96);
}
@@ -3021,7 +3040,7 @@ label.is-disabled.earth-mobile-settings-card {
pointer-events: auto;
}
.earth-mobile-details-media-credit .material-symbols-rounded {
.earth-mobile-details-media-credit > .material-symbols-rounded {
font-size: 13px;
}
@@ -3181,7 +3200,7 @@ label.is-disabled.earth-mobile-settings-card {
transform: scale(0.97);
}
.earth-mobile-details-actions .earth-mobile-action-btn .material-symbols-rounded {
.earth-mobile-details-actions .earth-mobile-action-btn > .material-symbols-rounded {
font-size: 17px;
}
+52 -18
View File
@@ -510,13 +510,19 @@ body[data-callout-line-style="bold"] .callout-connector circle {
-webkit-user-select: none;
}
.info-card-source-link {
display: inline-block;
margin-top: calc(8px * var(--hud-scale));
.info-card-source-link,
.info-card-auth-link {
display: inline-flex;
align-items: center;
gap: calc(4px * var(--hud-scale));
color: var(--hud-accent);
text-decoration: none;
}
.info-card-source-link {
margin-top: calc(8px * var(--hud-scale));
font-size: var(--hud-font-size-sm);
line-height: 1.45;
text-decoration: none;
}
.info-card-source-link:hover,
@@ -755,10 +761,12 @@ body[data-callout-line-style="bold"] .callout-connector circle {
}
.info-card-compute-collect-button {
--info-card-collect-icon-size: calc(13px * var(--hud-scale));
position: relative;
display: inline-flex;
align-items: center;
gap: 4px;
justify-content: center;
gap: calc(4px * var(--hud-scale));
padding: calc(3px * var(--hud-scale)) calc(8px * var(--hud-scale));
background: transparent;
color: var(--hud-text-soft);
@@ -800,15 +808,27 @@ body[data-callout-line-style="bold"] .callout-connector circle {
flex-shrink: 0;
width: calc(10px * var(--hud-scale));
height: calc(10px * var(--hud-scale));
vertical-align: middle;
border: 1.5px solid rgba(201, 220, 255, 0.35);
border-top-color: #c9dcff;
border-radius: 999px;
animation: info-card-location-spin 0.8s linear infinite;
}
.info-card-compute-candidate-preview.is-loading::before {
margin-inline-end: 4px;
.info-card-compute-collect-button.is-loading::before {
box-sizing: border-box;
width: var(--info-card-collect-icon-size);
height: var(--info-card-collect-icon-size);
}
.info-card-compute-collect-button.is-loading > .material-symbols-rounded {
display: none;
}
.info-card-compute-candidate-preview.is-loading {
display: inline-flex;
align-items: center;
justify-content: center;
gap: calc(4px * var(--hud-scale));
}
.info-card-unresolved-item.is-locating .info-card-unresolved-index {
@@ -819,8 +839,29 @@ body[data-callout-line-style="bold"] .callout-connector circle {
position: absolute;
}
.info-card-compute-collect-button .material-symbols-rounded {
font-size: calc(13px * var(--hud-scale));
.info-card-compute-collect-button > .material-symbols-rounded,
.info-card-source-link > .material-symbols-rounded,
.info-card-auth-link > .material-symbols-rounded,
.earth-workflow-menu__icon.material-symbols-rounded,
.earth-target-tray__icon.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.info-card-compute-collect-button > .material-symbols-rounded {
font-size: var(--info-card-collect-icon-size);
}
.info-card-source-link > .material-symbols-rounded,
.info-card-auth-link > .material-symbols-rounded {
font-size: calc(12.5px * var(--hud-scale));
}
.info-card-compute-collect-status {
@@ -830,11 +871,8 @@ body[data-callout-line-style="bold"] .callout-connector circle {
}
.info-card-auth-link {
display: inline-block;
margin-left: calc(6px * var(--hud-scale));
color: var(--hud-accent);
font-weight: 500;
text-decoration: none;
}
.info-card-auth-link:hover,
@@ -1045,11 +1083,6 @@ body[data-callout-line-style="bold"] .callout-connector circle {
.earth-workflow-menu__icon.material-symbols-rounded,
.earth-target-tray__icon.material-symbols-rounded {
font-size: 16px;
width: 16px;
height: 16px;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex: 0 0 auto;
}
.earth-workflow-menu__label {
@@ -1160,6 +1193,7 @@ body[data-callout-line-style="bold"] .callout-connector circle {
font-weight: 600;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 5px;
cursor: pointer;
letter-spacing: 0;
+12 -7
View File
@@ -24,12 +24,22 @@
cursor: grabbing;
}
.layer-panel-icon {
flex-shrink: 0;
.layer-panel-icon.material-symbols-rounded,
.layer-row-icon.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(15px * var(--hud-scale));
color: var(--hud-text-soft);
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.layer-panel-icon {
pointer-events: none;
}
@@ -197,11 +207,6 @@
}
.layer-row-icon {
flex-shrink: 0;
font-size: calc(15px * var(--hud-scale));
color: var(--hud-text-soft);
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
transition: color 0.18s ease;
}
@@ -184,7 +184,28 @@ body:not(.layout-mode-mobile) .news-region-card.is-spotlight:hover:not(.is-dragg
}
.news-region-card__content::-webkit-scrollbar { display:none; width:0; height:0; }
.news-region-card__footer { display:flex; align-items:center; gap:calc(4px * var(--hud-scale)); padding:calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale)); flex-shrink:0; border-top:1px solid var(--hud-border); }
.news-region-card__footer a { margin-left:auto; color:var(--hud-accent,#91baff); font-size:var(--hud-font-size-sm); text-decoration:none; white-space:nowrap; }
.news-region-card__source {
display: inline-flex;
align-items: center;
gap: var(--hud-gap-xs);
margin-inline-start: auto;
color: var(--hud-accent, #91baff);
font-size: var(--hud-font-size-sm);
text-decoration: none;
white-space: nowrap;
}
.news-region-card__source > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(13px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.news-region-card__count { min-width:calc(36px * var(--hud-scale)); text-align:center; font-size:var(--hud-font-size-sm); }
.news-region-card button { cursor:pointer; }
.news-region-card button:disabled { opacity:.35; cursor:default; }
+5 -5
View File
@@ -719,11 +719,11 @@
</div>
<div class="earth-mobile-search-chips" role="group" aria-label="快捷分类筛选">
<button type="button" class="earth-mobile-search-chip is-active" data-search-filter="all">全部</button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="satellite" data-search-keyword="卫星"><span aria-hidden="true">🛰️ </span><span>卫星</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="cable" data-search-keyword="海缆"><span aria-hidden="true">🌊 </span><span>海缆</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="landing_point" data-search-keyword="登陆点"><span aria-hidden="true">📍 </span><span>登陆点</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="compute_center" data-search-keyword="算力"><span aria-hidden="true">🖥️ </span><span>算力</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="bgp" data-search-keyword="BGP"><span aria-hidden="true">⚡ </span><span>BGP</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="satellite" data-search-keyword="卫星"><span class="material-symbols-rounded" aria-hidden="true">satellite_alt</span><span>卫星</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="cable" data-search-keyword="海缆"><span class="material-symbols-rounded" aria-hidden="true">cable</span><span>海缆</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="landing_point" data-search-keyword="登陆点"><span class="material-symbols-rounded" aria-hidden="true">location_on</span><span>登陆点</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="compute_center" data-search-keyword="算力"><span class="material-symbols-rounded" aria-hidden="true">memory</span><span>算力</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="bgp" data-search-keyword="BGP"><span class="material-symbols-rounded" aria-hidden="true">hub</span><span>BGP</span></button>
</div>
<div id="mobile-earth-search-meta" class="earth-mobile-search-meta">输入关键词或轻点上方分类快速探索地球对象</div>
<div id="mobile-earth-search-results" class="earth-mobile-search-results" role="listbox" aria-label="移动端搜索结果"></div>
+9 -8
View File
@@ -74,6 +74,11 @@ function safeMediaUrl(value) {
}
}
function computeSourceLink(url, label, buttonClass) {
if (!/^https:\/\//i.test(url || "")) return "";
return `<a class="${buttonClass} compute-source-link" href="${escape(url)}" target="_blank" rel="noopener noreferrer"><span class="earth-settings-chip__label">${escape(label)}</span><span class="material-symbols-rounded" aria-hidden="true">open_in_new</span></a>`;
}
export function initComputeTopic({
setMapQuery,
focusFacility,
@@ -906,9 +911,6 @@ export function initComputeTopic({
}
function mobileRegionDetailHtml(entry, view = participantView(entry)) {
const sourceUrl = /^https:\/\//i.test(view.evidence?.url || "")
? view.evidence.url
: "";
const isBilateral = ["CN", "US"].includes(entry.code) && countries.includes("CN") && countries.includes("US");
const facilityStatus = facilityError
? `<div class="compute-mobile__inline-error" role="alert">${escape(facilityError)} <button type="button" class="earth-mobile-action-btn earth-mobile-action-btn--ghost" data-action="retry">${text("重试", "Retry")}</button></div>`
@@ -929,7 +931,7 @@ export function initComputeTopic({
${view.members.length ? `<section class="compute-mobile__detail-section"><h3>${text("区域成员", "Region members")} <span>${view.members.length}</span></h3><div class="compute-card__members">${view.members.map((member) => `<span class="earth-mobile-settings-chip is-active earth-settings-chip--with-icon">${participantIdentity(member)}<span>${escape(nameOf(member))}</span></span>`).join("")}</div></section>` : ""}
<section class="compute-mobile__detail-section"><h3>${text("已核验设施样本", "Verified Facility Samples")} <span>${escape(view.sampleStatus)}</span></h3><p class="earth-mobile-detail-empty">${text("设施条数仅反映已收录公开样本。", "Facility counts reflect publicly indexed samples only.")}</p>${view.sourceBreakdown ? `<p class="earth-mobile-detail-type">${escape(view.sourceBreakdown)}</p>` : ""}${facilityStatus}</section>
${mediaHtml(view.locations)}
${view.evidence ? `<section class="compute-mobile__detail-section"><h3>${text("来源与证据", "Source and evidence")}</h3><p class="earth-mobile-detail-title">${escape(view.evidence.title || "")}</p><p class="earth-mobile-detail-type">${escape(view.evidence.publisher || "")} · ${escape(view.evidence.report_year || view.evidence.published_at || "")}</p>${view.evidence.locator ? `<p class="earth-mobile-detail-type">${escape(view.evidence.locator)}</p>` : ""}${sourceUrl ? `<a class="earth-mobile-action-btn" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开来源", "Open source")} ↗</a>` : ""}</section>` : ""}`;
${view.evidence ? `<section class="compute-mobile__detail-section"><h3>${text("来源与证据", "Source and evidence")}</h3><p class="earth-mobile-detail-title">${escape(view.evidence.title || "")}</p><p class="earth-mobile-detail-type">${escape(view.evidence.publisher || "")} · ${escape(view.evidence.report_year || view.evidence.published_at || "")}</p>${view.evidence.locator ? `<p class="earth-mobile-detail-type">${escape(view.evidence.locator)}</p>` : ""}${computeSourceLink(view.evidence.url, text("打开来源", "Open source"), "earth-mobile-action-btn")}</section>` : ""}`;
}
function destroyMobileCardPanels() {
@@ -1042,12 +1044,12 @@ export function initComputeTopic({
const lineageMarkup = renderLineageDrawerHtml(evidence);
if (body.innerHTML !== lineageMarkup) body.innerHTML = lineageMarkup;
} else if (evidence) {
const sourceUrl = /^https:\/\//i.test(evidence.url || "") ? evidence.url : "";
evidencePanel.querySelector(".hud-panel__title").textContent = evidence.title;
const pubDateNote = evidence.published_at
? `${text("发布日", "Published")} ${evidence.published_at}`
: `${text("报告年", "Report year")} ${evidence.report_year || ""}`;
const sourceMarkup = `<p class="compute-evidence__meta"><strong>${escape(evidence.publisher)}</strong> · ${escape(pubDateNote)}</p>${evidence.locator ? `<p class="compute-evidence__locator"><span class="material-symbols-rounded" aria-hidden="true">find_in_page</span><span>${escape(evidence.locator)}</span></p>` : ""}${sourceUrl ? `<a class="earth-settings-chip compute-evidence__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开权威原文", "Open verified source")} ↗</a>` : ""}`;
const sourceLink = computeSourceLink(evidence.url, text("打开权威原文", "Open verified source"), "earth-settings-chip compute-evidence__link");
const sourceMarkup = `<p class="compute-evidence__meta"><strong>${escape(evidence.publisher)}</strong> · ${escape(pubDateNote)}</p>${evidence.locator ? `<p class="compute-evidence__locator"><span class="material-symbols-rounded" aria-hidden="true">find_in_page</span><span>${escape(evidence.locator)}</span></p>` : ""}${sourceLink}`;
if (body.innerHTML !== sourceMarkup) body.innerHTML = sourceMarkup;
}
}
@@ -1063,7 +1065,6 @@ export function initComputeTopic({
}
const current = lineageData?.current || null;
const src = current?.source || fallbackEvidence || null;
const sourceUrl = /^https:\/\//i.test(src?.url || "") ? src.url : "";
const timestamps = lineageData?.timestamps || null;
const timeline = Array.isArray(lineageData?.timeline) ? lineageData.timeline : [];
const unit = current?.unit || (lineageTarget?.metric === "absolute" ? "EFlops" : "%");
@@ -1086,7 +1087,7 @@ export function initComputeTopic({
${src.locator ? `<p class="compute-evidence__locator"><span class="material-symbols-rounded" aria-hidden="true">find_in_page</span><span>${escape(src.locator)}</span></p>` : ""}
${src.excerpt ? `<blockquote class="compute-evidence__excerpt">${escape(src.excerpt)}</blockquote>` : ""}
${src.content_sha256 ? `<p class="compute-evidence__hash" title="${escape(src.content_sha256)}"><span>SHA-256</span><code>${escape(src.content_sha256.slice(0, 20))}…</code></p>` : ""}
${sourceUrl ? `<a class="earth-settings-chip compute-evidence__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开权威原文", "Open verified source")} ↗</a>` : ""}
${computeSourceLink(src.url, text("打开权威原文", "Open verified source"), "earth-settings-chip compute-evidence__link")}
</section>`
: "";
+9 -2
View File
@@ -168,7 +168,11 @@ function applyLocationStatusElement(statusEl, statusText, authRequired = false)
link.href = getAdminLoginUrl();
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.textContent = `${infoText('前往管理员登录')} ↗`;
const icon = document.createElement('span');
icon.className = 'material-symbols-rounded';
icon.setAttribute('aria-hidden', 'true');
icon.textContent = 'open_in_new';
link.append(infoText('前往管理员登录'), icon);
link.addEventListener('click', (event) => {
event.stopPropagation();
});
@@ -840,7 +844,10 @@ function renderDefaultCardContent(content, config, data) {
const fields = [['精度 / 测量', `${metadata.precision || '—'} / ${metadata.measurement || '—'}`]];
html += fields.map(([label, value]) => `<div class="info-card-property"><span class="info-card-label">${escapeInfoCardHtml(infoText(label))}</span><span class="info-card-value">${escapeInfoCardHtml(value)}</span></div>`).join('');
if (/^https?:\/\//i.test(metadata.source_url || '')) {
html += `<a class="info-card-source-link" href="${escapeInfoCardHtml(metadata.source_url)}" target="_blank" rel="noopener noreferrer">${escapeInfoCardHtml(infoText('查看原始来源'))} ↗</a>`;
html += `<a class="info-card-source-link" href="${escapeInfoCardHtml(metadata.source_url)}" target="_blank" rel="noopener noreferrer">
<span>${escapeInfoCardHtml(infoText('查看原始来源'))}</span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>`;
}
}
@@ -5,7 +5,6 @@ import {
toggleCables,
} from "./cables.js";
import {
clearSatelliteData,
getSatelliteLegendItems,
loadSatellites,
toggleSatellites,
@@ -173,7 +172,6 @@ function registerSatelliteStartupTask() {
);
await context.yieldFrame(12);
try {
clearSatelliteData();
const canApplyUpdate = () => !context.isCancelled() && context.isSatellitesEnabled();
const loadResult = await loadSatellites({
limit: context.getInitialSatelliteLoadLimit(),
-1
View File
@@ -4337,7 +4337,6 @@ async function ensureSatellitesEnabled(options = {}) {
createSatellites(scene, earth);
}
clearSatelliteData();
let loadResult;
try {
loadResult = await loadSatellites({
+17 -3
View File
@@ -74,7 +74,7 @@ export function initNewsRegionCards({ rootParent, spatial }) {
} : null;
card.source.hidden = !/^https?:\/\//i.test(url);
if (!card.source.hidden) card.source.href = url; else card.source.removeAttribute("href");
card.source.textContent = text("阅读原文 ↗","Read source ↗");
card.sourceLabel.textContent = text("阅读原文", "Read source");
if (card.analyze) card.analyze.disabled = !card.currentStory;
card.scrollbar?.update();
}
@@ -91,10 +91,24 @@ export function initNewsRegionCards({ rootParent, spatial }) {
const element=document.createElement("article");
element.className="hud-panel info-card news news-region-card";
element.dataset.region=region.key;
element.innerHTML=`<header class="info-card-header hud-panel-drag-handle"><span class="info-card-icon" aria-hidden="true">${NEWS_CARD_ICON}</span><h3 class="news-region-card__headline"></h3><span class="news-region-card__region"></span><div class="hud-panel__actions">${iconButton("news-analyze","forum",text("在 AI 参谋中分析","Analyze in AI Copilot"))}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}</div></header><div class="news-region-card__body hud-panel__body hud-panel__body--collapsible"><div class="info-card-content news-region-card__content hud-scroll-region"></div><footer class="news-region-card__footer">${iconButton("news-prev","chevron_left",text("上一条新闻","Previous story"))}<span class="news-region-card__count"></span>${iconButton("news-next","chevron_right",text("下一条新闻","Next story"))}${iconButton("news-play","pause",text("暂停轮播","Pause rotation"))}<a target="_blank" rel="noopener noreferrer" hidden></a></footer></div>`;
element.innerHTML = `<header class="info-card-header hud-panel-drag-handle"><span class="info-card-icon" aria-hidden="true">${NEWS_CARD_ICON}</span><h3 class="news-region-card__headline"></h3><span class="news-region-card__region"></span><div class="hud-panel__actions">${iconButton("news-analyze","forum",text("在 AI 参谋中分析","Analyze in AI Copilot"))}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}</div></header>
<div class="news-region-card__body hud-panel__body hud-panel__body--collapsible">
<div class="info-card-content news-region-card__content hud-scroll-region"></div>
<footer class="news-region-card__footer">
${iconButton("news-prev", "chevron_left", text("上一条新闻", "Previous story"))}
<span class="news-region-card__count"></span>
${iconButton("news-next", "chevron_right", text("下一条新闻", "Next story"))}
${iconButton("news-play", "pause", text("暂停轮播", "Pause rotation"))}
<a class="news-region-card__source" target="_blank" rel="noopener noreferrer" hidden>
<span class="news-region-card__source-label"></span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>
</footer>
</div>`;
const card={ element, hovered:false, signature:null, typing:false, writer:createTypewriter(), currentStory:null,
title:element.querySelector("h3"), region:element.querySelector(".news-region-card__region"), content:element.querySelector(".news-region-card__content"),
count:element.querySelector(".news-region-card__count"),source:element.querySelector("a"),
count:element.querySelector(".news-region-card__count"),source:element.querySelector(".news-region-card__source"),
sourceLabel:element.querySelector(".news-region-card__source-label"),
previous:element.querySelector('[data-action="news-prev"]'),next:element.querySelector('[data-action="news-next"]'),play:element.querySelector('[data-action="news-play"]'),analyze:element.querySelector('[data-action="news-analyze"]'),
};
card.panel=createHUDPanel({panel:element,header:element.querySelector("header"),body:element.querySelector(".news-region-card__body"),collapseBtn:element.querySelector('[data-action="card-collapse"]'),expandLabel:text("展开新闻","Expand news"),collapseLabel:text("折叠新闻","Collapse news")});
+27 -9
View File
@@ -1074,6 +1074,8 @@ function scheduleBackgroundSatelliteValidation({
})();
}
const lastSatelliteEtags = new Map();
export async function loadSatellites(options = {}) {
abortActiveSatelliteRevalidation();
const limit = getRequestedSatelliteLimit(options.limit);
@@ -1117,7 +1119,7 @@ export async function loadSatellites(options = {}) {
const networkResult = await fetchSatellitesWithRetry({
url: url.toString(),
etag: options.forceNetwork ? null : cachedSnapshot?.etag || null,
etag: options.cacheBust ? null : cachedSnapshot?.etag || lastSatelliteEtags.get(cacheKey) || null,
timeoutMs: options.timeoutMs || SATELLITE_FETCH_TIMEOUT_MS,
maxAttempts: options.maxAttempts || SATELLITE_FETCH_MAX_ATTEMPTS,
signal: options.signal,
@@ -1127,17 +1129,33 @@ export async function loadSatellites(options = {}) {
throw createAbortError("Satellite load aborted");
}
if (networkResult.notModified && cachedFeatures.length > 0) {
applyDecodedSatelliteFeatures(cachedFeatures);
return {
count: cachedFeatures.length,
requestedLimit: limit,
fromCache: true,
notModified: true,
};
if (networkResult.notModified) {
if (networkResult.etag) {
lastSatelliteEtags.set(cacheKey, networkResult.etag);
}
if (satelliteData.length > 0) {
return {
count: satelliteData.length,
requestedLimit: limit,
fromCache: true,
notModified: true,
};
}
if (cachedFeatures.length > 0) {
applyDecodedSatelliteFeatures(cachedFeatures);
return {
count: cachedFeatures.length,
requestedLimit: limit,
fromCache: true,
notModified: true,
};
}
}
const decodedFeatures = decodeSatellitePayload(networkResult.payload);
if (networkResult.etag) {
lastSatelliteEtags.set(cacheKey, networkResult.etag);
}
void writeSatelliteSnapshot(cacheKey, {
etag: networkResult.etag,
payload: networkResult.payload,
@@ -1274,7 +1274,10 @@ export function initSituationalCopilot({
<div class="copilot-source-card__title">${escape(selectedEv.title || turn.activeEvidenceId)}</div>
<div class="copilot-source-card__meta">
<span>${escape([selectedEv.publisher, selectedEv.locator].filter(Boolean).join(" · "))}</span>
${sourceUrl ? `<a class="copilot-source-card__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${escape(text("原文", "Source"))} ↗</a>` : ""}
${sourceUrl ? `<a class="copilot-source-card__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">
<span>${escape(text("原文", "Source"))}</span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>` : ""}
</div>
</div>
</div>` : ""}
+4 -1
View File
@@ -534,7 +534,10 @@ function renderEvidenceDrawerBlock(block, { collapsedOverride } = {}) {
</div>
<div class="wb-evidence-item__meta">
<span>${escapeWorkbenchHtml(metaParts)}</span>
${safeUrl ? `<a class="copilot-source-card__link" href="${escapeWorkbenchHtml(safeUrl)}" target="_blank" rel="noopener noreferrer">${escapeWorkbenchHtml(t("原文", "Source"))} ↗</a>` : ""}
${safeUrl ? `<a class="copilot-source-card__link" href="${escapeWorkbenchHtml(safeUrl)}" target="_blank" rel="noopener noreferrer">
<span>${escapeWorkbenchHtml(t("原文", "Source"))}</span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>` : ""}
</div>
</li>`;
})
@@ -5,6 +5,7 @@ import {
useReactTable,
type ColumnDef,
type SortingState,
type VisibilityState,
} from '@tanstack/react-table'
import { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react'
import {
@@ -86,6 +87,7 @@ interface DataTableProps<TData> {
resizableColumns?: boolean
columnWidthStorageKey?: string
enableSorting?: boolean
hiddenColumnIds?: readonly string[]
waterfall?: DataTableWaterfallConfig | false
scrollResetKey?: string | number
}
@@ -104,6 +106,7 @@ export function DataTable<TData>({
resizableColumns = true,
columnWidthStorageKey,
enableSorting,
hiddenColumnIds,
waterfall,
scrollResetKey,
}: DataTableProps<TData>) {
@@ -130,11 +133,20 @@ export function DataTable<TData>({
const [resizingColumnId, setResizingColumnId] = useState<string | null>(null)
const resizeCleanupRef = useRef<(() => void) | null>(null)
const columnVisibility = useMemo<VisibilityState>(() => {
if (!hiddenColumnIds?.length) return {}
const next: VisibilityState = {}
for (const id of hiddenColumnIds) {
next[id] = false
}
return next
}, [hiddenColumnIds])
const table = useReactTable({
data,
columns: memoizedColumns,
enableSorting: effectiveEnableSorting,
state: { sorting },
state: { sorting, columnVisibility },
onSortingChange: setSorting,
getRowId,
getCoreRowModel: getCoreRowModel(),
@@ -519,7 +531,7 @@ export function DataTable<TData>({
const allVisibleSelected =
visibleSelectableIds.length > 0 && visibleSelectableIds.every((rowId) => selection?.selectedRowIds.has(rowId))
const someVisibleSelected = visibleSelectableIds.some((rowId) => selection?.selectedRowIds.has(rowId))
const columnCount = columns.length + (selection ? 1 : 0) + (hasSpacer ? 1 : 0)
const columnCount = leafHeaders.length + (selection ? 1 : 0) + (hasSpacer ? 1 : 0)
const showWaterfallFooter =
!footer &&
@@ -23,6 +23,7 @@ import { adminRouteGroups, getVisibleAdminRoutes } from '../../routes/manifest'
import { useAdminSearch } from '../../search/AdminSearchContext'
import { AdminSearchSpotlight } from '../../search/AdminSearchSpotlight'
import { Button } from '../ui/button'
import { fetchRuntimeVersion, getCachedRuntimeVersion } from './runtimeVersion'
import {
ensureGroupOpen,
getInitialOpenKeys,
@@ -35,14 +36,22 @@ import {
writeStoredOpenKeys,
} from './sidebarState'
const COMPACT_DESKTOP_MEDIA_QUERY = '(min-width: 761px) and (max-width: 1360px)'
let cachedOpenKeys: string[] | null = null
let cachedCollapsed: boolean | null = null
let cachedCompactCollapsedOverride: boolean | null = null
let cachedMenuScrollTop = 0
function sameStringArray(a: readonly string[], b: readonly string[]) {
return a.length === b.length && a.every((item, index) => item === b[index])
}
function matchesCompactDesktop(): boolean {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
return window.matchMedia(COMPACT_DESKTOP_MEDIA_QUERY).matches
}
export function AdminLayout({ children }: { children: ReactNode }) {
const location = useLocation()
const navigate = useNavigate()
@@ -56,6 +65,9 @@ export function AdminLayout({ children }: { children: ReactNode }) {
const [searchOpen, setSearchOpen] = useState(false)
const [preferencesOpen, setPreferencesOpen] = useState(false)
const [highlightedSearchIndex, setHighlightedSearchIndex] = useState(0)
const [runtimeVersion, setRuntimeVersion] = useState<string>(
() => getCachedRuntimeVersion() ?? packageJson.version,
)
const menuViewportRef = useRef<HTMLDivElement>(null)
const mobileMenuViewportRef = useRef<HTMLDivElement>(null)
const searchInputRef = useRef<HTMLInputElement>(null)
@@ -80,12 +92,34 @@ export function AdminLayout({ children }: { children: ReactNode }) {
const activeGroupKey = activeRoute?.group
const activeRouteLabel = activeRoute ? t(activeRoute.labelKey) : ''
const [collapsed, setCollapsed] = useState<boolean>(() => {
const [desktopCollapsed, setDesktopCollapsed] = useState<boolean>(() => {
if (cachedCollapsed !== null) return cachedCollapsed
const stored = readStoredCollapsed()
cachedCollapsed = stored ?? false
return cachedCollapsed
})
const [isCompactDesktop, setIsCompactDesktop] = useState<boolean>(matchesCompactDesktop)
const [compactCollapsedOverride, setCompactCollapsedOverride] = useState<boolean | null>(
() => cachedCompactCollapsedOverride,
)
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return
const mediaQuery = window.matchMedia(COMPACT_DESKTOP_MEDIA_QUERY)
const handleChange = () => {
const matches = mediaQuery.matches
setIsCompactDesktop(matches)
if (!matches) {
cachedCompactCollapsedOverride = null
setCompactCollapsedOverride(null)
}
}
handleChange()
mediaQuery.addEventListener('change', handleChange)
return () => mediaQuery.removeEventListener('change', handleChange)
}, [])
const collapsed = isCompactDesktop ? (compactCollapsedOverride ?? true) : desktopCollapsed
const [openKeys, setOpenKeys] = useState<string[]>(() => {
const initial = getInitialOpenKeys({
@@ -114,9 +148,14 @@ export function AdminLayout({ children }: { children: ReactNode }) {
})), [t])
const updateCollapsed = (nextCollapsed: boolean) => {
if (isCompactDesktop) {
cachedCompactCollapsedOverride = nextCollapsed
setCompactCollapsedOverride(nextCollapsed)
return
}
cachedCollapsed = nextCollapsed
writeStoredCollapsed(nextCollapsed)
setCollapsed(nextCollapsed)
setDesktopCollapsed(nextCollapsed)
}
const updateOpenKeys = (nextKeys: string[]) => {
@@ -184,6 +223,18 @@ export function AdminLayout({ children }: { children: ReactNode }) {
void adminSearch.ensureDynamicIndex(searchQuery)
}, [adminSearch, searchQuery])
useEffect(() => {
let active = true
void fetchRuntimeVersion(packageJson.version).then((resolved) => {
if (active) {
setRuntimeVersion(resolved)
}
})
return () => {
active = false
}
}, [])
const renderNav = ({ mobile }: { mobile: boolean }) => {
const isCollapsed = !mobile && collapsed
return (
@@ -284,7 +335,18 @@ export function AdminLayout({ children }: { children: ReactNode }) {
<span className="admin__account-avatar" aria-hidden="true">{userInitial}</span>
<div>
<strong>{t('admin.greeting', { name: username })}</strong>
<span>{t('admin.version')} v{packageJson.version}</span>
<span
title={
runtimeVersion !== packageJson.version
? t('admin.versionDetail', {
backend: runtimeVersion,
ui: packageJson.version,
})
: undefined
}
>
{t('admin.version')} v{runtimeVersion}
</span>
</div>
</div>
<div className="admin__account-actions">
@@ -74,12 +74,72 @@ export function useSplitPaneResize({
const [width, setWidth] = useState<number>(() =>
readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth),
)
const preferredWidthRef = useRef<number>(
readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth),
)
const [isDragging, setIsDragging] = useState(false)
const dragCleanupRef = useRef<(() => void) | null>(null)
useEffect(() => {
setWidth(readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth))
}, [defaultWidth, maxWidth, minWidth, storageKey])
const stored = readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth)
preferredWidthRef.current = stored
const containerW = containerRef?.current?.clientWidth
const next = clampSplitPaneWidth(stored, minWidth, maxWidth, containerW, minOppositeWidth)
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${next}px`)
}
setWidth(next)
}, [containerRef, cssVarName, defaultWidth, maxWidth, minOppositeWidth, minWidth, storageKey])
useEffect(() => {
const container = containerRef?.current
let rafId = 0
const syncClamp = () => {
rafId = 0
if (document.body.classList.contains('an-is-resizing')) return
const containerW = container?.clientWidth || window.innerWidth
if (!Number.isFinite(containerW) || containerW <= 0) return
const next = clampSplitPaneWidth(
preferredWidthRef.current,
minWidth,
maxWidth,
containerW,
minOppositeWidth,
)
if (cssVarName && container) {
container.style.setProperty(cssVarName, `${next}px`)
}
setWidth((prev) => {
if (prev === next) return prev
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
return next
})
}
const scheduleSync = () => {
if (!rafId) {
rafId = window.requestAnimationFrame(syncClamp)
}
}
scheduleSync()
if (typeof ResizeObserver !== 'undefined' && container) {
const observer = new ResizeObserver(scheduleSync)
observer.observe(container)
return () => {
if (rafId) window.cancelAnimationFrame(rafId)
observer.disconnect()
}
}
window.addEventListener('resize', scheduleSync)
return () => {
if (rafId) window.cancelAnimationFrame(rafId)
window.removeEventListener('resize', scheduleSync)
}
}, [containerRef, cssVarName, maxWidth, minOppositeWidth, minWidth])
useEffect(() => () => {
dragCleanupRef.current?.()
@@ -138,6 +198,7 @@ export function useSplitPaneResize({
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${latestWidth}px`)
}
preferredWidthRef.current = latestWidth
setIsDragging(false)
setWidth(latestWidth)
writeStoredSplitWidth(storageKey, latestWidth)
@@ -169,10 +230,15 @@ export function useSplitPaneResize({
step === Number.NEGATIVE_INFINITY || step === Number.POSITIVE_INFINITY
? clampSplitPaneWidth(defaultWidth, minWidth, maxWidth, containerW, minOppositeWidth)
: clampSplitPaneWidth(width + step, minWidth, maxWidth, containerW, minOppositeWidth)
preferredWidthRef.current = next
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${next}px`)
}
setWidth(next)
writeStoredSplitWidth(storageKey, next)
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
},
[containerRef, defaultWidth, maxWidth, minOppositeWidth, minWidth, side, storageKey, width],
[containerRef, cssVarName, defaultWidth, maxWidth, minOppositeWidth, minWidth, side, storageKey, width],
)
return { width, isDragging, onPointerDown, onKeyDown }
@@ -0,0 +1,70 @@
const SEMVER_PATTERN = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/
let cachedRuntimeVersion: string | null = null
let inFlightPromise: Promise<string> | null = null
export function parseHealthVersion(payload: unknown): string | null {
if (!payload || typeof payload !== 'object') {
return null
}
const rawVersion = (payload as { version?: unknown }).version
if (typeof rawVersion !== 'string') {
return null
}
const normalized = rawVersion.trim().replace(/^v/i, '')
if (!normalized || !SEMVER_PATTERN.test(normalized)) {
return null
}
return normalized
}
export function getCachedRuntimeVersion(): string | null {
return cachedRuntimeVersion
}
export function resetRuntimeVersionCache(): void {
cachedRuntimeVersion = null
inFlightPromise = null
}
async function requestRuntimeVersion(
fallback: string,
fetcher: typeof fetch,
): Promise<string> {
try {
const response = await fetcher('/api/health', { cache: 'no-store' })
if (!response.ok) {
return fallback
}
const data: unknown = await response.json()
const version = parseHealthVersion(data)
if (!version) {
return fallback
}
cachedRuntimeVersion = version
return version
} catch {
return fallback
}
}
export async function fetchRuntimeVersion(
fallback: string,
fetcher: typeof fetch = fetch,
): Promise<string> {
if (cachedRuntimeVersion) {
return cachedRuntimeVersion
}
if (fetcher === fetch && inFlightPromise) {
return inFlightPromise
}
const promise = requestRuntimeVersion(fallback, fetcher).finally(() => {
if (fetcher === fetch) {
inFlightPromise = null
}
})
if (fetcher === fetch) {
inFlightPromise = promise
}
return promise
}
+3 -2
View File
@@ -78,7 +78,6 @@ export function ConfirmDialog({
open={open}
onOpenChange={onOpenChange}
title={title}
description={description}
width={420}
footer={(
<>
@@ -91,7 +90,9 @@ export function ConfirmDialog({
</>
)}
>
<span className="sr-only">{description || t('common.confirm')}</span>
<DialogPrimitive.Description className="an-confirm-dialog__body">
{description || t('common.confirm')}
</DialogPrimitive.Description>
</Dialog>
)
}
+16 -13
View File
@@ -1,5 +1,6 @@
import * as SelectPrimitive from '@radix-ui/react-select'
import { Check, ChevronDown } from 'lucide-react'
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { cn } from '../../utils'
const EMPTY_OPTION_VALUE = '__an_select_empty__'
@@ -39,19 +40,21 @@ export function Select({ value, onValueChange, options, placeholder, disabled, c
</SelectPrimitive.Trigger>
<SelectPrimitive.Portal>
<SelectPrimitive.Content className="an-select__content" position="popper" sideOffset={4}>
<SelectPrimitive.Viewport>
{options.map((option) => {
const itemValue = option.value === '' ? EMPTY_OPTION_VALUE : option.value
return (
<SelectPrimitive.Item key={itemValue} value={itemValue} className="an-select__item">
<SelectPrimitive.ItemText>{option.label}</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator className="an-select__indicator">
<Check size={14} />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
})}
</SelectPrimitive.Viewport>
<Scrollbar className="an-select__scroll" axis="y">
<SelectPrimitive.Viewport>
{options.map((option) => {
const itemValue = option.value === '' ? EMPTY_OPTION_VALUE : option.value
return (
<SelectPrimitive.Item key={itemValue} value={itemValue} className="an-select__item">
<SelectPrimitive.ItemText>{option.label}</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator className="an-select__indicator">
<Check size={14} />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
})}
</SelectPrimitive.Viewport>
</Scrollbar>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
</SelectPrimitive.Root>
+45 -36
View File
@@ -1081,41 +1081,6 @@
letter-spacing: 0;
}
.an-advisor-textarea,
.an-chat-textarea,
.an-advisor-page .an-json-editor {
scrollbar-width: thin;
scrollbar-color: var(--an-border-strong) transparent;
}
.an-advisor-textarea::-webkit-scrollbar,
.an-chat-textarea::-webkit-scrollbar,
.an-advisor-page .an-json-editor::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.an-advisor-textarea::-webkit-scrollbar-button,
.an-chat-textarea::-webkit-scrollbar-button,
.an-advisor-page .an-json-editor::-webkit-scrollbar-button {
display: none;
width: 0;
height: 0;
}
.an-advisor-textarea::-webkit-scrollbar-track,
.an-chat-textarea::-webkit-scrollbar-track,
.an-advisor-page .an-json-editor::-webkit-scrollbar-track {
background: transparent;
}
.an-advisor-textarea::-webkit-scrollbar-thumb,
.an-chat-textarea::-webkit-scrollbar-thumb,
.an-advisor-page .an-json-editor::-webkit-scrollbar-thumb {
border-radius: 999px;
background: var(--an-border-strong);
}
/* React Flow 3-Column Workflow Studio with Resizer Tracks */
.an-workflow-studio {
flex: 1 1 0;
@@ -1283,6 +1248,14 @@
box-shadow: var(--an-shadow);
}
.an-workflow-compact-rail-toggle.tui-button {
display: none;
}
.an-workflow-rail-backdrop {
display: none;
}
.an-workflow-mobile-node-bar {
display: none;
position: absolute;
@@ -2000,8 +1973,44 @@
@media (max-width: 1360px) and (min-width: 1025px) {
.an-workflow-studio {
grid-template-columns: var(--an-wf-rail-width, 244px) 14px minmax(300px, 1fr) 14px var(--an-wf-inspector-width, 356px);
position: relative;
grid-template-columns: minmax(460px, 1fr) 14px var(--an-wf-inspector-width, 340px);
}
.an-workflow-studio > .an-detail-resizer:first-of-type {
display: none;
}
.an-workflow-rail {
display: none;
}
.an-workflow-studio.is-compact-rail-open .an-workflow-rail-backdrop {
display: block;
position: absolute;
inset: 0;
z-index: 24;
border-radius: 10px;
background: rgba(15, 23, 42, 0.24);
}
.admin-theme-root[data-theme='dark'] .an-workflow-studio.is-compact-rail-open .an-workflow-rail-backdrop {
background: rgba(2, 6, 23, 0.48);
}
.an-workflow-studio.is-compact-rail-open .an-workflow-rail {
display: flex;
position: absolute;
inset: 0 auto 0 0;
width: min(300px, calc(100% - 48px));
z-index: 25;
box-shadow: 12px 0 32px rgba(2, 6, 23, 0.34);
}
.an-workflow-compact-rail-toggle.tui-button {
display: inline-flex;
}
.an-playground-shell.has-drawer {
grid-template-columns: minmax(0, 1fr) 14px var(--an-pg-drawer-width, 332px);
}
+62 -3
View File
@@ -602,6 +602,8 @@ export default function AdvisorWorkflows() {
const [inspectorWidth, setInspectorWidth] = useState<number>(() =>
readStoredWidth(WF_INSPECTOR_WIDTH_KEY, 396, 340, 560),
)
const [studioContainerWidth, setStudioContainerWidth] = useState(0)
const [compactRailOpen, setCompactRailOpen] = useState(false)
const [draggingResizer, setDraggingResizer] = useState<'rail' | 'inspector' | null>(null)
const [historyMeta, setHistoryMeta] = useState<{ canUndo: boolean; canRedo: boolean }>({
canUndo: false,
@@ -991,6 +993,34 @@ export default function AdvisorWorkflows() {
window.addEventListener('pointerup', stopMove, { once: true })
}, [inspectorWidth, railWidth])
useEffect(() => {
const el = studioRef.current
if (!el) return
const sync = () => {
const next = el.clientWidth
if (next > 0) setStudioContainerWidth(next)
}
sync()
if (typeof ResizeObserver === 'undefined') {
window.addEventListener('resize', sync)
return () => window.removeEventListener('resize', sync)
}
const observer = new ResizeObserver(sync)
observer.observe(el)
return () => observer.disconnect()
}, [])
useEffect(() => {
if (!compactRailOpen) return
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key === 'Escape') {
setCompactRailOpen(false)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [compactRailOpen])
const commitNodePositions = useCallback(
(movedNodes: Node<FlowNodeData>[]) => {
if (!movedNodes.length) return
@@ -1488,6 +1518,7 @@ export default function AdvisorWorkflows() {
(wfId: string, switchToCanvas = false) => {
setSelectedWfId(wfId)
setDeleteConfirmPending(false)
setCompactRailOpen(false)
setSearchParams({ workflow: wfId }, { replace: true })
if (switchToCanvas) setMobilePane('canvas')
},
@@ -2398,15 +2429,32 @@ export default function AdvisorWorkflows() {
<div
ref={studioRef}
className="an-workflow-studio"
className={`an-workflow-studio${compactRailOpen ? ' is-compact-rail-open' : ''}`}
data-mobile-pane={mobilePane}
style={
{
'--an-wf-rail-width': `${railWidth}px`,
'--an-wf-inspector-width': `${inspectorWidth}px`,
'--an-wf-rail-width': `${
studioContainerWidth > 0 && studioContainerWidth < railWidth + inspectorWidth + 376
? Math.max(230, Math.min(railWidth, studioContainerWidth - Math.min(inspectorWidth, 356) - 376))
: railWidth
}px`,
'--an-wf-inspector-width': `${
studioContainerWidth > 0
? typeof window !== 'undefined' && window.innerWidth <= 1360 && window.innerWidth > 1024
? Math.max(300, Math.min(inspectorWidth, studioContainerWidth - 474))
: Math.max(300, Math.min(inspectorWidth, studioContainerWidth - railWidth - 376))
: inspectorWidth
}px`,
} as CSSProperties
}
>
{compactRailOpen ? (
<div
className="an-workflow-rail-backdrop"
aria-hidden="true"
onClick={() => setCompactRailOpen(false)}
/>
) : null}
<aside className="an-workflow-rail" aria-label={tx('工作流目录', 'Workflow catalog')}>
<header className="an-drawer-pane__header">
<h3>{tx(`工作流目录 (${workflows.length})`, `Workflows (${workflows.length})`)}</h3>
@@ -2556,6 +2604,17 @@ export default function AdvisorWorkflows() {
</div>
<div className="an-workflow-canvas-actions">
<Button
type="button"
size="icon"
variant={compactRailOpen ? 'primary' : 'subtle'}
className="an-workflow-compact-rail-toggle"
onClick={() => setCompactRailOpen((open) => !open)}
title={tx(compactRailOpen ? '收起工作流目录' : '展开工作流目录', compactRailOpen ? 'Hide workflows' : 'Show workflows')}
aria-label={tx(compactRailOpen ? '收起工作流目录' : '展开工作流目录', compactRailOpen ? 'Hide workflows' : 'Show workflows')}
>
<Workflow size={14} />
</Button>
<Button
type="button"
size="icon"
@@ -139,7 +139,7 @@ export function CardImageSettings({active}:{active:boolean}) {
<Button size="icon" variant="subtle" title={t('重新加载','Reload')} aria-label={t('重新加载','Reload')} disabled={busy} onClick={()=>dirty?setConfirmation({label:t('放弃未保存的修改并重新加载?','Discard unsaved edits and reload?'),run:refresh}):refresh()}><RefreshCw size={16}/></Button>
<Button onClick={()=>void save()} disabled={!dirty || busy} loading={busy}><Save size={16}/>{t('保存','Save')}</Button>
</div>
{errorText?<p className="an-card-images-error" role="alert">{errorText}</p>:null}
{errorText?<Scrollbar className="an-card-images-error" axis="y"><p className="an-card-images-error__text" role="alert">{errorText}</p></Scrollbar>:null}
{message?<p className="an-card-images-message" role="status">{message}</p>:null}
{!draft?<p className="an-card-images-message">{busy?t('加载中…','Loading…'):t('暂无可用配置','Configuration unavailable')}</p>:<fieldset
ref={workspaceRef}
@@ -475,7 +475,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<div className="an-compute-status" role="status">
{message || (error && !saved ? t('配置读取失败', 'Configuration unavailable') : dirty ? t('有未发布修改', 'Unpublished changes') : saved?.is_default ? t('当前使用内置权威报告数据', 'Using bundled authoritative report data') : saved ? t(`当前已发布版本:${(saved.publish_id || saved.revision).slice(0, 12)}`, `Active revision: ${(saved.publish_id || saved.revision).slice(0, 12)}`) : t('正在读取配置…', 'Loading configuration…'))}
</div>
{error ? <p className="an-compute-error" role="alert">{error}</p> : null}
{error ? <Scrollbar className="an-compute-error" axis="y"><p className="an-compute-error__text" role="alert">{error}</p></Scrollbar> : null}
{draft && saved ? <>
<div className="an-compute-toolbar">
<div className="an-compute-actions" role="group" aria-label={t('数据分类', 'Data categories')}>
@@ -936,7 +936,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<span>{t('置信度', 'Confidence')}: {typeof candidate.confidence === 'number' && Number.isFinite(candidate.confidence) ? `${Math.round(candidate.confidence * 100)}%` : '—'}</span>
</div>
{codesEntries.length > 0 ? (
<div className="an-compute-table-wrap">
<Scrollbar className="an-compute-table-wrap" axis="x">
<table className="an-compute-table">
<thead>
<tr>
@@ -959,9 +959,11 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
))}
</tbody>
</table>
</div>
</Scrollbar>
) : (
<pre className="an-compute-code">{JSON.stringify(candidate.proposed_payload, null, 2)}</pre>
<Scrollbar className="an-compute-code-scroll" axis="x">
<pre className="an-compute-code">{JSON.stringify(candidate.proposed_payload, null, 2)}</pre>
</Scrollbar>
)}
{candidate.review_reason_code ? (
@@ -1042,7 +1044,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
{revisions.length === 0 ? (
<p className="an-compute-lead">{t('暂无发布版本记录。', 'No revisions recorded yet.')}</p>
) : (
<div className="an-compute-table-wrap">
<Scrollbar className="an-compute-table-wrap" axis="x">
<table className="an-compute-table">
<thead>
<tr>
@@ -1073,7 +1075,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
))}
</tbody>
</table>
</div>
</Scrollbar>
)}
</>}
</fieldset>
+50 -63
View File
@@ -10,7 +10,6 @@ import {
Globe2,
KeyRound,
Layers,
Maximize2,
PlugZap,
Power,
RefreshCw,
@@ -37,6 +36,7 @@ import { describeApiError, describeApiValue } from '../../i18n/api-errors'
import { translateLegacyAdminText } from '../../i18n/LegacyI18nBridge'
import { normalizeLocale } from '../../i18n/locale'
import { useAuthStore } from '../../stores/auth'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN, parseBackendDate } from '../../utils/datetime'
import { DataTable } from '../components/data-table/DataTable'
import { AdminLayout } from '../components/layout/AdminLayout'
@@ -1545,9 +1545,6 @@ function DashboardContent() {
</div>
<div className="an-dash-card__head-right">
{renderAssetDimTabs()}
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
<DashboardHorizontalBarChart
@@ -1571,9 +1568,6 @@ function DashboardContent() {
</div>
<div className="an-dash-card__head-right">
{renderRuntimeTabs()}
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
@@ -1651,9 +1645,6 @@ function DashboardContent() {
</div>
<div className="an-dash-card__head-right">
{renderOpsTabs()}
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
@@ -1709,7 +1700,7 @@ function DashboardContent() {
</div>
</div>
<div className="an-dash-hairline-list">
<Scrollbar className="an-dash-hairline-list" axis="y">
{opsTab === 'datasources' ? (
previewList.length > 0 ? (
(previewList as DashboardDatasourceRow[]).map((item) => {
@@ -1786,7 +1777,7 @@ function DashboardContent() {
) : (
<div className="an-dash-chart-empty">暂无采集器</div>
)}
</div>
</Scrollbar>
</div>
)
}
@@ -1812,13 +1803,10 @@ function DashboardContent() {
: '0 活跃告警'}
</span>
</span>
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
<div className="an-dash-hairline-list">
<Scrollbar className="an-dash-hairline-list" axis="y">
{activeAlerts.slice(0, 3).map((item) => {
const sev = alertSeverityBadge(item.severity)
return (
@@ -1862,7 +1850,7 @@ function DashboardContent() {
</div>
</div>
))}
</div>
</Scrollbar>
</div>
)
}
@@ -2169,7 +2157,7 @@ function DashboardContent() {
{isEnglish ? `${systemChannels.length} channels` : `${systemChannels.length} 条通道`}
</span>
</div>
<div className="an-dash-hairline-list">
<Scrollbar className="an-dash-hairline-list" axis="y">
{systemChannels.map((ch) => (
<div key={`hero-${ch.key}`} className="an-dash-hairline-row">
<div className="an-dash-hairline-row__main">
@@ -2180,7 +2168,7 @@ function DashboardContent() {
<span className={`an-dash-status-inline is-${ch.tone}`}>{ch.status}</span>
</div>
))}
</div>
</Scrollbar>
</div>
<div className="an-dash-hero__table">
@@ -2263,61 +2251,60 @@ function DashboardContent() {
{error ? <div className="an-alert an-alert--error">{error}</div> : null}
<div ref={stageRef} className="an-dash-stage" data-layout={activeHero ? 'focused' : 'bento'}>
<div className="an-dash-dock">
{dockedCards.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-docked"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
<div className="an-dash-card__dock">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">{card.dockKpi}</span>
<span className="an-dash-kpi-line__meta">{card.dockSub}</span>
</div>
</div>
</section>
))}
</div>
<div className="an-dash-hero-slot">
{activeHero ? (
<section key={activeHero.id} data-card-id={activeHero.id} className="an-dash-card is-hero">
{renderHeroBody(activeHero)}
</section>
) : (
cardDescriptors.map((card) => (
<Scrollbar className="an-dash-stage-scroll" axis="y">
<div ref={stageRef} className="an-dash-stage" data-layout={activeHero ? 'focused' : 'bento'}>
<div className="an-dash-dock">
{dockedCards.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-bento"
className="an-dash-card is-docked"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
{renderBentoCardBody(card)}
<div className="an-dash-card__dock">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
</div>
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">{card.dockKpi}</span>
<span className="an-dash-kpi-line__meta">{card.dockSub}</span>
</div>
</div>
</section>
))
)}
))}
</div>
<div className="an-dash-hero-slot">
{activeHero ? (
<section key={activeHero.id} data-card-id={activeHero.id} className="an-dash-card is-hero">
{renderHeroBody(activeHero)}
</section>
) : (
cardDescriptors.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-bento"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
{renderBentoCardBody(card)}
</section>
))
)}
</div>
</div>
</div>
</Scrollbar>
{stats?.last_updated ? (
<div className="an-page__footer-note">
+79 -125
View File
@@ -1,14 +1,17 @@
import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import { Download, RefreshCw, RotateCcw, Search, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router-dom'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN, formatDateZhCN, parseBackendDate } from '../../utils/datetime'
import { describeApiError } from '../../i18n/api-errors'
import { normalizeLocale } from '../../i18n/locale'
import { parseBackendDate } from '../../utils/datetime'
import { DataTable } from '../components/data-table/DataTable'
import { useWaterfallQuery } from '../components/data-table/useWaterfallQuery'
import { AdminLayout } from '../components/layout/AdminLayout'
import { SPLIT_RESIZE_END_EVENT } from '../components/layout/SplitPaneResizer'
import { SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
import { Badge } from '../components/ui/badge'
import { Button } from '../components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '../components/ui/card'
@@ -19,6 +22,7 @@ import { useToast } from '../components/ui/toast'
import { ComputeLedger } from './data-ledger/ComputeLedger'
import { LayerItemsLedger } from './data-ledger/LayerItemsLedger'
import { LayerNav } from './data-ledger/LayerNav'
import { formatLedgerCountry, formatLedgerDate } from './data-ledger/ledger-display'
import type { LedgerLayerSummary } from './data-ledger/ledger-model'
import { formatDataTypeLabel } from './dashboardHelpers'
@@ -53,27 +57,18 @@ interface SourceOption {
}
const DETAIL_BASE_FIELDS = ['source', 'data_type', 'source_id', 'country', 'city', 'collected_at', 'reference_date']
const DETAIL_FIELD_LABELS: Record<string, string> = {
source: '数据源',
data_type: '数据类型',
source_id: '原始 ID',
country: '国家',
city: '城市',
collected_at: '采集时间',
reference_date: '参考日期',
}
function formatFieldLabel(key: string) {
return DETAIL_FIELD_LABELS[key] || key.split('_').filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ')
return key.split('_').filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ')
}
function formatDetailValue(key: string, value: unknown) {
function formatDetailValue(key: string, value: unknown, isEnglish: boolean) {
if (value === null || value === undefined || value === '') return '-'
if (key === 'data_type') return formatDataTypeLabel(String(value), false)
if (key === 'data_type') return formatDataTypeLabel(String(value), isEnglish)
if (key === 'country') return formatLedgerCountry(String(value), isEnglish)
if (key === 'collected_at' || key === 'reference_date') {
const date = parseBackendDate(String(value))
if (!date || Number.isNaN(date.getTime())) return String(value)
return key === 'reference_date' ? formatDateZhCN(String(value)) : formatDateTimeZhCN(String(value))
const dateValue = String(value)
if (!parseBackendDate(dateValue)) return dateValue
return formatLedgerDate(dateValue, isEnglish, key === 'reference_date')
}
if (typeof value === 'object') return JSON.stringify(value, null, 2)
return String(value)
@@ -96,21 +91,26 @@ function typeTone(type: string) {
}
export default function DataList() {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
const isEnglish = locale === 'en-US'
const { toast } = useToast()
const [searchParams, setSearchParams] = useSearchParams()
const activeLayer = searchParams.get('layer') || 'compute'
const [layers, setLayers] = useState<LedgerLayerSummary[]>([])
const [layersLoading, setLayersLoading] = useState(false)
const [summaryWidth, setSummaryWidth] = useState(260)
const summaryWidthRef = useRef(summaryWidth)
summaryWidthRef.current = summaryWidth
const dataLayoutRef = useRef<HTMLDivElement | null>(null)
const summaryResizeCleanupRef = useRef<(() => void) | null>(null)
useEffect(() => () => {
summaryResizeCleanupRef.current?.()
}, [])
const summaryResize = useSplitPaneResize({
storageKey: 'planet.admin.dataSummaryWidth',
defaultWidth: 260,
minWidth: 220,
maxWidth: 420,
minOppositeWidth: 420,
side: 'left',
containerRef: dataLayoutRef,
cssVarName: '--an-data-summary-width',
})
const [sourceFilter, setSourceFilter] = useState(() => searchParams.get('source') || '')
const [typeFilter, setTypeFilter] = useState(() => searchParams.get('type') || '')
@@ -146,52 +146,6 @@ export default function DataList() {
setSearchParams(next, { replace: false })
}
const startSummaryResize = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
event.preventDefault()
summaryResizeCleanupRef.current?.()
const startX = event.clientX
const startWidth = summaryWidthRef.current
let latestWidth = startWidth
let rafId = 0
const applyFrame = () => {
rafId = 0
dataLayoutRef.current?.style.setProperty('--an-data-summary-width', `${latestWidth}px`)
}
const handleMove = (moveEvent: PointerEvent) => {
latestWidth = Math.min(420, Math.max(220, Math.round(startWidth + (moveEvent.clientX - startX))))
if (!rafId) {
rafId = window.requestAnimationFrame(applyFrame)
}
}
const cleanupListeners = () => {
if (rafId) {
window.cancelAnimationFrame(rafId)
rafId = 0
}
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopMove)
window.removeEventListener('pointercancel', stopMove)
summaryResizeCleanupRef.current = null
}
const stopMove = () => {
cleanupListeners()
dataLayoutRef.current?.style.setProperty('--an-data-summary-width', `${latestWidth}px`)
setSummaryWidth(latestWidth)
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
}
summaryResizeCleanupRef.current = cleanupListeners
document.body.classList.add('an-is-resizing')
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopMove, { once: true })
window.addEventListener('pointercancel', stopMove, { once: true })
}, [])
useEffect(() => {
const trimmed = searchText.trim()
if (!trimmed) {
@@ -229,11 +183,11 @@ export default function DataList() {
(error: unknown) => {
toast({
tone: 'error',
title: '加载采集数据失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.loadRawFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
},
[toast],
[t, toast],
)
const {
@@ -312,21 +266,21 @@ export default function DataList() {
link.click()
link.remove()
window.URL.revokeObjectURL(url)
toast({ tone: 'success', title: `已导出 ${format.toUpperCase()}` })
toast({ tone: 'success', title: t('dataLedger.exported', { format: format.toUpperCase() }) })
} catch (error) {
toast({ tone: 'error', title: '导出失败', description: error instanceof Error ? error.message : '请稍后重试' })
toast({ tone: 'error', title: t('dataLedger.exportFailed'), description: describeApiError(error, t('dataLedger.retry')) })
}
}
const rawActiveFilterCount = [sourceFilter, typeFilter, countryFilter, searchText.trim()].filter(Boolean).length
const sourceOptions = [{ value: 'all', label: '全部数据源' }, ...sources.map((source) => ({ label: source.source_name, value: source.source }))]
const typeOptions = [{ value: 'all', label: '全部类型' }, ...types.map((type) => ({ label: formatDataTypeLabel(type, false), value: type }))]
const countryOptions = [{ value: 'all', label: '全部国家/地区' }, ...countries.map((country) => ({ label: country, value: country }))]
const sourceOptions = [{ value: 'all', label: t('dataLedger.allSources') }, ...sources.map((source) => ({ label: source.source_name, value: source.source }))]
const typeOptions = [{ value: 'all', label: t('dataLedger.allTypes') }, ...types.map((type) => ({ label: formatDataTypeLabel(type, isEnglish), value: type }))]
const countryOptions = [{ value: 'all', label: t('dataLedger.allCountries') }, ...countries.map((country) => ({ label: formatLedgerCountry(country, isEnglish), value: country }))]
const columns = useMemo<Array<ColumnDef<CollectedData>>>(() => [
{
accessorKey: 'name',
header: '名称',
header: t('dataLedger.column.name'),
size: 320,
cell: ({ row }) => (
<button
@@ -343,7 +297,7 @@ export default function DataList() {
},
{
accessorKey: 'source',
header: '数据源',
header: t('dataLedger.column.source'),
size: 180,
cell: ({ row }) => row.original.source
? <Badge tone={sourceTone(row.original.source)} title={row.original.source}>{row.original.source_name || row.original.source}</Badge>
@@ -351,39 +305,39 @@ export default function DataList() {
},
{
accessorKey: 'data_type',
header: '数据类型',
header: t('dataLedger.column.data_type'),
size: 160,
cell: ({ row }) => row.original.data_type ? <Badge tone={typeTone(row.original.data_type)} title={row.original.data_type}>{formatDataTypeLabel(row.original.data_type, false)}</Badge> : '-',
cell: ({ row }) => row.original.data_type ? <Badge tone={typeTone(row.original.data_type)} title={row.original.data_type}>{formatDataTypeLabel(row.original.data_type, isEnglish)}</Badge> : '-',
},
{
accessorKey: 'collected_at',
header: '采集时间',
header: t('dataLedger.column.collected_at'),
size: 180,
cell: ({ row }) => formatDateTimeZhCN(row.original.collected_at),
cell: ({ row }) => formatLedgerDate(row.original.collected_at, isEnglish),
},
{
accessorKey: 'reference_date',
header: '参考日期',
header: t('dataLedger.column.reference_date'),
size: 140,
cell: ({ row }) => formatDateZhCN(row.original.reference_date),
cell: ({ row }) => formatLedgerDate(row.original.reference_date, isEnglish, true),
},
], [])
], [isEnglish, t])
const detailBaseItems = useMemo(() => {
if (!detailData) return []
return DETAIL_BASE_FIELDS.map((key) => ({
key,
label: formatFieldLabel(key),
value: formatDetailValue(key, key === 'source' ? detailData.source_name || detailData.source : detailData[key as keyof CollectedData]),
label: t('dataLedger.column.' + key, { defaultValue: formatFieldLabel(key) }),
value: formatDetailValue(key, key === 'source' ? detailData.source_name || detailData.source : detailData[key as keyof CollectedData], isEnglish),
})).filter((item) => item.value !== '-')
}, [detailData])
}, [detailData, isEnglish, t])
const detailMetadataItems = useMemo(() => {
if (!detailData?.metadata) return []
return Object.entries(detailData.metadata)
.filter(([key]) => key !== '_detail_url')
.map(([key, value]) => ({ key, label: formatFieldLabel(key), value: formatDetailValue(key, value), isBlock: typeof value === 'object' && value !== null }))
}, [detailData])
.map(([key, value]) => ({ key, label: t('dataLedger.column.' + key, { defaultValue: formatFieldLabel(key) }), value: formatDetailValue(key, value, isEnglish), isBlock: typeof value === 'object' && value !== null }))
}, [detailData, isEnglish, t])
const activeLayerMeta = useMemo(
() => layers.find((item) => item.id === activeLayer),
@@ -395,18 +349,18 @@ export default function DataList() {
<div className="an-page an-data-page">
<div className="an-page__header">
<div>
<h1>采集数据</h1>
<p>按地球图层分类复核基础设施、台账与原始采集元数据。</p>
<h1>{t('dataLedger.title')}</h1>
<p>{t('dataLedger.description')}</p>
</div>
{activeLayer === 'raw' ? (
<div className="an-toolbar">
<Badge tone="blue">{`结果 ${total.toLocaleString()} 条`}</Badge>
<Badge tone="slate">{`筛选 ${rawActiveFilterCount} 项`}</Badge>
<Badge tone="blue">{t('dataLedger.resultCount', { total: total.toLocaleString(locale) })}</Badge>
<Badge tone="slate">{t('dataLedger.filterCount', { count: rawActiveFilterCount })}</Badge>
</div>
) : null}
</div>
<div ref={dataLayoutRef} className="an-data-layout" style={{ '--an-data-summary-width': `${summaryWidth}px` } as CSSProperties}>
<div ref={dataLayoutRef} className="an-data-layout" style={{ '--an-data-summary-width': `${summaryResize.width}px` } as CSSProperties}>
<LayerNav
layers={layers}
activeLayer={activeLayer}
@@ -414,12 +368,12 @@ export default function DataList() {
onSelectLayer={handleSelectLayer}
/>
<button
type="button"
className="an-detail-resizer an-data-resizer"
onPointerDown={startSummaryResize}
aria-label="拖动调整图层导航宽度"
title="拖动调整图层导航宽度"
<SplitPaneResizer
label={t('dataLedger.resizeLayerNav')}
className="an-data-resizer"
isDragging={summaryResize.isDragging}
onPointerDown={summaryResize.onPointerDown}
onKeyDown={summaryResize.onKeyDown}
/>
{activeLayer === 'compute' ? (
@@ -428,13 +382,13 @@ export default function DataList() {
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>数据列表</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
<CardTitle>{t('dataLedger.list')}</CardTitle>
<p>{t('dataLedger.results', { total: total.toLocaleString(locale) })}</p>
</div>
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchRawData()}><RefreshCw size={14} />刷新</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('json')} title="导出 JSON"><Download size={14} />JSON</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('csv')} title="导出 CSV"><Download size={14} />CSV</Button>
<Button size="sm" variant="subtle" onClick={() => void fetchRawData()}><RefreshCw size={14} />{t('dataLedger.refresh')}</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('json')} title={t('dataLedger.exportFile', { format: 'JSON' })}><Download size={14} />JSON</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('csv')} title={t('dataLedger.exportFile', { format: 'CSV' })}><Download size={14} />CSV</Button>
</div>
</CardHeader>
<CardContent>
@@ -464,8 +418,8 @@ export default function DataList() {
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、描述、元数据等"
aria-label="搜索名称、描述、元数据等"
placeholder={t('dataLedger.rawSearch')}
aria-label={t('dataLedger.rawSearch')}
value={searchText}
onChange={(event) => setSearchText(event.target.value)}
/>
@@ -474,8 +428,8 @@ export default function DataList() {
size="icon"
variant="ghost"
onClick={() => setSearchText('')}
title="清空搜索"
aria-label="清空搜索"
title={t('dataLedger.clearSearch')}
aria-label={t('dataLedger.clearSearch')}
>
<X size={14} />
</Button>
@@ -486,8 +440,8 @@ export default function DataList() {
variant="subtle"
onClick={handleReset}
disabled={rawActiveFilterCount === 0}
title="重置筛选"
aria-label="重置筛选"
title={t('dataLedger.resetFilters')}
aria-label={t('dataLedger.resetFilters')}
>
<RotateCcw size={14} />
</Button>
@@ -515,25 +469,25 @@ export default function DataList() {
<LayerItemsLedger
key={activeLayer}
layerId={activeLayer}
layerName={activeLayerMeta?.name || activeLayer}
layerName={t('dataLedger.layer.' + activeLayer, { defaultValue: activeLayerMeta?.name || activeLayer })}
initialKinds={activeLayerMeta?.kinds || []}
/>
)}
</div>
</div>
<Dialog title="数据详情" open={detailVisible} onOpenChange={setDetailVisible} width={880}>
<Dialog title={t('dataLedger.rawDetail')} open={detailVisible} onOpenChange={setDetailVisible} width={880}>
{detailLoading ? (
<div className="an-loading"><span className="an-spinner" />加载中</div>
<div className="an-loading"><span className="an-spinner" />{t('common.loading')}</div>
) : detailData ? (
<div className="an-detail">
<section className="an-detail__hero">
<span>名称</span>
<span>{t('dataLedger.column.name')}</span>
<h2>{detailData.name || '-'}</h2>
</section>
{detailBaseItems.length > 0 ? (
<section className="an-detail__section">
<h3>基础信息</h3>
<h3>{t('dataLedger.basicInfo')}</h3>
<div className="an-detail__grid">
{detailBaseItems.map((item) => (
<div key={item.key}>
@@ -546,7 +500,7 @@ export default function DataList() {
) : null}
{detailMetadataItems.length > 0 ? (
<section className="an-detail__section">
<h3>扩展字段</h3>
<h3>{t('dataLedger.extraFields')}</h3>
<div className="an-detail__grid">
{detailMetadataItems.map((item) => (
<div key={item.key} className={item.isBlock ? 'is-block' : undefined}>
@@ -562,14 +516,14 @@ export default function DataList() {
</section>
) : null}
<section className="an-detail__section">
<h3>原始元数据</h3>
<h3>{t('dataLedger.rawMetadata')}</h3>
<Scrollbar className="an-code-scroll">
<pre className="an-json-view">{JSON.stringify(detailData.metadata || {}, null, 2)}</pre>
</Scrollbar>
</section>
</div>
) : (
<div className="an-empty">暂无数据</div>
<div className="an-empty">{t('common.noData')}</div>
)}
</Dialog>
</AdminLayout>
+3 -1
View File
@@ -673,7 +673,9 @@ export default function Logs() {
{event.occurrence_count > 1 ? <Badge tone="blue">{`${event.occurrence_count} 次`}</Badge> : null}
</div>
<p>{event.message}</p>
<pre>{stringifyContext(event.context)}</pre>
<Scrollbar className="an-log-occurrence__scroll">
<pre>{stringifyContext(event.context)}</pre>
</Scrollbar>
</div>
))}
{!groupEvents.length ? <EmptyState title="暂无发生明细" /> : null}
+76 -62
View File
@@ -43,7 +43,7 @@ import { describeApiError, localizeApiMessage } from '../../i18n/api-errors'
import { translateLegacyAdminText } from '../../i18n/LegacyI18nBridge'
import { useLocale, type SupportedLocale } from '../../i18n/locale'
import { AdminLayout } from '../components/layout/AdminLayout'
import { SPLIT_RESIZE_END_EVENT, SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
import { SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
import { DataTable } from '../components/data-table/DataTable'
import { DatasourceBatchBar, type DatasourceBatchAction } from '../components/datasources/DatasourceBatchBar'
import { Button, type ButtonProps } from '../components/ui/button'
@@ -836,12 +836,23 @@ function defaultColumns(onSelect: (record: TableRecord) => void, locale: Support
}
const EMPTY_TABLE_ROWS: TableRecord[] = []
const HIDDEN_DATASOURCE_COLUMNS_NONE: readonly string[] = []
const HIDDEN_DATASOURCE_COLUMNS_TABLET: readonly string[] = ['module']
const HIDDEN_DATASOURCE_COLUMNS_MOBILE: readonly string[] = ['module', 'metric', 'updated']
function getResponsiveColumnTier(): 'desktop' | 'tablet' | 'mobile' {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return 'desktop'
if (window.matchMedia('(max-width: 760px)').matches) return 'mobile'
if (window.matchMedia('(max-width: 1024px)').matches) return 'tablet'
return 'desktop'
}
const ModuleTable = memo(function ModuleTable({
rows,
selectedRowId,
onSelect,
columns,
hiddenColumnIds,
selection,
loading,
columnWidthStorageKey,
@@ -851,6 +862,7 @@ const ModuleTable = memo(function ModuleTable({
selectedRowId?: string | null
onSelect: (record: TableRecord) => void
columns?: Array<ColumnDef<TableRecord>>
hiddenColumnIds?: readonly string[]
selection?: {
selectedRowIds: Set<string>
onToggleAllVisible: (rowIds: string[]) => void
@@ -876,6 +888,7 @@ const ModuleTable = memo(function ModuleTable({
<DataTable
className={`an-resource-table${className ? ` ${className}` : ''}`}
columns={tableColumns}
hiddenColumnIds={hiddenColumnIds}
data={rows}
emptyText={localizeAdminText('当前模块暂无数据', locale)}
getRowClassName={getRowClassName}
@@ -2813,15 +2826,42 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const [selectedHistory, setSelectedHistory] = useState<TableRecord[]>([])
const [mobileResourceDetailOpen, setMobileResourceDetailOpen] = useState(false)
const [mobileHierarchyDetailOpen, setMobileHierarchyDetailOpen] = useState(false)
const [detailWidth, setDetailWidth] = useState(360)
const detailWidthRef = useRef(detailWidth)
detailWidthRef.current = detailWidth
const resourceLayoutRef = useRef<HTMLDivElement | null>(null)
const detailResizeCleanupRef = useRef<(() => void) | null>(null)
const [responsiveColumnTier, setResponsiveColumnTier] = useState<'desktop' | 'tablet' | 'mobile'>(
getResponsiveColumnTier,
)
useEffect(() => () => {
detailResizeCleanupRef.current?.()
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return
const mqTablet = window.matchMedia('(max-width: 1024px)')
const mqMobile = window.matchMedia('(max-width: 760px)')
const handleTierChange = () => {
setResponsiveColumnTier(mqMobile.matches ? 'mobile' : mqTablet.matches ? 'tablet' : 'desktop')
}
handleTierChange()
mqTablet.addEventListener('change', handleTierChange)
mqMobile.addEventListener('change', handleTierChange)
return () => {
mqTablet.removeEventListener('change', handleTierChange)
mqMobile.removeEventListener('change', handleTierChange)
}
}, [])
const hiddenDatasourceColumns = useMemo(() => {
if (responsiveColumnTier === 'mobile') return HIDDEN_DATASOURCE_COLUMNS_MOBILE
if (responsiveColumnTier === 'tablet') return HIDDEN_DATASOURCE_COLUMNS_TABLET
return HIDDEN_DATASOURCE_COLUMNS_NONE
}, [responsiveColumnTier])
const resourceLayoutRef = useRef<HTMLDivElement | null>(null)
const detailResize = useSplitPaneResize({
storageKey: 'planet.admin.resourceDetailWidth',
defaultWidth: 360,
minWidth: 300,
maxWidth: 640,
minOppositeWidth: 420,
side: 'right',
containerRef: resourceLayoutRef,
cssVarName: '--an-detail-width',
})
const hierarchyLayoutRef = useRef<HTMLDivElement | null>(null)
const hierarchyResize = useSplitPaneResize({
storageKey: 'planet.admin.hierarchyWidth',
@@ -2851,52 +2891,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
run: () => Promise<void>
}>(null)
const startDetailResize = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
event.preventDefault()
detailResizeCleanupRef.current?.()
const startX = event.clientX
const startWidth = detailWidthRef.current
let latestWidth = startWidth
let rafId = 0
const applyFrame = () => {
rafId = 0
resourceLayoutRef.current?.style.setProperty('--an-detail-width', `${latestWidth}px`)
}
const handleMove = (moveEvent: PointerEvent) => {
latestWidth = Math.min(640, Math.max(300, Math.round(startWidth - (moveEvent.clientX - startX))))
if (!rafId) {
rafId = window.requestAnimationFrame(applyFrame)
}
}
const cleanupListeners = () => {
if (rafId) {
window.cancelAnimationFrame(rafId)
rafId = 0
}
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopMove)
window.removeEventListener('pointercancel', stopMove)
detailResizeCleanupRef.current = null
}
const stopMove = () => {
cleanupListeners()
resourceLayoutRef.current?.style.setProperty('--an-detail-width', `${latestWidth}px`)
setDetailWidth(latestWidth)
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
}
detailResizeCleanupRef.current = cleanupListeners
document.body.classList.add('an-is-resizing')
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopMove, { once: true })
window.addEventListener('pointercancel', stopMove, { once: true })
}, [])
const startCredentialGuideDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
event.preventDefault()
const dialog = event.currentTarget.closest<HTMLElement>('.an-guide-modal')
@@ -3444,6 +3438,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
setMobileResourceDetailOpen(Boolean(record))
}, [])
useEffect(() => {
if (!mobileResourceDetailOpen && !mobileHierarchyDetailOpen) return
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setMobileResourceDetailOpen(false)
setMobileHierarchyDetailOpen(false)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [mobileHierarchyDetailOpen, mobileResourceDetailOpen])
const goBackResourceDetail = () => {
setSelectedHistory((history) => {
const previous = history[history.length - 1]
@@ -7732,7 +7738,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<div
ref={resourceLayoutRef}
className={`an-resource-layout${isDatasourceBuiltinSection ? ' an-resource-layout--datasources' : ''}${mobileResourceDetailOpen ? ' is-mobile-detail-open' : ''}`}
style={{ '--an-detail-width': `${detailWidth}px` } as CSSProperties}
style={{ '--an-detail-width': `${detailResize.width}px` } as CSSProperties}
>
<Panel className="an-resource-main">
<div className="an-panel-heading">
@@ -7752,6 +7758,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
selectedRowId={selected?.__rowId ?? null}
onSelect={openResourceDetail}
columns={isDatasourceBuiltinSection ? datasourceColumns : config.columns}
hiddenColumnIds={isDatasourceBuiltinSection ? hiddenDatasourceColumns : undefined}
loading={loading && rows.length === 0}
columnWidthStorageKey={`planet.table.widths.resource.${activeSection?.key || config.listTitle}`}
selection={datasourceSelection}
@@ -7762,14 +7769,21 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
</div>
</Panel>
<button
type="button"
className="an-detail-resizer"
onPointerDown={startDetailResize}
aria-label="拖动调整详情宽度"
title="拖动调整详情宽度"
<SplitPaneResizer
label="拖动调整详情宽度"
isDragging={detailResize.isDragging}
onPointerDown={detailResize.onPointerDown}
onKeyDown={detailResize.onKeyDown}
/>
{mobileResourceDetailOpen ? (
<div
className="an-resource-drawer-backdrop"
aria-hidden="true"
onClick={() => setMobileResourceDetailOpen(false)}
/>
) : null}
<div className="an-resource-side">
<div className="an-mobile-detail-bar">
<Button size="icon" variant="subtle" title={localizeAdminText('返回列表', locale)} aria-label={localizeAdminText('返回列表', locale)} onClick={() => setMobileResourceDetailOpen(false)}><ArrowLeft size={15} /></Button>
@@ -7826,7 +7840,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
confirmLabel: '重置',
run: () => loadCredentialGuide(credentialGuideProviderName, 'reset'),
})} loading={actionLoading}><RefreshCw size={15} /></Button>
<Button size="icon" variant="subtle" title="关闭" aria-label="关闭" onClick={() => setCredentialGuideOpen(false)}>×</Button>
<Button size="icon" variant="subtle" title="关闭" aria-label="关闭" onClick={() => setCredentialGuideOpen(false)}><X size={16} /></Button>
</div>
</div>
<Scrollbar className="an-guide-modal__body">
+8 -8
View File
@@ -21,21 +21,21 @@
.an-card-images-field .an-input,.an-card-images-field .an-select { width:100%; min-width:0; }
.an-card-images-field input[type=range] { width:100%; }
.an-card-images-editor-actions { display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:12px; margin-top:16px; }
.an-card-images-error,.an-card-images-message { margin:0; padding:8px 16px; overflow-wrap:anywhere; }
.an-card-images-error { color:var(--an-danger,#b42318); max-height:90px; overflow:auto; scrollbar-width:thin; scrollbar-color:var(--an-border-strong) transparent; }
.an-card-images-error::-webkit-scrollbar { width:6px; height:6px; }
.an-card-images-error::-webkit-scrollbar-button { display:none; width:0; height:0; }
.an-card-images-error::-webkit-scrollbar-track { background:transparent; }
.an-card-images-error::-webkit-scrollbar-thumb { border-radius:999px; background:var(--an-border-strong); }
.an-card-images-message { margin:0; padding:8px 16px; overflow-wrap:anywhere; }
.an-card-images-error { flex:0 0 auto; color:var(--an-danger,#b42318); }
.an-card-images-error > .tui-scrollbar__viewport { max-height:90px; padding:8px 16px; }
.an-card-images-error__text { margin:0; overflow-wrap:anywhere; }
.an-card-image-preview { max-width:440px; background:#091525; color:#e9f1fa; border:1px solid #315062; margin:16px 0; font-size:12px; }
.an-card-image-preview__title { background:#103546; padding:12px; font-weight:600; }
.an-card-image-preview__rows { padding:10px 14px; min-height:220px; }
.an-card-image-preview__rows>div { display:flex; align-items:flex-start; justify-content:space-between; gap:20px; border-bottom:1px solid rgba(255,255,255,.08); padding:12px 0; }
.an-card-image-preview__rows span { color:#a1b2c5; flex-shrink:0; }
.an-card-image-preview__rows strong { text-align:right; overflow-wrap:anywhere; }
@media(max-width:680px) {
.an-card-images-workspace { grid-template-columns:1fr; grid-template-rows:minmax(90px,25%) minmax(0,1fr); }
@media(max-width:1024px) {
.an-card-images-workspace { grid-template-columns:1fr; grid-template-rows:minmax(110px,28%) minmax(0,1fr); }
.an-card-images-workspace > .an-detail-resizer { display:none; }
.an-card-images-list { border-right:0; border-bottom:1px solid var(--an-border); }
}
@media(max-width:760px) {
.an-card-images-fields { grid-template-columns:1fr; }
}
+11 -17
View File
@@ -20,8 +20,10 @@
border-bottom: 1px solid var(--an-border);
flex: 0 0 auto;
}
.an-compute-status, .an-compute-error { padding: 8px 16px; margin: 0; overflow-wrap: anywhere; flex: 0 0 auto; }
.an-compute-error { color: var(--an-danger, #b42318); max-height: 96px; overflow: auto; scrollbar-width: thin; scrollbar-color: var(--an-border-strong) transparent; }
.an-compute-status { padding: 8px 16px; margin: 0; overflow-wrap: anywhere; flex: 0 0 auto; }
.an-compute-error { flex: 0 0 auto; color: var(--an-danger, #b42318); }
.an-compute-error > .tui-scrollbar__viewport { max-height: 96px; padding: 8px 16px; }
.an-compute-error__text { margin: 0; overflow-wrap: anywhere; }
.an-compute-scroll { flex: 1; min-height: 0; min-width: 0; }
.an-compute-content { min-width: 0; margin: 0; padding: 12px 16px 20px; border: 0; }
.an-compute-lead { margin: 8px 0 12px; font-size: 13px; color: var(--an-muted, #94a3b8); line-height: 1.5; }
@@ -119,7 +121,6 @@
}
.an-compute-table-wrap {
width: 100%;
overflow-x: auto;
}
.an-compute-table {
width: 100%;
@@ -153,26 +154,19 @@
padding-top: 4px;
border-top: 1px dashed var(--an-border);
}
.an-compute-code {
margin: 0;
padding: 8px 10px;
.an-compute-code-scroll {
border-radius: 6px;
border: 1px solid var(--an-border);
background: var(--an-bg-subtle, var(--an-surface));
}
.an-compute-code {
margin: 0;
padding: 8px 10px;
color: var(--an-text);
font-size: 12px;
overflow-x: auto;
scrollbar-width: thin;
scrollbar-color: var(--an-border-strong) transparent;
width: max-content;
min-width: 100%;
}
.an-compute-error::-webkit-scrollbar,
.an-compute-code::-webkit-scrollbar { width: 6px; height: 6px; }
.an-compute-error::-webkit-scrollbar-button,
.an-compute-code::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
.an-compute-error::-webkit-scrollbar-track,
.an-compute-code::-webkit-scrollbar-track { background: transparent; }
.an-compute-error::-webkit-scrollbar-thumb,
.an-compute-code::-webkit-scrollbar-thumb { border-radius: 999px; background: var(--an-border-strong); }
@media (max-width: 860px) {
.an-compute-fields--three { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.an-compute-review-box { grid-template-columns: minmax(0, 1fr); }
+74 -13
View File
@@ -1,4 +1,6 @@
import { useState, type CSSProperties, type MouseEvent } from 'react'
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent } from 'react'
import { createPortal } from 'react-dom'
import { clampTooltipCoords, getTooltipViewportBounds } from '../../components/tactile-ui'
import { formatNumber } from '../utils'
import type {
AssetDistributionItem,
@@ -13,26 +15,85 @@ interface ChartTooltipState {
y: number
}
function DashboardChartTooltip({ tip }: { tip: ChartTooltipState | null }) {
if (!tip) return null
const clampedX =
typeof window !== 'undefined' ? Math.min(window.innerWidth - 220, tip.x + 12) : tip.x + 12
const clampedY = Math.max(10, tip.y - 54)
return (
function positionChartTooltip(
tip: ChartTooltipState,
tipWidth: number,
tipHeight: number,
element?: Element | null,
): { left: number; top: number } {
const gap = 12
const bounds = getTooltipViewportBounds(8, element)
const rightX = tip.x + gap
const leftX = tip.x - tipWidth - gap
const preferredLeft = rightX + tipWidth > bounds.maxX && leftX >= bounds.minX ? leftX : rightX
const aboveY = tip.y - tipHeight - gap
const belowY = tip.y + gap + 4
const preferredTop = aboveY < bounds.minY && belowY + tipHeight <= bounds.maxY ? belowY : aboveY
return clampTooltipCoords(preferredLeft, preferredTop, tipWidth, tipHeight, 8, element)
}
function DashboardChartTooltip({
tip,
onDismiss,
}: {
tip: ChartTooltipState | null
onDismiss: () => void
}) {
const tooltipRef = useRef<HTMLDivElement | null>(null)
const [coords, setCoords] = useState<{ left: number; top: number } | null>(null)
useLayoutEffect(() => {
if (!tip) {
setCoords(null)
return
}
const rect = tooltipRef.current?.getBoundingClientRect()
const tipWidth = rect && rect.width > 0 ? rect.width : 200
const tipHeight = rect && rect.height > 0 ? rect.height : 44
setCoords(positionChartTooltip(tip, tipWidth, tipHeight, tooltipRef.current))
}, [tip])
useEffect(() => {
if (!tip) return
const handleDismiss = () => onDismiss()
window.addEventListener('scroll', handleDismiss, true)
window.addEventListener('wheel', handleDismiss, { passive: true })
window.addEventListener('resize', handleDismiss)
window.addEventListener('blur', handleDismiss)
const vv = window.visualViewport
vv?.addEventListener('resize', handleDismiss)
vv?.addEventListener('scroll', handleDismiss)
return () => {
window.removeEventListener('scroll', handleDismiss, true)
window.removeEventListener('wheel', handleDismiss)
window.removeEventListener('resize', handleDismiss)
window.removeEventListener('blur', handleDismiss)
vv?.removeEventListener('resize', handleDismiss)
vv?.removeEventListener('scroll', handleDismiss)
}
}, [onDismiss, tip])
if (!tip || typeof document === 'undefined') return null
const resolved = coords ?? positionChartTooltip(tip, 200, 44)
return createPortal(
<div
ref={tooltipRef}
className="an-dash-tooltip is-visible"
role="status"
aria-live="polite"
style={
{
'--an-tip-x': `${clampedX}px`,
'--an-tip-y': `${clampedY}px`,
'--an-tip-x': `${resolved.left}px`,
'--an-tip-y': `${resolved.top}px`,
} as CSSProperties
}
>
<div className="an-dash-tooltip__title">{tip.title}</div>
<div className="an-dash-tooltip__body">{tip.body}</div>
</div>
</div>,
document.body,
)
}
@@ -180,7 +241,7 @@ export function DashboardHorizontalBarChart({
)
})}
</svg>
<DashboardChartTooltip tip={tip} />
<DashboardChartTooltip tip={tip} onDismiss={() => setTip(null)} />
</div>
)
}
@@ -340,7 +401,7 @@ export function DashboardTaskTrendChart({
/>
))}
</svg>
<DashboardChartTooltip tip={tip} />
<DashboardChartTooltip tip={tip} onDismiss={() => setTip(null)} />
</div>
)
}
@@ -486,7 +547,7 @@ export function DashboardLayerDonutChart({
) : null}
</div>
</div>
<DashboardChartTooltip tip={tip} />
<DashboardChartTooltip tip={tip} onDismiss={() => setTip(null)} />
</div>
)
}
@@ -2,9 +2,11 @@ import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import { ArrowRight, Compass, MapPin, RefreshCw, RotateCcw, Search, Square, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN } from '../../../utils/datetime'
import { describeApiError, describeApiValue } from '../../../i18n/api-errors'
import { normalizeLocale } from '../../../i18n/locale'
import { DataTable } from '../../components/data-table/DataTable'
import { useWaterfallQuery } from '../../components/data-table/useWaterfallQuery'
import { Badge } from '../../components/ui/badge'
@@ -16,21 +18,20 @@ import { Select } from '../../components/ui/select'
import { TableActionButton } from '../../components/ui/table-action-button'
import { useToast } from '../../components/ui/toast'
import { StatusText } from '../../patterns/patterns'
import { formatLedgerCountry, formatLedgerDate } from './ledger-display'
import {
COMPUTE_SITE_TYPE_LABELS,
COMPUTE_SITE_TYPE_ORDER,
COMPUTE_STATUS_BUCKET_META,
EDITABLE_PRECISION_OPTIONS,
PRECISION_LABELS,
TERMINAL_STATUS_LABELS,
COMPUTE_STATUS_BUCKET_TONES,
EDITABLE_PRECISIONS,
type ComputeCandidate,
type ComputeLedgerResponse,
type ComputeLedgerRow,
type ComputeSiteType,
type ComputeStatusBucket,
} from './ledger-model'
export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
const isEnglish = locale === 'en-US'
const { toast } = useToast()
const navigate = useNavigate()
const [siteTypeFilter, setSiteTypeFilter] = useState('')
@@ -98,11 +99,11 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
(error: unknown) => {
toast({
tone: 'error',
title: '加载算力中心台账失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.loadComputeFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
},
[toast],
[t, toast],
)
const {
@@ -153,12 +154,14 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
[row.source_id]: { items: candidates, workflowRunId: runId || null },
}))
if (data.success && candidates.length > 0) {
toast({ tone: 'success', title: `已获取 ${candidates.length} 个候选坐标`, description: '点击行可查看并采纳候选位置' })
toast({ tone: 'success', title: t('dataLedger.foundCandidates', { count: candidates.length }), description: t('dataLedger.adoptCandidatesHint') })
} else if (data.terminal_status) {
const label = TERMINAL_STATUS_LABELS[data.terminal_status] || data.terminal_status
toast({ tone: 'default', title: `已确认:${label}`, description: data.failure_reason || undefined })
const label = t('dataLedger.terminal.' + data.terminal_status, { defaultValue: data.terminal_status })
toast({ tone: 'default', title: t('dataLedger.confirmedTerminal', { status: label }), description: data.failure_reason ? describeApiValue(data.failure_reason) : undefined })
} else {
toast({ tone: 'default', title: '未找到可用候选坐标', description: data.failure_reason || data.llm_failure_reason || undefined })
toast({ tone: 'default', title: t('dataLedger.noCandidates'), description: data.failure_reason || data.llm_failure_reason
? describeApiValue(data.failure_reason || data.llm_failure_reason)
: undefined })
}
setDetailRow({
...row,
@@ -172,8 +175,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
} catch (error) {
toast({
tone: 'error',
title: '重新定位失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.relocateFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
} finally {
setRelocatingIds((prev) => {
@@ -182,7 +185,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
return next
})
}
}, [fetchComputeLedger, onMutated, toast])
}, [fetchComputeLedger, onMutated, t, toast])
const selectedRows = useMemo(
() => items.filter((row) => !row.is_anonymous_placeholder && selectedRowIds.has(`${row.source}:${row.source_id}`)),
@@ -294,12 +297,14 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
toast({
tone: failed > 0 && found === 0 ? 'error' : found > 0 ? 'success' : 'default',
title: batchStopRef.current
? `已停止批量定位(已完成 ${done} / ${queue.length} 条)`
: `批量定位完成:候选 ${found} 条,暂不可定位 ${terminal} 条,未命中 ${missed} 条${failed ? `,失败 ${failed} 条` : ''}`,
? t('dataLedger.stoppedBatch', { done, total: queue.length })
: t(failed ? 'dataLedger.finishedBatchWithFailures' : 'dataLedger.finishedBatch', {
found, terminal, missed, failed,
}),
})
await fetchComputeLedger()
onMutated?.()
}, [batchProgress?.running, fetchComputeLedger, onMutated, selectedRows, toast])
}, [batchProgress?.running, fetchComputeLedger, onMutated, selectedRows, t, toast])
const openEditDialog = useCallback((row: ComputeLedgerRow) => {
setEditTarget(row)
@@ -315,7 +320,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
const lat = Number(editLat)
const lon = Number(editLon)
if (!Number.isFinite(lat) || !Number.isFinite(lon) || lat < -90 || lat > 90 || lon < -180 || lon > 180 || lat === 0 || lon === 0) {
toast({ tone: 'error', title: '请输入有效的非零经纬度坐标' })
toast({ tone: 'error', title: t('dataLedger.invalidCoordinates') })
return
}
setSavingEdit(true)
@@ -333,15 +338,15 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
verification_status: 'verified',
needs_confirmation: false,
})
toast({ tone: 'success', title: '坐标已保存' })
toast({ tone: 'success', title: t('dataLedger.coordinatesSaved') })
setEditTarget(null)
await fetchComputeLedger()
onMutated?.()
} catch (error) {
toast({
tone: 'error',
title: '保存坐标失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.saveCoordinatesFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
} finally {
setSavingEdit(false)
@@ -373,15 +378,15 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
needs_confirmation: false,
workflow_run_id: wfRunId || undefined,
})
toast({ tone: 'success', title: '已采纳候选坐标' })
toast({ tone: 'success', title: t('dataLedger.candidateAdopted') })
setDetailOpen(false)
await fetchComputeLedger()
onMutated?.()
} catch (error) {
toast({
tone: 'error',
title: '采纳候选失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.adoptCandidateFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
} finally {
setAdoptingKey(null)
@@ -393,22 +398,26 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
const allSiteTypeCount = COMPUTE_SITE_TYPE_ORDER.reduce((sum, key) => sum + (bySiteType[key] || 0), 0)
const statusOptions = [
{ value: 'all', label: '全部定位状态' },
{ value: 'located', label: `已定位 (${byStatus.located || 0})` },
{ value: 'needs_confirmation', label: `待确认 (${byStatus.needs_confirmation || 0})` },
{ value: 'terminal', label: `暂不可定位 (${byStatus.terminal || 0})` },
{ value: 'pending', label: `待定位 (${byStatus.pending || 0})` },
{ value: 'all', label: t('dataLedger.allStatuses') },
...Object.keys(COMPUTE_STATUS_BUCKET_TONES).map((value) => ({
value,
label: t('dataLedger.status.' + value) + ' (' + (byStatus[value] || 0).toLocaleString(locale) + ')',
})),
]
const countryOptions = useMemo(() => [
{ value: 'all', label: '全部国家/地区' },
...(payload?.countries || []).map((c) => ({ value: c, label: c })),
], [payload?.countries])
const countryOptions = [
{ value: 'all', label: t('dataLedger.allCountries') },
...(payload?.countries || []).map((value) => ({ value, label: formatLedgerCountry(value, isEnglish) })),
]
const precisionOptions = EDITABLE_PRECISIONS.map((value) => ({
value,
label: t('dataLedger.precision.' + value),
}))
const columns = useMemo<Array<ColumnDef<ComputeLedgerRow>>>(() => [
{
accessorKey: 'name',
header: '名称',
header: t('dataLedger.column.name'),
size: 220,
minSize: 160,
cell: ({ row }) => (
@@ -427,39 +436,39 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
},
{
accessorKey: 'site_type',
header: '设施类型',
header: t('dataLedger.column.site_type'),
size: 112,
minSize: 96,
cell: ({ row }) => (
<Badge tone="slate">
{COMPUTE_SITE_TYPE_LABELS[row.original.site_type as ComputeSiteType] || row.original.site_type}
{t('dataLedger.siteType.' + row.original.site_type, { defaultValue: row.original.site_type })}
</Badge>
),
},
{
accessorKey: 'operator',
header: '运营方',
header: t('dataLedger.column.operator'),
size: 140,
minSize: 100,
cell: ({ row }) => row.original.operator || '-',
},
{
accessorKey: 'country',
header: '国家',
header: t('dataLedger.column.country'),
size: 96,
minSize: 80,
cell: ({ row }) => row.original.country || '-',
cell: ({ row }) => formatLedgerCountry(row.original.country, isEnglish),
},
{
accessorKey: 'city',
header: '城市',
header: t('dataLedger.column.city'),
size: 112,
minSize: 84,
cell: ({ row }) => row.original.city || '-',
},
{
id: 'coordinates',
header: '坐标',
header: t('dataLedger.column.coordinates'),
size: 156,
minSize: 136,
cell: ({ row }) => (
@@ -470,54 +479,55 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
},
{
accessorKey: 'precision',
header: '精度',
header: t('dataLedger.column.precision'),
size: 76,
minSize: 68,
cell: ({ row }) => PRECISION_LABELS[row.original.precision] || row.original.precision || '-',
cell: ({ row }) => row.original.precision
? t('dataLedger.precision.' + row.original.precision, { defaultValue: row.original.precision })
: '-',
},
{
accessorKey: 'status_bucket',
header: '定位状态',
header: t('dataLedger.column.status_bucket'),
size: 156,
minSize: 128,
cell: ({ row }) => {
const meta = COMPUTE_STATUS_BUCKET_META[row.original.status_bucket as ComputeStatusBucket]
|| { label: row.original.status_bucket, tone: 'neutral' as const }
const terminalText = row.original.terminal_status
? TERMINAL_STATUS_LABELS[row.original.terminal_status] || row.original.terminal_status
: null
const { status_bucket: status, terminal_status: terminal } = row.original
const tone = COMPUTE_STATUS_BUCKET_TONES[status] || 'neutral'
const label = t('dataLedger.status.' + status, { defaultValue: status })
const terminalText = terminal ? t('dataLedger.terminal.' + terminal, { defaultValue: terminal }) : null
return (
<StatusText tone={meta.tone}>
{terminalText ? `${meta.label} · ${terminalText}` : meta.label}
<StatusText tone={tone}>
{terminalText ? `${label} · ${terminalText}` : label}
</StatusText>
)
},
},
{
accessorKey: 'updated_at',
header: '更新时间',
header: t('dataLedger.column.updated_at'),
size: 168,
minSize: 152,
cell: ({ row }) => (row.original.updated_at ? formatDateTimeZhCN(row.original.updated_at) : '-'),
cell: ({ row }) => formatLedgerDate(row.original.updated_at, isEnglish),
},
{
id: 'actions',
header: '操作',
header: t('dataLedger.column.actions'),
size: 80,
minSize: 80,
enableResizing: false,
cell: ({ row }) => {
const isAnonymousPlaceholder = Boolean(row.original.is_anonymous_placeholder)
const relocateTitle = isAnonymousPlaceholder
? '源数据为匿名占位条目,无可检索线索'
: '重新定位'
? t('dataLedger.anonymousPlaceholder')
: t('dataLedger.relocate')
return (
<div
className="an-table-actions"
onClick={(event) => event.stopPropagation()}
>
<TableActionButton
aria-label={isAnonymousPlaceholder ? `源数据为匿名占位条目,无可检索线索 ${row.original.name}` : `重新定位 ${row.original.name}`}
aria-label={isAnonymousPlaceholder ? t('dataLedger.anonymousPlaceholderRow', { name: row.original.name }) : t('dataLedger.relocateRow', { name: row.original.name })}
title={relocateTitle}
disabled={isAnonymousPlaceholder}
loading={relocatingIds.has(row.original.source_id)}
@@ -526,8 +536,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<Compass size={14} aria-hidden="true" />
</TableActionButton>
<TableActionButton
aria-label={`编辑坐标 ${row.original.name}`}
title="编辑坐标"
aria-label={t('dataLedger.editCoordinatesRow', { name: row.original.name })}
title={t('dataLedger.editCoordinates')}
onClick={() => openEditDialog(row.original)}
>
<MapPin size={14} aria-hidden="true" />
@@ -536,7 +546,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
)
},
},
], [handleForceRelocate, openEditDialog, relocatingIds])
], [handleForceRelocate, isEnglish, openEditDialog, relocatingIds, t])
const activeCandidates = detailRow ? candidatesBySourceId[detailRow.source_id] : undefined
const hasActiveFilters = Boolean(siteTypeFilter || statusFilter || countryFilter || searchInput.trim())
@@ -546,18 +556,18 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>算力中心台账</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
<CardTitle>{t('dataLedger.computeTitle')}</CardTitle>
<p>{t('dataLedger.results', { total: total.toLocaleString(locale) })}</p>
</div>
{showBatchBar ? (
<div className="an-batch-bar" role="toolbar" aria-label="批量操作">
<div className="an-batch-bar" role="toolbar" aria-label={t('dataLedger.batchActions')}>
<span className="an-batch-bar__count">
<strong>
{batchProgress?.running
? `${batchProgress.done}/${batchProgress.total}`
: selectedRows.length}
</strong>
{batchProgress?.running ? '定位中' : '已选择'}
{batchProgress?.running ? t('dataLedger.batchLocating') : t('dataLedger.selected')}
</span>
{batchProgress?.running ? (
<Button
@@ -566,10 +576,10 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
onClick={() => {
batchStopRef.current = true
}}
title="停止批量定位"
title={t('dataLedger.stopBatch')}
>
<Square size={13} aria-hidden="true" />
停止
{t('dataLedger.stop')}
</Button>
) : (
<Button
@@ -577,10 +587,10 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
variant="primary"
onClick={() => void handleBatchRelocate()}
disabled={!selectedRows.length}
title="批量定位选中条目"
title={t('dataLedger.startBatchTitle')}
>
<Compass size={14} aria-hidden="true" />
批量定位
{t('dataLedger.startBatch')}
<span className="an-batch-bar__num">{selectedRows.length}</span>
</Button>
)}
@@ -589,27 +599,27 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
variant="subtle"
onClick={() => setSelectedRowIds(new Set())}
disabled={Boolean(batchProgress?.running)}
title="清除选择"
aria-label="清除选择"
title={t('dataLedger.clearSelection')}
aria-label={t('dataLedger.clearSelection')}
>
<X size={14} />
</Button>
</div>
) : (
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchComputeLedger()}><RefreshCw size={14} />刷新</Button>
<Button size="sm" variant="subtle" onClick={() => void fetchComputeLedger()}><RefreshCw size={14} />{t('dataLedger.refresh')}</Button>
</div>
)}
</CardHeader>
<CardContent>
<div className="an-filter-grid--datasources an-filter-grid--ledger">
<div className="an-segmented an-segmented--counted" role="tablist" aria-label="设施类型">
<div className="an-segmented an-segmented--counted" role="tablist" aria-label={t('dataLedger.column.site_type')}>
<button
type="button"
className={!siteTypeFilter ? 'is-active' : ''}
onClick={() => { setSiteTypeFilter('') }}
>
<span>全部</span>
<span>{t('dataLedger.all')}</span>
<span className="an-segmented__count">{allSiteTypeCount}</span>
</button>
{COMPUTE_SITE_TYPE_ORDER.map((typeKey) => (
@@ -619,7 +629,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
className={siteTypeFilter === typeKey ? 'is-active' : ''}
onClick={() => { setSiteTypeFilter(typeKey) }}
>
<span>{COMPUTE_SITE_TYPE_LABELS[typeKey]}</span>
<span>{t('dataLedger.siteType.' + typeKey)}</span>
<span className="an-segmented__count">{bySiteType[typeKey] || 0}</span>
</button>
))}
@@ -648,8 +658,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、运营方、城市、说明"
aria-label="搜索名称、运营方、城市、说明"
placeholder={t('dataLedger.computeSearch')}
aria-label={t('dataLedger.computeSearch')}
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
/>
@@ -658,8 +668,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
size="icon"
variant="ghost"
onClick={() => setSearchInput('')}
title="清空搜索"
aria-label="清空搜索"
title={t('dataLedger.clearSearch')}
aria-label={t('dataLedger.clearSearch')}
>
<X size={14} />
</Button>
@@ -671,8 +681,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
variant="subtle"
onClick={handleReset}
disabled={!hasActiveFilters}
title="重置筛选"
aria-label="重置筛选"
title={t('dataLedger.resetFilters')}
aria-label={t('dataLedger.resetFilters')}
>
<RotateCcw size={14} />
</Button>
@@ -690,7 +700,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
selectedRowIds,
onToggleAllVisible: toggleAllVisibleSelection,
onToggleRow: (rowId) => toggleSingleSelection(rowId),
getCheckboxLabel: (row) => `选择 ${row.name}`,
getCheckboxLabel: (row) => t('dataLedger.selectRow', { name: row.name }),
isRowSelectable: (row) => !row.is_anonymous_placeholder,
}}
onRowClick={(row) => {
@@ -707,7 +717,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
/>
</CardContent>
<Dialog title={detailRow ? `${detailRow.name} 定位详情` : '算力中心详情'} open={detailOpen} onOpenChange={setDetailOpen} width={760}>
<Dialog title={detailRow ? t('dataLedger.locationDetails', { name: detailRow.name }) : t('dataLedger.computeDetails')} open={detailOpen} onOpenChange={setDetailOpen} width={760}>
{detailRow ? (
<div className="an-detail">
<div className="an-detail-links">
@@ -720,7 +730,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
navigate('/advisor/runs')
}}
>
<span>{`查看工作流运行记录 (${detailRow.workflow_run_id})`}</span>
<span>{t('dataLedger.viewWorkflowRun', { id: detailRow.workflow_run_id })}</span>
<ArrowRight size={14} />
</button>
) : null}
@@ -729,9 +739,9 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
className="an-detail-link"
onClick={() => void handleForceRelocate(detailRow)}
disabled={relocatingIds.has(detailRow.source_id) || Boolean(detailRow.is_anonymous_placeholder)}
title={detailRow.is_anonymous_placeholder ? '源数据为匿名占位条目,无可检索线索' : '重新定位'}
title={detailRow.is_anonymous_placeholder ? t('dataLedger.anonymousPlaceholder') : t('dataLedger.relocate')}
>
<span>{relocatingIds.has(detailRow.source_id) ? '正在重新定位...' : '重新定位'}</span>
<span>{relocatingIds.has(detailRow.source_id) ? t('dataLedger.relocating') : t('dataLedger.relocate')}</span>
<Compass size={14} />
</button>
<button
@@ -742,37 +752,38 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
openEditDialog(detailRow)
}}
>
<span>编辑坐标</span>
<span>{t('dataLedger.editCoordinates')}</span>
<MapPin size={14} />
</button>
</div>
<section className="an-detail__section">
<h3>核验依据与定位属性</h3>
<h3>{t('dataLedger.locationEvidence')}</h3>
<div className="an-detail__grid">
<div><span>来源标识</span><strong>{`${detailRow.source} / ${detailRow.source_id}`}</strong></div>
<div><span>设施类型</span><strong>{COMPUTE_SITE_TYPE_LABELS[detailRow.site_type] || detailRow.site_type}</strong></div>
<div><span>运营方</span><strong>{detailRow.operator || '-'}</strong></div>
<div><span>国家 / 城市</span><strong>{[detailRow.country, detailRow.city].filter(Boolean).join(' · ') || '-'}</strong></div>
<div><span>定位来源</span><strong>{detailRow.location_source || '-'}</strong></div>
<div><span>{t('dataLedger.sourceIdentifier')}</span><strong>{`${detailRow.source} / ${detailRow.source_id}`}</strong></div>
<div><span>{t('dataLedger.column.site_type')}</span><strong>{t('dataLedger.siteType.' + detailRow.site_type, { defaultValue: detailRow.site_type })}</strong></div>
<div><span>{t('dataLedger.column.operator')}</span><strong>{detailRow.operator || '-'}</strong></div>
<div><span>{t('dataLedger.countryAndCity')}</span><strong>{[detailRow.country && formatLedgerCountry(detailRow.country, isEnglish), detailRow.city].filter(Boolean).join(' · ') || '-'}</strong></div>
<div><span>{t('dataLedger.locationSource')}</span><strong>{detailRow.location_source || '-'}</strong></div>
<div>
<span>核验状态</span>
<span>{t('dataLedger.column.verification_status')}</span>
<strong>
{t('dataLedger.status.' + detailRow.status_bucket, { defaultValue: detailRow.status_bucket })}
{detailRow.terminal_status
? `${COMPUTE_STATUS_BUCKET_META[detailRow.status_bucket].label}(${TERMINAL_STATUS_LABELS[detailRow.terminal_status] || detailRow.terminal_status})`
: COMPUTE_STATUS_BUCKET_META[detailRow.status_bucket].label}
? ' · ' + t('dataLedger.terminal.' + detailRow.terminal_status, { defaultValue: detailRow.terminal_status })
: ''}
</strong>
</div>
</div>
<div className="an-ledger-note-box">
<span>依据说明</span>
<p>{detailRow.source_note || '暂无补充说明'}</p>
<span>{t('dataLedger.evidenceNote')}</span>
<p>{detailRow.source_note || t('dataLedger.noNotes')}</p>
</div>
</section>
{activeCandidates && activeCandidates.items.length > 0 ? (
<section className="an-detail__section">
<h3>{`新采集候选位置 (${activeCandidates.items.length})`}</h3>
<h3>{t('dataLedger.newCandidates', { count: activeCandidates.items.length })}</h3>
<Scrollbar className="an-ledger-candidate-scroll">
<div className="an-ledger-candidates">
{activeCandidates.items.map((cand, index) => {
@@ -781,7 +792,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<div key={key} className="an-ledger-candidate-item">
<div>
<strong>{cand.display_name || detailRow.name}</strong>
<p>{`${cand.latitude.toFixed(5)}, ${cand.longitude.toFixed(5)} · ${PRECISION_LABELS[cand.precision] || cand.precision} · ${[cand.country, cand.city].filter(Boolean).join(' / ') || '-'}`}</p>
<p>{`${cand.latitude.toFixed(5)}, ${cand.longitude.toFixed(5)} · ${t('dataLedger.precision.' + cand.precision, { defaultValue: cand.precision })} · ${[cand.country && formatLedgerCountry(cand.country, isEnglish), cand.city].filter(Boolean).join(' / ') || '-'}`}</p>
{cand.source_note ? <small>{cand.source_note}</small> : null}
</div>
<Button
@@ -790,7 +801,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
loading={adoptingKey === key}
onClick={() => void handleAdoptCandidate(detailRow, cand, index, activeCandidates.workflowRunId)}
>
采纳
{t('dataLedger.adopt')}
</Button>
</div>
)
@@ -804,7 +815,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
</Dialog>
<Dialog
title={editTarget ? `编辑坐标:${editTarget.name}` : '编辑坐标'}
title={editTarget ? t('dataLedger.editCoordinatesTitle', { name: editTarget.name }) : t('dataLedger.editCoordinates')}
open={Boolean(editTarget)}
onOpenChange={(open) => {
if (!open) setEditTarget(null)
@@ -812,31 +823,31 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
width={480}
footer={(
<>
<Button variant="subtle" onClick={() => setEditTarget(null)} disabled={savingEdit}>取消</Button>
<Button variant="primary" onClick={() => void handleSaveManualLocation()} loading={savingEdit}>保存坐标</Button>
<Button variant="subtle" onClick={() => setEditTarget(null)} disabled={savingEdit}>{t('common.cancel')}</Button>
<Button variant="primary" onClick={() => void handleSaveManualLocation()} loading={savingEdit}>{t('dataLedger.saveCoordinates')}</Button>
</>
)}
>
<div className="an-form-grid">
<div className="an-field">
<label htmlFor="ledger-edit-lat">纬度</label>
<Input id="ledger-edit-lat" value={editLat} onChange={(e) => setEditLat(e.target.value)} placeholder="如 35.7804" />
<label htmlFor="ledger-edit-lat">{t('dataLedger.latitude')}</label>
<Input id="ledger-edit-lat" value={editLat} onChange={(e) => setEditLat(e.target.value)} placeholder={t('dataLedger.latitudeExample')} />
</div>
<div className="an-field">
<label htmlFor="ledger-edit-lon">经度</label>
<Input id="ledger-edit-lon" value={editLon} onChange={(e) => setEditLon(e.target.value)} placeholder="如 -78.6391" />
<label htmlFor="ledger-edit-lon">{t('dataLedger.longitude')}</label>
<Input id="ledger-edit-lon" value={editLon} onChange={(e) => setEditLon(e.target.value)} placeholder={t('dataLedger.longitudeExample')} />
</div>
<div className="an-field">
<label htmlFor="ledger-edit-city">城市</label>
<Input id="ledger-edit-city" value={editCity} onChange={(e) => setEditCity(e.target.value)} placeholder="城市名称" />
<label htmlFor="ledger-edit-city">{t('dataLedger.column.city')}</label>
<Input id="ledger-edit-city" value={editCity} onChange={(e) => setEditCity(e.target.value)} placeholder={t('dataLedger.cityPlaceholder')} />
</div>
<div className="an-field">
<label htmlFor="ledger-edit-country">国家</label>
<Input id="ledger-edit-country" value={editCountry} onChange={(e) => setEditCountry(e.target.value)} placeholder="国家或地区" />
<label htmlFor="ledger-edit-country">{t('dataLedger.column.country')}</label>
<Input id="ledger-edit-country" value={editCountry} onChange={(e) => setEditCountry(e.target.value)} placeholder={t('dataLedger.countryPlaceholder')} />
</div>
<div className="an-field">
<label>精度</label>
<Select value={editPrecision} onValueChange={setEditPrecision} options={EDITABLE_PRECISION_OPTIONS} />
<label>{t('dataLedger.column.precision')}</label>
<Select value={editPrecision} onValueChange={setEditPrecision} options={precisionOptions} />
</div>
</div>
</Dialog>
@@ -2,13 +2,17 @@ import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import { RefreshCw, RotateCcw, Search, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { formatDateTimeZhCN } from '../../../utils/datetime'
import { useTranslation } from 'react-i18next'
import { describeApiError } from '../../../i18n/api-errors'
import { normalizeLocale } from '../../../i18n/locale'
import { DataTable } from '../../components/data-table/DataTable'
import { useWaterfallQuery } from '../../components/data-table/useWaterfallQuery'
import { Button } from '../../components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card'
import { Input } from '../../components/ui/input'
import { useToast } from '../../components/ui/toast'
import { formatDataTypeLabel } from '../dashboardHelpers'
import { formatLedgerCountry, formatLedgerDate } from './ledger-display'
import type { GenericLayerItemsResponse, LedgerKind } from './ledger-model'
const TIMESTAMP_COLUMN_KEYS = new Set([
@@ -20,6 +24,16 @@ const TIMESTAMP_COLUMN_KEYS = new Set([
'published_at',
])
const COLUMN_OVERRIDES: Record<string, Record<string, string>> = {
satellites: { source_id: 'norad_id' },
vessels: { name: 'vessel_name' },
bgp: { title: 'incident_title' },
'news:items': { title: 'news_title' },
'news:live_streams': { name: 'channel_name' },
weather: { reference_date: 'observed_at' },
geo: { name: 'tile_dataset' },
}
const WIDE_COLUMN_KEYS = new Set(['name', 'title', 'collector_id', 'location_label'])
const SOURCE_COLUMN_KEYS = new Set(['source'])
const IDENTIFIER_COLUMN_KEYS = new Set(['source_id', 'mmsi', 'international_designator'])
@@ -42,6 +56,9 @@ export function LayerItemsLedger({
layerName: string
initialKinds: LedgerKind[]
}) {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
const isEnglish = locale === 'en-US'
const { toast } = useToast()
const [kind, setKind] = useState<string>(initialKinds[0]?.id || 'all')
const [searchInput, setSearchInput] = useState('')
@@ -93,11 +110,11 @@ export function LayerItemsLedger({
(error: unknown) => {
toast({
tone: 'error',
title: `加载${layerName}台账失败`,
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.loadLayerFailed', { layer: layerName }),
description: describeApiError(error, t('dataLedger.retry')),
})
},
[layerName, toast],
[layerName, t, toast],
)
const {
@@ -121,24 +138,28 @@ export function LayerItemsLedger({
const columns = useMemo<Array<ColumnDef<Record<string, unknown>>>>(() => {
const defs = payload?.columns || []
const overrides = COLUMN_OVERRIDES[layerId + ':' + kind] || COLUMN_OVERRIDES[layerId]
return defs.map((col) => {
const sizing = columnWidthSpec(col.key)
const labelKey = overrides?.[col.key] || col.key
return {
accessorKey: col.key,
header: col.label,
header: isEnglish ? t('dataLedger.column.' + labelKey, { defaultValue: col.label }) : col.label,
size: sizing.size,
minSize: sizing.minSize,
cell: ({ row }) => {
const val = row.original[col.key]
if (val === null || val === undefined || val === '') return '-'
if (TIMESTAMP_COLUMN_KEYS.has(col.key) && typeof val === 'string') {
return formatDateTimeZhCN(val)
return formatLedgerDate(val, isEnglish)
}
if (col.key === 'country' || col.key === 'flag') return formatLedgerCountry(String(val), isEnglish)
if (col.key === 'data_type') return formatDataTypeLabel(String(val), isEnglish)
return String(val)
},
}
})
}, [payload?.columns])
}, [isEnglish, kind, layerId, payload?.columns, t])
const hasActiveFilters = Boolean(searchInput.trim() || (kinds.length > 0 && kind !== kinds[0].id))
@@ -146,17 +167,17 @@ export function LayerItemsLedger({
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>{`${layerName}台账`}</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
<CardTitle>{t('dataLedger.ledgerTitle', { layer: layerName })}</CardTitle>
<p>{t('dataLedger.results', { total: total.toLocaleString(locale) })}</p>
</div>
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchItems()}><RefreshCw size={14} />刷新</Button>
<Button size="sm" variant="subtle" onClick={() => void fetchItems()}><RefreshCw size={14} />{t('dataLedger.refresh')}</Button>
</div>
</CardHeader>
<CardContent>
<div className="an-filter-grid--datasources an-filter-grid--ledger">
{kinds.length > 0 ? (
<div className="an-segmented an-segmented--counted" role="tablist" aria-label={`${layerName}子分类`}>
<div className="an-segmented an-segmented--counted" role="tablist" aria-label={t('dataLedger.layerKinds', { layer: layerName })}>
{kinds.map((item) => (
<button
key={item.id}
@@ -164,7 +185,7 @@ export function LayerItemsLedger({
className={kind === item.id ? 'is-active' : ''}
onClick={() => setKind(item.id)}
>
<span>{item.label}</span>
<span>{t('dataLedger.kind.' + item.id, { defaultValue: item.label })}</span>
</button>
))}
</div>
@@ -172,8 +193,8 @@ export function LayerItemsLedger({
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、标识或来源"
aria-label="搜索名称、标识或来源"
placeholder={t('dataLedger.layerSearch')}
aria-label={t('dataLedger.layerSearch')}
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
/>
@@ -182,8 +203,8 @@ export function LayerItemsLedger({
size="icon"
variant="ghost"
onClick={() => setSearchInput('')}
title="清空搜索"
aria-label="清空搜索"
title={t('dataLedger.clearSearch')}
aria-label={t('dataLedger.clearSearch')}
>
<X size={14} />
</Button>
@@ -198,8 +219,8 @@ export function LayerItemsLedger({
if (kinds.length > 0) setKind(kinds[0].id)
}}
disabled={!hasActiveFilters}
title="重置筛选"
aria-label="重置筛选"
title={t('dataLedger.resetFilters')}
aria-label={t('dataLedger.resetFilters')}
>
<RotateCcw size={14} />
</Button>
@@ -1,3 +1,5 @@
import { useTranslation } from 'react-i18next'
import { normalizeLocale } from '../../../i18n/locale'
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card'
import { Badge } from '../../components/ui/badge'
@@ -15,17 +17,20 @@ export function LayerNav({
loading: boolean
onSelectLayer: (layerId: string) => void
}) {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
return (
<Card className="an-data-summary an-ledger-nav-card">
<CardHeader>
<CardTitle>图层分类</CardTitle>
<CardTitle>{t('dataLedger.layers')}</CardTitle>
<Badge tone="slate">{layers.length}</Badge>
</CardHeader>
<CardContent className="an-ledger-nav-card__content">
<Scrollbar className="an-ledger-nav-scroll">
<div className="an-ledger-nav-list" role="tablist" aria-label="图层分类">
<div className="an-ledger-nav-list" role="tablist" aria-label={t('dataLedger.layers')}>
{loading && layers.length === 0 ? (
<div className="an-loading"><span className="an-spinner" />加载中</div>
<div className="an-loading"><span className="an-spinner" />{t('common.loading')}</div>
) : (
layers.map((layer) => {
const isActive = layer.id === activeLayer
@@ -39,8 +44,8 @@ export function LayerNav({
className={cn('an-ledger-nav-item', isActive && 'is-active')}
onClick={() => onSelectLayer(layer.id)}
>
<span className="an-ledger-nav-item__name">{layer.name}</span>
<span className="an-ledger-nav-item__count">{layer.count.toLocaleString()}</span>
<span className="an-ledger-nav-item__name">{t('dataLedger.layer.' + layer.id, { defaultValue: layer.name })}</span>
<span className="an-ledger-nav-item__count">{layer.count.toLocaleString(locale)}</span>
</button>
)
})
@@ -0,0 +1,62 @@
import { formatDateTimeZhCN, formatDateZhCN, parseBackendDate } from '../../../utils/datetime'
const REGION_NAME_OVERRIDES: Record<string, string> = {
中非: 'CF',
多米尼加: 'DO',
埃斯瓦蒂尼: 'SZ',
巴勒斯坦: 'PS',
阿联酋: 'AE',
'中国(香港)': 'HK',
'中国(澳门)': 'MO',
'中国(台湾)': 'TW',
科索沃: 'RS',
Kosovo: 'RS',
}
const ENGLISH_REGION_OVERRIDES: Record<string, string> = {
HK: 'Hong Kong, China',
MO: 'Macao, China',
TW: 'Taiwan, China',
XK: 'Serbia',
}
let chineseRegionCodes: Map<string, string> | undefined
let englishRegionNames: Intl.DisplayNames | undefined
function getChineseRegionCodes() {
if (chineseRegionCodes) return chineseRegionCodes
const chineseNames = new Intl.DisplayNames('zh-CN', { type: 'region', fallback: 'none' })
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const codes = new Map<string, string>()
for (const first of letters) {
for (const second of letters) {
const code = first + second
const name = chineseNames.of(code)
if (name) codes.set(name, code)
}
}
chineseRegionCodes = codes
return codes
}
export function formatLedgerCountry(value: string | null | undefined, isEnglish: boolean) {
if (!value || !isEnglish) return value || '-'
const code = REGION_NAME_OVERRIDES[value] || getChineseRegionCodes().get(value)
|| (/^[A-Za-z]{2}$/.test(value) ? value.toUpperCase() : '')
if (!code) return value
englishRegionNames ??= new Intl.DisplayNames('en-US', { type: 'region', fallback: 'none' })
return ENGLISH_REGION_OVERRIDES[code] || englishRegionNames.of(code) || value
}
export function formatLedgerDate(value: string | null | undefined, isEnglish: boolean, dateOnly = false) {
if (!isEnglish) return dateOnly ? formatDateZhCN(value) : formatDateTimeZhCN(value)
const date = parseBackendDate(value)
if (!date) return '-'
return dateOnly
? date.toLocaleDateString('en-US')
: date.toLocaleString('en-US', { hour12: false })
}
@@ -99,41 +99,14 @@ export const COMPUTE_SITE_TYPE_ORDER: ComputeSiteType[] = [
'edge_node',
]
export const COMPUTE_SITE_TYPE_LABELS: Record<ComputeSiteType, string> = {
supercomputer: '超算',
gpu_cluster: 'GPU 集群',
data_center: '数据中心',
cloud_center: '云计算中心',
edge_node: '边缘节点',
}
export const COMPUTE_STATUS_BUCKET_META: Record<
export const COMPUTE_STATUS_BUCKET_TONES: Record<
ComputeStatusBucket,
{ label: string; tone: 'success' | 'warning' | 'neutral' | 'info' }
'success' | 'warning' | 'neutral' | 'info'
> = {
located: { label: '已定位', tone: 'success' },
needs_confirmation: { label: '待确认', tone: 'warning' },
terminal: { label: '暂不可定位', tone: 'neutral' },
pending: { label: '待定位', tone: 'info' },
located: 'success',
needs_confirmation: 'warning',
terminal: 'neutral',
pending: 'info',
}
export const TERMINAL_STATUS_LABELS: Record<string, string> = {
undisclosed: '位置未公开',
multi_site: '多地分布式部署',
planned: '规划中尚未建成',
cloud_only: '纯云服务无独立站点',
anonymous: '匿名设施',
}
export const PRECISION_LABELS: Record<string, string> = {
precise: '精确',
site: '园区',
city: '城市',
unknown: '未知',
}
export const EDITABLE_PRECISION_OPTIONS = [
{ value: 'precise', label: '精确' },
{ value: 'site', label: '园区' },
{ value: 'city', label: '城市' },
]
export const EDITABLE_PRECISIONS = ['precise', 'site', 'city']
+7 -2
View File
@@ -273,7 +273,7 @@
padding-top: 8px;
border-top: 1px solid var(--an-border);
}
@media (max-width: 1080px) {
@media (max-width: 1024px) {
.an-cloud-workspace {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr);
@@ -287,7 +287,12 @@
max-height: 46%;
}
}
@media (max-width: 680px) {
@media (max-height: 760px) and (max-width: 1024px) {
.an-cloud-pane--preview {
max-height: 36%;
}
}
@media (max-width: 760px) {
.an-cloud-kpis,
.an-cloud-regions,
.an-cloud-fields {
File diff suppressed because it is too large. Load diff
@@ -349,26 +349,28 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
</button>
</div>
{svg ? (
<div
role="button"
tabIndex={0}
className="markdown-renderer__mermaid-canvas"
onClick={(event) => {
if (isMermaidTextTarget(event.target)) return
if (window.getSelection()?.toString()) return
openExpanded()
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
<Scrollbar axis="x" className="markdown-renderer__mermaid-scroll">
<div
role="button"
tabIndex={0}
className="markdown-renderer__mermaid-canvas"
onClick={(event) => {
if (isMermaidTextTarget(event.target)) return
if (window.getSelection()?.toString()) return
openExpanded()
}
}}
aria-label={t('markdown.expandMermaid')}
title={t('markdown.clickToExpand')}
>
<span className="markdown-renderer__mermaid-canvas-inner" dangerouslySetInnerHTML={{ __html: svg }} />
</div>
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
openExpanded()
}
}}
aria-label={t('markdown.expandMermaid')}
title={t('markdown.clickToExpand')}
>
<span className="markdown-renderer__mermaid-canvas-inner" dangerouslySetInnerHTML={{ __html: svg }} />
</div>
</Scrollbar>
) : error ? (
<div className="markdown-renderer__mermaid-error">
<strong>{t('markdown.mermaidRenderFailed')}</strong>
@@ -13,7 +13,7 @@ import {
type ReactNode,
} from 'react'
import { TactileTooltip, type TooltipSide } from './Tooltip'
import { isFocusVisible, TactileTooltip, type TooltipSide } from './Tooltip'
import { renderTactileIcon, type TactileIconValue } from './icons'
import { classNames, mergeTactileOptions, tactileStyle, type TactileControlOptions } from './types'
import './styles.css'
@@ -116,7 +116,7 @@ function useTooltipHandlers<T extends HTMLElement>(
},
onFocus: (event: FocusEvent<T>) => {
props.onFocus?.(event)
setOpen(true)
if (isFocusVisible(event.currentTarget)) setOpen(true)
},
onBlur: (event: FocusEvent<T>) => {
props.onBlur?.(event)
@@ -1,6 +1,6 @@
import { useRef, useState } from 'react'
import { TactileTooltip, type TooltipSide } from './Tooltip'
import { isFocusVisible, TactileTooltip, type TooltipSide } from './Tooltip'
import { classNames, tactileStyle, type TactileControlOptions } from './types'
import './styles.css'
@@ -43,7 +43,9 @@ export function TactileSwitch({
onClick={() => onCheckedChange(!checked)}
onMouseEnter={() => setTooltipOpen(true)}
onMouseLeave={() => setTooltipOpen(false)}
onFocus={() => setTooltipOpen(true)}
onFocus={(event) => {
if (isFocusVisible(event.currentTarget)) setTooltipOpen(true)
}}
onBlur={() => setTooltipOpen(false)}
>
<span />
+113 -19
View File
@@ -1,17 +1,88 @@
import { useLayoutEffect, useState, type CSSProperties } from 'react'
import { useLayoutEffect, useRef, useState, type CSSProperties } from 'react'
import { createPortal } from 'react-dom'
import './styles.css'
export type TooltipSide = 'top' | 'right' | 'bottom' | 'left'
export interface TooltipViewportBounds {
minX: number
maxX: number
minY: number
maxY: number
}
export function isFocusVisible(element: HTMLElement): boolean {
try {
return element.matches(':focus-visible')
} catch {
return true
}
}
export function getCssZoom(element?: Element | null): number {
if (typeof window === 'undefined' || typeof document === 'undefined') return 1
const target = element ?? document.body ?? document.documentElement
const currentZoom = (target as (Element & { currentCSSZoom?: number }) | null)?.currentCSSZoom
if (typeof currentZoom === 'number' && Number.isFinite(currentZoom) && currentZoom > 0) {
return currentZoom
}
const htmlZoom = Number.parseFloat(getComputedStyle(document.documentElement).zoom || '1') || 1
const bodyZoom = document.body ? Number.parseFloat(getComputedStyle(document.body).zoom || '1') || 1 : 1
const combined = htmlZoom * bodyZoom
return Number.isFinite(combined) && combined > 0 ? combined : 1
}
export function snapToDevicePixel(value: number): number {
const dpr = typeof window !== 'undefined' && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1
return Math.round(value * dpr) / dpr
}
export function getTooltipViewportBounds(margin = 8, element?: Element | null): TooltipViewportBounds {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { minX: margin, maxX: 1280 - margin, minY: margin, maxY: 720 - margin }
}
const cssZoom = getCssZoom(element)
const clientW = (document.documentElement.clientWidth || window.innerWidth) * cssZoom
const clientH = (document.documentElement.clientHeight || window.innerHeight) * cssZoom
const vv = window.visualViewport
const offsetLeft = vv ? vv.offsetLeft : 0
const offsetTop = vv ? vv.offsetTop : 0
const width = vv ? Math.min(clientW, vv.width) : clientW
const height = vv ? Math.min(clientH, vv.height) : clientH
return {
minX: offsetLeft + margin,
maxX: offsetLeft + width - margin,
minY: offsetTop + margin,
maxY: offsetTop + height - margin,
}
}
export function clampTooltipCoords(
left: number,
top: number,
tipWidth: number,
tipHeight: number,
margin = 8,
element?: Element | null,
): { left: number; top: number } {
const bounds = getTooltipViewportBounds(margin, element)
const cssZoom = getCssZoom(element)
const clampedLeft = Math.min(Math.max(bounds.minX, left), Math.max(bounds.minX, bounds.maxX - tipWidth))
const clampedTop = Math.min(Math.max(bounds.minY, top), Math.max(bounds.minY, bounds.maxY - tipHeight))
return {
left: snapToDevicePixel(clampedLeft) / cssZoom,
top: snapToDevicePixel(clampedTop) / cssZoom,
}
}
export function TactileTooltip({
label,
anchor,
open,
side = 'bottom',
offset = 14,
crossOffset = 10,
offset = 8,
crossOffset = 0,
}: {
label?: string
anchor: HTMLElement | null
@@ -20,40 +91,63 @@ export function TactileTooltip({
offset?: number
crossOffset?: number
}) {
const tooltipRef = useRef<HTMLDivElement | null>(null)
const [style, setStyle] = useState<CSSProperties>({})
useLayoutEffect(() => {
if (!open || !label || !anchor) return
const update = () => {
const rect = anchor.getBoundingClientRect()
const estimatedWidth = Math.min(240, Math.max(48, label.length * 12))
const estimatedHeight = 32
const preferred = (() => {
if (side === 'top') return { left: rect.left + rect.width + crossOffset, top: rect.top - estimatedHeight - offset }
if (side === 'left') return { left: rect.left - estimatedWidth - offset, top: rect.top + rect.height + crossOffset }
if (side === 'right') return { left: rect.right + offset, top: rect.top + rect.height + crossOffset }
return { left: rect.left + rect.width + crossOffset, top: rect.bottom + offset }
})()
let left = preferred.left
let top = preferred.top
if (left + estimatedWidth > window.innerWidth - 8) left = window.innerWidth - estimatedWidth - 8
if (left < 8) left = 8
if (top + estimatedHeight > window.innerHeight - 8) top = Math.max(8, rect.top - estimatedHeight - offset)
if (top < 8) top = Math.min(window.innerHeight - estimatedHeight - 8, rect.bottom + offset)
setStyle({ left, top })
const tipRect = tooltipRef.current?.getBoundingClientRect()
const tipWidth = tipRect && tipRect.width > 0 ? tipRect.width : Math.min(240, Math.max(48, label.length * 12))
const tipHeight = tipRect && tipRect.height > 0 ? tipRect.height : 30
const bounds = getTooltipViewportBounds(8, tooltipRef.current)
let left = 0
let top = 0
if (side === 'top' || side === 'bottom') {
left = rect.left + (rect.width - tipWidth) / 2 + crossOffset
const preferTop = side === 'top'
const topY = rect.top - tipHeight - offset
const bottomY = rect.bottom + offset
if (preferTop) {
top = topY < bounds.minY && bottomY + tipHeight <= bounds.maxY ? bottomY : topY
} else {
top = bottomY + tipHeight > bounds.maxY && topY >= bounds.minY ? topY : bottomY
}
} else {
top = rect.top + (rect.height - tipHeight) / 2 + crossOffset
const preferLeft = side === 'left'
const leftX = rect.left - tipWidth - offset
const rightX = rect.right + offset
if (preferLeft) {
left = leftX < bounds.minX && rightX + tipWidth <= bounds.maxX ? rightX : leftX
} else {
left = rightX + tipWidth > bounds.maxX && leftX >= bounds.minX ? leftX : rightX
}
}
setStyle(clampTooltipCoords(left, top, tipWidth, tipHeight, 8, tooltipRef.current))
}
update()
window.addEventListener('scroll', update, true)
window.addEventListener('resize', update)
const vv = window.visualViewport
vv?.addEventListener('resize', update)
vv?.addEventListener('scroll', update)
return () => {
window.removeEventListener('scroll', update, true)
window.removeEventListener('resize', update)
vv?.removeEventListener('resize', update)
vv?.removeEventListener('scroll', update)
}
}, [anchor, crossOffset, label, offset, open, side])
if (!open || !label || typeof document === 'undefined') return null
return createPortal(
<div className="tui-tooltip" style={style} role="tooltip">
<div ref={tooltipRef} className="tui-tooltip" style={style} role="tooltip">
{label}
</div>,
document.body,
@@ -122,7 +122,9 @@ body[data-admin-theme='dark'] .tui-tooltip {
box-shadow: var(--tui-control-shadow-active, 0 1px 2px rgba(15, 23, 42, 0.14), 0 3px 8px rgba(15, 23, 42, 0.08));
}
[data-theme='dark'] .tui-button--tactile {
[data-theme='dark'] .tui-button--tactile,
body[data-admin-theme='dark'] .tui-button--tactile,
body:has(.admin-theme-root[data-theme='dark']) .tui-button--tactile {
background: var(--tui-control-dark-bg, var(--tui-surface-raised-dark));
box-shadow: var(--tui-control-dark-shadow, var(--tui-control-shadow, 0 2px 5px rgba(0, 0, 0, 0.38), 0 10px 20px rgba(0, 0, 0, 0.24)));
}
+352
View File
@@ -40,6 +40,7 @@ export const zhCN = {
logout: '退出登录',
greeting: '您好,{{name}}',
version: '版本号',
versionDetail: '服务端 v{{backend}} · 控制台镜像 v{{ui}}',
themeControl: '控制台主题',
languageControl: '控制台语言',
expandPreferences: '展开偏好设置',
@@ -207,6 +208,181 @@ export const zhCN = {
renderingDiagram: '正在渲染图表...',
viewerHint: '拖拽移动 · 滚轮缩放 · 点击空白关闭',
},
dataLedger: {
title: '采集数据',
description: '按地球图层分类复核基础设施、台账与原始采集元数据。',
layers: '图层分类',
resizeLayerNav: '拖动调整图层导航宽度',
results: '共 {{total}} 条结果',
resultCount: '结果 {{total}} 条',
filterCount: '筛选 {{count}} 项',
refresh: '刷新',
clearSearch: '清空搜索',
resetFilters: '重置筛选',
allCountries: '全部国家/地区',
allStatuses: '全部定位状态',
allSources: '全部数据源',
allTypes: '全部类型',
all: '全部',
list: '数据列表',
rawSearch: '搜索名称、描述、元数据等',
layerSearch: '搜索名称、标识或来源',
computeSearch: '搜索名称、运营方、城市、说明',
exportFile: '导出 {{format}}',
exported: '已导出 {{format}}',
exportFailed: '导出失败',
loadRawFailed: '加载采集数据失败',
loadLayerFailed: '加载{{layer}}台账失败',
retry: '请稍后重试',
ledgerTitle: '{{layer}}台账',
layerKinds: '{{layer}}子分类',
rawDetail: '数据详情',
basicInfo: '基础信息',
extraFields: '扩展字段',
rawMetadata: '原始元数据',
computeTitle: '算力中心台账',
loadComputeFailed: '加载算力中心台账失败',
relocate: '重新定位',
relocateRow: '重新定位 {{name}}',
relocating: '正在重新定位...',
relocateFailed: '重新定位失败',
anonymousPlaceholder: '源数据为匿名占位条目,无可检索线索',
anonymousPlaceholderRow: '源数据为匿名占位条目,无可检索线索 {{name}}',
editCoordinates: '编辑坐标',
editCoordinatesRow: '编辑坐标 {{name}}',
editCoordinatesTitle: '编辑坐标:{{name}}',
selectRow: '选择 {{name}}',
batchActions: '批量操作',
batchLocating: '定位中',
selected: '已选择',
stopBatch: '停止批量定位',
stop: '停止',
startBatchTitle: '批量定位选中条目',
startBatch: '批量定位',
clearSelection: '清除选择',
stoppedBatch: '已停止批量定位(已完成 {{done}} / {{total}} 条)',
finishedBatch: '批量定位完成:候选 {{found}} 条,暂不可定位 {{terminal}} 条,未命中 {{missed}} 条',
finishedBatchWithFailures: '批量定位完成:候选 {{found}} 条,暂不可定位 {{terminal}} 条,未命中 {{missed}} 条,失败 {{failed}} 条',
foundCandidates: '已获取 {{count}} 个候选坐标',
adoptCandidatesHint: '点击行可查看并采纳候选位置',
confirmedTerminal: '已确认:{{status}}',
noCandidates: '未找到可用候选坐标',
invalidCoordinates: '请输入有效的非零经纬度坐标',
coordinatesSaved: '坐标已保存',
saveCoordinatesFailed: '保存坐标失败',
candidateAdopted: '已采纳候选坐标',
adoptCandidateFailed: '采纳候选失败',
computeDetails: '算力中心详情',
locationDetails: '{{name}} 定位详情',
viewWorkflowRun: '查看工作流运行记录 ({{id}})',
locationEvidence: '核验依据与定位属性',
sourceIdentifier: '来源标识',
countryAndCity: '国家 / 城市',
locationSource: '定位来源',
evidenceNote: '依据说明',
noNotes: '暂无补充说明',
newCandidates: '新采集候选位置 ({{count}})',
adopt: '采纳',
saveCoordinates: '保存坐标',
latitude: '纬度',
longitude: '经度',
latitudeExample: '如 35.7804',
longitudeExample: '如 -78.6391',
cityPlaceholder: '城市名称',
countryPlaceholder: '国家或地区',
layer: {
compute: '算力',
satellites: '卫星',
cables: '海底光缆',
vessels: '船只',
bgp: 'BGP',
news: '新闻与直播',
weather: '气象',
geo: '地理/底图',
raw: '原始采集记录',
},
kind: {
submarine_cable: '海缆系统',
landing_point: '登陆点',
cable_landing_relation: '海缆登陆关系',
collectors: '观测站',
incidents: 'BGP 事件',
items: '新闻条目',
live_streams: 'Live 直播源',
all: '气象图层',
cloud_map_record: '云图记录',
wind_field_record: '风场记录',
},
siteType: {
supercomputer: '超算',
gpu_cluster: 'GPU 集群',
data_center: '数据中心',
cloud_center: '云计算中心',
edge_node: '边缘节点',
},
status: {
located: '已定位',
needs_confirmation: '待确认',
terminal: '暂不可定位',
pending: '待定位',
},
terminal: {
undisclosed: '位置未公开',
multi_site: '多地分布式部署',
planned: '规划中尚未建成',
cloud_only: '纯云服务无独立站点',
anonymous: '匿名设施',
},
precision: {
precise: '精确',
site: '园区',
city: '城市',
unknown: '未知',
},
column: {
name: '名称',
source: '数据源',
data_type: '数据类型',
source_id: '原始 ID',
country: '国家',
country_region: '国家/地区',
city: '城市',
collected_at: '采集时间',
reference_date: '参考日期',
site_type: '设施类型',
operator: '运营方',
coordinates: '坐标',
precision: '精度',
status_bucket: '定位状态',
updated_at: '更新时间',
verification_status: '核验状态',
actions: '操作',
international_designator: '国际编号',
constellation_group: '星座分组',
inclination: '轨道倾角',
region: '区域',
language: '语言',
mmsi: 'MMSI',
flag: '船旗',
vessel_type_name: '船型',
sog: '航速',
observed_at: '观测时间',
collector_id: '观测站 ID',
incident_type: '事件类型',
severity: '级别',
status: '状态',
started_at: '开始时间',
location_label: '地理落点',
enrichment_status: '处理状态',
published_at: '发布时间',
vessel_name: '船名',
channel_name: '频道名称',
tile_dataset: '瓦片数据集',
incident_title: '事件标题',
news_title: '新闻标题',
norad_id: 'NORAD ID',
},
},
users: {
actions: '操作',
active: '活跃',
@@ -286,6 +462,7 @@ export const enUS = {
logout: 'Log out',
greeting: 'Hi, {{name}}',
version: 'Version',
versionDetail: 'Server v{{backend}} · Console image v{{ui}}',
themeControl: 'Console theme',
languageControl: 'Console language',
expandPreferences: 'Expand preferences',
@@ -453,6 +630,181 @@ export const enUS = {
renderingDiagram: 'Rendering diagram...',
viewerHint: 'Drag to pan · Scroll to zoom · Click blank space to close',
},
dataLedger: {
title: 'Collected data',
description: 'Review infrastructure, ledgers, and raw collection metadata by Earth layer.',
layers: 'Earth layers',
resizeLayerNav: 'Resize the Earth layer navigation',
results: '{{total}} results',
resultCount: '{{total}} results',
filterCount: 'Active filters: {{count}}',
refresh: 'Refresh',
clearSearch: 'Clear search',
resetFilters: 'Reset filters',
allCountries: 'All countries and regions',
allStatuses: 'All location statuses',
allSources: 'All sources',
allTypes: 'All data types',
all: 'All',
list: 'Data records',
rawSearch: 'Search name, description, or metadata',
layerSearch: 'Search by name, ID, or source',
computeSearch: 'Search by name, operator, city, or notes',
exportFile: 'Export {{format}}',
exported: 'Exported {{format}}',
exportFailed: 'Export failed',
loadRawFailed: 'Failed to load collected data',
loadLayerFailed: 'Failed to load the {{layer}} ledger',
retry: 'Please try again later',
ledgerTitle: '{{layer}} ledger',
layerKinds: '{{layer}} categories',
rawDetail: 'Record details',
basicInfo: 'Basic information',
extraFields: 'Additional fields',
rawMetadata: 'Raw metadata',
computeTitle: 'Compute facility ledger',
loadComputeFailed: 'Failed to load the compute facility ledger',
relocate: 'Locate again',
relocateRow: 'Locate {{name}} again',
relocating: 'Locating…',
relocateFailed: 'Location lookup failed',
anonymousPlaceholder: 'The anonymous source record has no searchable location details',
anonymousPlaceholderRow: 'No searchable location details for anonymous record {{name}}',
editCoordinates: 'Edit coordinates',
editCoordinatesRow: 'Edit coordinates for {{name}}',
editCoordinatesTitle: 'Edit coordinates for {{name}}',
selectRow: 'Select {{name}}',
batchActions: 'Bulk actions',
batchLocating: 'Locating',
selected: 'Selected',
stopBatch: 'Stop bulk location lookup',
stop: 'Stop',
startBatchTitle: 'Look up locations for selected rows',
startBatch: 'Locate selected',
clearSelection: 'Clear selection',
stoppedBatch: 'Bulk lookup stopped after {{done}} of {{total}} rows',
finishedBatch: 'Bulk lookup complete. Candidates: {{found}}, unavailable: {{terminal}}, no match: {{missed}}',
finishedBatchWithFailures: 'Bulk lookup complete. Candidates: {{found}}, unavailable: {{terminal}}, no match: {{missed}}, failed: {{failed}}',
foundCandidates: 'Location candidates found: {{count}}',
adoptCandidatesHint: 'Open the row to review and adopt candidate locations',
confirmedTerminal: 'Confirmed: {{status}}',
noCandidates: 'No usable location candidates found',
invalidCoordinates: 'Enter valid nonzero latitude and longitude',
coordinatesSaved: 'Coordinates saved',
saveCoordinatesFailed: 'Failed to save coordinates',
candidateAdopted: 'Candidate coordinates adopted',
adoptCandidateFailed: 'Failed to adopt candidate coordinates',
computeDetails: 'Compute facility details',
locationDetails: 'Location details for {{name}}',
viewWorkflowRun: 'View workflow run ({{id}})',
locationEvidence: 'Verification and location details',
sourceIdentifier: 'Source identifier',
countryAndCity: 'Country / City',
locationSource: 'Location source',
evidenceNote: 'Evidence note',
noNotes: 'No additional notes',
newCandidates: 'New location candidates ({{count}})',
adopt: 'Adopt',
saveCoordinates: 'Save coordinates',
latitude: 'Latitude',
longitude: 'Longitude',
latitudeExample: 'e.g. 35.7804',
longitudeExample: 'e.g. -78.6391',
cityPlaceholder: 'City name',
countryPlaceholder: 'Country or region',
layer: {
compute: 'Compute',
satellites: 'Satellites',
cables: 'Submarine cables',
vessels: 'Vessels',
bgp: 'BGP',
news: 'News and livestreams',
weather: 'Weather',
geo: 'Geography and basemaps',
raw: 'Raw collection records',
},
kind: {
submarine_cable: 'Cable systems',
landing_point: 'Landing points',
cable_landing_relation: 'Cable landings',
collectors: 'Collectors',
incidents: 'BGP incidents',
items: 'News items',
live_streams: 'Livestream sources',
all: 'Weather layers',
cloud_map_record: 'Cloud map records',
wind_field_record: 'Wind field records',
},
siteType: {
supercomputer: 'Supercomputer',
gpu_cluster: 'GPU cluster',
data_center: 'Data center',
cloud_center: 'Cloud center',
edge_node: 'Edge node',
},
status: {
located: 'Located',
needs_confirmation: 'Needs confirmation',
terminal: 'Location unavailable',
pending: 'Pending location',
},
terminal: {
undisclosed: 'Location undisclosed',
multi_site: 'Distributed across multiple sites',
planned: 'Planned, not yet built',
cloud_only: 'Cloud-only service without a dedicated site',
anonymous: 'Anonymous facility',
},
precision: {
precise: 'Precise',
site: 'Campus',
city: 'City',
unknown: 'Unknown',
},
column: {
name: 'Name',
source: 'Source',
data_type: 'Data type',
source_id: 'Source ID',
country: 'Country',
country_region: 'Country / Region',
city: 'City',
collected_at: 'Collected at',
reference_date: 'Reference date',
site_type: 'Facility type',
operator: 'Operator',
coordinates: 'Coordinates',
precision: 'Precision',
status_bucket: 'Location status',
updated_at: 'Updated at',
verification_status: 'Verification status',
actions: 'Actions',
international_designator: 'International designator',
constellation_group: 'Constellation group',
inclination: 'Orbital inclination',
region: 'Region',
language: 'Language',
mmsi: 'MMSI',
flag: 'Flag',
vessel_type_name: 'Vessel type',
sog: 'Speed over ground',
observed_at: 'Observed at',
collector_id: 'Collector ID',
incident_type: 'Incident type',
severity: 'Severity',
status: 'Status',
started_at: 'Started at',
location_label: 'Location',
enrichment_status: 'Processing status',
published_at: 'Published at',
vessel_name: 'Vessel name',
channel_name: 'Channel name',
tile_dataset: 'Tile dataset',
incident_title: 'Incident title',
news_title: 'News headline',
norad_id: 'NORAD ID',
},
},
users: {
actions: 'Actions',
active: 'Active',
+4 -1
View File
@@ -680,6 +680,10 @@
border-bottom-color: var(--d-code-border);
}
.docs-markdown .markdown-renderer__mermaid-scroll {
width: 100%;
}
.docs-markdown .markdown-renderer__mermaid-canvas {
display: flex;
justify-content: center;
@@ -690,7 +694,6 @@
border: 0;
background: transparent;
color: inherit;
overflow-x: auto;
cursor: zoom-in;
user-select: none;
}
+6 -3
View File
@@ -10,12 +10,15 @@
.earth-desktop-handoff {
height: 100%;
min-height: 0;
overflow: auto;
background: radial-gradient(circle at 22% 18%, #0f2544 0%, #050c18 55%, #02040a 100%);
color: #e6f0ff;
}
.earth-desktop-handoff > .tui-scrollbar__viewport {
min-height: 100%;
display: grid;
place-items: center;
padding: 24px;
background: radial-gradient(circle at 22% 18%, #0f2544 0%, #050c18 55%, #02040a 100%);
color: #e6f0ff;
}
.earth-desktop-handoff__panel {
@@ -2,14 +2,16 @@ import { ArrowLeft, Download, ExternalLink } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import './Earth.css'
export default function EarthDesktopRedirect() {
const { t } = useTranslation()
return (
<main className="earth-desktop-handoff">
<section className="earth-desktop-handoff__panel">
<Scrollbar className="earth-desktop-handoff" axis="y">
<main>
<section className="earth-desktop-handoff__panel">
<h1 className="earth-desktop-handoff__title">
{t('earth.desktopTitle')}
</h1>
@@ -34,6 +36,7 @@ export default function EarthDesktopRedirect() {
</Link>
</div>
</section>
</main>
</main>
</Scrollbar>
)
}
@@ -0,0 +1,82 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import {
fetchRuntimeVersion,
getCachedRuntimeVersion,
parseHealthVersion,
resetRuntimeVersionCache,
} from '../src/admin/components/layout/runtimeVersion'
describe('runtimeVersion', () => {
beforeEach(() => {
resetRuntimeVersionCache()
})
test('parseHealthVersion validates and normalizes semver strings', () => {
expect(parseHealthVersion({ status: 'healthy', version: '0.84.1' })).toBe('0.84.1')
expect(parseHealthVersion({ version: ' v0.84.2-rc.1 ' })).toBe('0.84.2-rc.1')
expect(parseHealthVersion({ version: '' })).toBeNull()
expect(parseHealthVersion({ version: 'invalid' })).toBeNull()
expect(parseHealthVersion(null)).toBeNull()
})
test('fetchRuntimeVersion caches resolved backend version across calls', async () => {
let calls = 0
const fakeFetch = (async () => {
calls += 1
return new Response(JSON.stringify({ status: 'healthy', version: '0.84.1' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', fakeFetch)).toBe('0.84.1')
expect(getCachedRuntimeVersion()).toBe('0.84.1')
expect(await fetchRuntimeVersion('0.84.0', fakeFetch)).toBe('0.84.1')
expect(calls).toBe(1)
})
test('fetchRuntimeVersion deduplicates concurrent default fetch requests', async () => {
const originalFetch = globalThis.fetch
let calls = 0
globalThis.fetch = (async () => {
calls += 1
await Promise.resolve()
return new Response(JSON.stringify({ status: 'healthy', version: '0.84.1' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}) as typeof fetch
try {
const [first, second] = await Promise.all([
fetchRuntimeVersion('0.84.0'),
fetchRuntimeVersion('0.84.0'),
])
expect(first).toBe('0.84.1')
expect(second).toBe('0.84.1')
expect(calls).toBe(1)
} finally {
globalThis.fetch = originalFetch
}
})
test('fetchRuntimeVersion falls back without caching errors', async () => {
const serverErrorFetch = (async () => new Response('error', { status: 500 })) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', serverErrorFetch)).toBe('0.84.0')
expect(getCachedRuntimeVersion()).toBeNull()
const networkErrorFetch = (async () => {
throw new Error('network down')
}) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', networkErrorFetch)).toBe('0.84.0')
expect(getCachedRuntimeVersion()).toBeNull()
const recoveryFetch = (async () =>
new Response(JSON.stringify({ status: 'healthy', version: '0.84.2' }), {
status: 200,
})) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', recoveryFetch)).toBe('0.84.2')
expect(getCachedRuntimeVersion()).toBe('0.84.2')
})
})
@@ -0,0 +1,114 @@
import { afterEach, describe, expect, mock, test } from 'bun:test'
import { readFileSync } from 'node:fs'
mock.module('satellite.js', () => ({
twoline2satrec: () => ({ satnum: '25544' }),
propagate: () => ({ position: { x: 6800, y: 0, z: 0 } }),
eciToEcf: (position: { x: number; y: number; z: number }) => position,
gstime: () => 0,
}))
const COMPACT_PAYLOAD = {
format: 'satellite_compact_v1',
count: 2,
fields: [
'id',
'norad_cat_id',
'name',
'constellation_group',
'tle_line1',
'tle_line2',
'fallback_elements',
],
satellites: [
[
1,
25544,
'ISS (ZARYA)',
'space_station',
'1 25544U 98067A 26338.50000000 .00016717 00000-0 10270-3 0 9005',
'2 25544 51.6400 200.0000 0005000 100.0000 260.0000 15.50000000123456',
null,
],
[
2,
44713,
'STARLINK-1007',
'starlink',
'1 44713U 19074A 26338.50000000 .00001000 00000-0 10000-3 0 9001',
'2 44713 53.0000 120.0000 0001500 90.0000 270.0000 15.06000000123456',
null,
],
],
}
describe('satellite refresh preservation', () => {
const originalWindow = globalThis.window
const originalFetch = globalThis.fetch
afterEach(async () => {
const { clearSatelliteData } = await import('../public/earth/js/satellites.js')
clearSatelliteData()
globalThis.window = originalWindow
globalThis.fetch = originalFetch
})
test('preserves rendered satellites when forced refresh fails and supports 304 ETag reuse', async () => {
const { getSatelliteCount, loadSatellites } = await import(
'../public/earth/js/satellites.js'
)
globalThis.window = {
location: { origin: 'https://earth.test' },
dispatchEvent: () => true,
addEventListener: () => {},
removeEventListener: () => {},
} as unknown as Window & typeof globalThis
const seenHeaders: Array<Record<string, string>> = []
let mode: 'ok' | 'fail' | '304' = 'ok'
globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
seenHeaders.push({ ...(init?.headers as Record<string, string> | undefined) })
if (mode === 'fail') {
return new Response('backend unavailable', { status: 502 })
}
if (mode === '304') {
return new Response(null, {
status: 304,
headers: { etag: '"sat-v1"' },
})
}
return new Response(JSON.stringify(COMPACT_PAYLOAD), {
status: 200,
headers: {
'Content-Type': 'application/json',
etag: '"sat-v1"',
},
})
}) as typeof fetch
const initial = await loadSatellites({ skipCache: true })
expect(initial.count).toBe(2)
expect(getSatelliteCount()).toBe(2)
mode = 'fail'
await expect(loadSatellites({ forceNetwork: true, skipCache: true })).rejects.toThrow('HTTP 502')
expect(getSatelliteCount()).toBe(2)
mode = '304'
const revalidated = await loadSatellites({ forceNetwork: true, skipCache: true })
expect(revalidated.notModified).toBe(true)
expect(revalidated.count).toBe(2)
expect(getSatelliteCount()).toBe(2)
expect(seenHeaders[2]?.['If-None-Match']).toBe('"sat-v1"')
})
test('ensureSatellitesEnabled does not clear satellites before loading new data', () => {
const mainSource = readFileSync(new URL('../public/earth/js/main.js', import.meta.url), 'utf8')
const startIdx = mainSource.indexOf('async function ensureSatellitesEnabled(')
expect(startIdx).toBeGreaterThan(-1)
const snippet = mainSource.slice(startIdx, mainSource.indexOf('await loadSatellites(', startIdx))
expect(snippet).not.toContain('clearSatelliteData()')
})
})
+6
View File
@@ -156,6 +156,12 @@ export default defineConfig({
https: frontendHttps,
allowedHosts: true,
proxy: {
'/api/health': {
target: backendHttpTarget,
changeOrigin: true,
secure: false,
rewrite: (reqPath) => reqPath.replace(/^\/api/, ''),
},
'/api': {
target: backendHttpTarget,
changeOrigin: true,
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.84.1"
version = "0.84.2"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+3 -4
View File
@@ -670,11 +670,10 @@ release-oriented change.
- Before committing a release, verify target version consistency.
- Before pushing a release, run the smallest relevant validation for the changed scope and report what was or was not validated.
- Do not include generated runtime output directories in release commits.
- **Scoped Release & Deployment Classification**: Releases resolve changed paths (`scripts/release_scope.py`) against the previous stable tag and record exact service image digests plus `client.mode` (`none` | `hotfix` | `full`) in OCI `release-manifest:<tag>` (and in `release-manifest.json` when a client Release is published):
- **Scoped Release & Deployment Classification**: Releases resolve changed paths (`scripts/release_scope.py`) against the previous stable tag and record exact service image digests plus `client.mode` (`none` | `hotfix` | `full`) in OCI `release-manifest:<tag>` (and in `release-manifest.json` when a full desktop Release is published):
- `admin`-only, `backend`-only, or `aiprovider`-only changes (`client.mode == "none"`) push **only** the affected container image(s) + OCI `release-manifest:<tag>`, must **not** package desktop clients or publish client update manifests, and must **not** create a Gitea Release.
- Only releases with client updates (`client.mode` = `hotfix` or `full`) create a Gitea Release. Production `planet-release-deploy` inspects Git tags + OCI `release-manifest:<tag>` directly (with fallback to Gitea Releases for legacy tags) so server-only releases still roll out to the changed containers cleanly.
- `frontend/public/earth/**` (without `client/**`) emits only the lightweight L1 Earth hotfix bundle (`--hotfix`) while preserving the prior `shell_version`.
- `client/**` triggers full multi-platform desktop installer builds (`--all`, producing `.exe`/`.zip`, `.AppImage`/`.deb`, `.zip`) plus the L1 hotfix bundle.
- `frontend/public/earth/**` (without `client/**`, `client.mode == "hotfix"`) emits only the lightweight L1 Earth hotfix bundle (`--hotfix`) while preserving the prior `shell_version`, embeds the hotfix bundle and release notes inside OCI `release-manifest:<tag>` (`bundle_storage: "oci"`), and must **not** create a Gitea Release so `/releases/latest` always retains full desktop installers.
- Only full desktop client releases (`client/**`, `client.mode == "full"`) trigger full multi-platform desktop installer builds (`--all`, producing `.exe`/`.zip`, `.AppImage`/`.deb`, `.zip`) plus the L1 hotfix bundle and create a Gitea Release. Production `planet-release-deploy` inspects Git tags + OCI `release-manifest:<tag>` directly (with fallback to Gitea Releases for legacy tags) so server-only and OCI hotfix releases roll out cleanly.
- Docs/harness-only changes do not trigger production rollouts.
- **Production Deployment Gate (`发版 ≠ 已部署`)**: `scripts/release_publish.py` only publishes container images, OCI `release-manifest:<tag>`, and optional Gitea Releases; it never updates host-resident files or verifies live rollout. Whenever the user asks to `部署`, `发版部署`, or `上线`:
1. Inspect `git diff --name-only <prev_tag>..<tag>` for host-managed files not auto-updated by `planet-release-deploy.timer` (`scripts/production_deploy.py`, `scripts/production_registry.py`, `scripts/release_publish.py`, `deploy/systemd/*`, `docker-compose.deploy.yml`, `deploy/nginx/*`). If any changed, sync them onto the production host **before** rollout or `--retry` so stale host verification rules (e.g., anonymous polling hitting newly protected endpoints) cannot trigger false-positive rollbacks.
+29 -8
View File
@@ -107,6 +107,8 @@ function readRepoText(relativePath) {
return readFileSync(new URL(`../../${relativePath}`, import.meta.url), 'utf8')
}
const smokeAppVersion = readRepoText('VERSION').trim() || '0.0.0'
function extractBalanced(text, start, openChar, closeChar) {
let depth = 0
let quote = null
@@ -932,8 +934,14 @@ function tokenResponse() {
})
}
function apiPayloadFor(requestUrl, method) {
// Single opaque RGB (128, 0, 0) pixel encodes sea level in Terrarium.
const smokeTerrainPng = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNoYGAAAAGEAIH5/mWIAAAAAElFTkSuQmCC'
function apiPayloadFor(requestUrl, method, postData) {
const url = new URL(requestUrl)
if (method === 'GET' && url.pathname === '/api/health') {
return jsonResponse({ status: 'healthy', version: smokeAppVersion })
}
const path = url.pathname.replace(/^\/api\/v1/, '') || '/'
if (method === 'GET' && earthGeoJsonPaths.has(path)) {
@@ -1546,6 +1554,19 @@ function apiPayloadFor(requestUrl, method) {
if (method === 'DELETE' && /^\/earth\/tiles\/[a-z0-9_]+\/cache$/.test(path)) {
return jsonResponse({ removed_files: 5 })
}
if (method === 'POST' && path === '/visualization/terrain/terrarium/batch') {
const { tiles } = JSON.parse(postData ?? '{}')
if (!Array.isArray(tiles) || tiles.length === 0) {
return jsonResponse({ detail: 'Expected terrain tile coordinates' }, 422)
}
return jsonResponse({
tiles: tiles.map(({ z, x, y }) => ({ z, x, y, content_type: 'image/png', data: smokeTerrainPng })),
errors: [],
})
}
if (method === 'GET' && /^\/visualization\/terrain\/terrarium\/\d+\/\d+\/\d+\.png$/.test(path)) {
return { status: 200, contentType: 'image/png', body: Buffer.from(smokeTerrainPng, 'base64') }
}
if (path === '/earth/wind/meta') {
return jsonResponse({
available: true,
@@ -1921,7 +1942,8 @@ function apiPayloadFor(requestUrl, method) {
async function installApiMocks(context) {
await context.route('**/api/**', async (route) => {
const response = apiPayloadFor(route.request().url(), route.request().method())
const request = route.request()
const response = apiPayloadFor(request.url(), request.method(), request.postData())
await route.fulfill(response)
})
}
@@ -3141,7 +3163,7 @@ async function main() {
&& !english.classList.contains('is-active')
&& getComputedStyle(segmented).getPropertyValue('--active-index').trim() === '0'
)
}, null, { timeout: 5000 })
}, null, { polling: 100, timeout: SMOKE_RENDER_TIMEOUT_MS })
const zhSystemText = await earthFrame.evaluate(() => (
document.querySelector('.earth-settings-sheet [data-settings-tab-panel="system"]')?.innerText || ''
))
@@ -3164,7 +3186,7 @@ async function main() {
&& !chinese.classList.contains('is-active')
&& getComputedStyle(segmented).getPropertyValue('--active-index').trim() === '1'
)
}, null, { timeout: 5000 })
}, null, { polling: 100, timeout: SMOKE_RENDER_TIMEOUT_MS })
const hdTextureStatus = await earthFrame.evaluate(async () => {
const { earthMessage, formatEarthMessage } = await import('/earth/js/i18n.js?frontend_smoke_i18n')
const ui = await import('/earth/js/ui.js?frontend_smoke_i18n')
@@ -3383,7 +3405,7 @@ async function main() {
const ui = await import('/earth/js/ui.js')
ui.setLoading(false)
ui.showStatusMessage('成功加载 12 条电缆', 'success')
await new Promise((resolve) => window.setTimeout(resolve, 360))
// Read the temporary toast before a startup notification can replace it.
const status = document.getElementById('status-message')
const brand = document.getElementById('brand-panel')
const ticker = document.getElementById('desktop-news-ticker')
@@ -3396,7 +3418,7 @@ async function main() {
stacked: status?.classList.contains('earth-status-message--ticker-stack') === true,
left: rect?.left || 0,
right: rect?.right || 0,
top: rect?.top || 0,
top: status?.offsetTop || 0,
brandRight: brandRect?.right || 0,
tickerLeft: tickerRect?.left || 0,
tickerTop: tickerRect?.top || 0,
@@ -3408,9 +3430,8 @@ async function main() {
status.style.minWidth = '260px'
window.dispatchEvent(new Event('resize'))
}
const stackedRect = status?.getBoundingClientRect()
const stackedWhenConstrained = status?.classList.contains('earth-status-message--ticker-stack') === true
const stackedTop = stackedRect?.top || 0
const stackedTop = status?.offsetTop || 0
if (status instanceof HTMLElement) {
status.style.minWidth = ''
window.dispatchEvent(new Event('resize'))
+231 -1
View File
@@ -473,7 +473,7 @@ class ScopedReleaseTests(unittest.TestCase):
self.assertEqual(rc, 0)
stdout = out.getvalue()
self.assertIn("scope_client_mode: hotfix", stdout)
self.assertIn("gitea_release: create", stdout)
self.assertIn("gitea_release: skip", stdout)
self.assertIn("assets_count: 1", stdout)
self.assertIn("planet-earth-bundle-0.80.1.tar.gz", stdout)
self.assertNotIn("Planet-0.80.1.exe", stdout)
@@ -515,6 +515,236 @@ class ScopedReleaseTests(unittest.TestCase):
pub_mock.assert_not_called()
self.assertIn("skipped Gitea Release: no client update", out.getvalue())
def test_release_publish_hotfix_skips_gitea_release(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
manifest = {
"schema_version": 1,
"tag": "v0.84.2",
"commit": "a" * 40,
"previous_tag": "v0.84.0",
"components": ["earth-hotfix"],
"changed_services": [],
"services": {
k: f"gitea.rclaw.top/linkong/planet/{k}:v0.84.0@sha256:{'1' * 64}"
for k in registry.SERVICES
},
"client": {
"mode": "hotfix",
"shell_version": "0.84.0",
"min_shell_version": "0.84.0",
"bundle": "planet-earth-bundle-0.84.2.tar.gz",
"bundle_sha256": "a" * 64,
"bundle_storage": "oci",
},
}
(root / registry.MANIFEST_NAME).write_text(json.dumps(manifest))
changelog = root / "CHANGELOG.md"
changelog.write_text("# Changelog\n")
@contextmanager
def fake_prepare(*_args, **_kwargs):
yield root, changelog
out = io.StringIO()
with (
patch.object(
publish,
"run_git_origin_url",
return_value="https://gitea.rclaw.top/linkong/planet.git",
),
patch.object(publish, "git_credential_authorization", return_value="token test"),
patch.object(publish, "api_request", return_value=(404, None)),
patch.object(publisher, "prepare", side_effect=fake_prepare),
patch.object(publish, "publish_release") as pub_mock,
redirect_stdout(out),
):
rc = publish.main(["--tag", "v0.84.2", "--scope", "hotfix", "--use-git-credential"])
self.assertEqual(rc, 0)
pub_mock.assert_not_called()
self.assertIn("skipped Gitea Release to preserve /releases/latest", out.getvalue())
def test_resolve_release_bundle_oci_extracts_and_verifies_bundle_and_notes(self):
tag = "v1.1.0"
commit = "f" * 40
bundle_name = "planet-earth-bundle-1.1.0.tar.gz"
bundle_data = hotfix(tag)
bundle_sha = hashlib.sha256(bundle_data).hexdigest()
layer_buf = io.BytesIO()
with tarfile.open(fileobj=layer_buf, mode="w:gz") as layer_tar:
for name, content in {
bundle_name: bundle_data,
registry.RELEASE_NOTES_NAME: b"## 1.1.0\n\n- Fixed cloud shader",
}.items():
info = tarfile.TarInfo(name)
info.size = len(content)
layer_tar.addfile(info, io.BytesIO(content))
layer_bytes = layer_buf.getvalue()
layer_digest = registry.digest(layer_bytes)
cfg = json.dumps(
{
"os": "linux",
"architecture": "amd64",
"config": {"Labels": {"org.opencontainers.image.revision": commit}},
}
).encode()
oci_manifest = json.dumps(
{
"config": {"digest": registry.digest(cfg)},
"layers": [{"digest": layer_digest}],
}
).encode()
release_manifest = {
"schema_version": 1,
"tag": tag,
"commit": commit,
"services": {
k: f"gitea.rclaw.top/linkong/planet/{k}:v1.0.0@sha256:{'1' * 64}"
for k in registry.SERVICES
},
"client": {
"mode": "hotfix",
"shell_version": "1.0.0",
"min_shell_version": "1.0.0",
"bundle": bundle_name,
"bundle_sha256": bundle_sha,
"bundle_storage": "oci",
},
}
with patch.object(
registry,
"read_url",
side_effect=[b'{"token":"read"}', oci_manifest, cfg, layer_bytes],
):
name, data, sha, notes = registry.resolve_release_bundle_oci(tag, commit, release_manifest)
self.assertEqual(name, bundle_name)
self.assertEqual(data, bundle_data)
self.assertEqual(sha, bundle_sha)
self.assertIn("Fixed cloud shader", notes)
bad_manifest = {
**release_manifest,
"client": {**release_manifest["client"], "bundle_sha256": "0" * 64},
}
with (
patch.object(
registry,
"read_url",
side_effect=[b'{"token":"read"}', oci_manifest, cfg, layer_bytes],
),
self.assertRaisesRegex(ValueError, "SHA-256"),
):
registry.resolve_release_bundle_oci(tag, commit, bad_manifest)
empty_buf = io.BytesIO()
with tarfile.open(fileobj=empty_buf, mode="w:gz") as empty_tar:
info = tarfile.TarInfo("release-manifest.json")
info.size = 2
empty_tar.addfile(info, io.BytesIO(b"{}"))
empty_layer = empty_buf.getvalue()
empty_oci = json.dumps(
{
"config": {"digest": registry.digest(cfg)},
"layers": [{"digest": registry.digest(empty_layer)}],
}
).encode()
with patch.object(
registry,
"read_url",
side_effect=[b'{"token":"read"}', empty_oci, cfg, empty_layer],
):
self.assertIsNone(registry.resolve_release_bundle_oci(tag, commit, release_manifest))
def test_deploy_discovers_and_rolls_out_oci_hotfix_without_gitea_release(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
host = deploy.Host(base / "host", base / "settings", base / "state")
host.state.mkdir()
(host.directory("v1.0.0")).mkdir(parents=True)
for name in deploy.HOST_FILES:
(host.directory("v1.0.0") / name).write_text("host-managed")
deploy.point_current(host, "v1.0.0")
old_refs = {
"aiprovider": f"gitea.rclaw.top/linkong/planet/aiprovider:v1.0.0@sha256:{'1' * 64}",
"backend": f"gitea.rclaw.top/linkong/planet/backend:v1.0.0@sha256:{'2' * 64}",
"admin": f"gitea.rclaw.top/linkong/planet/admin:v1.0.0@sha256:{'3' * 64}",
}
bundle_name = "planet-earth-bundle-1.1.0.tar.gz"
bundle_data = hotfix("v1.1.0")
bundle_sha = hashlib.sha256(bundle_data).hexdigest()
manifest = {
"schema_version": 1,
"tag": "v1.1.0",
"commit": "f" * 40,
"previous_tag": "v1.0.0",
"components": ["earth-hotfix"],
"changed_services": [],
"services": old_refs,
"client": {
"mode": "hotfix",
"shell_version": "1.0.0",
"min_shell_version": "1.0.0",
"bundle": bundle_name,
"bundle_sha256": bundle_sha,
"bundle_storage": "oci",
},
}
host.env.write_text(
"\n".join(
[f"{registry.SERVICES[k]}={v}" for k, v in old_refs.items()]
+ ["CLIENT_UPDATE_PUBLISH_TOKEN=tok"]
)
+ "\n"
)
live_manifest = base / "manifest.json"
live_manifest.write_bytes(b"{}")
tags_payload = json.dumps(
[
{"name": "v1.1.0", "commit": {"sha": "f" * 40}},
{"name": "v1.0.0", "commit": {"sha": "a" * 40}},
]
).encode()
with (
patch.object(deploy, "read_url", return_value=tags_payload),
patch.object(deploy, "resolve_release_manifest_oci", return_value=manifest),
patch.object(deploy, "release_by_tag") as release_by_tag_mock,
patch.object(deploy, "resolved_images", return_value=old_refs),
patch.object(
deploy,
"resolve_release_bundle_oci",
return_value=(bundle_name, bundle_data, bundle_sha, "OCI notes"),
),
patch.object(deploy, "inspect", side_effect=lambda name: {"Config": {"Image": old_refs[name]}, "State": {"Health": {"Status": "healthy"}}}),
patch.object(deploy, "data_containers", return_value={"postgres": "same", "redis": "same"}),
patch.object(deploy, "live_manifest_path", return_value=live_manifest),
patch.object(deploy, "docker") as docker_mock,
patch.object(deploy, "backup_database", side_effect=lambda p: p.write_bytes(b"ok")),
patch.object(deploy, "rollout_services") as rollout_mock,
patch.object(deploy, "check_routes"),
patch.object(deploy, "publish_hotfix_bundle") as hotfix_mock,
patch.object(deploy, "check_hotfix") as check_hotfix_mock,
):
deploy.reconcile(host)
deploy.reconcile(host, check=True)
self.assertEqual(host.current(), "v1.1.0")
release_by_tag_mock.assert_not_called()
docker_mock.assert_not_called()
rollout_mock.assert_not_called()
self.assertEqual(hotfix_mock.call_args.kwargs["notes"], "OCI notes")
self.assertEqual(hotfix_mock.call_args.kwargs["shell_version"], "1.0.0")
self.assertEqual(
hotfix_mock.call_args.kwargs["release_html_url"],
"https://gitea.rclaw.top/linkong/planet/releases/tag/v1.0.0",
)
self.assertEqual(check_hotfix_mock.call_count, 2)
check_hotfix_mock.assert_called_with("v1.1.0", bundle_sha, shell_version="1.0.0")
def test_deploy_discovers_server_only_release_from_tags_and_oci_without_gitea_release(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
+26 -5
View File
@@ -30,6 +30,7 @@ if __package__:
release_by_tag,
release_manifest,
resolve_image,
resolve_release_bundle_oci,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
@@ -47,6 +48,7 @@ else:
release_by_tag,
release_manifest,
resolve_image,
resolve_release_bundle_oci,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
@@ -382,15 +384,31 @@ def resolved_images(tag, commit, manifest=None):
return images
def _load_release_bundle_and_notes(release, tag, commit, manifest):
"""Load the L1 hotfix bundle and release notes from Gitea Release or OCI manifest."""
client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full"
if client_mode == "none":
return None, None, None, ""
if release is None:
oci_bundle = resolve_release_bundle_oci(tag, commit, manifest)
if oci_bundle is None:
raise RuntimeError(f"Missing OCI hotfix bundle for {tag}")
return oci_bundle
name, data, sha = release_bundle(release, tag)
return name, data, sha, (release or {}).get("body") or ""
def deploy(host, release, previous, tag, images, commit, *, manifest=None):
client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full"
client_info = (manifest or {}).get("client") or {}
if client_mode == "none":
name, data, sha = None, None, None
name, data, sha, release_notes = None, None, None, ""
minimum = None
shell_version = client_info.get("shell_version")
else:
name, data, sha = release_bundle(release, tag)
name, data, sha, release_notes = _load_release_bundle_and_notes(
release, tag, commit, manifest
)
minimum = client_info.get("min_shell_version") or minimum_shell(data, tag)
shell_version = client_info.get("shell_version") or tag[1:]
@@ -447,7 +465,7 @@ def deploy(host, release, previous, tag, images, commit, *, manifest=None):
publish_url=PUBLIC,
publish_token=token,
tag=tag,
notes=(release or {}).get("body") or "",
notes=release_notes,
release_html_url=f"{SERVER}/{REPO}/releases/tag/v{shell_version}",
assets=[(archive, sha)],
min_shell_version=minimum,
@@ -510,7 +528,10 @@ def discover_latest_release(previous, *, check=False):
commit = sha if (isinstance(sha, str) and re.fullmatch("[0-9a-f]{40,64}", sha)) else tag_commit(tag)
manifest = resolve_release_manifest_oci(tag, commit)
if manifest is not None:
if manifest["client"]["mode"] == "none":
mode = manifest["client"]["mode"]
if mode == "none":
return tag, commit, manifest, None
if mode == "hotfix" and manifest["client"].get("bundle_storage") == "oci":
return tag, commit, manifest, None
release = release_by_tag(tag)
if release is not None:
@@ -550,7 +571,7 @@ def reconcile(host, *, check=False, retry=False):
sha = None
shell_version = (manifest or {}).get("client", {}).get("shell_version") if manifest else tag[1:]
if client_mode != "none":
_, data, sha = release_bundle(release, tag)
_, data, sha, _ = _load_release_bundle_and_notes(release, tag, commit, manifest)
minimum_shell(data, tag)
if tag == previous:
for name, ref in images.items():
+74 -3
View File
@@ -3,8 +3,10 @@
from __future__ import annotations
import hashlib
import io
import json
import re
import tarfile
import time
import urllib.error
import urllib.parse
@@ -16,6 +18,7 @@ REGISTRY = urllib.parse.urlsplit(SERVER).netloc
API = f"{SERVER}/api/v1/repos/{REPO}"
MANIFEST_NAME = "release-manifest.json"
MANIFEST_IMAGE = "release-manifest"
RELEASE_NOTES_NAME = "release-notes.md"
DEFAULT_USER_AGENT = "Planet-Release-Deploy/1.0"
SERVICES = {
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
@@ -189,8 +192,8 @@ def descriptor_digest(desc):
return value
def _fetch_oci_config(repository, name, tag, commit):
"""Fetch and verify the linux/amd64 OCI manifest digest and revision label."""
def _fetch_oci_manifest_and_config(repository, name, tag, commit):
"""Fetch and verify the linux/amd64 OCI manifest, config digest, and revision label."""
query = urllib.parse.urlencode(
{"service": "container_registry", "scope": f"repository:{repository}:pull"}
)
@@ -228,7 +231,16 @@ def _fetch_oci_config(repository, name, tag, commit):
raise ValueError(f"{name}:{tag} is not a linux/amd64 image")
if labels.get("org.opencontainers.image.revision") != commit:
raise ValueError(f"{name}:{tag} belongs to a different commit")
return digest(raw), labels
return digest(raw), manifest, labels, token
def _fetch_oci_config(repository, name, tag, commit):
"""Fetch and verify the linux/amd64 OCI manifest digest and revision label."""
fetched = _fetch_oci_manifest_and_config(repository, name, tag, commit)
if fetched is None:
return None
manifest_digest, _manifest, labels, _token = fetched
return manifest_digest, labels
def resolve_image(service, tag, commit):
@@ -257,3 +269,62 @@ def resolve_release_manifest_oci(tag, commit):
raise ValueError(f"{name}:{tag} is missing planet.release.manifest label")
manifest = json.loads(raw_manifest)
return _validate_release_manifest(manifest, tag)
def resolve_release_bundle_oci(tag, commit, manifest):
"""Read and verify an L1 hotfix bundle embedded in OCI release-manifest:<tag>."""
version(tag)
client = (manifest or {}).get("client") or {}
bundle_name = client.get("bundle")
expected_sha = client.get("bundle_sha256")
if (
not isinstance(bundle_name, str)
or not bundle_name
or not isinstance(expected_sha, str)
or not re.fullmatch(r"[a-f0-9]{64}", expected_sha)
):
raise ValueError("Release manifest is missing hotfix bundle metadata")
name = manifest_image_name()
fetched = _fetch_oci_manifest_and_config(f"{REPO}/{MANIFEST_IMAGE}", name, tag, commit)
if fetched is None:
return None
_manifest_digest, oci_manifest, _labels, token = fetched
headers = {"Authorization": "Bearer " + token}
base = f"{SERVER}/v2/{REPO}/{MANIFEST_IMAGE}"
for layer in reversed(oci_manifest.get("layers") or []):
layer_digest = descriptor_digest(layer)
blob = read_url(
f"{base}/blobs/{layer_digest}",
headers=headers,
limit=32 * 1024 * 1024,
)
if digest(blob) != layer_digest:
raise ValueError("OCI release manifest layer failed digest verification")
notes = ""
bundle_data = None
bundle_sha = None
with tarfile.open(fileobj=io.BytesIO(blob), mode="r:*") as archive:
for member in archive.getmembers():
member_name = member.name.lstrip("./")
if not member.isfile():
continue
if member_name == RELEASE_NOTES_NAME and member.size <= 64 * 1024:
extracted = archive.extractfile(member)
if extracted is not None:
notes = extracted.read().decode("utf-8", errors="replace").strip()
elif member_name == bundle_name:
if not 0 < member.size <= 32 * 1024 * 1024:
raise ValueError("OCI hotfix bundle exceeds allowed size")
extracted = archive.extractfile(member)
if extracted is None:
raise ValueError("Could not extract OCI hotfix bundle")
bundle_data = extracted.read()
bundle_sha = hashlib.sha256(bundle_data).hexdigest()
if bundle_sha != expected_sha:
raise ValueError("OCI hotfix bundle failed SHA-256 verification")
if bundle_data is not None and bundle_sha is not None:
return bundle_name, bundle_data, bundle_sha, notes
return None
+49 -11
View File
@@ -18,6 +18,7 @@ if __package__:
from .production_registry import (
API,
MANIFEST_NAME,
RELEASE_NOTES_NAME,
REPO,
SERVER,
SERVICES,
@@ -27,16 +28,19 @@ if __package__:
release_by_tag,
release_manifest,
resolve_image,
resolve_release_bundle_oci,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
)
from .release_publish import extract_release_notes
from .release_scope import resolve_release_scope
else:
from production_registry import (
API,
MANIFEST_NAME,
RELEASE_NOTES_NAME,
REPO,
SERVER,
SERVICES,
@@ -46,11 +50,13 @@ else:
release_by_tag,
release_manifest,
resolve_image,
resolve_release_bundle_oci,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
)
from release_publish import extract_release_notes
from release_scope import resolve_release_scope
@@ -248,22 +254,34 @@ def resolve_previous_release_state(previous_tag):
return pins, previous_tag[1:], previous_tag[1:]
def ensure_release_manifest_image(tag, commit, manifest):
def ensure_release_manifest_image(tag, commit, manifest, *, bundle_path=None, release_notes=None):
"""Push and verify the minimal OCI release-manifest:<tag> metadata artifact."""
bundle_in_oci = (manifest.get("client") or {}).get("bundle_storage") == "oci"
existing = resolve_release_manifest_oci(tag, commit)
if existing is not None:
if existing != manifest:
raise RuntimeError(f"Published OCI release manifest for {tag} differs from expected manifest")
if bundle_in_oci and resolve_release_bundle_oci(tag, commit, manifest) is None:
raise RuntimeError(f"Published OCI release manifest for {tag} is missing embedded hotfix bundle")
print(f"Verified OCI {manifest_image_name()}:{tag}", flush=True)
return existing
with tempfile.TemporaryDirectory(prefix="planet-manifest-") as tmp:
ctx = Path(tmp)
(ctx / "release-manifest.json").write_text(
payload = ctx / "payload"
payload.mkdir()
(payload / MANIFEST_NAME).write_text(
json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
)
if bundle_path is not None:
shutil.copy2(bundle_path, payload / bundle_path.name)
if release_notes:
(payload / RELEASE_NOTES_NAME).write_text(
release_notes.strip()[:32768] + "\n",
encoding="utf-8",
)
(ctx / "Dockerfile").write_text(
"FROM scratch\nCOPY release-manifest.json /release-manifest.json\n",
"FROM scratch\nCOPY payload/ /\n",
encoding="utf-8",
)
cmd = [
@@ -294,6 +312,8 @@ def ensure_release_manifest_image(tag, commit, manifest):
verified = resolve_release_manifest_oci(tag, commit)
if verified != manifest:
raise RuntimeError(f"Pushed OCI release manifest is missing or mismatched for {tag}")
if bundle_in_oci and resolve_release_bundle_oci(tag, commit, manifest) is None:
raise RuntimeError(f"Pushed OCI release manifest is missing embedded hotfix bundle for {tag}")
print(f"Verified OCI {manifest_image_name()}:{tag}", flush=True)
return verified
@@ -308,6 +328,15 @@ def build_release_manifest(tag, commit, scope, service_refs, packages, *, shell_
else:
resolved_shell = shell_version or ver
resolved_min_shell = min_shell_version or resolved_shell
client_info = {
"mode": scope.client_mode,
"shell_version": resolved_shell,
"min_shell_version": resolved_min_shell,
"bundle": bundle_path.name if bundle_path else None,
"bundle_sha256": package_hash(bundle_path) if bundle_path else None,
}
if bundle_path is not None:
client_info["bundle_storage"] = "oci" if scope.client_mode == "hotfix" else "release"
return {
"schema_version": 1,
"tag": tag,
@@ -316,13 +345,7 @@ def build_release_manifest(tag, commit, scope, service_refs, packages, *, shell_
"components": list(scope.components),
"changed_services": list(scope.services),
"services": dict(service_refs),
"client": {
"mode": scope.client_mode,
"shell_version": resolved_shell,
"min_shell_version": resolved_min_shell,
"bundle": bundle_path.name if bundle_path else None,
"bundle_sha256": package_hash(bundle_path) if bundle_path else None,
},
"client": client_info,
}
@@ -406,7 +429,22 @@ def prepare(tag, assets_dir, suffixes, *, already_published=False, scope_overrid
shell_version=prev_shell_version,
min_shell_version=prev_min_shell_version,
)
ensure_release_manifest_image(tag, commit, manifest)
oci_bundle_path = None
oci_release_notes = None
if (manifest.get("client") or {}).get("bundle_storage") == "oci" and not already_published:
bundle_name = (manifest.get("client") or {}).get("bundle")
oci_bundle_path = next(
(p for p in staged_packages if p.name == bundle_name),
None,
)
oci_release_notes = extract_release_notes(worktree / "docs/CHANGELOG.md", tag)
ensure_release_manifest_image(
tag,
commit,
manifest,
bundle_path=oci_bundle_path,
release_notes=oci_release_notes,
)
(stage / MANIFEST_NAME).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
yield stage, worktree / "docs/CHANGELOG.md"
# The verified public release now holds these bytes. Keep the cache on upload failure.
+18 -3
View File
@@ -575,9 +575,13 @@ def main(argv: list[str] | None = None) -> int:
print(f"scope_components: {','.join(scope.components)}")
print(f"scope_services: {','.join(scope.services) or 'none'}")
print(f"scope_client_mode: {scope.client_mode}")
print(
f"gitea_release: {'skip (no client update)' if scope.client_mode == 'none' else 'create'}"
)
if scope.client_mode == "full":
gitea_release_action = "create"
elif scope.client_mode == "hotfix":
gitea_release_action = "skip (OCI hotfix; preserves /releases/latest desktop installers)"
else:
gitea_release_action = "skip (no client update)"
print(f"gitea_release: {gitea_release_action}")
print(f"scope_previous_tag: {scope.previous_tag or 'none'}")
print(f"notes_length: {len(notes)}")
print(f"assets_count: {len(assets)}")
@@ -630,6 +634,17 @@ def main(argv: list[str] | None = None) -> int:
flush=True,
)
return 0
if client_mode == "hotfix":
if published:
raise RuntimeError(
f"Hotfix-only release {args.tag} must not have a published Gitea Release"
)
print(
f"Published hotfix release {args.tag} via OCI manifest and bundle "
"(skipped Gitea Release to preserve /releases/latest)",
flush=True,
)
return 0
if published:
pub_manifest = release_manifest(public, args.tag)
if pub_manifest is None or pub_manifest["client"]["mode"] != "none":
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.84.1"
version = "0.84.2"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },