diff --git a/.codex/skills/release/SKILL.md b/.codex/skills/release/SKILL.md index 56c2860e..e370ff8e 100644 --- a/.codex/skills/release/SKILL.md +++ b/.codex/skills/release/SKILL.md @@ -187,7 +187,9 @@ and builds/uploads **only** the affected targets: service image(s) + OCI `release-manifest:`, **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:` (`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`. diff --git a/AGENTS.md b/AGENTS.md index c9255e12..8127668d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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:` 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:`. +- **Client-Only Gitea Releases**: Releases without desktop shell updates + (`client.mode == "none"` or `"hotfix"`) push changed container images plus OCI + `release-manifest:` (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:`. - **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**: `scripts/release_publish.py` only publishes container images, OCI `release-manifest:`, and optional Gitea Releases; it never updates diff --git a/VERSION b/VERSION index e1858a2c..7a10a81e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.84.1 +0.84.2 diff --git a/backend/app/main.py b/backend/app/main.py index cc231c41..cce4b4b6 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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() diff --git a/backend/app/services/earth_clouds.py b/backend/app/services/earth_clouds.py index c03ba759..893cc352 100644 --- a/backend/app/services/earth_clouds.py +++ b/backend/app/services/earth_clouds.py @@ -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"), } diff --git a/backend/app/services/earth_clouds_fx.py b/backend/app/services/earth_clouds_fx.py index 13074cf2..dc189214 100644 --- a/backend/app/services/earth_clouds_fx.py +++ b/backend/app/services/earth_clouds_fx.py @@ -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 diff --git a/backend/app/services/earth_tiles.py b/backend/app/services/earth_tiles.py index f43561e8..2880d14e 100644 --- a/backend/app/services/earth_tiles.py +++ b/backend/app/services/earth_tiles.py @@ -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 diff --git a/backend/app/services/scheduler.py b/backend/app/services/scheduler.py index 23d669f4..d7f83349 100644 --- a/backend/app/services/scheduler.py +++ b/backend/app/services/scheduler.py @@ -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) diff --git a/backend/tests/test_earth_clouds.py b/backend/tests/test_earth_clouds.py index 4062b907..c42fb05c 100644 --- a/backend/tests/test_earth_clouds.py +++ b/backend/tests/test_earth_clouds.py @@ -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 diff --git a/backend/tests/test_earth_tiles_and_wind.py b/backend/tests/test_earth_tiles_and_wind.py index 6e9b1526..ff007b9c 100644 --- a/backend/tests/test_earth_tiles_and_wind.py +++ b/backend/tests/test_earth_tiles_and_wind.py @@ -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 diff --git a/client/package.json b/client/package.json index decd354c..8286b8ea 100644 --- a/client/package.json +++ b/client/package.json @@ -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", diff --git a/client/scripts/dist-target.mjs b/client/scripts/dist-target.mjs index f8a173ca..5b88540c 100644 --- a/client/scripts/dist-target.mjs +++ b/client/scripts/dist-target.mjs @@ -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]) } } diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5c40afb8..e8b0f468 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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 diff --git a/docs/HARNESS.md b/docs/HARNESS.md index 9f53a142..9e4902ee 100644 --- a/docs/HARNESS.md +++ b/docs/HARNESS.md @@ -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:` (and `release-manifest.json` when a client Release is -created). Releases with `client.mode == "none"` push only changed service -images + OCI `release-manifest:` 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:` (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:` (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 diff --git a/docs/technical/en/ops-runbook.md b/docs/technical/en/ops-runbook.md index c912398d..52c5632c 100644 --- a/docs/technical/en/ops-runbook.md +++ b/docs/technical/en/ops-runbook.md @@ -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:` 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:` 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:` 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:` (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:` (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. diff --git a/docs/technical/zh/ops-runbook.md b/docs/technical/zh/ops-runbook.md index e629d457..69655056 100644 --- a/docs/technical/zh/ops-runbook.md +++ b/docs/technical/zh/ops-runbook.md @@ -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:`。当版本不包含客户端或 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:`。当版本不包含桌面客户端壳包更新(`client.mode == "none"` 或 `"hotfix"`)时,**不创建新的 Gitea Release**(其中 `hotfix` 会把 L1 Earth 热更包与变更说明直接打入 OCI `release-manifest:`,从而让 Gitea `/releases/latest` 始终保留全平台桌面安装包);仅当包含全平台桌面客户端更新(`client.mode == "full"`)时才创建 Gitea Release 并附带 `release-manifest.json` 与对应安装包/热更包。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。 -生产机的 `planet-release-deploy.timer` 约每两分钟检查 Gitea 最新正式标签、OCI `release-manifest:`(及客户端更新版本对应的 Gitea Release)。确认清单与摘要齐全后,服务按不可变摘要仅拉取并滚动更新有变动的容器,备份 PostgreSQL,验证健康接口;仅在 `client.mode != "none"` 时发布并回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。 +生产机的 `planet-release-deploy.timer` 约每两分钟检查 Gitea 最新正式标签、OCI `release-manifest:`(及客户端全量/历史版本对应的 Gitea Release)。确认清单与摘要齐全后,服务按不可变摘要仅拉取并滚动更新有变动的容器,备份 PostgreSQL,验证健康接口;当 `client.mode != "none"` 时自动从 OCI 或 Release 读取并发布、回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。 上线失败时,服务恢复上一版的镜像摘要和热更新清单,保留数据库里的业务写入。事务记录在重启后仍可恢复。失败的版本会暂停自动重试,较新的正式版仍可上线。`/var/lib/planet-release-deploy/last-success/` 和 `last-failed/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。 diff --git a/docs/version-history.md b/docs/version-history.md index f9deaa72..1bc0fffc 100644 --- a/docs/version-history.md +++ b/docs/version-history.md @@ -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 参谋自进化加固与数据源连通性修复、桌面客户端启动与资源包更新及代码文档清理 | diff --git a/frontend/package.json b/frontend/package.json index cc93b360..9d2658b8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "planet-frontend", - "version": "0.84.1", + "version": "0.84.2", "private": true, "packageManager": "bun@1", "dependencies": { diff --git a/frontend/public/earth/css/compute-topic.css b/frontend/public/earth/css/compute-topic.css index 03d75533..02b5176f 100644 --- a/frontend/public/earth/css/compute-topic.css +++ b/frontend/public/earth/css/compute-topic.css @@ -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; diff --git a/frontend/public/earth/css/hud.css b/frontend/public/earth/css/hud.css index dbd5d68e..28cd5de8 100644 --- a/frontend/public/earth/css/hud.css +++ b/frontend/public/earth/css/hud.css @@ -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; } diff --git a/frontend/public/earth/css/info-panel.css b/frontend/public/earth/css/info-panel.css index 5c7e2022..346260af 100644 --- a/frontend/public/earth/css/info-panel.css +++ b/frontend/public/earth/css/info-panel.css @@ -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; diff --git a/frontend/public/earth/css/layer-panel.css b/frontend/public/earth/css/layer-panel.css index b67dfcce..82b953fc 100644 --- a/frontend/public/earth/css/layer-panel.css +++ b/frontend/public/earth/css/layer-panel.css @@ -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; } diff --git a/frontend/public/earth/css/news-region-cards.css b/frontend/public/earth/css/news-region-cards.css index d2af3299..cea530e3 100644 --- a/frontend/public/earth/css/news-region-cards.css +++ b/frontend/public/earth/css/news-region-cards.css @@ -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; } diff --git a/frontend/public/earth/index.html b/frontend/public/earth/index.html index 933f9e70..3da95224 100644 --- a/frontend/public/earth/index.html +++ b/frontend/public/earth/index.html @@ -719,11 +719,11 @@
- - - - - + + + + +
输入关键词或轻点上方分类快速探索地球对象
diff --git a/frontend/public/earth/js/compute-topic.js b/frontend/public/earth/js/compute-topic.js index 9db88c9d..58dadb6e 100644 --- a/frontend/public/earth/js/compute-topic.js +++ b/frontend/public/earth/js/compute-topic.js @@ -74,6 +74,11 @@ function safeMediaUrl(value) { } } +function computeSourceLink(url, label, buttonClass) { + if (!/^https:\/\//i.test(url || "")) return ""; + return `${escape(label)}`; +} + 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 ? `` @@ -929,7 +931,7 @@ export function initComputeTopic({ ${view.members.length ? `

${text("区域成员", "Region members")} ${view.members.length}

${view.members.map((member) => `${participantIdentity(member)}${escape(nameOf(member))}`).join("")}
` : ""}

${text("已核验设施样本", "Verified Facility Samples")} ${escape(view.sampleStatus)}

${text("设施条数仅反映已收录公开样本。", "Facility counts reflect publicly indexed samples only.")}

${view.sourceBreakdown ? `

${escape(view.sourceBreakdown)}

` : ""}${facilityStatus}
${mediaHtml(view.locations)} - ${view.evidence ? `

${text("来源与证据", "Source and evidence")}

${escape(view.evidence.title || "")}

${escape(view.evidence.publisher || "")} · ${escape(view.evidence.report_year || view.evidence.published_at || "")}

${view.evidence.locator ? `

${escape(view.evidence.locator)}

` : ""}${sourceUrl ? `${text("打开来源", "Open source")} ↗` : ""}
` : ""}`; + ${view.evidence ? `

${text("来源与证据", "Source and evidence")}

${escape(view.evidence.title || "")}

${escape(view.evidence.publisher || "")} · ${escape(view.evidence.report_year || view.evidence.published_at || "")}

${view.evidence.locator ? `

${escape(view.evidence.locator)}

` : ""}${computeSourceLink(view.evidence.url, text("打开来源", "Open source"), "earth-mobile-action-btn")}
` : ""}`; } 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 = `

${escape(evidence.publisher)} · ${escape(pubDateNote)}

${evidence.locator ? `

${escape(evidence.locator)}

` : ""}${sourceUrl ? `${text("打开权威原文", "Open verified source")} ↗` : ""}`; + const sourceLink = computeSourceLink(evidence.url, text("打开权威原文", "Open verified source"), "earth-settings-chip compute-evidence__link"); + const sourceMarkup = `

${escape(evidence.publisher)} · ${escape(pubDateNote)}

${evidence.locator ? `

${escape(evidence.locator)}

` : ""}${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 ? `

${escape(src.locator)}

` : ""} ${src.excerpt ? `
${escape(src.excerpt)}
` : ""} ${src.content_sha256 ? `

SHA-256${escape(src.content_sha256.slice(0, 20))}…

` : ""} - ${sourceUrl ? `${text("打开权威原文", "Open verified source")} ↗` : ""} + ${computeSourceLink(src.url, text("打开权威原文", "Open verified source"), "earth-settings-chip compute-evidence__link")} ` : ""; diff --git a/frontend/public/earth/js/info-card.js b/frontend/public/earth/js/info-card.js index c5a967a4..4d9a62d0 100644 --- a/frontend/public/earth/js/info-card.js +++ b/frontend/public/earth/js/info-card.js @@ -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]) => `
${escapeInfoCardHtml(infoText(label))}${escapeInfoCardHtml(value)}
`).join(''); if (/^https?:\/\//i.test(metadata.source_url || '')) { - html += `${escapeInfoCardHtml(infoText('查看原始来源'))} ↗`; + html += ` + ${escapeInfoCardHtml(infoText('查看原始来源'))} + + `; } } diff --git a/frontend/public/earth/js/layer-startup-tasks.js b/frontend/public/earth/js/layer-startup-tasks.js index da3fa641..4be1a57c 100644 --- a/frontend/public/earth/js/layer-startup-tasks.js +++ b/frontend/public/earth/js/layer-startup-tasks.js @@ -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(), diff --git a/frontend/public/earth/js/main.js b/frontend/public/earth/js/main.js index 121480a9..01c54f0b 100644 --- a/frontend/public/earth/js/main.js +++ b/frontend/public/earth/js/main.js @@ -4337,7 +4337,6 @@ async function ensureSatellitesEnabled(options = {}) { createSatellites(scene, earth); } - clearSatelliteData(); let loadResult; try { loadResult = await loadSatellites({ diff --git a/frontend/public/earth/js/news-region-cards.js b/frontend/public/earth/js/news-region-cards.js index f1145fc6..f32a5ead 100644 --- a/frontend/public/earth/js/news-region-cards.js +++ b/frontend/public/earth/js/news-region-cards.js @@ -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=`

${iconButton("news-analyze","forum",text("在 AI 参谋中分析","Analyze in AI Copilot"))}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}
${iconButton("news-prev","chevron_left",text("上一条新闻","Previous story"))}${iconButton("news-next","chevron_right",text("下一条新闻","Next story"))}${iconButton("news-play","pause",text("暂停轮播","Pause rotation"))}
`; + element.innerHTML = `

${iconButton("news-analyze","forum",text("在 AI 参谋中分析","Analyze in AI Copilot"))}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}
+
+
+
+ ${iconButton("news-prev", "chevron_left", text("上一条新闻", "Previous story"))} + + ${iconButton("news-next", "chevron_right", text("下一条新闻", "Next story"))} + ${iconButton("news-play", "pause", text("暂停轮播", "Pause rotation"))} + +
+
`; 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")}); diff --git a/frontend/public/earth/js/satellites.js b/frontend/public/earth/js/satellites.js index 98b0f148..0931cf13 100644 --- a/frontend/public/earth/js/satellites.js +++ b/frontend/public/earth/js/satellites.js @@ -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, diff --git a/frontend/public/earth/js/situational-copilot.js b/frontend/public/earth/js/situational-copilot.js index 57b7f42f..de9e4d2c 100644 --- a/frontend/public/earth/js/situational-copilot.js +++ b/frontend/public/earth/js/situational-copilot.js @@ -1274,7 +1274,10 @@ export function initSituationalCopilot({
${escape(selectedEv.title || turn.activeEvidenceId)}
${escape([selectedEv.publisher, selectedEv.locator].filter(Boolean).join(" · "))} - ${sourceUrl ? `${escape(text("原文", "Source"))} ↗` : ""} + ${sourceUrl ? ` + ${escape(text("原文", "Source"))} + + ` : ""}
` : ""} diff --git a/frontend/public/earth/js/workbench-blocks.js b/frontend/public/earth/js/workbench-blocks.js index c9e87c0e..ed5f1978 100644 --- a/frontend/public/earth/js/workbench-blocks.js +++ b/frontend/public/earth/js/workbench-blocks.js @@ -534,7 +534,10 @@ function renderEvidenceDrawerBlock(block, { collapsedOverride } = {}) {
${escapeWorkbenchHtml(metaParts)} - ${safeUrl ? `${escapeWorkbenchHtml(t("原文", "Source"))} ↗` : ""} + ${safeUrl ? ` + ${escapeWorkbenchHtml(t("原文", "Source"))} + + ` : ""}
`; }) diff --git a/frontend/src/admin/components/data-table/DataTable.tsx b/frontend/src/admin/components/data-table/DataTable.tsx index 401161ab..2ee81eee 100644 --- a/frontend/src/admin/components/data-table/DataTable.tsx +++ b/frontend/src/admin/components/data-table/DataTable.tsx @@ -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 { resizableColumns?: boolean columnWidthStorageKey?: string enableSorting?: boolean + hiddenColumnIds?: readonly string[] waterfall?: DataTableWaterfallConfig | false scrollResetKey?: string | number } @@ -104,6 +106,7 @@ export function DataTable({ resizableColumns = true, columnWidthStorageKey, enableSorting, + hiddenColumnIds, waterfall, scrollResetKey, }: DataTableProps) { @@ -130,11 +133,20 @@ export function DataTable({ const [resizingColumnId, setResizingColumnId] = useState(null) const resizeCleanupRef = useRef<(() => void) | null>(null) + const columnVisibility = useMemo(() => { + 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({ 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 && diff --git a/frontend/src/admin/components/layout/AdminLayout.tsx b/frontend/src/admin/components/layout/AdminLayout.tsx index 41a86986..b10c0219 100644 --- a/frontend/src/admin/components/layout/AdminLayout.tsx +++ b/frontend/src/admin/components/layout/AdminLayout.tsx @@ -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( + () => getCachedRuntimeVersion() ?? packageJson.version, + ) const menuViewportRef = useRef(null) const mobileMenuViewportRef = useRef(null) const searchInputRef = useRef(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(() => { + const [desktopCollapsed, setDesktopCollapsed] = useState(() => { if (cachedCollapsed !== null) return cachedCollapsed const stored = readStoredCollapsed() cachedCollapsed = stored ?? false return cachedCollapsed }) + const [isCompactDesktop, setIsCompactDesktop] = useState(matchesCompactDesktop) + const [compactCollapsedOverride, setCompactCollapsedOverride] = useState( + () => 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(() => { 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 }) {
{t('admin.greeting', { name: username })} - {t('admin.version')} v{packageJson.version} + + {t('admin.version')} v{runtimeVersion} +
diff --git a/frontend/src/admin/components/layout/SplitPaneResizer.tsx b/frontend/src/admin/components/layout/SplitPaneResizer.tsx index 6c1c1645..fb6e24a9 100644 --- a/frontend/src/admin/components/layout/SplitPaneResizer.tsx +++ b/frontend/src/admin/components/layout/SplitPaneResizer.tsx @@ -74,12 +74,72 @@ export function useSplitPaneResize({ const [width, setWidth] = useState(() => readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth), ) + const preferredWidthRef = useRef( + 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 } diff --git a/frontend/src/admin/components/layout/runtimeVersion.ts b/frontend/src/admin/components/layout/runtimeVersion.ts new file mode 100644 index 00000000..6ded04f7 --- /dev/null +++ b/frontend/src/admin/components/layout/runtimeVersion.ts @@ -0,0 +1,70 @@ +const SEMVER_PATTERN = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/ + +let cachedRuntimeVersion: string | null = null +let inFlightPromise: Promise | 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 { + 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 { + 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 +} diff --git a/frontend/src/admin/components/ui/dialog.tsx b/frontend/src/admin/components/ui/dialog.tsx index 72f9f9db..2d7ae0de 100644 --- a/frontend/src/admin/components/ui/dialog.tsx +++ b/frontend/src/admin/components/ui/dialog.tsx @@ -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({ )} > - {description || t('common.confirm')} + + {description || t('common.confirm')} + ) } diff --git a/frontend/src/admin/components/ui/select.tsx b/frontend/src/admin/components/ui/select.tsx index 52500f7d..f94d7fd2 100644 --- a/frontend/src/admin/components/ui/select.tsx +++ b/frontend/src/admin/components/ui/select.tsx @@ -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 - - {options.map((option) => { - const itemValue = option.value === '' ? EMPTY_OPTION_VALUE : option.value - return ( - - {option.label} - - - - - ) - })} - + + + {options.map((option) => { + const itemValue = option.value === '' ? EMPTY_OPTION_VALUE : option.value + return ( + + {option.label} + + + + + ) + })} + + diff --git a/frontend/src/admin/pages/AdvisorPages.css b/frontend/src/admin/pages/AdvisorPages.css index 535ec688..5c7bc574 100644 --- a/frontend/src/admin/pages/AdvisorPages.css +++ b/frontend/src/admin/pages/AdvisorPages.css @@ -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); } diff --git a/frontend/src/admin/pages/AdvisorWorkflows.tsx b/frontend/src/admin/pages/AdvisorWorkflows.tsx index 3931d1ba..c0cde92a 100644 --- a/frontend/src/admin/pages/AdvisorWorkflows.tsx +++ b/frontend/src/admin/pages/AdvisorWorkflows.tsx @@ -602,6 +602,8 @@ export default function AdvisorWorkflows() { const [inspectorWidth, setInspectorWidth] = useState(() => 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[]) => { 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() {
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 ? ( +
+
- {errorText?

{errorText}

:null} + {errorText?

{errorText}

:null} {message?

{message}

:null} {!draft?

{busy?t('加载中…','Loading…'):t('暂无可用配置','Configuration unavailable')}

:
{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…'))}
- {error ?

{error}

: null} + {error ?

{error}

: null} {draft && saved ? <>
@@ -936,7 +936,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) { {t('置信度', 'Confidence')}: {typeof candidate.confidence === 'number' && Number.isFinite(candidate.confidence) ? `${Math.round(candidate.confidence * 100)}%` : '—'}
{codesEntries.length > 0 ? ( -
+ @@ -959,9 +959,11 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) { ))}
-
+ ) : ( -
{JSON.stringify(candidate.proposed_payload, null, 2)}
+ +
{JSON.stringify(candidate.proposed_payload, null, 2)}
+
)} {candidate.review_reason_code ? ( @@ -1042,7 +1044,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) { {revisions.length === 0 ? (

{t('暂无发布版本记录。', 'No revisions recorded yet.')}

) : ( -
+ @@ -1073,7 +1075,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) { ))}
-
+ )} } diff --git a/frontend/src/admin/pages/Dashboard.tsx b/frontend/src/admin/pages/Dashboard.tsx index f211b8e1..cd70bdfd 100644 --- a/frontend/src/admin/pages/Dashboard.tsx +++ b/frontend/src/admin/pages/Dashboard.tsx @@ -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() {
{renderAssetDimTabs()} -
{renderRuntimeTabs()} -
@@ -1651,9 +1645,6 @@ function DashboardContent() {
{renderOpsTabs()} -
@@ -1709,7 +1700,7 @@ function DashboardContent() { -
+ {opsTab === 'datasources' ? ( previewList.length > 0 ? ( (previewList as DashboardDatasourceRow[]).map((item) => { @@ -1786,7 +1777,7 @@ function DashboardContent() { ) : (
暂无采集器
)} -
+ ) } @@ -1812,13 +1803,10 @@ function DashboardContent() { : '0 活跃告警'} - -
+ {activeAlerts.slice(0, 3).map((item) => { const sev = alertSeverityBadge(item.severity) return ( @@ -1862,7 +1850,7 @@ function DashboardContent() {
))} - + ) } @@ -2169,7 +2157,7 @@ function DashboardContent() { {isEnglish ? `${systemChannels.length} channels` : `${systemChannels.length} 条通道`} -
+ {systemChannels.map((ch) => (
@@ -2180,7 +2168,7 @@ function DashboardContent() { {ch.status}
))} -
+
@@ -2263,61 +2251,60 @@ function DashboardContent() { {error ?
{error}
: null} -
-
- {dockedCards.map((card) => ( -
switchFocus(card.id)} - onKeyDown={(event) => handleCardKeyDown(event, card.id)} - > -
-
-
- {card.icon} -

{card.title}

-
- -
-
- {card.dockKpi} - {card.dockSub} -
-
-
- ))} -
- -
- {activeHero ? ( -
- {renderHeroBody(activeHero)} -
- ) : ( - cardDescriptors.map((card) => ( + +
+
+ {dockedCards.map((card) => (
switchFocus(card.id)} onKeyDown={(event) => handleCardKeyDown(event, card.id)} > - {renderBentoCardBody(card)} +
+
+
+ {card.icon} +

{card.title}

+
+
+
+ {card.dockKpi} + {card.dockSub} +
+
- )) - )} + ))} +
+ +
+ {activeHero ? ( +
+ {renderHeroBody(activeHero)} +
+ ) : ( + cardDescriptors.map((card) => ( +
switchFocus(card.id)} + onKeyDown={(event) => handleCardKeyDown(event, card.id)} + > + {renderBentoCardBody(card)} +
+ )) + )} +
-
+ {stats?.last_updated ? (
diff --git a/frontend/src/admin/pages/DataList.tsx b/frontend/src/admin/pages/DataList.tsx index 851f9ca8..e9bedd33 100644 --- a/frontend/src/admin/pages/DataList.tsx +++ b/frontend/src/admin/pages/DataList.tsx @@ -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 = { - 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([]) const [layersLoading, setLayersLoading] = useState(false) - const [summaryWidth, setSummaryWidth] = useState(260) - const summaryWidthRef = useRef(summaryWidth) - summaryWidthRef.current = summaryWidth const dataLayoutRef = useRef(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) => { - 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>>(() => [ { accessorKey: 'name', - header: '名称', + header: t('dataLedger.column.name'), size: 320, cell: ({ row }) => ( - - + + +
@@ -464,8 +418,8 @@ export default function DataList() {
- + {detailLoading ? ( -
加载中
+
{t('common.loading')}
) : detailData ? (
- 名称 + {t('dataLedger.column.name')}

{detailData.name || '-'}

{detailBaseItems.length > 0 ? (
-

基础信息

+

{t('dataLedger.basicInfo')}

{detailBaseItems.map((item) => (
@@ -546,7 +500,7 @@ export default function DataList() { ) : null} {detailMetadataItems.length > 0 ? (
-

扩展字段

+

{t('dataLedger.extraFields')}

{detailMetadataItems.map((item) => (
@@ -562,14 +516,14 @@ export default function DataList() {
) : null}
-

原始元数据

+

{t('dataLedger.rawMetadata')}

{JSON.stringify(detailData.metadata || {}, null, 2)}
) : ( -
暂无数据
+
{t('common.noData')}
)}
diff --git a/frontend/src/admin/pages/Logs.tsx b/frontend/src/admin/pages/Logs.tsx index a3b9b40c..c8f2bcf5 100644 --- a/frontend/src/admin/pages/Logs.tsx +++ b/frontend/src/admin/pages/Logs.tsx @@ -673,7 +673,9 @@ export default function Logs() { {event.occurrence_count > 1 ? {`${event.occurrence_count} 次`} : null}

{event.message}

-
{stringifyContext(event.context)}
+ +
{stringifyContext(event.context)}
+
))} {!groupEvents.length ? : null} diff --git a/frontend/src/admin/pages/PlainResourcePages.tsx b/frontend/src/admin/pages/PlainResourcePages.tsx index 1bc5c76f..07f8ec8d 100644 --- a/frontend/src/admin/pages/PlainResourcePages.tsx +++ b/frontend/src/admin/pages/PlainResourcePages.tsx @@ -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> + hiddenColumnIds?: readonly string[] selection?: { selectedRowIds: Set onToggleAllVisible: (rowIds: string[]) => void @@ -876,6 +888,7 @@ const ModuleTable = memo(function ModuleTable({ ([]) 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(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(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(null) const hierarchyResize = useSplitPaneResize({ storageKey: 'planet.admin.hierarchyWidth', @@ -2851,52 +2891,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) { run: () => Promise }>(null) - const startDetailResize = useCallback((event: ReactPointerEvent) => { - 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) => { event.preventDefault() const dialog = event.currentTarget.closest('.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 }) {
@@ -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 }) {
- @@ -7826,7 +7840,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) { confirmLabel: '重置', run: () => loadCredentialGuide(credentialGuideProviderName, 'reset'), })} loading={actionLoading}> - +
diff --git a/frontend/src/admin/pages/card-images.css b/frontend/src/admin/pages/card-images.css index aa8952da..05f73685 100644 --- a/frontend/src/admin/pages/card-images.css +++ b/frontend/src/admin/pages/card-images.css @@ -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; } } diff --git a/frontend/src/admin/pages/compute-comparison.css b/frontend/src/admin/pages/compute-comparison.css index c1de7f49..43a6f9c7 100644 --- a/frontend/src/admin/pages/compute-comparison.css +++ b/frontend/src/admin/pages/compute-comparison.css @@ -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); } diff --git a/frontend/src/admin/pages/dashboardCharts.tsx b/frontend/src/admin/pages/dashboardCharts.tsx index 10fbefcc..d4640e63 100644 --- a/frontend/src/admin/pages/dashboardCharts.tsx +++ b/frontend/src/admin/pages/dashboardCharts.tsx @@ -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(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(
{tip.title}
{tip.body}
-
+ , + document.body, ) } @@ -180,7 +241,7 @@ export function DashboardHorizontalBarChart({ ) })} - + setTip(null)} /> ) } @@ -340,7 +401,7 @@ export function DashboardTaskTrendChart({ /> ))} - + setTip(null)} /> ) } @@ -486,7 +547,7 @@ export function DashboardLayerDonutChart({ ) : null} - + setTip(null)} /> ) } diff --git a/frontend/src/admin/pages/data-ledger/ComputeLedger.tsx b/frontend/src/admin/pages/data-ledger/ComputeLedger.tsx index 26adc461..14dc5e88 100644 --- a/frontend/src/admin/pages/data-ledger/ComputeLedger.tsx +++ b/frontend/src/admin/pages/data-ledger/ComputeLedger.tsx @@ -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>>(() => [ { 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 }) => ( - {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 })} ), }, { 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 ( - - {terminalText ? `${meta.label} · ${terminalText}` : meta.label} + + {terminalText ? `${label} · ${terminalText}` : label} ) }, }, { 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 (
event.stopPropagation()} > void }) { openEditDialog(row.original)} >