forked from linkong/planet
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19d5ac0fee | ||
|
|
3265d22af5 |
No files matched your search
+101
-5
@@ -1,19 +1,115 @@
|
||||
# agents.md
|
||||
# AGENTS.md
|
||||
|
||||
**AI Agent 角色设定。定义 AI 如何行为、沟通和工作。**
|
||||
|
||||
---
|
||||
|
||||
## Harness Compatibility
|
||||
|
||||
This file is the single authoritative agent guide for the Planet repository.
|
||||
The older lowercase `agents.md` entry has been merged here so coding agents and
|
||||
harness tools use one source of truth.
|
||||
|
||||
### Read First
|
||||
|
||||
Read these files before changing code:
|
||||
|
||||
1. `rules.md` - mandatory repository rules. Always load `core`, `security`, and
|
||||
`workflow`; load `docs`, `uiux`, `frontend`, `backend`, `earth`, `ai`, or
|
||||
`release` when the task touches those areas.
|
||||
2. `AGENTS.md` - this file, including role, communication, workflow, and
|
||||
harness compatibility guidance.
|
||||
3. `project_context.md` - static project background. Prefer newer
|
||||
implementation docs when this context disagrees with current code.
|
||||
4. `README.md` - current architecture, startup, and toolchain summary.
|
||||
5. `docs/HARNESS.md` - harness workflow, conflict policy, and validation tiers.
|
||||
6. `CODEMAP.md` - codebase entry points, ownership boundaries, and deeper docs.
|
||||
|
||||
For documentation work, also read `docs/documentation-coverage-rules.md`.
|
||||
|
||||
### Start Safely
|
||||
|
||||
Before editing:
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
scripts/harness/doctor.sh
|
||||
```
|
||||
|
||||
Use focused context commands before reading large files:
|
||||
|
||||
```bash
|
||||
rg -n "<symbol-or-term>" <path>
|
||||
git diff --stat HEAD
|
||||
git diff --name-only HEAD
|
||||
git diff --unified=0 HEAD -- <path>
|
||||
```
|
||||
|
||||
Preserve user changes already present in the worktree.
|
||||
|
||||
### Validation
|
||||
|
||||
Fast local harness validation:
|
||||
|
||||
```bash
|
||||
scripts/harness/quick-check.sh
|
||||
```
|
||||
|
||||
Full local validation:
|
||||
|
||||
```bash
|
||||
scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
`validate.sh` includes the quick check and the frontend Bun build. Docker image
|
||||
smoke builds are intentionally opt-in:
|
||||
|
||||
```bash
|
||||
PLANET_HARNESS_DOCKER_SMOKE=1 scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
Harness scripts resolve `bun`, `uv`, and optional delivery tools from the
|
||||
current non-interactive environment first. If a tool is missing there, they ask
|
||||
the user's login interactive shell instead of assuming a specific dotfile.
|
||||
|
||||
### High-Risk Areas
|
||||
|
||||
- `planet.sh` owns local lifecycle, ports, WSL/LAN behavior, and destructive
|
||||
`destroy` cleanup.
|
||||
- Frontend package management is Bun-only. Do not use npm, pnpm, or yarn.
|
||||
- Frontend changes must satisfy `scripts/harness/frontend-rules-check.sh`; use
|
||||
rendered smoke evidence for public pages, auth guards, authenticated admin
|
||||
route/section availability, safe navigation/search/tab interactions, mobile
|
||||
layout, and 125% / 150% zoom, not only a build.
|
||||
- `aiprovider` is a protocol/provider adapter; keep business prompts and product
|
||||
workflows in the backend.
|
||||
- Earth rendering depends on layer order, depth behavior, picking, and
|
||||
performance-sensitive Three.js code.
|
||||
- Secrets belong in environment files or configured settings stores, never in
|
||||
committed files.
|
||||
- Backend service code must use structured logging instead of `print()` or
|
||||
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
|
||||
|
||||
### Conflict Policy
|
||||
|
||||
Existing project rules and workflows win. If new harness guidance conflicts with
|
||||
`rules.md`, `AGENTS.md`, current docs, scripts, or CI, keep the existing
|
||||
behavior and document the compatibility note in `docs/harness-audit.md` or
|
||||
`docs/HARNESS.md`.
|
||||
|
||||
---
|
||||
|
||||
## Identity
|
||||
|
||||
You are **opencode**, an AI coding assistant specialized in enterprise-level systems.
|
||||
|
||||
You are working on the **智能星球计划 (Intelligent Planet Plan)** - a situational awareness system for data-centric competition featuring:
|
||||
- Python FastAPI backend
|
||||
- React Admin dashboard
|
||||
- Unreal Engine 5 3D visualization
|
||||
- React admin console, public Docs UI, and browser Web Earth shell
|
||||
- AI Provider model gateway
|
||||
- Multi-source data collection
|
||||
- Polarized 3D large display (4K, 120Hz)
|
||||
- Future physical display directions such as UE5 / Cesium remain optional
|
||||
roadmap work, not the active local development loop
|
||||
|
||||
---
|
||||
|
||||
@@ -226,6 +322,6 @@ class TOP500Collector:
|
||||
|
||||
1. **Rules are hard constraints** - follow `rules.md` absolutely
|
||||
2. **Context provides understanding** - use `project_context.md` for background
|
||||
3. **Role defines behavior** - follow `agents.md` for how to work
|
||||
3. **Role defines behavior** - follow `AGENTS.md` for how to work
|
||||
4. **Quality over speed** - Enterprise systems require precision
|
||||
5. **Communicate clearly** - Precision in, precision out
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
# Code Map
|
||||
|
||||
This map gives agents and maintainers a quick orientation without replacing the
|
||||
deeper architecture docs. Current implementation docs under `docs/technical/`
|
||||
are the source of detail for specific subsystems.
|
||||
|
||||
## Top-Level Areas
|
||||
|
||||
| Path | Role | Notes |
|
||||
| --- | --- | --- |
|
||||
| `backend/` | FastAPI backend, auth, APIs, data collectors, AI task orchestration, persistence | Tests live in `backend/tests/`; run backend tests from `backend/` with the root uv project. |
|
||||
| `frontend/` | React admin console, Docs UI, Web Earth shell, Vite build | Use Bun only. Public Earth assets live under `frontend/public/earth/`. |
|
||||
| `aiprovider/` | Model provider/protocol adapter service | Keep it free of product-specific prompts and workflows. |
|
||||
| `motion_agent/` | Motion capture protocol service used by `planet.sh` | Often dry-runs when cameras are unavailable, especially in WSL. |
|
||||
| `scripts/` | Utility scripts and harness wrappers | Harness commands live in `scripts/harness/`. |
|
||||
| `docs/` | Plans, technical docs, changelog, harness docs | Public technical docs are explicitly registered by the frontend Docs catalog. |
|
||||
| `deploy/helm/planet/` | Helm chart for staging/deployment smoke paths | CI runs helm lint/template when delivery checks are available. |
|
||||
| `.gitea/workflows/` | CI, release image build, staging deploy workflows | This repository uses Gitea workflow files, not `.github/workflows/`. |
|
||||
| `planet.sh` | Main local lifecycle script | Owns init/start/restart/stop/health/log/createuser/destroy. |
|
||||
|
||||
## Runtime Entry Points
|
||||
|
||||
| Runtime | Entry Point | Validation |
|
||||
| --- | --- | --- |
|
||||
| Local full stack | `./planet.sh start` | `./planet.sh health` |
|
||||
| Backend API | `backend/app/main.py` | `cd backend && uv run --frozen --group dev --project .. python -m pytest -q` |
|
||||
| Frontend app | `frontend/src/main.tsx` and `frontend/vite.config.mts` | `cd frontend && bun run build` |
|
||||
| AI Provider | `aiprovider/main.py` | `curl http://localhost:8010/health` after startup |
|
||||
| Motion Agent | `python -m motion_agent` via `planet.sh` | `./planet.sh health` or dry-run startup |
|
||||
| Docs UI | `frontend/src/pages/Docs/` | Docs catalog metadata plus frontend build |
|
||||
|
||||
## Ownership Boundaries
|
||||
|
||||
- Backend owns business state, auth, evidence collection, prompt selection, AI
|
||||
task orchestration, and database persistence.
|
||||
- `aiprovider` owns provider identity, request adapter style, model gateway
|
||||
retries, and health/status endpoints only.
|
||||
- Frontend owns operator workflows, Docs presentation, Web Earth orchestration,
|
||||
and client-side state that mirrors backend truth.
|
||||
- Web Earth rendering changes must preserve documented layer order, altitude
|
||||
offsets, picking behavior, legend semantics, and performance constraints.
|
||||
- `planet.sh` owns local environment bootstrap and service lifecycle. Prefer
|
||||
wrapping it from harness scripts instead of duplicating its internals.
|
||||
- Harness scripts source `scripts/harness/lib.sh` so agent shells that cannot
|
||||
see `bun` or `uv` in non-interactive `PATH` can still resolve the user's login
|
||||
interactive command path without hardcoding `.zshrc`.
|
||||
|
||||
## Validation Commands
|
||||
|
||||
```bash
|
||||
scripts/harness/doctor.sh
|
||||
scripts/harness/security-check.sh
|
||||
scripts/harness/backend-rules-check.sh
|
||||
scripts/harness/frontend-rules-check.sh
|
||||
scripts/harness/docs-consistency-check.sh
|
||||
scripts/harness/quick-check.sh
|
||||
scripts/harness/validate.sh
|
||||
./planet.sh health
|
||||
```
|
||||
|
||||
CI-equivalent local checks:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
uv run --frozen --group dev --project .. python -m pytest -s tests/test_api.py tests/test_realtime_sources.py -q
|
||||
|
||||
cd frontend
|
||||
bun install --frozen-lockfile
|
||||
bun run build
|
||||
PLANET_FRONTEND_SMOKE_URL=http://127.0.0.1:4173 bun ../scripts/harness/frontend-smoke.mjs
|
||||
```
|
||||
|
||||
The frontend smoke covers public routes, unauthenticated admin guards,
|
||||
login-error handling, the Earth iframe entry, and authenticated `super_admin`
|
||||
admin route/section rendering with mocked API data. Authenticated admin checks
|
||||
run on desktop, mobile, and 125% / 150% zoom; desktop and mobile passes also
|
||||
check for accidental global horizontal overflow. A second smoke layer exercises
|
||||
safe desktop/mobile navigation, admin search, section tab switching, dialog
|
||||
opening, and non-destructive shortcut links.
|
||||
|
||||
Optional delivery smoke, when Docker and Helm are available:
|
||||
|
||||
```bash
|
||||
PLANET_HARNESS_DOCKER_SMOKE=1 scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
## Deeper Docs
|
||||
|
||||
| Topic | Start Here |
|
||||
| --- | --- |
|
||||
| Data products and flows | `docs/technical/zh/platform-data-flows.md` and `docs/technical/en/platform-data-flows.md` |
|
||||
| Operations and local lifecycle | `docs/technical/zh/ops-runbook.md` and `docs/technical/en/ops-runbook.md` |
|
||||
| `planet.sh` startup behavior | `docs/technical/zh/ops-planet-sh-startup.md` and `docs/technical/en/ops-planet-sh-startup.md` |
|
||||
| AI Provider | `docs/technical/zh/agents-aiprovider.md` and `docs/technical/en/agents-aiprovider.md` |
|
||||
| Admin frontend | `docs/technical/zh/frontend-admin-frontend-context.md` and `docs/technical/en/frontend-admin-frontend-context.md` |
|
||||
| Earth frontend | `docs/technical/zh/earth-frontend-context.md` and `docs/technical/en/earth-frontend-context.md` |
|
||||
| Earth render order | `docs/technical/zh/earth-render-layer-order.md` and `docs/technical/en/earth-render-layer-order.md` |
|
||||
| Documentation rules | `docs/documentation-coverage-rules.md` |
|
||||
| Harness workflow | `docs/HARNESS.md` |
|
||||
|
||||
## Known Sharp Edges
|
||||
|
||||
- `project_context.md` is static background for agents. It now labels future
|
||||
stack directions separately, but current code and technical docs still win
|
||||
when details diverge.
|
||||
- README now describes Web Earth, React admin, FastAPI, and `aiprovider` as the
|
||||
active local development shape.
|
||||
- Local `destroy` is intentionally destructive for Planet-owned Docker and build
|
||||
state. Never run it as a validation shortcut.
|
||||
@@ -83,7 +83,7 @@
|
||||
| 组件 | 用途 |
|
||||
|------|------|
|
||||
| React 18 | UI 框架 |
|
||||
| Ant Design Pro | 管理后台组件 |
|
||||
| Tactile UI / Radix primitives / lucide-react | 管理后台组件、基础交互与图标 |
|
||||
| Axios | HTTP 客户端 |
|
||||
| Socket.io-client | WebSocket 客户端 |
|
||||
| ECharts | 统计图表 |
|
||||
|
||||
@@ -11,17 +11,20 @@ To get higher limits, set PEERINGDB_API_KEY environment variable.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from typing import Dict, Any, List
|
||||
from datetime import UTC, datetime
|
||||
import os
|
||||
from typing import Any, Dict, List
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.services.collectors.base import HTTPCollector
|
||||
|
||||
|
||||
# PeeringDB API key - read from environment variable
|
||||
PEERINGDB_API_KEY = os.environ.get("PEERINGDB_API_KEY", "")
|
||||
logger = get_logger(__name__, service="collector")
|
||||
|
||||
|
||||
class PeeringDBIXPCollector(HTTPCollector):
|
||||
@@ -39,6 +42,7 @@ class PeeringDBIXPCollector(HTTPCollector):
|
||||
"User-Agent": "Planet-Intelligence-System/1.0 (Python/collector)",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
@property
|
||||
def request_url(self) -> str:
|
||||
base = self._resolved_url or self.base_url
|
||||
@@ -61,7 +65,11 @@ class PeeringDBIXPCollector(HTTPCollector):
|
||||
if response.status_code == 429:
|
||||
# Rate limited - wait and retry with exponential backoff
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
@@ -72,13 +80,21 @@ class PeeringDBIXPCollector(HTTPCollector):
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
raise
|
||||
|
||||
print(f"Warning: PeeringDB collection failed after {max_retries} retries: {last_error}")
|
||||
logger.warning_event(
|
||||
"PeeringDB collection failed after retries",
|
||||
event="collector.peeringdb.retries_exhausted",
|
||||
context={"max_retries": max_retries, "last_error": last_error},
|
||||
)
|
||||
return {}
|
||||
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
@@ -146,6 +162,7 @@ class PeeringDBNetworkCollector(HTTPCollector):
|
||||
"User-Agent": "Planet-Intelligence-System/1.0 (Python/collector)",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
@property
|
||||
def request_url(self) -> str:
|
||||
base = self._resolved_url or self.base_url
|
||||
@@ -167,7 +184,11 @@ class PeeringDBNetworkCollector(HTTPCollector):
|
||||
|
||||
if response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
@@ -178,13 +199,21 @@ class PeeringDBNetworkCollector(HTTPCollector):
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
raise
|
||||
|
||||
print(f"Warning: PeeringDB collection failed after {max_retries} retries: {last_error}")
|
||||
logger.warning_event(
|
||||
"PeeringDB collection failed after retries",
|
||||
event="collector.peeringdb.retries_exhausted",
|
||||
context={"max_retries": max_retries, "last_error": last_error},
|
||||
)
|
||||
return {}
|
||||
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
@@ -254,6 +283,7 @@ class PeeringDBFacilityCollector(HTTPCollector):
|
||||
"User-Agent": "Planet-Intelligence-System/1.0 (Python/collector)",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
@property
|
||||
def request_url(self) -> str:
|
||||
base = self._resolved_url or self.base_url
|
||||
@@ -275,7 +305,11 @@ class PeeringDBFacilityCollector(HTTPCollector):
|
||||
|
||||
if response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
@@ -286,13 +320,21 @@ class PeeringDBFacilityCollector(HTTPCollector):
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
raise
|
||||
|
||||
print(f"Warning: PeeringDB collection failed after {max_retries} retries: {last_error}")
|
||||
logger.warning_event(
|
||||
"PeeringDB collection failed after retries",
|
||||
event="collector.peeringdb.retries_exhausted",
|
||||
context={"max_retries": max_retries, "last_error": last_error},
|
||||
)
|
||||
return {}
|
||||
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
"""Space-Track TLE Collector
|
||||
"""Space-Track TLE Collector.
|
||||
|
||||
Collects satellite TLE (Two-Line Element) data from Space-Track.org.
|
||||
API documentation: https://www.space-track.org/documentation
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Dict, Any, List
|
||||
import httpx
|
||||
from typing import Any, Dict, List
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.services.collectors.base import BaseCollector
|
||||
import httpx
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.logging import get_logger
|
||||
from app.core.satellite_tle import build_tle_lines_from_elements
|
||||
from app.services.collectors.base import BaseCollector
|
||||
|
||||
|
||||
logger = get_logger(__name__, service="collector")
|
||||
|
||||
|
||||
class SpaceTrackTLECollector(BaseCollector):
|
||||
@@ -53,10 +57,16 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
password = settings.SPACETRACK_PASSWORD
|
||||
|
||||
if not username or not password:
|
||||
print("SPACETRACK: No credentials configured, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track credentials are not configured; using sample data",
|
||||
event="collector.spacetrack.credentials_missing",
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
print(f"SPACETRACK: Attempting to fetch TLE data with username: {username}")
|
||||
logger.info_event(
|
||||
"Space-Track TLE fetch started",
|
||||
event="collector.spacetrack.fetch.start",
|
||||
)
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
@@ -78,11 +88,17 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
print(f"SPACETRACK: Login response status: {login_response.status_code}")
|
||||
print(f"SPACETRACK: Login response URL: {login_response.url}")
|
||||
logger.info_event(
|
||||
"Space-Track login response received",
|
||||
event="collector.spacetrack.login.response",
|
||||
context={"status_code": login_response.status_code},
|
||||
)
|
||||
|
||||
if login_response.status_code == 403:
|
||||
print("SPACETRACK: Trying alternate login method...")
|
||||
logger.warning_event(
|
||||
"Space-Track login returned forbidden; trying alternate method",
|
||||
event="collector.spacetrack.login.forbidden",
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=120.0,
|
||||
@@ -90,11 +106,6 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
) as alt_client:
|
||||
await alt_client.get(f"{self.site_root}/")
|
||||
|
||||
form_data = {
|
||||
"username": username,
|
||||
"password": password,
|
||||
"query": "class/gp/NORAD_CAT_ID/25544/format/json",
|
||||
}
|
||||
alt_login = await alt_client.post(
|
||||
self.login_url,
|
||||
data={
|
||||
@@ -102,77 +113,59 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
print(f"SPACETRACK: Alt login status: {alt_login.status_code}")
|
||||
logger.info_event(
|
||||
"Space-Track alternate login response received",
|
||||
event="collector.spacetrack.alt_login.response",
|
||||
context={"status_code": alt_login.status_code},
|
||||
)
|
||||
|
||||
if alt_login.status_code == 200:
|
||||
tle_response = await alt_client.get(self.probe_url)
|
||||
if tle_response.status_code == 200:
|
||||
data = tle_response.json()
|
||||
print(f"SPACETRACK: Received {len(data)} records via alt method")
|
||||
logger.info_event(
|
||||
"Space-Track alternate query completed",
|
||||
event="collector.spacetrack.alt_query.completed",
|
||||
context={"record_count": len(data)},
|
||||
)
|
||||
return data
|
||||
|
||||
if login_response.status_code != 200:
|
||||
print(f"SPACETRACK: Login failed, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track login failed; using sample data",
|
||||
event="collector.spacetrack.login.failed",
|
||||
context={"status_code": login_response.status_code},
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
tle_response = await client.get(self.probe_url)
|
||||
print(f"SPACETRACK: TLE query status: {tle_response.status_code}")
|
||||
|
||||
if tle_response.status_code != 200:
|
||||
print(f"SPACETRACK: Query failed, using sample data")
|
||||
return self._get_sample_data()
|
||||
|
||||
data = tle_response.json()
|
||||
print(f"SPACETRACK: Received {len(data)} records")
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"SPACETRACK: Error - {e}, using sample data")
|
||||
return self._get_sample_data()
|
||||
|
||||
print(f"SPACETRACK: Attempting to fetch TLE data with username: {username}")
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=120.0,
|
||||
follow_redirects=True,
|
||||
headers={
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Accept": "application/json, text/html, */*",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
},
|
||||
) as client:
|
||||
# First, visit the main page to get any cookies
|
||||
await client.get(f"{self.site_root}/")
|
||||
|
||||
# Login to get session cookie
|
||||
login_response = await client.post(
|
||||
self.login_url,
|
||||
data={
|
||||
"identity": username,
|
||||
"password": password,
|
||||
},
|
||||
logger.info_event(
|
||||
"Space-Track TLE query response received",
|
||||
event="collector.spacetrack.query.response",
|
||||
context={"status_code": tle_response.status_code},
|
||||
)
|
||||
print(f"SPACETRACK: Login response status: {login_response.status_code}")
|
||||
print(f"SPACETRACK: Login response URL: {login_response.url}")
|
||||
print(f"SPACETRACK: Login response body: {login_response.text[:500]}")
|
||||
|
||||
if login_response.status_code != 200:
|
||||
print(f"SPACETRACK: Login failed, using sample data")
|
||||
return self._get_sample_data()
|
||||
|
||||
# Query for TLE data (get first 1000 satellites)
|
||||
tle_response = await client.get(self.query_url)
|
||||
print(f"SPACETRACK: TLE query status: {tle_response.status_code}")
|
||||
|
||||
if tle_response.status_code != 200:
|
||||
print(f"SPACETRACK: Query failed, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track TLE query failed; using sample data",
|
||||
event="collector.spacetrack.query.failed",
|
||||
context={"status_code": tle_response.status_code},
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
data = tle_response.json()
|
||||
print(f"SPACETRACK: Received {len(data)} records")
|
||||
logger.info_event(
|
||||
"Space-Track TLE fetch completed",
|
||||
event="collector.spacetrack.fetch.completed",
|
||||
context={"record_count": len(data)},
|
||||
)
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"SPACETRACK: Error - {e}, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track TLE fetch failed; using sample data",
|
||||
event="collector.spacetrack.fetch.failed",
|
||||
context={"error": str(e)},
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
def transform(self, raw_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
|
||||
@@ -45,7 +45,7 @@ DOCS_METADATA: tuple[DocsMetadata, ...] = (
|
||||
DocsMetadata("earth-bgp-context.md", "earth-bgp-context", "docs_developer", "Earth", 14, "BGP 态势上下文", "BGP Context"),
|
||||
DocsMetadata("earth-interactable-usage.md", "earth-interactable-usage", "docs_developer", "Earth", 16, "智能星球可交互图标接入", "Intelligent Planet Interactable Usage"),
|
||||
DocsMetadata("earth-interactable-clustering.md", "earth-interactable-clustering", "docs_developer", "Earth", 17, "智能星球可交互图标聚类策略", "Intelligent Planet Interactable Clustering"),
|
||||
DocsMetadata("earth-toolbar-overlay-coordination.md", "earth-toolbar-overlay-coordination", "docs_developer", "Earth", 17, "智能星球工具栏与浮层协同", "Intelligent Planet Toolbar and Overlay Coordination"),
|
||||
DocsMetadata("earth-toolbar-overlay-coordination.md", "earth-toolbar-overlay-coordination", "docs_developer", "Earth", 18, "智能星球工具栏与浮层协同", "Intelligent Planet Toolbar and Overlay Coordination"),
|
||||
DocsMetadata("earth-news-sources.md", "earth-news-sources", "docs_developer", "Earth", 19, "智能星球新闻源配置", "Intelligent Planet News Source Configuration"),
|
||||
DocsMetadata("frontend-admin-frontend-context.md", "frontend-admin-frontend-context", "docs_developer", "Frontend", 20, "控制台前端结构", "Admin Frontend Context"),
|
||||
DocsMetadata("frontend-layout-guidelines.md", "frontend-layout-guidelines", "docs_developer", "Frontend", 21, "前端布局指南", "Frontend Layout Guidelines"),
|
||||
@@ -56,7 +56,7 @@ DOCS_METADATA: tuple[DocsMetadata, ...] = (
|
||||
DocsMetadata("backend-datasources-api-performance.md", "backend-datasources-api-performance", "docs_developer", "Backend", 33, "数据源 API 性能", "Datasource API Performance"),
|
||||
DocsMetadata("data-job-earth-sync-architecture.md", "data-job-earth-sync-architecture", "docs_developer", "Backend", 34, "数据作业与 Outbox 技术架构", "Data Jobs and Outbox Architecture"),
|
||||
DocsMetadata("backend-enum-contracts.md", "backend-enum-contracts", "docs_developer", "Backend", 35, "后端枚举与字符串兼容契约", "Backend Enum and String Compatibility Contract"),
|
||||
DocsMetadata("location-pipeline-development.md", "location-pipeline-development", "docs_developer", "Backend", 36, "通用位置估算管线开发说明", "Shared Location Resolution Pipeline Development Guide"),
|
||||
DocsMetadata("location-pipeline-development.md", "location-pipeline-development", "docs_developer", "Backend", 35, "通用位置估算管线开发说明", "Shared Location Resolution Pipeline Development Guide"),
|
||||
DocsMetadata("earth-news-live-streams-collector-format.md", "earth-news-live-streams-collector-format", "docs_developer", "Backend", 36, "新闻直播采集格式", "News Live Streams Collector Format"),
|
||||
DocsMetadata("docs-gatekeeper-development.md", "docs-gatekeeper-development", "docs_developer", "Backend", 37, "Docs Gatekeeper 开发说明", "Docs Gatekeeper Development Guide"),
|
||||
DocsMetadata("agents-aiprovider.md", "agents-aiprovider", "docs_developer", "Agents", 40, "AI Provider 指南", "AI Provider Guide"),
|
||||
|
||||
@@ -2307,7 +2307,10 @@ def _diversify_news_items_for_locale(
|
||||
buckets: dict[str, list[ParsedNewsItem]] = {}
|
||||
order: list[str] = []
|
||||
for item in ranked:
|
||||
key = _news_item_source_id(item) or item.source or item.feed_name or item.id
|
||||
if active_region == "global":
|
||||
key = item.feed_region or "global"
|
||||
else:
|
||||
key = _news_item_source_id(item) or item.source or item.feed_name or item.id
|
||||
if key not in buckets:
|
||||
buckets[key] = []
|
||||
order.append(key)
|
||||
@@ -2751,6 +2754,7 @@ async def get_earth_news_payload(
|
||||
)
|
||||
await record_earth_news_sources_health(db, health_by_source)
|
||||
ranked_fetched_items = _rank_and_trim_items(fetched_items, active_region=active_region)
|
||||
await _enqueue_unverified_locations(ranked_fetched_items)
|
||||
await upsert_earth_news_items(db, ranked_fetched_items)
|
||||
|
||||
items = await _call_store_list_items(
|
||||
@@ -2802,7 +2806,8 @@ async def get_earth_news_payload(
|
||||
)
|
||||
else:
|
||||
cruise_items = items
|
||||
await _enqueue_unverified_locations(items)
|
||||
enqueue_candidates = {item.id: item for item in [*items, *cruise_items] if item.id}
|
||||
await _enqueue_unverified_locations(list(enqueue_candidates.values()))
|
||||
stale = bool(errors and items)
|
||||
|
||||
return _build_payload(
|
||||
|
||||
@@ -14,10 +14,14 @@ from app.core.logging import get_logger
|
||||
logger = get_logger(__name__, service="earth_news")
|
||||
|
||||
TARGET_LOCATION_STREAM = "earth_news:target_location:jobs"
|
||||
TARGET_LOCATION_PRIORITY_STREAM = "earth_news:target_location:priority"
|
||||
TARGET_LOCATION_GROUP = "earth_news_target_location"
|
||||
TARGET_LOCATION_DEAD_LETTER_STREAM = "earth_news:target_location:dead"
|
||||
TARGET_LOCATION_RESULT_TTL_SECONDS = 60 * 60 * 12
|
||||
TARGET_LOCATION_JOB_DEDUP_TTL_SECONDS = 60 * 60 * 6
|
||||
TARGET_LOCATION_PRIORITY_JOB_DEDUP_TTL_SECONDS = 60 * 5
|
||||
TARGET_LOCATION_PENDING_RECLAIM_IDLE_MS = 2 * 60 * 1000
|
||||
TARGET_LOCATION_PRIORITY_READ_BLOCK_MS = 1
|
||||
TARGET_LOCATION_MAX_ATTEMPTS = 3
|
||||
|
||||
_redis_client: redis.Redis | None = None
|
||||
@@ -28,6 +32,7 @@ class NewsTargetLocationMessage:
|
||||
message_id: str
|
||||
item_id: str
|
||||
payload: dict[str, Any]
|
||||
stream_name: str = TARGET_LOCATION_STREAM
|
||||
attempts: int = 0
|
||||
|
||||
|
||||
@@ -44,7 +49,7 @@ class NewsTargetLocationQueue(Protocol):
|
||||
) -> list[NewsTargetLocationMessage]:
|
||||
...
|
||||
|
||||
async def ack(self, message_id: str) -> None:
|
||||
async def ack(self, message: NewsTargetLocationMessage) -> None:
|
||||
...
|
||||
|
||||
async def retry_or_dead_letter(
|
||||
@@ -71,6 +76,10 @@ def _queued_key(item_id: str) -> str:
|
||||
return f"earth_news:target_location:queued:{item_id}"
|
||||
|
||||
|
||||
def _priority_queued_key(item_id: str) -> str:
|
||||
return f"earth_news:target_location:priority_queued:{item_id}"
|
||||
|
||||
|
||||
class RedisStreamsNewsTargetLocationQueue:
|
||||
def __init__(self, client: redis.Redis | None = None) -> None:
|
||||
self.client = client or _get_redis_client()
|
||||
@@ -79,34 +88,44 @@ class RedisStreamsNewsTargetLocationQueue:
|
||||
async def _ensure_group(self) -> None:
|
||||
if self._group_ready:
|
||||
return
|
||||
try:
|
||||
await self.client.xgroup_create(
|
||||
TARGET_LOCATION_STREAM,
|
||||
TARGET_LOCATION_GROUP,
|
||||
id="0",
|
||||
mkstream=True,
|
||||
)
|
||||
except ResponseError as exc:
|
||||
if "BUSYGROUP" not in str(exc):
|
||||
raise
|
||||
for stream_name in (TARGET_LOCATION_PRIORITY_STREAM, TARGET_LOCATION_STREAM):
|
||||
try:
|
||||
await self.client.xgroup_create(
|
||||
stream_name,
|
||||
TARGET_LOCATION_GROUP,
|
||||
id="0",
|
||||
mkstream=True,
|
||||
)
|
||||
except ResponseError as exc:
|
||||
if "BUSYGROUP" not in str(exc):
|
||||
raise
|
||||
self._group_ready = True
|
||||
|
||||
async def enqueue(self, *, item_id: str, payload: dict[str, Any], force: bool = False) -> bool:
|
||||
await self._ensure_group()
|
||||
if force:
|
||||
await self.client.delete(_result_key(item_id), _queued_key(item_id))
|
||||
await self.client.delete(_result_key(item_id))
|
||||
queued_key = _priority_queued_key(item_id)
|
||||
elif await self.client.exists(_result_key(item_id)):
|
||||
return False
|
||||
else:
|
||||
queued_key = _queued_key(item_id)
|
||||
dedup_ttl = (
|
||||
TARGET_LOCATION_PRIORITY_JOB_DEDUP_TTL_SECONDS
|
||||
if force
|
||||
else TARGET_LOCATION_JOB_DEDUP_TTL_SECONDS
|
||||
)
|
||||
queued = await self.client.set(
|
||||
_queued_key(item_id),
|
||||
queued_key,
|
||||
"1",
|
||||
nx=True,
|
||||
ex=TARGET_LOCATION_JOB_DEDUP_TTL_SECONDS,
|
||||
ex=dedup_ttl,
|
||||
)
|
||||
if not queued:
|
||||
return bool(await self.client.exists(_queued_key(item_id)))
|
||||
return bool(await self.client.exists(queued_key))
|
||||
stream_name = TARGET_LOCATION_PRIORITY_STREAM if force else TARGET_LOCATION_STREAM
|
||||
await self.client.xadd(
|
||||
TARGET_LOCATION_STREAM,
|
||||
stream_name,
|
||||
{
|
||||
"item_id": item_id,
|
||||
"attempts": "0",
|
||||
@@ -123,39 +142,104 @@ class RedisStreamsNewsTargetLocationQueue:
|
||||
block_ms: int,
|
||||
) -> list[NewsTargetLocationMessage]:
|
||||
await self._ensure_group()
|
||||
streams = await self.client.xreadgroup(
|
||||
streams = []
|
||||
priority_claimed = await self._claim_stale_messages(
|
||||
stream_name=TARGET_LOCATION_PRIORITY_STREAM,
|
||||
consumer_name=consumer_name,
|
||||
count=count,
|
||||
)
|
||||
if priority_claimed:
|
||||
return priority_claimed
|
||||
|
||||
priority_messages = await self.client.xreadgroup(
|
||||
TARGET_LOCATION_GROUP,
|
||||
consumer_name,
|
||||
{TARGET_LOCATION_STREAM: ">"},
|
||||
{TARGET_LOCATION_PRIORITY_STREAM: ">"},
|
||||
count=count,
|
||||
block=block_ms,
|
||||
block=TARGET_LOCATION_PRIORITY_READ_BLOCK_MS,
|
||||
)
|
||||
if priority_messages:
|
||||
streams = priority_messages
|
||||
else:
|
||||
regular_claimed = await self._claim_stale_messages(
|
||||
stream_name=TARGET_LOCATION_STREAM,
|
||||
consumer_name=consumer_name,
|
||||
count=count,
|
||||
)
|
||||
if regular_claimed:
|
||||
return regular_claimed
|
||||
streams = await self.client.xreadgroup(
|
||||
TARGET_LOCATION_GROUP,
|
||||
consumer_name,
|
||||
{TARGET_LOCATION_STREAM: ">"},
|
||||
count=count,
|
||||
block=block_ms,
|
||||
)
|
||||
messages: list[NewsTargetLocationMessage] = []
|
||||
for _stream_name, stream_messages in streams:
|
||||
for stream_name, stream_messages in streams:
|
||||
for message_id, fields in stream_messages:
|
||||
raw_payload = fields.get("payload")
|
||||
item_id = fields.get("item_id")
|
||||
if not raw_payload or not item_id:
|
||||
await self.ack(message_id)
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(raw_payload)
|
||||
except json.JSONDecodeError:
|
||||
await self.ack(message_id)
|
||||
continue
|
||||
attempts = int(fields.get("attempts") or 0)
|
||||
messages.append(
|
||||
NewsTargetLocationMessage(
|
||||
message_id=message_id,
|
||||
item_id=item_id,
|
||||
payload=payload,
|
||||
attempts=attempts,
|
||||
)
|
||||
)
|
||||
message = await self._message_from_fields(stream_name, message_id, fields)
|
||||
if message is not None:
|
||||
messages.append(message)
|
||||
return messages
|
||||
|
||||
async def ack(self, message_id: str) -> None:
|
||||
await self.client.xack(TARGET_LOCATION_STREAM, TARGET_LOCATION_GROUP, message_id)
|
||||
async def _claim_stale_messages(
|
||||
self,
|
||||
*,
|
||||
stream_name: str,
|
||||
consumer_name: str,
|
||||
count: int,
|
||||
) -> list[NewsTargetLocationMessage]:
|
||||
try:
|
||||
_next_id, claimed, _deleted = await self.client.xautoclaim(
|
||||
stream_name,
|
||||
TARGET_LOCATION_GROUP,
|
||||
consumer_name,
|
||||
TARGET_LOCATION_PENDING_RECLAIM_IDLE_MS,
|
||||
start_id="0-0",
|
||||
count=count,
|
||||
)
|
||||
except ResponseError:
|
||||
return []
|
||||
messages: list[NewsTargetLocationMessage] = []
|
||||
for message_id, fields in claimed:
|
||||
message = await self._message_from_fields(stream_name, message_id, fields)
|
||||
if message is not None:
|
||||
messages.append(message)
|
||||
return messages
|
||||
|
||||
async def _message_from_fields(
|
||||
self,
|
||||
stream_name: str,
|
||||
message_id: str,
|
||||
fields: dict[str, str],
|
||||
) -> NewsTargetLocationMessage | None:
|
||||
raw_payload = fields.get("payload")
|
||||
item_id = fields.get("item_id")
|
||||
if not raw_payload or not item_id:
|
||||
await self._discard_message(stream_name, message_id)
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(raw_payload)
|
||||
except json.JSONDecodeError:
|
||||
await self._discard_message(stream_name, message_id)
|
||||
return None
|
||||
attempts = int(fields.get("attempts") or 0)
|
||||
return NewsTargetLocationMessage(
|
||||
message_id=message_id,
|
||||
item_id=item_id,
|
||||
payload=payload,
|
||||
stream_name=stream_name,
|
||||
attempts=attempts,
|
||||
)
|
||||
|
||||
async def ack(self, message: NewsTargetLocationMessage) -> None:
|
||||
await self.client.xack(message.stream_name, TARGET_LOCATION_GROUP, message.message_id)
|
||||
await self.client.xdel(message.stream_name, message.message_id)
|
||||
|
||||
async def _discard_message(self, stream_name: str, message_id: str) -> None:
|
||||
await self.client.xack(stream_name, TARGET_LOCATION_GROUP, message_id)
|
||||
await self.client.xdel(stream_name, message_id)
|
||||
|
||||
async def retry_or_dead_letter(
|
||||
self,
|
||||
@@ -163,7 +247,7 @@ class RedisStreamsNewsTargetLocationQueue:
|
||||
*,
|
||||
error: str,
|
||||
) -> None:
|
||||
await self.ack(message.message_id)
|
||||
await self.ack(message)
|
||||
if message.attempts + 1 >= TARGET_LOCATION_MAX_ATTEMPTS:
|
||||
await self.client.xadd(
|
||||
TARGET_LOCATION_DEAD_LETTER_STREAM,
|
||||
@@ -176,7 +260,7 @@ class RedisStreamsNewsTargetLocationQueue:
|
||||
)
|
||||
return
|
||||
await self.client.xadd(
|
||||
TARGET_LOCATION_STREAM,
|
||||
message.stream_name,
|
||||
{
|
||||
"item_id": message.item_id,
|
||||
"attempts": str(message.attempts + 1),
|
||||
@@ -231,4 +315,4 @@ async def save_target_location_patch(item_id: str, patch: dict[str, Any]) -> Non
|
||||
TARGET_LOCATION_RESULT_TTL_SECONDS,
|
||||
json.dumps(patch, ensure_ascii=False),
|
||||
)
|
||||
await client.delete(_queued_key(item_id))
|
||||
await client.delete(_queued_key(item_id), _priority_queued_key(item_id))
|
||||
@@ -19,6 +19,17 @@ from app.services.earth_news_classification import (
|
||||
normalize_breaking_scope,
|
||||
)
|
||||
|
||||
CRUISE_REGION_ORDER = (
|
||||
"americas",
|
||||
"europe",
|
||||
"middle-east-africa",
|
||||
"asia-pacific",
|
||||
"global",
|
||||
)
|
||||
CRUISE_REGION_QUERY_MULTIPLIER = 12
|
||||
CRUISE_REGION_QUERY_MIN_LIMIT = 240
|
||||
CRUISE_REGION_QUERY_MAX_LIMIT = 1000
|
||||
|
||||
|
||||
def _coerce_datetime(value: datetime | None) -> datetime | None:
|
||||
if value is None:
|
||||
@@ -106,6 +117,41 @@ def _sort_parsed_news_items(items: list[ParsedNewsItem], *, active_region: str)
|
||||
)
|
||||
|
||||
|
||||
def _diversify_parsed_news_items_by_region(
|
||||
items: list[ParsedNewsItem],
|
||||
*,
|
||||
limit: int,
|
||||
) -> list[ParsedNewsItem]:
|
||||
if limit <= 0:
|
||||
return []
|
||||
sorted_items = _sort_parsed_news_items(items, active_region="global")
|
||||
buckets: dict[str, list[ParsedNewsItem]] = {}
|
||||
for item in sorted_items:
|
||||
region = item.feed_region or "global"
|
||||
buckets.setdefault(region, []).append(item)
|
||||
|
||||
ordered_regions = [
|
||||
*[region for region in CRUISE_REGION_ORDER if buckets.get(region)],
|
||||
*sorted(region for region in buckets if region not in CRUISE_REGION_ORDER),
|
||||
]
|
||||
diversified: list[ParsedNewsItem] = []
|
||||
cursor = 0
|
||||
while len(diversified) < limit:
|
||||
added = False
|
||||
for region in ordered_regions:
|
||||
bucket = buckets.get(region) or []
|
||||
if cursor >= len(bucket):
|
||||
continue
|
||||
diversified.append(bucket[cursor])
|
||||
added = True
|
||||
if len(diversified) >= limit:
|
||||
break
|
||||
if not added:
|
||||
break
|
||||
cursor += 1
|
||||
return diversified
|
||||
|
||||
|
||||
def _query_sort_key(active_region: str):
|
||||
if active_region == "global":
|
||||
return (
|
||||
@@ -167,6 +213,8 @@ async def list_earth_news_items(
|
||||
[record_to_parsed_news_item(record) for record in records],
|
||||
active_region=active_region,
|
||||
)
|
||||
if active_region == "global" and not source_ids:
|
||||
return _diversify_parsed_news_items_by_region(items, limit=limit)
|
||||
return items[:limit]
|
||||
|
||||
|
||||
@@ -177,15 +225,20 @@ async def list_earth_news_cruise_items(
|
||||
categories: set[str] | None = None,
|
||||
source_ids: set[str] | None = None,
|
||||
) -> list[ParsedNewsItem]:
|
||||
query_limit = min(
|
||||
max(limit * CRUISE_REGION_QUERY_MULTIPLIER, CRUISE_REGION_QUERY_MIN_LIMIT),
|
||||
CRUISE_REGION_QUERY_MAX_LIMIT,
|
||||
)
|
||||
query = (
|
||||
select(EarthNewsItem)
|
||||
.order_by(
|
||||
EarthNewsItem.region.asc(),
|
||||
EarthNewsItem.published_at.is_(None),
|
||||
EarthNewsItem.published_at.desc().nullslast(),
|
||||
EarthNewsItem.last_seen_at.desc(),
|
||||
EarthNewsItem.region.asc(),
|
||||
EarthNewsItem.feed_name.asc(),
|
||||
)
|
||||
.limit(min(max(limit * 4, limit), 200))
|
||||
.limit(query_limit)
|
||||
)
|
||||
category_clause = _category_filter_clause(categories)
|
||||
if category_clause is not None:
|
||||
@@ -194,11 +247,10 @@ async def list_earth_news_cruise_items(
|
||||
if source_clause is not None:
|
||||
query = query.where(source_clause)
|
||||
result = await db.execute(query)
|
||||
items = _sort_parsed_news_items(
|
||||
return _diversify_parsed_news_items_by_region(
|
||||
[record_to_parsed_news_item(record) for record in result.scalars().all()],
|
||||
active_region="global",
|
||||
limit=limit,
|
||||
)
|
||||
return items[:limit]
|
||||
|
||||
|
||||
async def get_earth_news_freshness(
|
||||
|
||||
@@ -29,6 +29,9 @@ logger = get_logger(__name__, service="earth_news")
|
||||
WORKER_BATCH_SIZE = 4
|
||||
WORKER_BLOCK_MS = 5000
|
||||
WORKER_BACKOFF_SECONDS = 5.0
|
||||
WORKER_JOB_TIMEOUT_MIN_SECONDS = 20.0
|
||||
WORKER_JOB_TIMEOUT_MAX_SECONDS = 90.0
|
||||
WORKER_JOB_TIMEOUT_GRACE_SECONDS = 10.0
|
||||
|
||||
_worker_task: asyncio.Task | None = None
|
||||
|
||||
@@ -109,12 +112,25 @@ async def _run_target_location_worker() -> None:
|
||||
if not messages:
|
||||
continue
|
||||
provider_client = await _build_provider_client()
|
||||
for message in messages:
|
||||
job_timeout = _get_worker_job_timeout(provider_client)
|
||||
|
||||
async def handle_message(message: NewsTargetLocationMessage) -> None:
|
||||
try:
|
||||
await process_target_location_message(message, provider_client=provider_client)
|
||||
await queue.ack(message.message_id)
|
||||
await asyncio.wait_for(
|
||||
process_target_location_message(message, provider_client=provider_client),
|
||||
timeout=job_timeout,
|
||||
)
|
||||
await queue.ack(message)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except TimeoutError as exc:
|
||||
logger.warning_event(
|
||||
"Earth news target location worker job timed out",
|
||||
event="earth_news.target_location.worker_job_timeout",
|
||||
context={"item_id": message.item_id, "timeout_seconds": job_timeout},
|
||||
)
|
||||
with suppress(Exception):
|
||||
await queue.retry_or_dead_letter(message, error=str(exc) or "job timed out")
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Earth news target location worker job failed",
|
||||
@@ -124,6 +140,8 @@ async def _run_target_location_worker() -> None:
|
||||
with suppress(Exception):
|
||||
await queue.retry_or_dead_letter(message, error=str(exc))
|
||||
|
||||
await asyncio.gather(*(handle_message(message) for message in messages))
|
||||
|
||||
|
||||
def start_earth_news_target_worker() -> None:
|
||||
global _worker_task
|
||||
@@ -140,3 +158,15 @@ async def stop_earth_news_target_worker() -> None:
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
_worker_task = None
|
||||
|
||||
|
||||
def _get_worker_job_timeout(provider_client: AIProviderClient | None) -> float:
|
||||
timeout = float(getattr(provider_client, "timeout", 0) or WORKER_JOB_TIMEOUT_MIN_SECONDS)
|
||||
retry_attempts = float(getattr(provider_client, "retry_attempts", 1) or 1)
|
||||
return min(
|
||||
max(
|
||||
timeout * retry_attempts + WORKER_JOB_TIMEOUT_GRACE_SECONDS,
|
||||
WORKER_JOB_TIMEOUT_MIN_SECONDS,
|
||||
),
|
||||
WORKER_JOB_TIMEOUT_MAX_SECONDS,
|
||||
)
|
||||
@@ -24,6 +24,7 @@ from app.services.earth_news import (
|
||||
from app.services.earth_news_queue import NewsTargetLocationMessage
|
||||
from app.services.earth_news_worker import process_target_location_message
|
||||
from app.services.collectors.media_news_archive import MediaNewsArchiveCollector
|
||||
from app.services.earth_news_store import _diversify_parsed_news_items_by_region
|
||||
|
||||
|
||||
def test_serialize_item_includes_region_anchor_for_cruise():
|
||||
@@ -172,6 +173,68 @@ def test_diversify_news_items_prefers_display_ready_content_across_sources():
|
||||
assert [item.id.split(":", 1)[0] for item in result] == ["source-b", "source-c", "source-a"]
|
||||
|
||||
|
||||
def test_cruise_news_diversity_keeps_regions_from_being_starved():
|
||||
published_at = datetime(2026, 6, 26, 8, 0, tzinfo=UTC)
|
||||
|
||||
def make_item(region: str, index: int) -> ParsedNewsItem:
|
||||
return ParsedNewsItem(
|
||||
id=f"{region}:{index}",
|
||||
title=f"{region} story {index}",
|
||||
summary=f"{region} summary {index}",
|
||||
url=f"https://example.com/{region}/{index}",
|
||||
source=region,
|
||||
feed_name=region,
|
||||
feed_region=region,
|
||||
homepage_url="https://example.com",
|
||||
published_at=published_at - timedelta(minutes=index),
|
||||
)
|
||||
|
||||
items = [
|
||||
*[make_item("asia-pacific", index) for index in range(40)],
|
||||
make_item("europe", 1),
|
||||
make_item("middle-east-africa", 1),
|
||||
make_item("americas", 1),
|
||||
make_item("global", 1),
|
||||
]
|
||||
|
||||
result = _diversify_parsed_news_items_by_region(items, limit=8)
|
||||
regions = [item.feed_region for item in result]
|
||||
|
||||
assert "europe" in regions
|
||||
assert "middle-east-africa" in regions
|
||||
assert "americas" in regions
|
||||
assert regions.count("asia-pacific") < len(regions)
|
||||
|
||||
|
||||
def test_global_news_diversity_uses_same_region_balance():
|
||||
published_at = datetime(2026, 6, 26, 8, 0, tzinfo=UTC)
|
||||
|
||||
def make_item(region: str, index: int) -> ParsedNewsItem:
|
||||
return ParsedNewsItem(
|
||||
id=f"{region}:global:{index}",
|
||||
title=f"{region} story {index}",
|
||||
summary=f"{region} summary {index}",
|
||||
url=f"https://example.com/{region}/global/{index}",
|
||||
source=region,
|
||||
feed_name=region,
|
||||
feed_region=region,
|
||||
homepage_url="https://example.com",
|
||||
published_at=published_at - timedelta(minutes=index),
|
||||
)
|
||||
|
||||
items = [
|
||||
*[make_item("asia-pacific", index) for index in range(24)],
|
||||
*[make_item("europe", index) for index in range(2)],
|
||||
*[make_item("middle-east-africa", index) for index in range(2)],
|
||||
*[make_item("americas", index) for index in range(2)],
|
||||
]
|
||||
|
||||
result = _diversify_parsed_news_items_by_region(items, limit=6)
|
||||
regions = {item.feed_region for item in result}
|
||||
|
||||
assert {"europe", "middle-east-africa", "americas"}.issubset(regions)
|
||||
|
||||
|
||||
def test_serialize_item_falls_back_to_global_anchor():
|
||||
item = ParsedNewsItem(
|
||||
id="custom:test",
|
||||
|
||||
@@ -8,6 +8,42 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [0.72.0] — 2026-06-29
|
||||
|
||||
Released: 2026-06-29
|
||||
|
||||
### Highlights
|
||||
- 将 agent 入口收敛到单一 `AGENTS.md`,并让 harness 明确阻止小写入口再次分叉。
|
||||
- 新增完整本地 harness 验证层,覆盖 backend/frontend/docs/security 静态规则、前端 build 和 Playwright 路由/交互 smoke。
|
||||
- 扩展 Earth News 与控制台 smoke,确保新闻源测试、新增取消、手动新闻组创建、桌面/移动菜单和 zoom 布局都在发布前验证。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 `scripts/harness/*` 规则检查、doctor、validate 和前端 smoke 脚本,并将未跟踪 harness 设施纳入发布。
|
||||
- 清理 SpaceTrack 与 PeeringDB collector 的 stdout/debug 输出,改用结构化日志并移除 SpaceTrack 不可达重复 fetch 路径。
|
||||
- 强化控制台布局、auth 表单、Docs 页面、Earth shell 和 Earth toolbar 的响应式与无障碍细节。
|
||||
- 同步 README、CODEMAP、HARNESS、harness audit、用户手册、快速开始和开发者文档,明确当前 Web Earth / React admin / FastAPI / aiprovider 边界。
|
||||
- 将 backend、frontend、docs 和 Earth News 检查纳入 `scripts/harness/quick-check.sh` 与 `scripts/harness/validate.sh` 的稳定验证面。
|
||||
|
||||
---
|
||||
|
||||
## [0.71.1] — 2026-06-26
|
||||
|
||||
Released: 2026-06-26
|
||||
|
||||
### Highlights
|
||||
- 修复 Earth 欧洲、美洲、中东与非洲等区域新闻被亚太来源和旧来源过滤饿死的问题,滚动条、面板和巡航重新回到同一批区域 payload。
|
||||
- 将当前可见新闻和巡航新闻提升到目标位置/翻译优先队列,避免历史普通 Redis backlog 阻塞用户正在看的新闻精修。
|
||||
- 新增 agent harness 入口、代码地图、验证脚本与双语技术说明,让后续维护能按现有 uv/Bun/Gitea 工作流检查而不替代项目规则。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- EarthFeed 在全局和巡航队列中按区域轮转候选新闻,保留区域视图的“当前区域 + global”规则,并补充回归测试。
|
||||
- `news.js` 按区域、类型、来源和数量隔离并发刷新请求,丢弃旧区域响应;跨区域时不再复用旧来源筛选。
|
||||
- 新闻展示在中文本地化未完成时回退原始标题和摘要,避免出现有内容却显示“新闻汉化中”的卡片。
|
||||
- 新闻目标位置 worker 新增优先 stream、pending reclaim、任务超时和并发处理;无效消息会确认并删除,减少队列堆积。
|
||||
- 补充 Earth 新闻源、Earth 前端结构、harness 和版本历史文档,并移除控制台 auth store 的调试日志。
|
||||
|
||||
---
|
||||
|
||||
## [0.71.0] — 2026-06-11
|
||||
|
||||
Released: 2026-06-11
|
||||
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
# Agent Harness
|
||||
|
||||
This harness improves discoverability, repeatability, and agent safety for the
|
||||
existing Planet project. It does not replace current project rules, scripts, CI,
|
||||
or release workflows.
|
||||
|
||||
## Authority And Conflicts
|
||||
|
||||
Existing project rules are authoritative:
|
||||
|
||||
1. `rules.md`
|
||||
2. `AGENTS.md`
|
||||
3. Current implementation docs under `docs/technical/`
|
||||
4. Existing scripts, especially `planet.sh`
|
||||
5. Existing Gitea workflow files under `.gitea/workflows/`
|
||||
|
||||
When harness guidance conflicts with any of the above, keep the existing rule,
|
||||
do not overwrite the existing workflow, and add a compatibility note here or in
|
||||
`docs/harness-audit.md`.
|
||||
|
||||
For frontend or documentation audits, also read the Rules Coverage Evidence
|
||||
section in `docs/harness-audit.md`. It maps `rules.md` clauses to the current
|
||||
static checks, Playwright smoke coverage, and remaining manual review areas, so
|
||||
an agent can distinguish a proved harness pass from a rule that still needs
|
||||
human-quality inspection.
|
||||
|
||||
## Starting Work
|
||||
|
||||
Recommended startup flow:
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
scripts/harness/doctor.sh
|
||||
```
|
||||
|
||||
Then read only the relevant implementation docs:
|
||||
|
||||
- Backend/API/data work: `docs/technical/zh/backend-*.md` and matching English
|
||||
docs when public docs are affected.
|
||||
- Frontend/admin work: `docs/technical/zh/frontend-admin-frontend-context.md`.
|
||||
- Earth work: `docs/technical/zh/earth-frontend-context.md`,
|
||||
`docs/technical/zh/earth-render-layer-order.md`, and style docs when visual
|
||||
semantics change.
|
||||
- Operations work: `docs/technical/zh/ops-runbook.md` and
|
||||
`docs/technical/zh/ops-planet-sh-startup.md`.
|
||||
- AI Provider work: `docs/technical/zh/agents-aiprovider.md`.
|
||||
- Documentation work: `docs/documentation-coverage-rules.md`.
|
||||
|
||||
Use focused inspection commands before broad reads:
|
||||
|
||||
```bash
|
||||
rg -n "<symbol-or-term>" <path>
|
||||
git diff --stat HEAD
|
||||
git diff --name-only HEAD
|
||||
git diff --unified=0 HEAD -- <path>
|
||||
```
|
||||
|
||||
## Existing Commands
|
||||
|
||||
| Purpose | Command |
|
||||
| --- | --- |
|
||||
| First setup | `./planet.sh init` |
|
||||
| Start local stack | `./planet.sh start` |
|
||||
| Start with LAN access | `./planet.sh start --allow-lan` |
|
||||
| Restart all services | `./planet.sh restart` |
|
||||
| Restart one area | `./planet.sh restart -b`, `-f`, `-a`, or `-d` |
|
||||
| Health check | `./planet.sh health` |
|
||||
| Logs | `./planet.sh log`, `./planet.sh log -b`, `-f`, `-a`, or `-m` |
|
||||
| Create local user | `./planet.sh createuser` |
|
||||
| Destructive local reset | `./planet.sh destroy` |
|
||||
| Backend smoke tests | `cd backend && uv run --frozen --group dev --project .. python -m pytest -s tests/test_api.py tests/test_realtime_sources.py -q` |
|
||||
| Frontend build | `cd frontend && bun install --frozen-lockfile && bun run build` |
|
||||
| Mock AIS WebSocket | `bun run mock:ais-ws` |
|
||||
|
||||
## Harness Commands
|
||||
|
||||
| Tier | Command | What It Does |
|
||||
| --- | --- | --- |
|
||||
| Doctor | `scripts/harness/doctor.sh` | Checks required files, required tools, optional delivery tools, and forbidden frontend lockfiles. |
|
||||
| Security | `scripts/harness/security-check.sh` | Checks that environment/private-key files are not tracked and scans for high-confidence committed secret tokens. |
|
||||
| Backend Rules | `scripts/harness/backend-rules-check.sh` | Checks backend app Python for direct `print()`, `breakpoint()`, and `pdb.set_trace()` debug calls so service code uses structured logging. |
|
||||
| Frontend Rules | `scripts/harness/frontend-rules-check.sh` | Checks Bun-only scripts, admin route manifest coherence, literal internal route links, admin search route targets, frontend debug output, native button safety, icon-button accessibility, no nested Cards, no AntD/Space layout primitives, ConnectionTestInput usage, admin/docs shell height-chain sizing, viewport-scaled font sizes, zero letter spacing, and high-signal UI rule warnings. |
|
||||
| Docs Consistency | `scripts/harness/docs-consistency-check.sh` | Checks frontend Docs metadata against backend Gatekeeper metadata, public Docs registration, full technical-doc bilingual file pairs, public doc links, readable link titles, language-scoped technical links, README/project-context admin stack drift, supported credential collector contracts, manual console route coverage against the actual admin manifest, documented UI route drift, documented `?section=` deep-link validity against the actual admin section config in technical docs and active plan docs, and the harness rules-coverage notes. |
|
||||
| Quick | `scripts/harness/quick-check.sh` | Runs doctor, whitespace diff check, shell syntax checks, security scan, backend/frontend/doc consistency checks, and CI backend smoke tests. |
|
||||
| Full | `scripts/harness/validate.sh` | Runs quick check, frontend Bun install/build, Playwright route smoke, optional Helm checks, and opt-in Docker image smoke builds. |
|
||||
|
||||
Docker image smoke builds are expensive and are off by default:
|
||||
|
||||
```bash
|
||||
PLANET_HARNESS_DOCKER_SMOKE=1 scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
Frontend Playwright smoke runs by default in full validation after the frontend
|
||||
build. It starts a local Vite preview and checks the `/` to Earth redirect,
|
||||
public pages, unknown-route login fallback, protected admin route login
|
||||
fallback, authenticated unknown-route fallback to `/admin`, Docs loading with
|
||||
mocked API content, Docs detail page
|
||||
language/theme/search interactions, every Docs catalog slug exposed by the
|
||||
frontend/backend metadata, the Earth iframe entry point, login error handling,
|
||||
register + email verification, password reset, standalone email verification,
|
||||
and authenticated `super_admin` rendering for every admin route plus core
|
||||
`section` deep links derived from the actual admin route and section config.
|
||||
Authenticated admin
|
||||
checks run at desktop size, mobile size, and 125% / 150% zoom; desktop and
|
||||
mobile passes also fail on global horizontal overflow so table/detail panels
|
||||
must keep overflow ownership inside their own scroll regions. The smoke also
|
||||
derives the sidebar menu from the actual admin route manifest and clicks every
|
||||
visible `super_admin` menu entry on both desktop and mobile viewports, then
|
||||
exercises safe interaction paths for admin search, section tabs, the AI settings
|
||||
shortcut, logs view switching, user dialog opening, and data distribution toggles.
|
||||
It also exercises Earth News source testing, add/cancel source draft behavior,
|
||||
and manual news group creation against mocked `/earth/news-*` APIs.
|
||||
Documented AI and collector
|
||||
deep links such as `/ai?section=integrations`, `/ai?section=playground`, and
|
||||
`/collection-management?section=collector_credentials` are part of the rendered
|
||||
smoke surface:
|
||||
|
||||
```bash
|
||||
PLANET_HARNESS_FRONTEND_SMOKE=0 scripts/harness/validate.sh
|
||||
PLANET_HARNESS_FRONTEND_SMOKE_PORT=4174 scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
## Environment Requirements
|
||||
|
||||
Required for normal development:
|
||||
|
||||
- `zsh` for `planet.sh`
|
||||
- `uv` for Python dependency and test execution
|
||||
- `bun` for frontend dependency and build execution
|
||||
- Python resolved by `uv` from the root `pyproject.toml`
|
||||
|
||||
Harness command lookup first checks the current non-interactive `PATH`. If a
|
||||
required tool is not visible there, `scripts/harness/lib.sh` asks the user's
|
||||
login interactive shell (`$SHELL`, then `zsh`, then `bash`) for the command
|
||||
path. This avoids hardcoding a dotfile while still covering agent environments
|
||||
that do not inherit the user's normal shell setup.
|
||||
|
||||
Required for full local stack operation:
|
||||
|
||||
- Docker and Docker Compose
|
||||
- PostgreSQL and Redis containers started by `planet.sh`
|
||||
|
||||
Optional for delivery smoke:
|
||||
|
||||
- Docker daemon for image builds
|
||||
- Helm for chart lint/template checks
|
||||
|
||||
If a required local tool is missing, do not install system software
|
||||
automatically. Report the gap and point to `./planet.sh init` or
|
||||
`scripts/bootstrap-dev.sh` as the existing bootstrap path.
|
||||
|
||||
## What Agents Must Not Change Automatically
|
||||
|
||||
- Do not replace Bun with npm, pnpm, or yarn.
|
||||
- Do not migrate CI from `.gitea/workflows/` to `.github/workflows/`.
|
||||
- Do not rewrite `planet.sh` lifecycle behavior as a parallel script.
|
||||
- Do not run `./planet.sh destroy` unless explicitly requested.
|
||||
- Do not commit `.env`, secrets, private keys, logs, or generated build output.
|
||||
- Do not add external integrations, hooks, or new dependency managers just to
|
||||
satisfy harness structure.
|
||||
- Do not publish internal harness docs into the product Docs UI unless a
|
||||
maintainer explicitly asks for it.
|
||||
|
||||
## Hooks And Reminders
|
||||
|
||||
No automatic hooks are installed in this phase. Manual reminders:
|
||||
|
||||
- Run `scripts/harness/quick-check.sh` before handing off small changes.
|
||||
- Run `scripts/harness/validate.sh` before larger cross-subsystem changes.
|
||||
- Run `scripts/harness/security-check.sh` after touching config, auth,
|
||||
credentials, docs examples, or generated fixtures.
|
||||
- Run `scripts/harness/backend-rules-check.sh` after backend service edits to
|
||||
catch direct stdout/debugger calls before they reach runtime logs.
|
||||
- Run `scripts/harness/frontend-rules-check.sh` after frontend edits to expose
|
||||
route, package-manager, debug-output, and UI rule warnings.
|
||||
- Run `scripts/harness/docs-consistency-check.sh` after docs edits or feature
|
||||
route changes.
|
||||
- Add focused tests before modifying backend service behavior or frontend
|
||||
workflows.
|
||||
- For docs changes, run the checks listed in
|
||||
`docs/documentation-coverage-rules.md`.
|
||||
|
||||
## Reusable Workflows
|
||||
|
||||
### Feature Work
|
||||
|
||||
1. Read `rules.md` modules for the touched area.
|
||||
2. Check `CODEMAP.md` for entry points and ownership boundaries.
|
||||
3. Inspect existing tests and docs before editing.
|
||||
4. Make the smallest behavior-preserving or feature-scoped change.
|
||||
5. Run `scripts/harness/quick-check.sh` or a narrower documented command.
|
||||
6. Update relevant docs when behavior, workflow, or operations change.
|
||||
7. For rendered frontend changes, verify the affected route with Playwright or
|
||||
the full harness smoke, because `bun run build` alone does not prove page
|
||||
usability.
|
||||
|
||||
### Bug Fix
|
||||
|
||||
1. Reproduce with a focused test or command.
|
||||
2. Patch the owning module, not a caller-side workaround.
|
||||
3. Run the focused regression test.
|
||||
4. Run `scripts/harness/quick-check.sh` when the change is safe to validate
|
||||
locally.
|
||||
|
||||
### Documentation Change
|
||||
|
||||
1. Read `docs/documentation-coverage-rules.md`.
|
||||
2. Route docs by audience: UI users, operations, or second-party developers.
|
||||
3. Keep Chinese and English technical docs paired by filename; public Docs also
|
||||
need matching frontend/backend metadata when exposed in the product Docs UI.
|
||||
4. Run the repository-specific docs checks that match the changed files.
|
||||
|
||||
### Release Or Delivery Change
|
||||
|
||||
Use the existing release skill/workflow and `.gitea/workflows/` files. Harness
|
||||
validation can smoke-check Helm and Docker locally, but it must not replace the
|
||||
release process.
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
- `docs/harness-audit.md` records the discovery pass that led to this harness.
|
||||
- `AGENTS.md` is the single authoritative agent guide. The older lowercase
|
||||
`agents.md` entry has been merged into it and should remain absent.
|
||||
- `CODEMAP.md` is intentionally high level; deeper subsystem docs stay in
|
||||
`docs/technical/{zh,en}/`.
|
||||
- `scripts/harness/frontend-smoke.mjs` is a lightweight route/section smoke
|
||||
with mocked API data. It proves route shells, auth guards, and primary admin
|
||||
sections render, but it is not a replacement for feature-specific browser QA
|
||||
against a real backend.
|
||||
- Frontend smoke prints phase-level progress by default. Use
|
||||
`PLANET_FRONTEND_SMOKE_PROGRESS=verbose` to print each route/menu/doc item
|
||||
when diagnosing a slow or failing smoke run, or set it to `0` to suppress
|
||||
progress lines.
|
||||
@@ -0,0 +1,154 @@
|
||||
# Harness Audit
|
||||
|
||||
Last audited: 2026-06-26
|
||||
|
||||
This audit records the repository state used to add the agent harness. It is a
|
||||
compatibility note, not a replacement for existing rules or architecture docs.
|
||||
|
||||
## Existing Commands
|
||||
|
||||
| Area | Existing Command | Notes |
|
||||
| --- | --- | --- |
|
||||
| Bootstrap | `./planet.sh init` | Syncs uv/Bun dependencies, creates missing env files, starts data services, seeds defaults. |
|
||||
| Start | `./planet.sh start` | Starts backend, frontend, AI Provider, PostgreSQL/Redis, and Motion Agent when available. |
|
||||
| LAN start | `./planet.sh start --allow-lan` | Opens frontend/backend/AI Provider ports and requests Windows firewall/port cleanup when needed. |
|
||||
| Restart | `./planet.sh restart` | Supports scoped restart flags for backend, frontend, AI Provider, database, and Motion Agent. |
|
||||
| Health | `./planet.sh health` | Checks containers, backend `/health`, AI Provider `/health`, frontend, and Motion Agent state. |
|
||||
| Logs | `./planet.sh log` | Supports backend, frontend, AI Provider, and Motion Agent log views. |
|
||||
| User fallback | `./planet.sh createuser` | Interactive emergency/local account creation. |
|
||||
| Destructive reset | `./planet.sh destroy` | Requires confirmation and removes Planet-owned Docker/build/runtime state. Not a validation command. |
|
||||
| Backend CI smoke | `cd backend && uv run --frozen --group dev --project .. python -m pytest -s tests/test_api.py tests/test_realtime_sources.py -q` | Mirrors `.gitea/workflows/ci.yaml`. |
|
||||
| Frontend build | `cd frontend && bun install --frozen-lockfile && bun run build` | Bun-only workflow. |
|
||||
| Root helper | `bun run mock:ais-ws` | Runs `scripts/mock-ais-ws-server.ts` from the root package. |
|
||||
|
||||
## Existing Agent Instructions
|
||||
|
||||
| File | Status | Notes |
|
||||
| --- | --- | --- |
|
||||
| `AGENTS.md` | Present | Single authoritative agent behavior guide. It references `rules.md`, `project_context.md`, harness validation, and high-risk areas. |
|
||||
| `rules.md` | Present | Mandatory modular rules. Always load `core`, `security`, and `workflow`; load topic modules as needed. |
|
||||
| `project_context.md` | Present | Static context. Some roadmap-era stack details are older than the current README/docs. |
|
||||
| `.claude/commands/*.md` | Present | Existing command docs for cleanup, docs, goal-driven, and release workflows. |
|
||||
| `.codex/skills/*.md` | Present | Existing local skills for cleanup, docs, goal-driven, and release. |
|
||||
|
||||
## Existing CI Gates
|
||||
|
||||
The repository uses `.gitea/workflows/`, not `.github/workflows/`.
|
||||
|
||||
| Workflow | Gate |
|
||||
| --- | --- |
|
||||
| `.gitea/workflows/ci.yaml` | Backend smoke tests, frontend Bun build, Docker build smoke, Helm lint/template. |
|
||||
| `.gitea/workflows/release.yaml` | Builds and pushes frontend, backend, and AI Provider images on main/tag/manual release events. |
|
||||
| `.gitea/workflows/deploy-staging.yaml` | Deploys Helm release to staging and runs curl smoke tests inside the cluster. |
|
||||
|
||||
## Existing Docs And Architecture Maps
|
||||
|
||||
| Area | Docs |
|
||||
| --- | --- |
|
||||
| Current architecture and startup | `README.md` |
|
||||
| Technical docs index | `docs/technical/zh/README.md`, `docs/technical/en/README.md` |
|
||||
| Documentation rules | `docs/documentation-coverage-rules.md` |
|
||||
| Operations | `docs/technical/zh/ops-runbook.md`, `docs/technical/en/ops-runbook.md` |
|
||||
| Startup internals | `docs/technical/zh/ops-planet-sh-startup.md`, `docs/technical/en/ops-planet-sh-startup.md` |
|
||||
| AI Provider | `docs/technical/zh/agents-aiprovider.md`, `docs/technical/en/agents-aiprovider.md` |
|
||||
| Frontend admin | `docs/technical/zh/frontend-admin-frontend-context.md`, `docs/technical/en/frontend-admin-frontend-context.md` |
|
||||
| Earth rendering | `docs/technical/zh/earth-frontend-context.md`, `docs/technical/zh/earth-render-layer-order.md`, `docs/technical/zh/earth-layer-style-reference.md` |
|
||||
| Plans and history | `docs/plans/README.md`, `docs/deprecated/README.md` |
|
||||
|
||||
## Release And Deploy Process
|
||||
|
||||
- Release workflow is documented in `.codex/skills/release/SKILL.md` and
|
||||
`.claude/commands/release.md`.
|
||||
- Version-bearing files include `VERSION`, `frontend/package.json`,
|
||||
`pyproject.toml`, `uv.lock`, `docs/CHANGELOG.md`, and
|
||||
`docs/version-history.md`.
|
||||
- Delivery automation lives in `.gitea/workflows/release.yaml` and
|
||||
`.gitea/workflows/deploy-staging.yaml`.
|
||||
- Helm chart entry point is `deploy/helm/planet/Chart.yaml`.
|
||||
|
||||
## Missing Or Unclear Areas
|
||||
|
||||
- The older lowercase `agents.md` entry has been merged into uppercase
|
||||
`AGENTS.md` so coding agents and harness tools use one source of truth.
|
||||
- `project_context.md` originally included older roadmap assumptions such as
|
||||
Celery, Kafka, TimescaleDB, MinIO, and UE5 as active stack elements. The
|
||||
harness pass updated it to separate active stack facts from future directions;
|
||||
current code and technical docs still remain authoritative when details drift.
|
||||
- No safe automatic hook system was already configured. This phase documents
|
||||
manual reminders instead of adding hooks.
|
||||
- `.github/workflows/` is absent by design; CI is under `.gitea/workflows/`.
|
||||
|
||||
## Conflicts And Preserved Rules
|
||||
|
||||
| Conflict Or Tension | Resolution |
|
||||
| --- | --- |
|
||||
| Prompt suggested `AGENTS.md`; repository already had `agents.md`. | Merged the lowercase guide into uppercase `AGENTS.md`; harness doctor now requires `AGENTS.md` and keeps `agents.md` absent to prevent split authority. |
|
||||
| Harness validation could duplicate CI. | Added wrapper scripts that call existing commands and mirror current CI gates where practical. |
|
||||
| Full Docker smoke builds are expensive locally. | Kept them opt-in with `PLANET_HARNESS_DOCKER_SMOKE=1`. |
|
||||
| Internal harness docs could clutter public Docs UI. | Kept `docs/HARNESS.md` and `docs/harness-audit.md` as repository docs, not product Docs entries. |
|
||||
| Existing frontend toolchain is Bun-only. | Harness scripts and docs use Bun only and flag npm/pnpm/yarn lockfiles as failures. |
|
||||
| Agents often miss user-installed Bun or uv in non-interactive shells. | Added `scripts/harness/lib.sh` to resolve tools from current `PATH` first and then the user's login interactive shell without hardcoding a dotfile. |
|
||||
| Always-loaded security rules had no standalone harness gate. | Added `scripts/harness/security-check.sh` to block tracked `.env` / key files and scan for high-confidence committed private keys or provider tokens; quick-check now runs it. |
|
||||
| Build success does not prove frontend page usability. | Added static frontend rules/doc checks and a Playwright route smoke for public pages, protected admin fallback, Docs loading and detail interactions, Earth iframe entry, login/register/verification/password-reset interactions, authenticated admin route/section rendering with mocked API data across desktop, mobile, and 125% / 150% zoom, plus manifest-derived desktop/mobile menu navigation and safe search/tab/dialog/Earth News interactions. |
|
||||
| Route fallback behavior can regress even when every named page renders. | Extended the frontend smoke to verify `/` redirects to Earth, unauthenticated unknown routes show the login page, and authenticated unknown routes navigate back to `/admin`. |
|
||||
| Frontend smoke route lists can drift from `AdminRoutes` and resource-page sections. | Updated the smoke to derive protected route checks and authenticated section deep-link checks from `AdminRoutes.tsx` and `PlainResourcePages.tsx`, including redirect-only `/alerts`. |
|
||||
| Docs smoke mocks can drift from the product Docs catalog. | Updated the frontend smoke to derive mocked Docs catalog/content from `frontend/src/pages/Docs/docs-content.ts` plus backend Gatekeeper access metadata, then open every Chinese Docs catalog slug. |
|
||||
| User manuals can miss a real console menu entry after route changes. | Added a docs consistency check that compares the manual console overview tables with `frontend/src/admin/routes/manifest.tsx`; fixed the missing `/docs` row in both user manuals. |
|
||||
| Rendered pages can still contain broken internal shortcuts. | Added literal internal route-link checks and an interaction smoke for the AI settings shortcut; this caught and fixed a stale `/admin/settings` link that should point to `/settings`. |
|
||||
| Global search entries can drift because their route targets live in data objects rather than JSX links. | Added a frontend rules check that validates every admin search `routePath` against the actual frontend route set. |
|
||||
| Responsive styling fixes can satisfy one viewport by breaking the no-viewport-font rule. | Added a frontend rules failure for `font-size` values that use viewport or container query width units, and replaced public auth shell `vw` font sizing with fixed desktop/mobile sizes. |
|
||||
| Typography polish can accidentally reintroduce squeezed non-zero letter spacing. | Normalized active frontend `letter-spacing` values to `0` and made the frontend rules check fail non-zero `letter-spacing` / `letterSpacing` declarations, with only inherit/default-zero forms allowed. |
|
||||
| Native buttons can accidentally submit forms or keep controls clickable while loading after a props-spread reorder. | Added a frontend rules failure for TSX `<button>` elements without explicit `type` and for buttons whose `disabled` state can be overridden by a later props spread; fixed the data distribution buttons and auth button disabled ordering. |
|
||||
| Admin/docs shell layouts can reintroduce brittle viewport sizing after a responsive fix. | Changed the admin and Docs route shells to use the existing `html/body/#root` 100% height chain, and added a frontend rules failure for exact `100vh` / `100vw` shell sizing in those CSS files. |
|
||||
| Compact workspaces can drift back into card-in-card layouts or implicit AntD `Space` wrappers. | Added frontend rules failures for nested `Card` components, AntD imports, and `<Space>` layout primitives in active frontend source. |
|
||||
| Connection-test controls can drift back into detached toolbar buttons. | Added a shared `ConnectionTestInput` suffix pattern for AI Provider and WebSearch Base URL fields, disabled WebSearch configuration/test controls when the tool is off, and made the frontend rules check fail detached AI/WebSearch connection-test buttons. |
|
||||
| Public docs can reference stale admin section URLs. | Added docs consistency validation for documented `?section=` links and rendered smoke coverage for documented AI / collector deep links. |
|
||||
| Active plan docs can preserve old admin deep-link assumptions after the technical docs are corrected. | Extended docs consistency checks to active `docs/plans/*.md` files for stale admin tab-query terms and actual `?section=` validity; corrected the docs audience split plan to current section routes. |
|
||||
| Top-level README can drift from the actual frontend stack while technical docs stay current. | Updated README from Ant Design Pro to Tactile UI / Radix primitives / lucide-react and added README stale admin-stack terms to docs consistency checks. |
|
||||
| Agent background context can reintroduce inactive stack assumptions. | Updated `project_context.md` and the root agent guide to label current stack facts versus future directions, then added exact stale-stack patterns for them to docs consistency checks. |
|
||||
| Docs `?section=` validation can drift if the harness owns its own route/section table. | Changed the docs consistency check to derive section keys from `AdminRoutes.tsx` and `PlainResourcePages.tsx` resource configs before validating documented deep links. |
|
||||
| Public Docs can drift between frontend catalog metadata and backend Gatekeeper authorization metadata. | Added a docs consistency check that compares filename, slug, group, order, and bilingual titles across both metadata sources; aligned existing order drift for toolbar overlay and location pipeline docs. |
|
||||
| Non-public technical docs can silently become Chinese-only or English-only. | Added a full `docs/technical/{zh,en}` filename-pair check so every technical Markdown file has a same-named counterpart before docs consistency passes. |
|
||||
| Credentialed collector docs can drift from backend support wiring. | Added docs consistency validation for every built-in collector marked `requires_credentials=true` and `credential_status=supported`: it must have a provider, default credential guide, supported connectivity provider, frontend credential UI/guidance, a regression test, and zh/en connectivity documentation. |
|
||||
| Backend collectors can leak debug output or credential-adjacent context through stdout. | Replaced SpaceTrack and PeeringDB collector `print()` calls with structured logger events, removed unreachable duplicate SpaceTrack fetch code, and added `scripts/harness/backend-rules-check.sh` to block future backend app `print()`, `breakpoint()`, or `pdb.set_trace()` calls. |
|
||||
|
||||
## Rules Coverage Evidence
|
||||
|
||||
This matrix records how the current harness checks the `rules.md` modules that
|
||||
matter for this frontend and documentation pass. "Automated" means the listed
|
||||
command fails when the rule regresses. "Smoke" means the rendered product route
|
||||
or interaction is opened with Playwright. "Manual" means the rule is still a
|
||||
judgment call and must be inspected during review.
|
||||
|
||||
| `rules.md` Area | Rule Surface | Harness Evidence | Remaining Review |
|
||||
| --- | --- | --- | --- |
|
||||
| `core` | Remove stale transitional paths, duplicated helpers, and naming drift after large changes. | `scripts/harness/docs-consistency-check.sh` blocks known stale stack terms, old `?tab=` links, public Docs metadata drift, and README/project context drift. `scripts/harness/frontend-rules-check.sh` blocks repeated detached AI/WebSearch connection-test buttons by requiring `ConnectionTestInput`. | Naming quality, function size, and whether a new abstraction is worth keeping remain manual review items. |
|
||||
| `core` | Keep one source of truth for route, Docs, and section state. | Frontend route, admin manifest, admin search targets, Docs catalog metadata, backend Gatekeeper metadata, manual route tables, and documented `?section=` links are all parsed from source and compared by `frontend-rules-check.sh`, `docs-consistency-check.sh`, and `frontend-smoke.mjs`. | Business-state ownership inside feature components still needs focused review when behavior changes. |
|
||||
| `security` | Do not commit secrets, tracked env files, private keys, or exposed tokens. | `scripts/harness/security-check.sh` fails on tracked `.env` / private-key files and high-confidence provider tokens. `backend-rules-check.sh` blocks backend stdout/debugger calls, and `frontend-rules-check.sh` fails frontend console output that includes token material. | Whether a newly added setting should be masked or stored server-side still requires feature-specific review. |
|
||||
| `workflow` | Frontend package management must stay Bun-only. | `scripts/harness/doctor.sh` and `frontend-rules-check.sh` fail forbidden frontend lockfiles and `npm` / `pnpm` / `yarn` script usage. `validate.sh` uses Bun for install, build, preview, and smoke. | New dependency legitimacy and maintenance quality are manual unless a dependency is actually added. |
|
||||
| `workflow` | Agents should find `bun` and `uv` even when non-interactive `PATH` is incomplete. | `scripts/harness/lib.sh` checks the current `PATH`, then asks `$SHELL`, `zsh`, and `bash` login interactive shells for the command path without hardcoding a dotfile. `doctor.sh`, `quick-check.sh`, and `validate.sh` all source it. | System package installation remains outside harness scope and should be reported instead of auto-fixed. |
|
||||
| `docs` | Keep public Docs whitelist-driven and synchronized with backend authorization metadata. | `docs-consistency-check.sh` compares frontend Docs metadata against backend Gatekeeper metadata, verifies files exist for both languages, checks public link titles, and blocks missing zh/en technical doc pairs. `frontend-smoke.mjs` opens every Chinese Docs catalog slug plus detail/search/language/theme interactions. | Quality of prose, examples, and whether a doc should be public are still editorial review items. |
|
||||
| `docs` | User manuals must match real console routes and deep links. | `docs-consistency-check.sh` compares manual console tables with `frontend/src/admin/routes/manifest.tsx` and validates documented `?section=` links from actual `AdminRoutes.tsx` plus `PlainResourcePages.tsx` section config. | Screenshots and UI-copy nuance are not exhaustively validated. |
|
||||
| `uiux` | Admin pages are compact single-screen workspaces with explicit overflow ownership. | `frontend-rules-check.sh` warns on suspicious `overflow: hidden`, blocks exact `100vh` / `100vw` shell sizing in admin/Docs CSS, and `frontend-smoke.mjs` checks every admin route at desktop, mobile, and 125% / 150% zoom. Desktop/mobile smoke also fails global horizontal overflow. | Visual density, hierarchy, and whether a scroll owner feels ergonomic remain manual QA. |
|
||||
| `uiux` | Controls use expected patterns and accessible icon buttons. | `frontend-rules-check.sh` blocks icon `Button` without `aria-label` and `title`, native `<button>` without explicit `type`, nested Cards, AntD imports, `<Space>`, and detached connection-test buttons. Smoke exercises search, tabs, dialogs, data toggles, and connection-test actions. | Native buttons with visible text are not treated as icon-only by static checks; semantics still need review when adding custom controls. |
|
||||
| `uiux` | Text should fit, avoid viewport-scaled font sizes, and keep letter spacing at zero. | `frontend-rules-check.sh` fails viewport/container-width font-size units and non-zero `letter-spacing` / `letterSpacing`. `frontend-smoke.mjs` checks rendered routes for global overflow across desktop/mobile. | Per-element text clipping without page-level overflow is not exhaustively detected and needs visual review for changed screens. |
|
||||
| `frontend` | Keep shared behavior in reusable components and existing project patterns. | `frontend-rules-check.sh` enforces shared `ConnectionTestInput`, route/link/search consistency, no debug output, native button safety, Tactile/Radix/lucide direction instead of AntD/Space, and whitelist-driven public Docs. `bun x tsc --noEmit` and `bun run build` verify TypeScript/build health. | Broad casts, inline styles, and overflow issues are warnings when context may be legitimate; review changed lines before accepting them. |
|
||||
| `frontend` | Responsive adaptations must preserve the primary action path. | `frontend-smoke.mjs` clicks every visible admin menu entry on desktop and mobile, opens protected routes unauthenticated and authenticated, verifies root/unknown route fallback, and exercises core auth flows. | Deep feature workflows beyond smoke data, such as destructive or long-running actions, require targeted tests before behavior changes. |
|
||||
| `earth` | Earth render work needs real rendering checks. | Full smoke opens `/earth` and verifies the `3D Earth` iframe entry point. Earth News settings routes are included through the admin manifest/menu smoke, mocked `/earth/news-*` API responses, source test, add/cancel source draft, and manual news group creation checks. The broader Earth-specific layer/depth rules remain in `rules.md` and Earth docs. | The harness still does not claim full 3D layer visual verification; layer-depth and picking changes need targeted browser/canvas QA. |
|
||||
|
||||
## Harness Files Added
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| `AGENTS.md` | Single authoritative agent guide and coding-agent entry point. |
|
||||
| `docs/HARNESS.md` | Harness workflow, validation tiers, conflict policy, and manual reminders. |
|
||||
| `CODEMAP.md` | High-level codebase map and validation references. |
|
||||
| `scripts/harness/lib.sh` | Shared command lookup and run helpers. |
|
||||
| `scripts/harness/doctor.sh` | Environment and repository-shape check. |
|
||||
| `scripts/harness/security-check.sh` | High-confidence secret and tracked environment/key file check. |
|
||||
| `scripts/harness/backend-rules-check.sh` | Backend app debug-call guard for direct stdout/debugger usage. |
|
||||
| `scripts/harness/frontend-rules-check.sh` | Bun-only, route manifest, literal internal link, admin-search route target, debug-output, native-button safety, icon-button accessibility, Card nesting, AntD/Space avoidance, ConnectionTestInput, admin/docs shell viewport sizing, viewport-font, zero-letter-spacing, and UI rules static check. |
|
||||
| `scripts/harness/docs-consistency-check.sh` | Frontend/backend Docs metadata alignment, public Docs metadata, full technical-doc bilingual pair, link-title, language-scoped technical link, supported credential collector contracts, manual console route coverage, documented route, admin-config-derived section deep-link consistency, and harness rules-coverage note check. |
|
||||
| `scripts/harness/frontend-smoke.mjs` | Playwright route, Docs detail/language/theme/search interaction, public auth form interaction, desktop/mobile/zoom rendering, safe admin navigation/search/tab/dialog/Earth News interactions, and authenticated admin route/section smoke for the built frontend preview. |
|
||||
| `scripts/harness/quick-check.sh` | Fast deterministic local validation. |
|
||||
| `scripts/harness/validate.sh` | Full local validation wrapper with optional delivery smoke. |
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
**状态**:待实施
|
||||
**创建日期**:2026-05-12
|
||||
**校正日期**:2026-06-26,控制台深链已从旧 tab 查询口径更新为当前 `?section=` 口径。
|
||||
**核心目标**:把 `docs/technical/{zh,en}/manual.md` 拆成"纯客户视角"的使用手册,把 `planet.sh`、日志、LAN、故障排查这类运维内容迁到独立 `ops-runbook.md`,并把分层规则写进 `documentation-coverage-rules.md` 和 `.claude/commands/docs.md`,让以后写文档时自动按受众归档。
|
||||
|
||||
## 背景
|
||||
@@ -31,12 +32,12 @@
|
||||
3. **登录与找回密码** — 登录页、忘记密码流程
|
||||
4. **账户设置** — 修改密码、修改邮箱(需重新验证)、查看权限组、登出
|
||||
5. **Console 总览** — 左侧菜单结构、各路由用途
|
||||
6. **配置数据采集器** — `/collection-management?tab=collector_credentials`:选择 collector、连接测试、保存凭证;BarentsWatch / AISStream 两个典型例子
|
||||
7. **配置 AI 凭证** — `/ai?tab=providers`:默认 provider、模型、Base URL、API Key、本地代理;工具 tab(WebSearch、OCR)
|
||||
6. **配置数据采集器** — `/collection-management?section=collector_credentials`:选择 collector、连接测试、保存凭证;BarentsWatch / AISStream 两个典型例子
|
||||
7. **配置 AI 凭证** — `/ai?section=integrations`:默认 provider、模型、Base URL、API Key、本地代理;工具 section(WebSearch、OCR)位于 `/ai?section=tools`
|
||||
8. **系统设置** — `/settings` 其他子 tab(系统设置、电视直播源、SMTP 邮件)
|
||||
9. **用户管理(管理员)** — `/users`:创建、删除、改角色、Gatekeeper 权限组
|
||||
10. **数据探索** — `/datasources`、`/data`、`/bgp`、`/alerts/*`
|
||||
11. **AI 测试台** — `/ai?tab=playground`
|
||||
11. **AI 测试台** — `/ai?section=playground`
|
||||
12. **Earth 公开页面** — 现 manual.md 的 Earth 章节原样保留(图层、图例、搜索、位置候选、设置、视角、动捕、巡航、移动端)
|
||||
13. **Docs 文档站** — 当前 Docs 章节保留(权限组说明)
|
||||
|
||||
@@ -48,7 +49,7 @@
|
||||
|
||||
- 打开管理员给你的 URL
|
||||
- 注册账号 + 邮箱验证
|
||||
- 登录后第一次做什么(建议先到 `/collection-management?tab=collector_credentials` 配一个 collector,再到 `/ai` 配模型)
|
||||
- 登录后第一次做什么(建议先到 `/collection-management?section=collector_credentials` 配一个 collector,再到 `/ai?section=integrations` 配模型)
|
||||
- 看 Earth
|
||||
|
||||
部署/开发的 quickstart 内容并入 `ops-runbook.md` 的"首次部署"小节,**不**再单独出 `ops-quickstart.md`,避免新增维护点。
|
||||
|
||||
@@ -8,7 +8,7 @@ The console now separates the "data source catalog" from "collector configuratio
|
||||
- Lists all data sources, including built-in and custom sources.
|
||||
- Clicking a name only opens an information drawer.
|
||||
- Focuses on status, manual collection, and running collection tasks.
|
||||
- `/collection-management?tab=collector_credentials`
|
||||
- `/collection-management?section=collector_credentials`
|
||||
- Displays as "Collectors".
|
||||
- Owns endpoint, headers, base parameters, and credentials.
|
||||
- Every collector exposes a connection button for health checks.
|
||||
|
||||
@@ -77,6 +77,8 @@ Earth settings are now grouped by `data-settings-tab` and `data-settings-tab-pan
|
||||
|
||||
The news category selector in Display reuses the same chip-selector pattern as Cruise Modules. It only filters news categories for the current browser on the Earth frontend. It does not toggle layers, basemap, boundaries, TV, data points, BGP, vessels, satellites, or compute centers; those remain owned by the layer panel, media panel, and admin configuration. `controls.js` persists only `shared.newsCategoryFilters` and broadcasts `earth:news-category-filters-change`; `news.js` sends the selected categories to `/api/v1/news/earth-feed?categories=...&locale=zh-CN`, so Web and UE clients share the same backend category filtering path.
|
||||
|
||||
The news panel, ticker, and news cruise must consume `items` / `cruise_items` from the same `/api/v1/news/earth-feed` response instead of keeping separate regional caches. `news.js` builds a refresh request key from region, category, source, and limit; only concurrent requests with the same key reuse the promise, and stale responses from an older region are dropped by token. Source filtering is also region-scoped: when the user moves from Asia Pacific to Europe or another region, source IDs saved for the old region must not be appended to the next fetch. After the new payload arrives, the saved source list is intersected with the available `sources`; if the intersection is empty, the current region falls back to all available sources. This keeps the ticker, panel, and cruise cards aligned after region switches.
|
||||
|
||||
Shortcut configuration is a device-local preference owned by `controls.js`: read, capture, enable/disable, and reset all stay in the Earth frontend. It should not be written to backend user settings and should not affect other browsers. New shortcuts must provide a default key, display label, disabled/enabled state, and reset path instead of being hard-coded only in a keydown handler.
|
||||
|
||||
### 4. UI and Status Messages
|
||||
@@ -350,7 +352,7 @@ For future Earth changes:
|
||||
|
||||
The Earth frontend and the console frontend are not the same UI system:
|
||||
|
||||
- Console frontend: React + Ant Design workbench
|
||||
- Console frontend: React + Tactile UI / Radix primitives / lucide workbench
|
||||
- Earth frontend: native HUD + Three.js display under `public/earth`
|
||||
|
||||
Therefore:
|
||||
|
||||
@@ -160,6 +160,19 @@ When `sources` is omitted, the service layer prefers stories that already have d
|
||||
|
||||
Source testing only proves that a specific RSS/Atom/XML feed can be parsed. It does not mean those items have already been written to the news table or are visible in the current region/category view. Saving or resetting news sources increments the configuration version and clears cache; if an enabled feed has no recent stored items, the next `earth-feed` request supplements from RSS so newly enabled sources such as 36Kr and Ebrun are not masked by fresh Google News rows.
|
||||
|
||||
## Regional Balancing and Async Enrichment
|
||||
|
||||
`earth_news_items` is the current-state table for EarthFeed. When no explicit `sources` filter is present, the endpoint sorts by Breaking state, region, and publish time, then applies a regional round-robin so Asia Pacific or any other high-volume source cannot fill the entire global view and cruise queue. The default region order is Americas, Europe, Middle East / Africa, Asia Pacific, then Global; unknown regions participate after the known regions. Regional views still follow the active-region-plus-global rule and do not mix unrelated regions into the regional panel.
|
||||
|
||||
Both `items` and `cruise_items` are enqueued for target-location and localization enrichment, but the frontend must not wait for AI before rendering. If the requested display locale is not ready yet, Web Earth falls back to the original `title / summary` so a card does not show a "translation pending" placeholder when readable source content already exists. After translation, classification, Breaking, or target-location enrichment completes, the same `earth_news_items` row is updated and Earth receives a news reload / patch.
|
||||
|
||||
Target-location enrichment uses two Redis Streams queues:
|
||||
|
||||
- `earth_news:target_location:priority`: priority jobs for currently visible `items` and `cruise_items`, with a short dedupe TTL.
|
||||
- `earth_news:target_location:jobs`: normal background enrichment jobs, with a longer dedupe TTL.
|
||||
|
||||
The worker always drains the priority queue before the regular queue; stale pending messages are reclaimed after the idle threshold, each AI job has a hard timeout, and failures go through retry or dead-letter handling. This prevents a large historical regular backlog from starving the Europe, Americas, or other regional news currently visible to the user.
|
||||
|
||||
## Breaking News Insertion
|
||||
|
||||
The news system keeps three separate decisions:
|
||||
|
||||
@@ -155,7 +155,6 @@ Purpose:
|
||||
Current usage:
|
||||
|
||||
- Admin data sources, collected data, collection management, logs, alerts, and BGP pages
|
||||
- Old AntD legacy pages continue using shared scrolling behavior through compatibility wrappers
|
||||
|
||||
### 3. `TableScrollRegion`
|
||||
|
||||
@@ -275,17 +274,16 @@ File:
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- `/ai` now owns LLM Provider, AI Tool configuration, and the testbench instead of nesting them under `/settings`
|
||||
- The `模型供应商` tab manages default provider, model, base URL, provider key, local `aiprovider` proxy, and connection test; provider and model fields use editable comboboxes so users can manually enter new providers/models if the models.dev catalog stops updating
|
||||
- The `工具` tab first selects a tool from a dropdown menu, then renders that tool's configuration; it currently includes WebSearch and OCR
|
||||
- `/ai` now owns LLM Provider, AI Tool configuration, and Playground instead of nesting them under `/settings`
|
||||
- The `模型供应商` section manages default provider, model, base URL, provider key, local `aiprovider` proxy, and connection test; provider and model fields use editable comboboxes so users can manually enter new providers/models if the models.dev catalog stops updating
|
||||
- The `工具调用` section first selects a tool from a dropdown menu, then renders that tool's configuration; it currently includes WebSearch and OCR
|
||||
- WebSearch configuration includes provider, search key, base URL, timeout, result count, and advanced provider options
|
||||
- OCR configuration includes provider, Base URL, API key, model/engine, languages, timeout, file-size limit, and output format
|
||||
- The `测试台` tab embeds the former Playground real session, preset prompts, and AI Provider status debugging
|
||||
- The page reuses the Settings single-screen tabs, panel card, and internal scrolling style
|
||||
- The `Playground` section embeds the former Playground real session, preset prompts, and AI Provider status debugging
|
||||
- The page reuses the Settings single-screen section, panel card, and internal scrolling style
|
||||
- AI Provider and WebSearch connection tests use `ConnectionTestInput`, with the connector icon fixed at the end of the Base URL input; when WebSearch is disabled, every configuration field and the test entry point are greyed out except the switch
|
||||
|
||||
Legacy `/settings?tab=ai` should redirect to `/ai?tab=providers`.
|
||||
Legacy `/playground` should redirect to `/ai?tab=playground`.
|
||||
AI configuration no longer lives under `/settings`; `/playground` should redirect to `/ai?section=playground`.
|
||||
|
||||
### 3. Business Data Gateway
|
||||
|
||||
@@ -342,11 +340,11 @@ Current page boundary:
|
||||
- Endpoint, headers, and config are displayed here, not edited.
|
||||
- Credential-bearing collectors point users to `Collection Management -> Collectors`.
|
||||
|
||||
Keep this boundary: do not put custom datasource editing, built-in endpoint overrides, or credential forms back into `/datasources`. Those configuration entry points live at `/collection-management?tab=collector_credentials`.
|
||||
Keep this boundary: do not put custom datasource editing, built-in endpoint overrides, or credential forms back into `/datasources`. Those configuration entry points live at `/collection-management?section=collector_credentials`.
|
||||
|
||||
### Collectors Page
|
||||
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) has three route modes: `/settings` for System Settings, `/earth-content` for Earth Content, and `/collection-management` for Collection Management. The `collector_credentials` tab is shown as `Collectors` under `/collection-management`.
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) has three route modes: `/settings` for System Settings, `/earth-content` for Earth Content, and `/collection-management` for Collection Management. The `collector_credentials` section is shown as `Collectors` under `/collection-management`.
|
||||
|
||||
The `System Display` section under `/settings` includes the `Demo Mode` switch. When enabled, Earth OOBE ignores existing current collected data and the local `browse first` temporary skip state, then opens the initialization guide directly. This switch is only for demos and acceptance checks; it does not change datasources, collection queues, or Earth content resources.
|
||||
|
||||
@@ -391,6 +389,7 @@ These principles have been repeatedly validated in the project:
|
||||
4. Do not use `overflow: hidden` to mask structural issues
|
||||
5. Do not compress the main work area to make summary cards show completely
|
||||
6. Custom scrollbars must be floating overlays; they must not squeeze content width
|
||||
7. The Admin shell relies on the root `height: 100%` chain and should not use exact `100vh` sizing at the workspace root
|
||||
|
||||
For detailed experience, see:
|
||||
|
||||
@@ -411,7 +410,7 @@ Do not write local CSS patches first, then retrofit the structure.
|
||||
|
||||
The console frontend and the Earth frontend are not the same system:
|
||||
|
||||
- Console frontend: React + Ant Design workbench
|
||||
- Console frontend: React + Tactile UI / Radix primitives / lucide workbench
|
||||
- Earth frontend: independent native HUD system under `public/earth`
|
||||
|
||||
Therefore:
|
||||
|
||||
@@ -210,6 +210,11 @@ Inspection order:
|
||||
3. Does the real scroll node explicitly use `overflow: auto`?
|
||||
4. Have intermediate wrapper layers silently changed layout semantics?
|
||||
|
||||
The current Admin and Docs root shells rely on the `html` / `body` / `#root`
|
||||
`height: 100%` chain. Do not reintroduce exact `100vh` / `100vw` sizing on
|
||||
these embedded workspace shells; modals, overlays, and narrow-screen safety
|
||||
boundaries may still use `calc(100vh - ...)` as a maximum-size constraint.
|
||||
|
||||
### 5. UI State and Display State Out of Sync
|
||||
|
||||
Repeated in Earth-related changes:
|
||||
|
||||
+15
-14
@@ -22,7 +22,7 @@ URLs below use the local default `http://localhost:3000`. Replace the prefix wit
|
||||
1. Open `http://localhost:3000/login` and click "Register" under the form.
|
||||
2. On `/register`, fill in:
|
||||
- **Username**: 3–50 characters, used to log in
|
||||
- **Email**: receives the verification code; editable later in account settings
|
||||
- **Email**: receives the verification code; in the current version, ask an administrator to maintain email changes in user management
|
||||
- **Password**: at least 8 characters
|
||||
3. After submission you are taken to the verify page. A 6-digit code is sent to your email. It expires in 10 minutes.
|
||||
4. Enter the code and click "Verify and Sign In". On success the system stores a session and sends you to the console.
|
||||
@@ -52,23 +52,23 @@ If you see "Email not verified", the page automatically redirects to `/verify-em
|
||||
3. After receiving the code, enter it together with a new password (≥ 8 characters) and click "Reset Password".
|
||||
4. The system sends you back to `/login` — sign in with the new password.
|
||||
|
||||
## Account Settings
|
||||
## Account Area And Sign Out
|
||||
|
||||
Click your username at the top-right of the console to open account settings:
|
||||
The account area at the bottom of the console sidebar shows the current username, version, and theme control. The current version does not include a signed-in self-service account settings page:
|
||||
|
||||
- Change password: enter current password + new password
|
||||
- Change email: the system sends a verification code to the new address; the change applies only after verification
|
||||
- View Gatekeeper groups: lists current groups (`docs_user` / `docs_developer` / `docs_admin`)
|
||||
- Log out: clears the current session
|
||||
- Use `/forgot-password` for password reset through email verification
|
||||
- Administrators maintain email, role, and Gatekeeper groups at `/users`
|
||||
- The sign-out icon in the account area clears the current session and returns to the login page
|
||||
|
||||
## Console Overview
|
||||
|
||||
The console at `http://localhost:3000/admin` is built with React + Ant Design. The left menu is organized by work domain.
|
||||
The console at `http://localhost:3000/admin` is built with React plus Tactile UI / Radix primitives and lucide icons. The left menu is organized by work domain.
|
||||
|
||||
| Page | Route | Purpose |
|
||||
| --- | --- | --- |
|
||||
| Dashboard | `/admin` | System overview |
|
||||
| Earth | `/earth` | Open the public Earth page |
|
||||
| Docs | `/docs` | Open the docs site and show documents allowed by Gatekeeper permissions |
|
||||
| Datasources | `/datasources` | Source directory and collection triggers |
|
||||
| Collected Data | `/data` | Data already ingested |
|
||||
| BGP | `/bgp` | BGP situational view |
|
||||
@@ -86,7 +86,7 @@ Menu items hide automatically when you lack permission. If a menu is missing, ch
|
||||
|
||||
## Configure Data Collectors
|
||||
|
||||
`/collection-management?tab=collector_credentials` is the "Collectors" page. It manages connection configuration for every collector, not just credentials. Legacy `/settings?tab=collector_credentials` redirects here; the datasource directory remains at `/datasources`.
|
||||
`/collection-management?section=collector_credentials` is the "Collectors" page. It manages connection configuration for every collector, not just credentials; the datasource directory remains at `/datasources`.
|
||||
|
||||
Steps:
|
||||
|
||||
@@ -127,7 +127,7 @@ The default guide follows the BarentsWatch official tutorial and reminds you to
|
||||
|
||||
Steps:
|
||||
|
||||
1. Open `/collection-management?tab=collector_credentials` and select `AISStream Realtime Vessels : aisstream_vessels`
|
||||
1. Open `/collection-management?section=collector_credentials` and select `AISStream Realtime Vessels : aisstream_vessels`
|
||||
2. Fill the AISStream API Key
|
||||
3. Keep the default endpoint `wss://stream.aisstream.io/v0/stream`
|
||||
4. Click the plug icon to test; confirm it reports `Reachable`
|
||||
@@ -141,11 +141,12 @@ Steps:
|
||||
|
||||
## Configure AI Credentials
|
||||
|
||||
`/ai?tab=providers` is the AI management entry. Three key sub-tabs:
|
||||
`/ai?section=integrations` is the AI management entry. Key sections:
|
||||
|
||||
- `Model Providers`: default LLM provider, model, base URL, API key, local `aiprovider` proxy, connection test
|
||||
- `Tools`: a dropdown for specific tools — currently WebSearch and OCR
|
||||
- `Tool Calls`: a dropdown for specific tools — currently WebSearch and OCR
|
||||
- `Prompts`: a task dropdown for news localization, alert analysis, BGP briefs, and other LLM tasks. Operators can edit the prompt or reset it to the default
|
||||
- `Playground`: real session, preset request, and AI Provider status debugging
|
||||
|
||||
### Model Providers
|
||||
|
||||
@@ -170,7 +171,7 @@ The plug icon at the end of the Base URL input runs a connection test. A passing
|
||||
|
||||
After selecting a task, the page shows the effective prompt, whether it is customized, the shipped default version, and a reset button. Saving affects only that task. Reset restores the default prompt from the current release package. Business facts, context, and output schemas are still assembled by the backend for each task.
|
||||
|
||||
The legacy link `/settings?tab=ai` redirects to `/ai?tab=providers`.
|
||||
AI configuration no longer lives in System Settings; `/playground` redirects to `/ai?section=playground`.
|
||||
|
||||
## Datasources and Task Logs
|
||||
|
||||
@@ -245,7 +246,7 @@ To let a regular user read developer or operations docs, add `docs_developer` or
|
||||
|
||||
## AI Testbench
|
||||
|
||||
`/ai?tab=playground` is for real-pipeline debugging:
|
||||
`/ai?section=playground` is for real-pipeline debugging:
|
||||
|
||||
- Pick the active provider
|
||||
- Run preset requests or custom prompts
|
||||
|
||||
@@ -32,8 +32,8 @@ The default role is `viewer`: you can sign in but only see public pages. For col
|
||||
|
||||
After landing on the `/admin` dashboard, here's a recommended walk-through:
|
||||
|
||||
1. `/collection-management?tab=collector_credentials`: pick a collector and click the plug icon to test connectivity. Free collectors (e.g. open BGP) usually work right away; credential-bearing ones like `AISStream` or `BarentsWatch` need an API key / client secret first
|
||||
2. `/ai?tab=providers`: fill an LLM provider (e.g. `minimax` / `openai`), model, base URL, API key, and click the plug at the end of the base URL to test. WebSearch / OCR tools are optional
|
||||
1. `/collection-management?section=collector_credentials`: pick a collector and click the plug icon to test connectivity. Free collectors (e.g. open BGP) usually work right away; credential-bearing ones like `AISStream` or `BarentsWatch` need an API key / client secret first
|
||||
2. `/ai?section=integrations`: fill an LLM provider (e.g. `minimax` / `openai`), model, base URL, API key, and click the plug at the end of the base URL to test. WebSearch / OCR tools are optional
|
||||
3. `/datasources` or `/data`: check whether collectors have produced data. Use `/datasources -> Built-in Sources` for finite collectors: with no rows selected, click `Trigger All`; after selecting rows, the primary button becomes `Trigger Selected N`. The top-right queue button shows progress. Use `/datasources -> Realtime Sources` for AISStream / WebSocket health and counters
|
||||
4. `/alerts/system`: verify system alerts look right
|
||||
5. `/users` (super_admin only): open accounts for teammates or adjust their groups
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
- 展示所有数据源,包括内置和自定义。
|
||||
- 点击名称只打开信息抽屉。
|
||||
- 负责查看状态、触发采集和查看采集中任务。
|
||||
- `/collection-management?tab=collector_credentials`
|
||||
- `/collection-management?section=collector_credentials`
|
||||
- 显示为“采集器”。
|
||||
- 负责 endpoint、请求头、基础参数和凭证配置。
|
||||
- 所有采集器都提供连接按钮,用于健康检查。
|
||||
|
||||
@@ -77,6 +77,8 @@ Earth 设置面板现在按 `data-settings-tab` 和 `data-settings-tab-panel`
|
||||
|
||||
`显示` 分类里的新闻类型选择复用巡航模块的 chip 选择器形态,只控制星球端当前浏览器的新闻分类显示。它不会打开或关闭图层、底图、边界、TV、数据点、BGP、船舶、卫星或算力中心;这些仍由图层面板、媒体面板和控制台配置各自负责。`controls.js` 只持久化 `shared.newsCategoryFilters` 并广播 `earth:news-category-filters-change`,`news.js` 会把选中的类型拼到 `/api/v1/news/earth-feed?categories=...&locale=zh-CN`,让 Web 和 UE 走同一套后端类型过滤。
|
||||
|
||||
新闻面板、滚动条和新闻巡航必须消费同一次 `/api/v1/news/earth-feed` 响应里的 `items` / `cruise_items`,不能各自缓存区域状态。`news.js` 的刷新请求以区域、类型、来源和数量生成 request key;只有 key 相同的并发请求才复用 promise,旧区域请求返回时会被 token 丢弃。来源过滤也必须按区域作用域处理:当用户从亚太切到欧洲等其它区域时,旧区域保存的来源 ID 不允许继续拼到下一次 fetch 里;拿到新 payload 后再与 `sources` 列表做交集,若没有交集则回退到当前区域所有可用来源。这样滚动条、面板和巡航才会在区域切换后展示同一批新闻。
|
||||
|
||||
快捷键配置属于设备本地偏好,由 `controls.js` 负责读取、捕获、启用/禁用和重置。它不应写入后端用户设置,也不应影响其它浏览器。后续新增快捷键时,必须同时提供默认键、显示标签、可禁用状态和重置路径,避免只在 keydown handler 中硬编码。
|
||||
|
||||
### 4. UI 与状态消息
|
||||
|
||||
@@ -160,6 +160,19 @@ Web 星球端的新闻类型按钮只保存当前浏览器的显示偏好;偏
|
||||
|
||||
源测试只证明当前 RSS/Atom/XML 能解析到条目,不等于这些条目已经入库展示。展示链路还会检查区域、类型过滤和数据库新鲜度。保存或重置新闻源会递增配置版本并清理缓存;如果当前启用的 Feed 子项在库里没有近期条目,下一次 `earth-feed` 请求会补抓,避免新启用的 36氪、亿邦被旧 Google News 缓存挡住。
|
||||
|
||||
## 区域均衡与异步精修
|
||||
|
||||
`earth_news_items` 是 EarthFeed 的当前状态表。接口在没有显式 `sources` 过滤时会先按 Breaking、区域、发布时间排序,再做区域轮转,避免亚太或任一高频来源把全球视图和巡航队列全部占满。默认区域顺序是美洲、欧洲、中东与非洲、亚太、全球;未知区域只在已知区域之后参与轮转。区域视图仍遵守“当前区域 + global”的规则,不会把其它区域混进区域面板。
|
||||
|
||||
`items` 和 `cruise_items` 都会进入目标位置与本地化精修队列,但前端不能等 AI 完成后再展示。标题或摘要没有目标语言翻译时,Web Earth 先显示原始 `title / summary`,避免卡片出现“新闻汉化中”而实际内容已经可读。后台完成翻译、分类、Breaking 或目标坐标后,会更新同一条 `earth_news_items` 并通过 Earth news reload / patch 刷新前端。
|
||||
|
||||
目标位置队列使用 Redis Streams 两级队列:
|
||||
|
||||
- `earth_news:target_location:priority`:当前可见 `items` 与 `cruise_items` 的优先精修任务,短 TTL 去重。
|
||||
- `earth_news:target_location:jobs`:普通后台精修任务,长 TTL 去重。
|
||||
|
||||
Worker 总是先处理优先队列,再处理普通队列;pending 消息超过空闲阈值会被 reclaim,单条 AI 任务有超时保护,失败后进入重试或 dead letter。这样即使历史普通队列有大量 backlog,当前打开的欧洲、美洲等区域新闻也不会被长队列饿死。
|
||||
|
||||
## Breaking News 插队
|
||||
|
||||
新闻体系里有三套互不替代的判断:
|
||||
|
||||
@@ -274,17 +274,16 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
职责:
|
||||
|
||||
- `/ai` 独立承载 LLM Provider、AI Tool 配置和测试台,不再放在 `/settings` 的系统配置 tabs 中
|
||||
- `模型供应商` tab 管理默认 provider、模型、base URL、provider key、本地 `aiprovider` 代理和连接测试;provider 和模型输入使用可输入组合框,models.dev 目录停更时用户仍可手动填新 provider/model
|
||||
- `工具` tab 先通过下拉菜单选择工具,再管理对应配置;当前包含 WebSearch 和 OCR
|
||||
- `/ai` 独立承载 LLM Provider、AI Tool 配置和 Playground,不再放在 `/settings` 的系统配置分区中
|
||||
- `模型供应商` 分区管理默认 provider、模型、base URL、provider key、本地 `aiprovider` 代理和连接测试;provider 和模型输入使用可输入组合框,models.dev 目录停更时用户仍可手动填新 provider/model
|
||||
- `工具调用` 分区先通过下拉菜单选择工具,再管理对应配置;当前包含 WebSearch 和 OCR
|
||||
- WebSearch 配置包含 provider、搜索 key、base URL、超时、结果数和高级 provider 参数
|
||||
- OCR 配置包含 provider、Base URL、API Key、模型/engine、语言、超时、文件大小上限和输出格式
|
||||
- `测试台` tab 嵌入原 Playground 的真实会话、预设请求和 AI Provider 状态调试
|
||||
- 页面复用 Settings 的单屏 tabs、panel card 和内部滚动样式
|
||||
- `Playground` 分区嵌入原 Playground 的真实会话、预设请求和 AI Provider 状态调试
|
||||
- 页面复用 Settings 的单屏分区、panel card 和内部滚动样式
|
||||
- AI Provider / WebSearch 的连接测试使用 `ConnectionTestInput`,连接器图标固定在 Base URL 输入框末端;WebSearch 未启用时,除开关外的配置项和测试入口都置灰
|
||||
|
||||
旧的 `/settings?tab=ai` 应跳转到 `/ai?tab=providers`。
|
||||
旧的 `/playground` 应跳转到 `/ai?tab=playground`。
|
||||
AI 配置不再挂在 `/settings` 下;`/playground` 应跳转到 `/ai?section=playground`。
|
||||
|
||||
### 3. 业务数据网关
|
||||
|
||||
@@ -342,7 +341,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
- endpoint、headers、config 只展示,不在这里编辑。
|
||||
- 需要凭证的采集器提示用户到“采集管理 -> 采集器”维护。
|
||||
|
||||
这个边界很重要:后续不要把自定义数据源编辑、内置 endpoint 覆盖或凭证表单再塞回 `/datasources`。这些配置入口统一放在 `/collection-management?tab=collector_credentials`。
|
||||
这个边界很重要:后续不要把自定义数据源编辑、内置 endpoint 覆盖或凭证表单再塞回 `/datasources`。这些配置入口统一放在 `/collection-management?section=collector_credentials`。
|
||||
|
||||
页面顶部的总进度区域新增 `采集中 N` 标签:
|
||||
|
||||
@@ -355,7 +354,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
### 采集器设置页
|
||||
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) 会按路由进入三种模式:`/settings` 是系统设置,`/earth-content` 是智能星球内容,`/collection-management` 是采集管理。`collector_credentials` tab 当前在 `/collection-management` 下显示为“采集器”。
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) 会按路由进入三种模式:`/settings` 是系统设置,`/earth-content` 是智能星球内容,`/collection-management` 是采集管理。`collector_credentials` section 当前在 `/collection-management` 下显示为“采集器”。
|
||||
|
||||
`/settings` 的“系统显示”分区包含 `演示模式` 开关。开启后,智能星球的 OOBE 会忽略“已有当前采集数据”和本地“先浏览”临时跳过状态,直接展示初始化引导;该开关仅用于演示/验收流程,不改变数据源、采集队列或智能星球内容资源配置。
|
||||
|
||||
@@ -368,7 +367,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
- 不需要凭证的采集器只显示基础配置:endpoint、默认 endpoint、请求头、timeout、retry。
|
||||
- `BarentsWatch AIS` 使用专用凭证表单。
|
||||
|
||||
连接图标使用内联 `PlugConnectIcon`,视觉语义来自 Tabler `plug-connected`。后续如果控制台重写图标体系,应迁移到 Tabler Icons,而不是继续使用 Ant Design 刷新图标表达连接。
|
||||
连接测试入口使用现有 `Button icon="test"` 图标语义。后续如果控制台重写图标体系,应迁移到现有 lucide / Tactile UI 图标体系,而不是用普通刷新图标表达连接。
|
||||
|
||||
`Client Secret` 的表单语义:
|
||||
|
||||
@@ -421,6 +420,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
4. 不要用 `overflow: hidden` 掩盖结构问题
|
||||
5. 不要为了摘要卡完整显示去压缩主工作区
|
||||
6. 自定义滚动条必须是浮层,不得挤压内容宽度
|
||||
7. Admin shell 依赖 root `height: 100%` 高度链,不在根工作区重新写精确 `100vh`
|
||||
|
||||
详细经验见:
|
||||
|
||||
|
||||
@@ -210,6 +210,10 @@
|
||||
3. 真正滚动节点是否明确 `overflow: auto`
|
||||
4. 中间包装层是否偷偷改了布局语义
|
||||
|
||||
当前 Admin 和 Docs 根 shell 依赖 `html` / `body` / `#root` 的 `height: 100%`
|
||||
链路。不要在这些嵌入式工作区根容器上重新写精确 `100vh` / `100vw`;
|
||||
弹窗、浮层和窄屏安全边界可以继续使用 `calc(100vh - ...)` 作为最大尺寸约束。
|
||||
|
||||
### 5. UI 状态和显示状态不同步
|
||||
|
||||
Earth 相关改动里反复出现:
|
||||
|
||||
+15
-14
@@ -22,7 +22,7 @@
|
||||
1. 打开 `http://localhost:3000/login`,点击表单下方"注册账户"。
|
||||
2. 在 `/register` 填写:
|
||||
- **用户名**:3–50 位字符,登录时使用
|
||||
- **邮箱**:用于接收验证码,可在账户设置中修改
|
||||
- **邮箱**:用于接收验证码;当前版本如需修改邮箱,请联系管理员在用户管理中维护
|
||||
- **密码**:至少 8 位
|
||||
3. 提交后会跳到验证页,已将 6 位验证码发到你的邮箱。10 分钟内有效。
|
||||
4. 输入验证码,点击"验证并登录"。验证通过后系统会自动写入登录态并跳到控制台。
|
||||
@@ -52,23 +52,23 @@
|
||||
3. 收到验证码后,在下一步填入验证码 + 新密码(至少 8 位),点击"重置密码"。
|
||||
4. 系统会跳回 `/login`,用新密码登录即可。
|
||||
|
||||
## 账户设置
|
||||
## 账户区与退出
|
||||
|
||||
控制台右上角点击你的用户名进入账户设置,可以:
|
||||
控制台左侧底部的账户区会显示当前用户名、版本号和主题切换。当前版本还没有登录后的自助账户设置页:
|
||||
|
||||
- 修改密码:输入当前密码 + 新密码
|
||||
- 修改邮箱:输入新邮箱后系统会发验证码到新地址,验证通过后才生效
|
||||
- 查看权限组:列出你目前拥有的 Gatekeeper 权限组(`docs_user` / `docs_developer` / `docs_admin`)
|
||||
- 登出:清除当前会话
|
||||
- 忘记密码或需要重置密码时,使用 `/forgot-password` 邮件验证码流程
|
||||
- 邮箱、角色和 Gatekeeper 权限组由管理员在 `/users` 维护
|
||||
- 点击账户区的退出图标会清除当前会话并返回登录页
|
||||
|
||||
## 控制台总览
|
||||
|
||||
控制台 `http://localhost:3000/admin` 使用 React + Ant Design,左侧菜单按工作域组织。
|
||||
控制台 `http://localhost:3000/admin` 使用 React + Tactile UI / Radix 基础组件和 lucide 图标,左侧菜单按工作域组织。
|
||||
|
||||
| 页面 | 路由 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| 仪表盘 | `/admin` | 系统概览 |
|
||||
| 智能星球 | `/earth` | 跳到公开智能星球页面 |
|
||||
| 文档 | `/docs` | 打开文档站并按 Gatekeeper 权限查看可见文档 |
|
||||
| 数据源 | `/datasources` | 数据源目录、触发采集 |
|
||||
| 采集数据 | `/data` | 已落库的数据 |
|
||||
| BGP 观测 | `/bgp` | BGP 专题观测 |
|
||||
@@ -86,7 +86,7 @@
|
||||
|
||||
## 配置数据采集器
|
||||
|
||||
`/collection-management?tab=collector_credentials` 是"采集器"页。这里统一维护所有采集器的连接配置,不仅是凭证。旧链接 `/settings?tab=collector_credentials` 会自动跳转到这个入口;数据源目录仍保留在 `/datasources`。
|
||||
`/collection-management?section=collector_credentials` 是"采集器"页。这里统一维护所有采集器的连接配置,不仅是凭证;数据源目录仍保留在 `/datasources`。
|
||||
|
||||
操作步骤:
|
||||
|
||||
@@ -130,7 +130,7 @@
|
||||
|
||||
操作步骤:
|
||||
|
||||
1. `/collection-management?tab=collector_credentials` 选择 `AISStream 实时船舶 : aisstream_vessels`
|
||||
1. `/collection-management?section=collector_credentials` 选择 `AISStream 实时船舶 : aisstream_vessels`
|
||||
2. 在 `AISStream 凭证` 填入 API Key
|
||||
3. Endpoint 保持默认 `wss://stream.aisstream.io/v0/stream`
|
||||
4. 点击插头图标进行连接测试,确认显示 `可用`
|
||||
@@ -144,11 +144,12 @@
|
||||
|
||||
## 配置 AI 凭证
|
||||
|
||||
`/ai?tab=providers` 是 AI 模型管理入口。包含三个核心子 tab:
|
||||
`/ai?section=integrations` 是 AI 模型管理入口。主要分区包括:
|
||||
|
||||
- `模型供应商`:默认 LLM provider、模型、Base URL、API Key、本地 `aiprovider` 代理和连接测试
|
||||
- `工具`:通过下拉菜单选择具体工具,当前支持 WebSearch 和 OCR
|
||||
- `工具调用`:通过下拉菜单选择具体工具,当前支持 WebSearch 和 OCR
|
||||
- `提示词`:通过功能入口下拉菜单选择新闻汉化、告警研判、BGP 简报等 LLM 任务,手动调整提示词或重置为缺省
|
||||
- `Playground`:真实会话、预设请求和 AI Provider 状态调试
|
||||
|
||||
### 模型供应商
|
||||
|
||||
@@ -173,7 +174,7 @@ Base URL 输入框尾端的插头图标会触发连接测试。测试通过会
|
||||
|
||||
选择功能入口后,页面会显示当前提示词、是否已自定义、缺省版本和重置按钮。保存只影响该功能入口;重置会恢复当前发布包中的缺省提示词。业务事实、上下文和输出 schema 仍由后端按功能入口自动传入。
|
||||
|
||||
旧链接 `/settings?tab=ai` 会跳到 `/ai?tab=providers`。
|
||||
旧的 AI 配置入口不再放在系统设置里;`/playground` 会跳到 `/ai?section=playground`。
|
||||
|
||||
## 系统设置
|
||||
|
||||
@@ -244,7 +245,7 @@ Base URL 输入框尾端的插头图标会触发连接测试。测试通过会
|
||||
|
||||
## AI 测试台
|
||||
|
||||
`/ai?tab=playground` 用于真实分析链路调试。可以:
|
||||
`/ai?section=playground` 用于真实分析链路调试。可以:
|
||||
|
||||
- 选择当前 provider
|
||||
- 用预设请求或自定义 prompt 触发分析
|
||||
|
||||
@@ -32,8 +32,8 @@
|
||||
|
||||
进入 `/admin` 仪表盘后,建议按这个顺序熟悉控制台:
|
||||
|
||||
1. `/collection-management?tab=collector_credentials`:选一个采集器,点插头图标做连接测试。免费 collector(开源 BGP 等)通常直接可用;像 `AISStream`、`BarentsWatch` 这类需要凭证的,需要先填 API Key/Client Secret
|
||||
2. `/ai?tab=providers`:填一个 LLM provider(例如 `minimax` / `openai`)、模型名、Base URL、API Key,点 Base URL 末端的插头测试连接。WebSearch / OCR 工具可选
|
||||
1. `/collection-management?section=collector_credentials`:选一个采集器,点插头图标做连接测试。免费 collector(开源 BGP 等)通常直接可用;像 `AISStream`、`BarentsWatch` 这类需要凭证的,需要先填 API Key/Client Secret
|
||||
2. `/ai?section=integrations`:填一个 LLM provider(例如 `minimax` / `openai`)、模型名、Base URL、API Key,点 Base URL 末端的插头测试连接。WebSearch / OCR 工具可选
|
||||
3. `/datasources` 或 `/data`:看采集器是否已经产出数据。有限采集器看 `/datasources -> 内置源`,不勾选时点“触发全部”,勾选后主按钮会变成“触发已选 N”;右上角队列按钮可查看进度。AISStream / WebSocket 长连接看 `/datasources -> 实时源` 的健康状态和计数
|
||||
4. `/alerts/system`:看系统告警是否正常
|
||||
5. `/users`(仅 `super_admin`):根据需要给同事开账号或调权限组
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.71.0`
|
||||
- `dev` 当前开发分支历史推导到:`0.72.0`
|
||||
|
||||
## Timeline
|
||||
|
||||
| Version | Type | Branch | Commit | Summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `0.72.0` | feature | `dev` | `pending` | 新增完整 agent harness、单一 AGENTS 入口、Earth News smoke 覆盖和 collector 结构化日志清理,并同步控制台/Earth/Docs 响应式维护文档 |
|
||||
| `0.71.1` | bugfix | `dev` | `pending` | 修复 Earth 新闻区域切换、滚动条/面板/巡航一致性和新闻精修队列饿死问题,并补充 agent harness 与双语维护文档 |
|
||||
| `0.71.0` | feature | `dev` | `pending` | Motion Agent 升级为 Web/UE 共用双向控制与真实识别服务,新增 Earth 手动新闻工作流、来源多样化,并完善启动/测试 harness 与双语文档 |
|
||||
| `0.70.0` | feature | `dev` | `pending` | 新增后端枚举契约治理、Earth 新闻分类/Breaking 链路和船只当前状态快照,清理错误视口刷新逻辑并同步双语文档 |
|
||||
| `0.69.0` | feature | `dev` | `pending` | 新增 Earth 新闻源治理、新闻类型服务端过滤、观测日志 fingerprint 聚合和 TV/HLS 播放恢复改进 |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-frontend",
|
||||
"version": "0.71.0",
|
||||
"version": "0.72.0",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
|
||||
@@ -254,19 +254,31 @@
|
||||
.earth-toolbar-btn .icon,
|
||||
.earth-toolbar-hub-btn .material-symbols-rounded {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
z-index: 4;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.earth-toolbar-btn .icon {
|
||||
.earth-toolbar-btn .icon,
|
||||
.earth-toolbar-hub-btn .material-symbols-rounded,
|
||||
.earth-zoom-btn > span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: transform 0.16s ease, opacity 0.16s ease;
|
||||
color: rgba(243, 244, 246, 0.9);
|
||||
text-shadow: 0 1.5px 3px rgba(0, 0, 0, 0.5);
|
||||
transition:
|
||||
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
color 0.3s ease,
|
||||
opacity 0.16s ease;
|
||||
backface-visibility: hidden;
|
||||
-webkit-backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.earth-zoom-btn > span {
|
||||
position: relative;
|
||||
z-index: 4;
|
||||
}
|
||||
|
||||
.earth-toolbar-btn .material-symbols-rounded,
|
||||
.earth-toolbar-hub-btn .material-symbols-rounded {
|
||||
font-size: calc(21px * var(--toolbar-scale));
|
||||
@@ -299,22 +311,34 @@
|
||||
--btn-scale: 1;
|
||||
--press-offset: 0px;
|
||||
--float-offset: 0px;
|
||||
--mouse-x: 0.5;
|
||||
--mouse-y: 0.5;
|
||||
--toolbar-atmosphere-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.25);
|
||||
--toolbar-atmosphere-hover: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.55);
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
transform-style: preserve-3d;
|
||||
transform-origin: center center;
|
||||
will-change: transform, box-shadow;
|
||||
z-index: 2;
|
||||
border: 1px solid rgba(255, 255, 255, 0.14);
|
||||
border: none;
|
||||
outline: none;
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.085), transparent 38%),
|
||||
rgba(255, 255, 255, var(--toolbar-glass-opacity));
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.16) 0%,
|
||||
rgba(255, 255, 255, 0.02) 40%,
|
||||
rgba(15, 23, 42, 0.35) 75%,
|
||||
rgba(3, 7, 18, 0.85) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 8px 28px rgba(0, 0, 0, 0.38),
|
||||
inset 0 1.5px 2px rgba(255, 255, 255, 0.22),
|
||||
inset 0 -1.5px 2px rgba(0, 0, 0, 0.28);
|
||||
backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(108%) brightness(0.92);
|
||||
-webkit-backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(108%) brightness(0.92);
|
||||
0 8px 24px -4px rgba(0, 0, 0, 0.65),
|
||||
inset 0 0 1.5px 1.2px rgba(255, 255, 255, 0.15),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.45),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.03),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.06);
|
||||
backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(130%);
|
||||
-webkit-backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(130%);
|
||||
|
||||
transform:
|
||||
translate3d(
|
||||
@@ -325,121 +349,182 @@
|
||||
scale(var(--btn-scale));
|
||||
|
||||
transition:
|
||||
transform 0.22s ease,
|
||||
box-shadow 0.22s ease,
|
||||
background 0.22s ease,
|
||||
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
box-shadow 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
background 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
opacity 0.18s ease;
|
||||
}
|
||||
|
||||
.liquid-glass-surface::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
top: 4%;
|
||||
left: 15%;
|
||||
width: 70%;
|
||||
height: 32%;
|
||||
border-radius: 50% 50% 45% 45% / 65% 65% 35% 35%;
|
||||
background:
|
||||
radial-gradient(circle at 32% 20%, rgba(255, 255, 255, 0.13), transparent 34%),
|
||||
radial-gradient(circle at 54% 54%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.035), transparent 58%);
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
rgba(255, 255, 255, 0.38) 0%,
|
||||
rgba(255, 255, 255, 0.1) 50%,
|
||||
rgba(255, 255, 255, 0) 100%
|
||||
);
|
||||
filter: blur(0.4px);
|
||||
opacity: 1;
|
||||
pointer-events: none;
|
||||
transform: translate3d(calc(var(--elastic-x) * 0.08), calc(var(--elastic-y) * 0.08), 0);
|
||||
transition: opacity 0.18s ease, transform 0.18s ease;
|
||||
transform:
|
||||
translate(
|
||||
calc((var(--mouse-x, 0.5) - 0.5) * 5px),
|
||||
calc((var(--mouse-y, 0.5) - 0.5) * 3px)
|
||||
);
|
||||
transform-origin: top center;
|
||||
transition: transform 0.25s ease-out;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.liquid-glass-surface::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
bottom: -10%;
|
||||
left: 12%;
|
||||
width: 76%;
|
||||
height: 35%;
|
||||
border-radius: 50%;
|
||||
background:
|
||||
radial-gradient(circle at 50% 50%, transparent 58%, rgba(0, 0, 0, 0.1) 100%);
|
||||
box-shadow:
|
||||
inset 0 0 0 0.5px rgba(255, 255, 255, 0.06);
|
||||
opacity: 1;
|
||||
radial-gradient(
|
||||
ellipse at bottom,
|
||||
var(--toolbar-atmosphere-color) 0%,
|
||||
rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.02) 70%,
|
||||
rgba(0, 0, 0, 0) 100%
|
||||
);
|
||||
filter: blur(1px);
|
||||
opacity: 0.9;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.18s ease, box-shadow 0.18s ease;
|
||||
transform:
|
||||
translate(
|
||||
calc((var(--mouse-x, 0.5) - 0.5) * -3px),
|
||||
calc((var(--mouse-y, 0.5) - 0.5) * -2px)
|
||||
);
|
||||
transition:
|
||||
transform 0.25s ease-out,
|
||||
opacity 0.3s ease;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.earth-toolbar-hub-btn.liquid-glass-surface {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.095), transparent 40%),
|
||||
rgba(255, 255, 255, 0.07);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.18) 0%,
|
||||
rgba(255, 255, 255, 0.025) 42%,
|
||||
rgba(15, 23, 42, 0.32) 74%,
|
||||
rgba(3, 7, 18, 0.82) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 9px 30px rgba(0, 0, 0, 0.4),
|
||||
inset 0 1.5px 2px rgba(255, 255, 255, 0.24),
|
||||
inset 0 -1.5px 2px rgba(0, 0, 0, 0.3);
|
||||
0 9px 26px -4px rgba(0, 0, 0, 0.68),
|
||||
inset 0 0 1.8px 1.3px rgba(255, 255, 255, 0.17),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.5),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.04),
|
||||
inset 0 7px 13px rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover {
|
||||
--btn-scale: 1.03;
|
||||
--press-offset: -1px;
|
||||
--btn-scale: 1.05;
|
||||
--press-offset: -3px;
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.14), transparent 40%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.12), transparent 62%),
|
||||
rgba(255, 255, 255, 0.085);
|
||||
border-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.42);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.22) 0%,
|
||||
rgba(255, 255, 255, 0.04) 40%,
|
||||
rgba(15, 23, 42, 0.25) 75%,
|
||||
rgba(3, 7, 18, 0.8) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 40px rgba(0, 0, 0, 0.44),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.36),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover::before {
|
||||
opacity: 1;
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.2), transparent 36%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.14), transparent 62%);
|
||||
transform: translate3d(calc(var(--elastic-x) * 0.08), calc(var(--elastic-y) * 0.08 - 1px), 0);
|
||||
0 14px 28px -6px rgba(0, 0, 0, 0.8),
|
||||
0 0 15px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 1.8px 1.2px rgba(255, 255, 255, 0.22),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.65),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.04),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover::after {
|
||||
opacity: 1;
|
||||
box-shadow:
|
||||
inset 0 0 0 0.75px rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.16);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover .icon,
|
||||
.earth-toolbar-hub-btn.liquid-glass-surface:hover > .material-symbols-rounded,
|
||||
.earth-zoom-btn.liquid-glass-surface:hover > span {
|
||||
color: #ffffff;
|
||||
transform: scale(1.06);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:active,
|
||||
.liquid-glass-surface.is-pressed {
|
||||
--btn-scale: 0.94;
|
||||
--press-offset: 3px;
|
||||
--btn-scale: 0.95;
|
||||
--press-offset: -1px;
|
||||
transition: transform 0.1s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
box-shadow:
|
||||
0 4px 14px rgba(0, 0, 0, 0.28),
|
||||
inset 0 1px 2px rgba(255, 255, 255, 0.18),
|
||||
inset 0 -1px 3px rgba(0, 0, 0, 0.34);
|
||||
0 5px 12px -3px rgba(0, 0, 0, 0.9),
|
||||
0 0 8px -2px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 1.5px 1.2px rgba(255, 255, 255, 0.18),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.55),
|
||||
inset 0 -1px 4px rgba(255, 255, 255, 0.01);
|
||||
}
|
||||
|
||||
.liquid-glass-surface.active {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.14), transparent 40%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.13), transparent 62%),
|
||||
rgba(255, 255, 255, 0.09);
|
||||
border-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.42);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.24) 0%,
|
||||
rgba(255, 255, 255, 0.045) 40%,
|
||||
rgba(15, 23, 42, 0.24) 75%,
|
||||
rgba(3, 7, 18, 0.78) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 40px rgba(0, 0, 0, 0.46),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.38),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.2);
|
||||
0 13px 28px -6px rgba(0, 0, 0, 0.78),
|
||||
0 0 16px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 1.9px 1.25px rgba(255, 255, 255, 0.24),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.66),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.04),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.11);
|
||||
}
|
||||
|
||||
.liquid-glass-surface.active:hover {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.16), transparent 40%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.17), transparent 64%),
|
||||
rgba(255, 255, 255, 0.1);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.28) 0%,
|
||||
rgba(255, 255, 255, 0.055) 40%,
|
||||
rgba(15, 23, 42, 0.22) 75%,
|
||||
rgba(3, 7, 18, 0.76) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 42px rgba(0, 0, 0, 0.48),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.42),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.18);
|
||||
0 15px 30px -6px rgba(0, 0, 0, 0.82),
|
||||
0 0 18px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 2px 1.25px rgba(255, 255, 255, 0.27),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.7),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.05),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.earth-toolbar-cluster.is-expanded .earth-toolbar-hub-btn.liquid-glass-surface {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.15), transparent 42%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.15), transparent 64%),
|
||||
rgba(255, 255, 255, 0.095);
|
||||
border-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.44);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.24) 0%,
|
||||
rgba(255, 255, 255, 0.045) 40%,
|
||||
rgba(15, 23, 42, 0.24) 75%,
|
||||
rgba(3, 7, 18, 0.78) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 42px rgba(0, 0, 0, 0.48),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.4),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.18);
|
||||
0 14px 30px -6px rgba(0, 0, 0, 0.82),
|
||||
0 0 17px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 2px 1.25px rgba(255, 255, 255, 0.26),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.68),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.05),
|
||||
inset 0 7px 13px rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.earth-rotate-toggle .icon-play,
|
||||
|
||||
Vendored
+5
-1
@@ -5600,6 +5600,8 @@ function setupLiquidGlassInteractions() {
|
||||
surface.style.setProperty("--tilt-y", "0deg");
|
||||
surface.style.setProperty("--panel-tilt-x", "0deg");
|
||||
surface.style.setProperty("--panel-tilt-y", "0deg");
|
||||
surface.style.setProperty("--mouse-x", "0.5");
|
||||
surface.style.setProperty("--mouse-y", "0.5");
|
||||
surface.style.setProperty("--dock-scale", "1");
|
||||
surface.style.setProperty("--dock-lift", "0px");
|
||||
surface.style.setProperty("--dock-shift-x", "0px");
|
||||
@@ -5616,13 +5618,15 @@ function setupLiquidGlassInteractions() {
|
||||
|
||||
surfaces.forEach((surface) => {
|
||||
resetSurface(surface);
|
||||
const isToolbarSurface = Boolean(surface.closest(".earth-toolbar-items"));
|
||||
const isToolbarSurface = Boolean(surface.closest(".earth-toolbar"));
|
||||
const isPanelSurface = surface.classList.contains("hud-panel");
|
||||
|
||||
bindListener(surface, "pointermove", (event) => {
|
||||
const rect = surface.getBoundingClientRect();
|
||||
const px = (event.clientX - rect.left) / rect.width;
|
||||
const py = (event.clientY - rect.top) / rect.height;
|
||||
surface.style.setProperty("--mouse-x", `${px.toFixed(3)}`);
|
||||
surface.style.setProperty("--mouse-y", `${py.toFixed(3)}`);
|
||||
if (isPanelSurface) {
|
||||
const panelTiltX = (0.5 - py) * 5;
|
||||
const panelTiltY = (px - 0.5) * 6;
|
||||
|
||||
@@ -107,6 +107,9 @@ export function getNewsDisplayTitle(item, locale = DEFAULT_LOCALE) {
|
||||
if (localized || item?.display_title) {
|
||||
return normalizeText(item?.display_title || localized);
|
||||
}
|
||||
if (item?.title) {
|
||||
return normalizeText(item.title);
|
||||
}
|
||||
return normalizeText(
|
||||
TITLE_PLACEHOLDERS[item?.enrichment_status]
|
||||
|| "新闻汉化中",
|
||||
@@ -118,6 +121,9 @@ export function getNewsDisplaySummary(item, locale = DEFAULT_LOCALE) {
|
||||
if (localized || item?.display_summary) {
|
||||
return normalizeText(item?.display_summary || localized);
|
||||
}
|
||||
if (item?.summary) {
|
||||
return normalizeText(item.summary);
|
||||
}
|
||||
return normalizeText(
|
||||
SUMMARY_PLACEHOLDERS[item?.enrichment_status]
|
||||
|| "中文概要生成中,请稍后刷新。",
|
||||
@@ -126,8 +132,8 @@ export function getNewsDisplaySummary(item, locale = DEFAULT_LOCALE) {
|
||||
|
||||
export function isNewsContentReady(item, locale = DEFAULT_LOCALE) {
|
||||
const localized = getLocalization(item, locale);
|
||||
const title = normalizeText(item?.display_title || localized.title);
|
||||
const summary = normalizeText(item?.display_summary || localized.summary);
|
||||
const title = normalizeText(item?.display_title || localized.title || item?.title);
|
||||
const summary = normalizeText(item?.display_summary || localized.summary || item?.summary);
|
||||
return Boolean(title && summary);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,8 @@ const NEWS_SOURCE_FILTER_STORAGE_KEY = "planet.earth.newsSourceFilters.v1";
|
||||
|
||||
let initialized = false;
|
||||
let refreshPromise = null;
|
||||
let refreshRequestKey = "";
|
||||
let activeRefreshToken = 0;
|
||||
let payload = null;
|
||||
let lastFocus = null;
|
||||
let lastFetchAt = 0;
|
||||
@@ -488,7 +490,8 @@ function getEnabledNewsSourceIds(nextPayload = payload) {
|
||||
if (!available.length) return [];
|
||||
if (!Array.isArray(activeNewsSourceFilters)) return available;
|
||||
const allowed = new Set(activeNewsSourceFilters);
|
||||
return available.filter((id) => allowed.has(id));
|
||||
const enabled = available.filter((id) => allowed.has(id));
|
||||
return enabled.length > 0 ? enabled : available;
|
||||
}
|
||||
|
||||
function reconcileNewsSourceFilters(nextPayload = payload) {
|
||||
@@ -522,6 +525,15 @@ function getNewsSourceSignature(nextPayload = payload) {
|
||||
return enabled.join(",");
|
||||
}
|
||||
|
||||
function getNewsSourceSignatureForFetch(lat, lon) {
|
||||
const currentRegion = payload?.focus?.region || null;
|
||||
const nextRegion = inferRegion(lat, lon);
|
||||
if (currentRegion && nextRegion !== currentRegion) {
|
||||
return "";
|
||||
}
|
||||
return getNewsSourceSignature();
|
||||
}
|
||||
|
||||
function getNewsLimit() {
|
||||
return newsFullListMode ? NEWS_FULL_LIMIT : NEWS_SUMMARY_LIMIT;
|
||||
}
|
||||
@@ -707,6 +719,7 @@ function renderEmptyState(message) {
|
||||
|
||||
function renderPayload(nextPayload) {
|
||||
payload = nextPayload;
|
||||
reconcileNewsSourceFilters(nextPayload);
|
||||
const {
|
||||
board,
|
||||
empty,
|
||||
@@ -945,9 +958,9 @@ function connectNewsRealtime() {
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchNews(lat, lon) {
|
||||
const categorySignature = getNewsCategorySignature();
|
||||
const sourceSignature = getNewsSourceSignature();
|
||||
async function fetchNews(lat, lon, context = {}) {
|
||||
const categorySignature = context.categorySignature ?? getNewsCategorySignature();
|
||||
const sourceSignature = context.sourceSignature ?? getNewsSourceSignatureForFetch(lat, lon);
|
||||
if (categorySignature === "__none__" || sourceSignature === "__none__") {
|
||||
return {
|
||||
...(payload || {}),
|
||||
@@ -990,15 +1003,30 @@ async function fetchNews(lat, lon) {
|
||||
}
|
||||
|
||||
async function refreshNews(lat, lon, { silent = false } = {}) {
|
||||
if (refreshPromise) return refreshPromise;
|
||||
const targetRegion = inferRegion(lat, lon);
|
||||
const categorySignature = getNewsCategorySignature();
|
||||
const sourceSignature = getNewsSourceSignatureForFetch(lat, lon);
|
||||
const requestKey = [
|
||||
targetRegion,
|
||||
categorySignature,
|
||||
sourceSignature,
|
||||
getNewsLimit(),
|
||||
].join("|");
|
||||
|
||||
if (refreshPromise && refreshRequestKey === requestKey) return refreshPromise;
|
||||
const requestToken = ++activeRefreshToken;
|
||||
refreshRequestKey = requestKey;
|
||||
|
||||
const { status } = getElements();
|
||||
if (status) {
|
||||
status.textContent = "正在同步全球态势新闻...";
|
||||
}
|
||||
|
||||
refreshPromise = fetchNews(lat, lon)
|
||||
refreshPromise = fetchNews(lat, lon, { categorySignature, sourceSignature })
|
||||
.then((nextPayload) => {
|
||||
if (requestToken !== activeRefreshToken) {
|
||||
return nextPayload;
|
||||
}
|
||||
renderPayload(nextPayload);
|
||||
lastFetchAt = Date.now();
|
||||
lastCategorySignature = getNewsCategorySignature();
|
||||
@@ -1012,6 +1040,9 @@ async function refreshNews(lat, lon, { silent = false } = {}) {
|
||||
return nextPayload;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (requestToken !== activeRefreshToken) {
|
||||
return null;
|
||||
}
|
||||
console.error("加载 Earth RSS 新闻失败:", error);
|
||||
const message = error?.name === "AbortError"
|
||||
? "新闻聚合请求超时,请稍后重试"
|
||||
@@ -1024,7 +1055,10 @@ async function refreshNews(lat, lon, { silent = false } = {}) {
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
refreshPromise = null;
|
||||
if (requestToken === activeRefreshToken) {
|
||||
refreshPromise = null;
|
||||
refreshRequestKey = "";
|
||||
}
|
||||
});
|
||||
|
||||
return refreshPromise;
|
||||
|
||||
@@ -117,6 +117,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
setCollapsed((value) => !value)
|
||||
}}
|
||||
aria-label={collapsed ? '展开菜单' : '折叠菜单'}
|
||||
title={collapsed ? '展开菜单' : '折叠菜单'}
|
||||
>
|
||||
{collapsed ? <Menu size={18} /> : <X size={18} />}
|
||||
</Button>
|
||||
@@ -254,7 +255,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
) : null}
|
||||
<main className="admin__content">
|
||||
<header className="admin__topbar">
|
||||
<Button size="icon" variant="ghost" className="admin__mobile-menu" onClick={() => setMobileNavOpen(true)} aria-label="打开导航">
|
||||
<Button size="icon" variant="ghost" className="admin__mobile-menu" onClick={() => setMobileNavOpen(true)} aria-label="打开导航" title="打开导航">
|
||||
<Menu size={18} />
|
||||
</Button>
|
||||
<div className="admin__search" onBlur={handleSearchBlur}>
|
||||
|
||||
@@ -30,7 +30,7 @@ export function Dialog({ open, onOpenChange, title, description, children, foote
|
||||
) : null}
|
||||
</div>
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button size="icon" variant="ghost" aria-label="关闭">
|
||||
<Button size="icon" variant="ghost" aria-label="关闭" title="关闭">
|
||||
<X size={16} />
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
|
||||
@@ -46,7 +46,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
{item.description}
|
||||
</ToastPrimitive.Description>
|
||||
) : null}
|
||||
<ToastPrimitive.Close className="an-toast__close" aria-label="关闭通知">
|
||||
<ToastPrimitive.Close className="an-toast__close" aria-label="关闭通知" title="关闭通知">
|
||||
<X size={14} />
|
||||
</ToastPrimitive.Close>
|
||||
</ToastPrimitive.Root>
|
||||
|
||||
@@ -410,8 +410,8 @@ export default function DataList() {
|
||||
<CardHeader>
|
||||
<CardTitle>数据概览</CardTitle>
|
||||
<div className="an-segmented">
|
||||
<button className={distributionDimension === 'source' ? 'is-active' : ''} onClick={() => setDistributionDimension('source')}>按数据源</button>
|
||||
<button className={distributionDimension === 'type' ? 'is-active' : ''} onClick={() => setDistributionDimension('type')}>按类型</button>
|
||||
<button type="button" className={distributionDimension === 'source' ? 'is-active' : ''} onClick={() => setDistributionDimension('source')}>按数据源</button>
|
||||
<button type="button" className={distributionDimension === 'type' ? 'is-active' : ''} onClick={() => setDistributionDimension('type')}>按类型</button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -34,7 +34,7 @@ import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { useWebSocket } from '../../hooks/useWebSocket'
|
||||
import { AdminLayout } from '../components/layout/AdminLayout'
|
||||
import { DataTable } from '../components/data-table/DataTable'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { Button, type ButtonProps } from '../components/ui/button'
|
||||
import { ConfirmDialog, Dialog } from '../components/ui/dialog'
|
||||
import { Textarea } from '../components/ui/input'
|
||||
import { AdminSwitch } from '../components/ui/switch'
|
||||
@@ -177,7 +177,7 @@ interface PlaygroundActionResponse {
|
||||
session?: PlaygroundThreadResponse['session']
|
||||
}
|
||||
|
||||
const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
|
||||
function apiPath(path: string) {
|
||||
if (path.startsWith('/api/')) return path
|
||||
@@ -813,11 +813,43 @@ type FieldConfig = {
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
help?: string
|
||||
inputAction?: {
|
||||
ariaLabel?: string
|
||||
disabled?: boolean
|
||||
icon?: ButtonProps['icon']
|
||||
loading?: boolean
|
||||
onClick: () => void
|
||||
title: string
|
||||
}
|
||||
wide?: boolean
|
||||
secretVisible?: boolean
|
||||
onToggleSecret?: (visible: boolean) => void
|
||||
}
|
||||
|
||||
function ConnectionTestInput({
|
||||
action,
|
||||
children,
|
||||
}: {
|
||||
action: NonNullable<FieldConfig['inputAction']>
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="an-connection-test-input">
|
||||
{children}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="subtle"
|
||||
icon={action.icon || 'connect'}
|
||||
title={action.title}
|
||||
aria-label={action.ariaLabel || action.title}
|
||||
disabled={action.disabled}
|
||||
loading={action.loading}
|
||||
onClick={action.onClick}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const fieldLabels: Record<string, string> = {
|
||||
key: '键',
|
||||
label: '标签',
|
||||
@@ -2298,19 +2330,37 @@ function FieldGrid({
|
||||
return (
|
||||
<label key={field.key} className={className} data-admin-search-target={searchTarget} data-admin-search-field={field.key} data-admin-search-text={searchText}>
|
||||
<span>{field.label}</span>
|
||||
<input
|
||||
className="an-input"
|
||||
type={field.type === 'number' ? 'number' : 'text'}
|
||||
value={text(value, '')}
|
||||
placeholder={field.placeholder}
|
||||
disabled={field.disabled}
|
||||
onChange={(event) => onDraftChange(setNestedDraftField(
|
||||
draft,
|
||||
record,
|
||||
field.key,
|
||||
field.type === 'number' ? Number(event.target.value) : event.target.value,
|
||||
))}
|
||||
/>
|
||||
{field.inputAction ? (
|
||||
<ConnectionTestInput action={{ ...field.inputAction, disabled: field.disabled || field.inputAction.disabled }}>
|
||||
<input
|
||||
className="an-input an-connection-test-input__control"
|
||||
type={field.type === 'number' ? 'number' : 'text'}
|
||||
value={text(value, '')}
|
||||
placeholder={field.placeholder}
|
||||
disabled={field.disabled}
|
||||
onChange={(event) => onDraftChange(setNestedDraftField(
|
||||
draft,
|
||||
record,
|
||||
field.key,
|
||||
field.type === 'number' ? Number(event.target.value) : event.target.value,
|
||||
))}
|
||||
/>
|
||||
</ConnectionTestInput>
|
||||
) : (
|
||||
<input
|
||||
className="an-input"
|
||||
type={field.type === 'number' ? 'number' : 'text'}
|
||||
value={text(value, '')}
|
||||
placeholder={field.placeholder}
|
||||
disabled={field.disabled}
|
||||
onChange={(event) => onDraftChange(setNestedDraftField(
|
||||
draft,
|
||||
record,
|
||||
field.key,
|
||||
field.type === 'number' ? Number(event.target.value) : event.target.value,
|
||||
))}
|
||||
/>
|
||||
)}
|
||||
{field.help ? <small>{field.help}</small> : null}
|
||||
</label>
|
||||
)
|
||||
@@ -4761,7 +4811,21 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
{ value: 'anthropic-messages', label: 'Anthropic Messages' },
|
||||
{ value: 'ollama-generate', label: 'Ollama Generate' },
|
||||
] },
|
||||
{ key: 'base_url', label: 'LLM 基础地址', wide: true },
|
||||
{
|
||||
key: 'base_url',
|
||||
label: 'LLM 基础地址',
|
||||
wide: true,
|
||||
inputAction: activeGroup ? {
|
||||
title: '测试 AI Provider 连通性',
|
||||
icon: 'test',
|
||||
loading: actionLoading,
|
||||
onClick: () => void testConnection(
|
||||
'AI Provider',
|
||||
'/settings/integrations/ai-provider/connect',
|
||||
sanitizeSecretDrafts(stripInternalFields(record), activeGroup.record, ['api_key', 'service_token'], revealedFor('ai_provider')),
|
||||
),
|
||||
} : undefined,
|
||||
},
|
||||
{ key: 'model', label: '默认模型' },
|
||||
{
|
||||
key: 'api_key',
|
||||
@@ -4785,28 +4849,47 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
onToggleSecret: toggleActiveSecret('service_token', 'ai_provider'),
|
||||
},
|
||||
]
|
||||
const webSearchDisabled = activeGroup?.key.startsWith('web_search:') && !Boolean(record.enabled)
|
||||
const webFields: FieldConfig[] = [
|
||||
{ key: 'provider', label: '搜索供应商' },
|
||||
{ key: 'base_url', label: 'API 基础地址', wide: true },
|
||||
{ key: 'enabled', label: '启用 WebSearch', type: 'boolean' },
|
||||
{ key: 'provider', label: '搜索供应商', disabled: webSearchDisabled },
|
||||
{
|
||||
key: 'base_url',
|
||||
label: 'API 基础地址',
|
||||
wide: true,
|
||||
disabled: webSearchDisabled,
|
||||
inputAction: activeGroup ? {
|
||||
title: '测试 Web Search 连通性',
|
||||
icon: 'test',
|
||||
loading: actionLoading,
|
||||
disabled: webSearchDisabled,
|
||||
onClick: () => void testConnection(
|
||||
'Web Search',
|
||||
'/settings/integrations/web-search/connect',
|
||||
sanitizeSecretDrafts(stripInternalFields(record), activeGroup.record, ['api_key'], revealedFor('web_search')),
|
||||
),
|
||||
} : undefined,
|
||||
},
|
||||
{
|
||||
key: 'api_key',
|
||||
label: 'WebSearch API Key',
|
||||
type: 'secret',
|
||||
placeholder: '输入新的 WebSearch API Key',
|
||||
disabled: webSearchDisabled,
|
||||
secretVisible: Boolean(visibleSecretFields[secretFieldKey('api_key')]),
|
||||
onToggleSecret: toggleActiveSecret('api_key', 'web_search'),
|
||||
},
|
||||
{ key: 'max_results', label: '最大结果数', type: 'number' },
|
||||
{ key: 'timeout_seconds', label: '超时(秒)', type: 'number' },
|
||||
{ key: 'endpoint_path', label: '接口路径' },
|
||||
{ key: 'search_depth', label: '搜索深度' },
|
||||
{ key: 'engine', label: 'SerpAPI 引擎' },
|
||||
{ key: 'categories', label: 'SearXNG 分类' },
|
||||
{ key: 'search_path', label: 'Firecrawl 搜索路径' },
|
||||
{ key: 'scrape_path', label: 'Firecrawl 抓取路径' },
|
||||
{ key: 'include_answer', label: '包含答案', type: 'boolean' },
|
||||
{ key: 'include_raw_content', label: '包含原始内容', type: 'boolean' },
|
||||
{ key: 'include_text', label: '包含正文', type: 'boolean' },
|
||||
{ key: 'max_results', label: '最大结果数', type: 'number', disabled: webSearchDisabled },
|
||||
{ key: 'timeout_seconds', label: '超时(秒)', type: 'number', disabled: webSearchDisabled },
|
||||
{ key: 'endpoint_path', label: '接口路径', disabled: webSearchDisabled },
|
||||
{ key: 'search_depth', label: '搜索深度', disabled: webSearchDisabled },
|
||||
{ key: 'engine', label: 'SerpAPI 引擎', disabled: webSearchDisabled },
|
||||
{ key: 'categories', label: 'SearXNG 分类', disabled: webSearchDisabled },
|
||||
{ key: 'search_path', label: 'Firecrawl 搜索路径', disabled: webSearchDisabled },
|
||||
{ key: 'scrape_path', label: 'Firecrawl 抓取路径', disabled: webSearchDisabled },
|
||||
{ key: 'include_answer', label: '包含答案', type: 'boolean', disabled: webSearchDisabled },
|
||||
{ key: 'include_raw_content', label: '包含原始内容', type: 'boolean', disabled: webSearchDisabled },
|
||||
{ key: 'include_text', label: '包含正文', type: 'boolean', disabled: webSearchDisabled },
|
||||
]
|
||||
const ocrFields: FieldConfig[] = [
|
||||
{ key: 'provider', label: 'OCR 供应商', type: 'select', options: [
|
||||
@@ -4959,14 +5042,12 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
<>
|
||||
<Button size="icon" variant="subtle" title={isActiveDefault ? '当前已是默认' : '设为默认'} aria-label={isActiveDefault ? '当前已是默认' : '设为默认'} onClick={() => void setActiveAsDefault()} loading={actionLoading} disabled={isActiveDefault}><CheckCircle2 size={15} /></Button>
|
||||
<Button size="icon" variant="subtle" title="恢复默认配置" aria-label="恢复默认配置" onClick={restoreActiveDefaults}><Redo2 size={15} /></Button>
|
||||
<Button size="icon" variant="subtle" icon="test" title="测试 Web Search 连通性" aria-label="测试 Web Search 连通性" onClick={() => void testConnection('Web Search', '/settings/integrations/web-search/connect', sanitizeSecretDrafts(stripInternalFields(record), activeGroup.record, ['api_key'], revealedFor('web_search')))} loading={actionLoading} />
|
||||
</>
|
||||
) : null}
|
||||
{activeSection.key === 'integrations' ? (
|
||||
<>
|
||||
<Button size="icon" variant="subtle" title={isActiveDefault ? '当前已是默认' : '设为默认'} aria-label={isActiveDefault ? '当前已是默认' : '设为默认'} onClick={() => void setActiveAsDefault()} loading={actionLoading} disabled={isActiveDefault}><CheckCircle2 size={15} /></Button>
|
||||
<Button size="icon" variant="subtle" title="恢复默认配置" aria-label="恢复默认配置" onClick={restoreActiveDefaults}><Redo2 size={15} /></Button>
|
||||
<Button size="icon" variant="subtle" icon="test" title="测试 AI Provider 连通性" aria-label="测试 AI Provider 连通性" onClick={() => void testConnection('AI Provider', '/settings/integrations/ai-provider/connect', sanitizeSecretDrafts(stripInternalFields(record), activeGroup.record, ['api_key', 'service_token'], revealedFor('ai_provider')))} loading={actionLoading} />
|
||||
</>
|
||||
) : null}
|
||||
{activeGroup?.key.startsWith('ocr:') ? (
|
||||
@@ -6276,20 +6357,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
|
||||
actions.push(<Button key="refresh-preset" variant="primary" onClick={() => void requestAction('刷新模型列表', 'post', `/settings/integrations/ai-provider/presets/${encodeURIComponent(id)}/refresh`, undefined, { refresh: false, successDescription: '模型预设已刷新,未保存 provider 表单。' })} loading={actionLoading}><RefreshCw size={15} />刷新模型</Button>)
|
||||
}
|
||||
|
||||
if (config === configs.ai && endpointKey === 'integrations') {
|
||||
const integrationKey = pick(selected, ['__title', 'key', 'provider'], '')
|
||||
if (integrationKey === 'ai_provider') {
|
||||
actions.push(
|
||||
<Button key="connect-ai" size="icon" variant="subtle" icon="test" title="测试 AI Provider 连通性" aria-label="测试 AI Provider 连通性" onClick={() => void testConnection('AI Provider', '/settings/integrations/ai-provider/connect', cleanRecord(selected))} loading={actionLoading} />,
|
||||
)
|
||||
}
|
||||
if (integrationKey === 'web_search') {
|
||||
actions.push(
|
||||
<Button key="connect-web" size="icon" variant="subtle" icon="test" title="测试 Web Search 连通性" aria-label="测试 Web Search 连通性" onClick={() => void testConnection('Web Search', '/settings/integrations/web-search/connect', cleanRecord(selected))} loading={actionLoading} />,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (config === configs.ai && endpointKey === 'prompts' && id) {
|
||||
actions.push(<Button key="reset-prompt" variant="danger" onClick={() => setConfirmAction({
|
||||
title: '重置 Prompt',
|
||||
@@ -7150,7 +7217,7 @@ const configs = {
|
||||
{ key: 'prompts', label: '提示词', url: '/settings/ai-prompts', map: (payload) => dataArray(payload).map((row) => ({ ...row, __module: '提示词', __status: pick(row, ['source'], 'prompt') })) },
|
||||
{ key: 'playground', label: 'Playground', url: '/ai/playground/session', map: (payload) => isObjectRecord(payload) ? [{ ...payload, __title: 'Playground 会话', __module: 'Playground', __status: 'saved' }] : [] },
|
||||
],
|
||||
actions: [makeAction('设置', <Settings2 size={15} />, `/admin/${'settings'}`)],
|
||||
actions: [makeAction('设置', <Settings2 size={15} />, '/settings')],
|
||||
detailTitle: 'AI 配置详情',
|
||||
},
|
||||
earthContent: {
|
||||
@@ -7274,7 +7341,7 @@ const configs = {
|
||||
detailTitle: '日志详情',
|
||||
},
|
||||
settings: {
|
||||
title: '设置',
|
||||
title: '系统设置',
|
||||
description: '管理系统显示、通知策略、安全策略和 SMTP 邮件。',
|
||||
listTitle: '设置分区',
|
||||
listDescription: '仅展示系统设置分区;AI 集成和采集器调度分别在对应模块管理。',
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
import { adminRoutes, getVisibleAdminRoutes } from '../routes/manifest'
|
||||
import type { AdminSearchTarget } from './types'
|
||||
|
||||
const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
|
||||
function apiPath(path: string) {
|
||||
if (path.startsWith('/api/')) return path
|
||||
@@ -88,7 +88,7 @@ const sectionTargets = [
|
||||
{ key: 'collectors', label: '采集调度', terms: ['schedule', 'frequency'] },
|
||||
{ key: 'collection_history', label: '采集历史 / 快照', terms: ['history', 'snapshot'] },
|
||||
] },
|
||||
{ routePath: '/settings', routeLabel: '设置', icon: Settings, sections: [
|
||||
{ routePath: '/settings', routeLabel: '系统设置', icon: Settings, sections: [
|
||||
{ key: 'system', label: '系统显示', terms: ['system', 'display'] },
|
||||
{ key: 'notifications', label: '通知策略', terms: ['notification', 'email'] },
|
||||
{ key: 'security', label: '安全策略', terms: ['security', 'password'] },
|
||||
@@ -117,7 +117,7 @@ const fieldTargets = [
|
||||
{ routePath: '/ai', routeLabel: 'AI', sectionKey: 'prompts', sectionLabel: '提示词', labels: ['System Prompt', '任务提示词', '重置 Prompt'] },
|
||||
{ routePath: '/collection-management', routeLabel: '采集管理', sectionKey: 'collector_credentials', sectionLabel: '采集器', labels: ['凭证教程', '生成凭证教程', '采集器配置', '映射模板', '目标 Schema'] },
|
||||
{ routePath: '/earth-content', routeLabel: '智能星球内容', sectionKey: 'tv', sectionLabel: '电视直播', labels: ['默认频道', '自动回退', '直播源', '频道', '主页地址'] },
|
||||
{ routePath: '/settings', routeLabel: '设置', sectionKey: 'smtp', sectionLabel: 'SMTP 邮件', labels: ['主机', '端口', '用户名', '密码', '使用 TLS', '发件邮箱'] },
|
||||
{ routePath: '/settings', routeLabel: '系统设置', sectionKey: 'smtp', sectionLabel: 'SMTP 邮件', labels: ['主机', '端口', '用户名', '密码', '使用 TLS', '发件邮箱'] },
|
||||
]
|
||||
|
||||
const curatedDynamicLikeTargets = [
|
||||
|
||||
@@ -117,8 +117,8 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.admin {
|
||||
min-height: 100vh;
|
||||
height: 100vh;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 236px minmax(0, 1fr);
|
||||
background: var(--an-bg);
|
||||
@@ -597,7 +597,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
|
||||
.admin__content {
|
||||
min-width: 0;
|
||||
height: 100vh;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-rows: 48px minmax(0, 1fr);
|
||||
}
|
||||
@@ -2038,7 +2038,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
font-size: calc(0.74rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.3;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
letter-spacing: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
@@ -2048,7 +2048,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.6rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.3;
|
||||
letter-spacing: 0.08em;
|
||||
letter-spacing: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
@@ -2183,7 +2183,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
font-size: calc(0.62rem * var(--hud-scale));
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
letter-spacing: 0.04em;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.an-tv-earth-preview .tv-panel-tag--status {
|
||||
@@ -2221,7 +2221,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
|
||||
.an-tv-earth-preview .tv-panel-catalog {
|
||||
font-size: calc(0.66rem * var(--hud-scale));
|
||||
letter-spacing: 0.04em;
|
||||
letter-spacing: 0;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
@@ -2371,6 +2371,24 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.an-connection-test-input {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.an-connection-test-input__control {
|
||||
padding-right: 38px;
|
||||
}
|
||||
|
||||
.an-connection-test-input > .tui-button {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 4px;
|
||||
width: 28px;
|
||||
height: 24px;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.an-news-feed-list {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
@@ -4066,7 +4084,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.admin__content {
|
||||
height: 100vh;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.admin__topbar {
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
font: inherit;
|
||||
font-size: var(--segmented-control-font-size, calc(10px * var(--segmented-control-scale, 1)));
|
||||
font-weight: var(--segmented-control-font-weight, 800);
|
||||
letter-spacing: var(--segmented-control-letter-spacing, 0.04em);
|
||||
letter-spacing: var(--segmented-control-letter-spacing, 0);
|
||||
cursor: pointer;
|
||||
transition: color 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ const DEFAULT_WS_URL = (() => {
|
||||
return `${protocol}//${window.location.host}/ws`
|
||||
})()
|
||||
|
||||
const WS_URL = (import.meta as any).env?.VITE_WS_URL || DEFAULT_WS_URL
|
||||
const WS_URL = import.meta.env.VITE_WS_URL || DEFAULT_WS_URL
|
||||
const WS_CONNECT_TIMEOUT_MS = 4500
|
||||
|
||||
function buildWebSocketCandidates(): string[] {
|
||||
if ((import.meta as any).env?.VITE_WS_URL) {
|
||||
if (import.meta.env.VITE_WS_URL) {
|
||||
return [WS_URL]
|
||||
}
|
||||
|
||||
|
||||
@@ -117,13 +117,13 @@ select {
|
||||
color: #2563eb;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
letter-spacing: 0;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.auth-shell__heading h1 {
|
||||
margin-top: 10px;
|
||||
font-size: clamp(28px, 4vw, 38px);
|
||||
font-size: 38px;
|
||||
line-height: 1.12;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
@@ -240,7 +240,7 @@ select {
|
||||
max-width: 720px;
|
||||
margin-top: 14px;
|
||||
color: #081424;
|
||||
font-size: clamp(30px, 5vw, 52px);
|
||||
font-size: 52px;
|
||||
line-height: 1.05;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
@@ -266,4 +266,8 @@ select {
|
||||
min-height: calc(100vh - 20px);
|
||||
border-radius: 22px;
|
||||
}
|
||||
|
||||
.auth-shell__heading h1 {
|
||||
font-size: 30px;
|
||||
}
|
||||
}
|
||||
@@ -71,10 +71,15 @@ export function AuthButton({
|
||||
loading,
|
||||
children,
|
||||
variant = 'primary',
|
||||
type = 'button',
|
||||
disabled,
|
||||
className,
|
||||
...props
|
||||
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { loading?: boolean; variant?: 'primary' | 'secondary' | 'ghost' }) {
|
||||
const buttonClassName = ['auth-button', `auth-button--${variant}`, className].filter(Boolean).join(' ')
|
||||
|
||||
return (
|
||||
<button className={`auth-button auth-button--${variant}`} disabled={props.disabled || loading} {...props}>
|
||||
<button {...props} type={type} className={buttonClassName} disabled={disabled || loading}>
|
||||
{loading ? <Loader2 className="auth-button__spinner" size={16} /> : null}
|
||||
{children}
|
||||
</button>
|
||||
|
||||
@@ -148,7 +148,7 @@
|
||||
/* ─── Page shell ─────────────────────────────────────────────────────────────── */
|
||||
|
||||
.docs-page {
|
||||
height: 100vh;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 280px minmax(0, 1fr);
|
||||
background: var(--d-bg);
|
||||
@@ -887,7 +887,7 @@
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.docs-toc__nav {
|
||||
|
||||
@@ -100,8 +100,8 @@ export default function Docs() {
|
||||
const themeOptions = useMemo(() => [
|
||||
{
|
||||
value: 'light' as const,
|
||||
label: '浅色',
|
||||
title: '浅色',
|
||||
label: lang === 'zh' ? '浅色' : 'Light',
|
||||
title: lang === 'zh' ? '浅色' : 'Light',
|
||||
icon: (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
@@ -111,8 +111,8 @@ export default function Docs() {
|
||||
},
|
||||
{
|
||||
value: 'system' as const,
|
||||
label: '系统',
|
||||
title: '跟随系统',
|
||||
label: lang === 'zh' ? '系统' : 'System',
|
||||
title: lang === 'zh' ? '跟随系统' : 'Follow system',
|
||||
icon: (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
|
||||
@@ -122,15 +122,15 @@ export default function Docs() {
|
||||
},
|
||||
{
|
||||
value: 'dark' as const,
|
||||
label: '深色',
|
||||
title: '深色',
|
||||
label: lang === 'zh' ? '深色' : 'Dark',
|
||||
title: lang === 'zh' ? '深色' : 'Dark',
|
||||
icon: (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
], [])
|
||||
], [lang])
|
||||
|
||||
const handleLangChange = useCallback((newLang: DocsLang) => {
|
||||
setLang(newLang)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.earth-page-frame {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
display: block;
|
||||
}
|
||||
@@ -1,16 +1,13 @@
|
||||
import './Earth.css'
|
||||
|
||||
function Earth() {
|
||||
return (
|
||||
<iframe
|
||||
className="earth-page-frame"
|
||||
src="/earth/index.html"
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
border: "none",
|
||||
display: "block",
|
||||
}}
|
||||
title="3D Earth"
|
||||
/>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export default Earth;
|
||||
export default Earth
|
||||
@@ -2,7 +2,7 @@ import axios from 'axios'
|
||||
import { useEffect, useState, type FormEvent } from 'react'
|
||||
import { AuthButton, AuthField, AuthForm, AuthInput, AuthLinks, AuthNotice, AuthShell, BackToLogin } from '../Auth/AuthShell'
|
||||
|
||||
const API_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
|
||||
interface ErrorBody {
|
||||
response?: {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Link, useNavigate } from 'react-router-dom'
|
||||
import { AuthButton, AuthField, AuthForm, AuthInput, AuthLinks, AuthNotice, AuthShell } from '../Auth/AuthShell'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
|
||||
const API_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
const RESEND_COOLDOWN_SECONDS = 60
|
||||
|
||||
interface ErrorBody {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { AuthButton, AuthField, AuthForm, AuthInput, AuthLinks, AuthNotice, AuthShell, BackToLogin } from '../Auth/AuthShell'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
|
||||
const API_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
|
||||
interface ErrorBody {
|
||||
response?: {
|
||||
|
||||
@@ -16,7 +16,7 @@ import type {
|
||||
Summary,
|
||||
} from './types'
|
||||
|
||||
const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
|
||||
export class HttpSituationalAwarenessGateway implements SituationalAwarenessGateway {
|
||||
private bgpSummaryPromise: Promise<BGPSummarySnapshot> | null = null
|
||||
|
||||
@@ -17,7 +17,7 @@ interface AuthState {
|
||||
clearAuth: () => void
|
||||
}
|
||||
|
||||
const API_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
@@ -37,17 +37,14 @@ export const useAuthStore = create<AuthState>()(
|
||||
const { access_token, user } = response.data
|
||||
set({ token: access_token, user })
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
|
||||
console.log('[Auth] Logged in, token:', access_token.substring(0, 30) + '...')
|
||||
},
|
||||
|
||||
logout() {
|
||||
console.log('[Auth] Logging out...')
|
||||
set({ token: null, user: null })
|
||||
delete axios.defaults.headers.common['Authorization']
|
||||
},
|
||||
|
||||
clearAuth() {
|
||||
console.log('[Auth] Clearing all auth data...')
|
||||
set({ token: null, user: null })
|
||||
localStorage.removeItem('auth-storage')
|
||||
delete axios.defaults.headers.common['Authorization']
|
||||
|
||||
Vendored
+9
@@ -1 +1,10 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_URL?: string
|
||||
readonly VITE_WS_URL?: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
+42
-45
@@ -25,39 +25,43 @@
|
||||
|
||||
## Technology Stack
|
||||
|
||||
Current implementation truth lives in `README.md`, `CODEMAP.md`, and
|
||||
`docs/technical/{zh,en}/`. This file is background context; when it conflicts
|
||||
with current code or harness checks, prefer the current implementation docs.
|
||||
|
||||
### Backend
|
||||
- **Framework:** Python FastAPI 0.109+
|
||||
- **ORM:** SQLAlchemy 2.0+
|
||||
- **Database Migration:** Alembic
|
||||
- **Task Queue:** Celery 5.3+
|
||||
- **Message Queue:** Kafka 3.0+
|
||||
- **Caching:** Redis 7.0+
|
||||
- **Database Migration:** Alembic / SQLAlchemy migrations
|
||||
- **Task Runtime:** APScheduler, backend background tasks, and database job state
|
||||
- **Runtime Coordination:** Redis 7.0+ cache/streams
|
||||
- **Package Manager / Runner:** uv
|
||||
|
||||
### Frontend
|
||||
- **Framework:** React 18
|
||||
- **UI Library:** Ant Design Pro
|
||||
- **UI Layer:** Tactile UI, Radix primitives, lucide-react
|
||||
- **HTTP Client:** Axios
|
||||
- **State Management:** React Query
|
||||
- **State Management:** Zustand and local React state
|
||||
- **Real-time:** Socket.io-client
|
||||
- **Charts:** ECharts
|
||||
- **Package Manager / Runner:** Bun 1
|
||||
- **3D Earth:** Three.js Web Earth
|
||||
|
||||
### Visualization (UE5)
|
||||
- **Engine:** Unreal Engine 5.3+
|
||||
- **Geospatial:** Cesium for Unreal 1.5+
|
||||
- **Particles:** Niagara
|
||||
- **3D Rendering:** Nanite + Lumen
|
||||
### Visualization Direction
|
||||
- **Current:** Browser Web Earth with Three.js assets under `frontend/public/earth/`
|
||||
- **Future / optional:** UE5, Cesium for Unreal, and Niagara remain physical
|
||||
big-screen exploration directions, not required local development dependencies.
|
||||
|
||||
### Database
|
||||
- **Relational:** PostgreSQL 15+ (users, config)
|
||||
- **Time-series:** TimescaleDB
|
||||
- **Cache:** Redis 7+ (sessions, cache)
|
||||
- **Storage:** MinIO (S3-compatible)
|
||||
- **Cache / Streams:** Redis 7+ (sessions, cache, runtime events)
|
||||
- **Future / optional:** TimescaleDB, MinIO, Kafka, and Celery are evolution
|
||||
boundaries only; do not assume they exist in the active local stack.
|
||||
|
||||
### Deployment
|
||||
- **Container:** Docker 24+
|
||||
- **Orchestration:** Docker Compose
|
||||
- **Reverse Proxy:** Nginx
|
||||
- **Packaging:** Helm chart under `deploy/helm/planet/`
|
||||
|
||||
---
|
||||
|
||||
@@ -71,7 +75,7 @@
|
||||
│ │ │ │ ├── auth.py
|
||||
│ │ │ │ ├── users.py
|
||||
│ │ │ │ ├── datasources.py
|
||||
│ │ │ │ ├── tasks.py
|
||||
│ │ │ │ ├── docs.py
|
||||
│ │ │ │ └── websocket.py
|
||||
│ │ │ └── endpoints/
|
||||
│ │ ├── core/
|
||||
@@ -93,50 +97,43 @@
|
||||
│ │ │ │ └── huggingface.py
|
||||
│ │ │ └── analysis.py
|
||||
│ │ ├── tasks/
|
||||
│ │ │ └── scheduler.py
|
||||
│ │ ├── services/
|
||||
│ │ │ ├── collectors/
|
||||
│ │ │ └── docs_gatekeeper.py
|
||||
│ │ └── db/
|
||||
│ │ └── session.py
|
||||
│ │ └── database.py
|
||||
│ ├── tests/
|
||||
│ │ ├── api/
|
||||
│ │ ├── unit/
|
||||
│ │ └── conftest.py
|
||||
│ ├── pyproject.toml
|
||||
│ ├── uv.lock
|
||||
│ │ ├── test_api.py
|
||||
│ │ └── test_realtime_sources.py
|
||||
│ └── alembic/
|
||||
│
|
||||
├── frontend/ # React Admin
|
||||
├── frontend/ # React Admin, Docs UI, and Web Earth shell
|
||||
│ ├── src/
|
||||
│ │ ├── api/ # Axios instances
|
||||
│ │ ├── components/ # Reusable components
|
||||
│ │ ├── pages/ # Route pages
|
||||
│ │ ├── admin/ # Console routes, pages, Tactile/Radix wrappers
|
||||
│ │ ├── components/ # Reusable UI and Web Earth components
|
||||
│ │ ├── pages/ # Public route pages
|
||||
│ │ │ ├── Login/
|
||||
│ │ │ ├── Dashboard/
|
||||
│ │ │ ├── Users/
|
||||
│ │ │ ├── DataSources/
|
||||
│ │ │ └── Settings/
|
||||
│ │ ├── stores/ # Zustand/Redux
|
||||
│ │ │ ├── Register/
|
||||
│ │ │ ├── Docs/
|
||||
│ │ │ └── Earth/
|
||||
│ │ ├── stores/ # Zustand stores
|
||||
│ │ ├── hooks/
|
||||
│ │ ├── types/
|
||||
│ │ └── App.tsx
|
||||
│ ├── package.json
|
||||
│ └── tests/
|
||||
│ └── public/earth/ # Web Earth static assets
|
||||
│
|
||||
├── unreal/ # UE5 Project
|
||||
│ ├── Content/
|
||||
│ │ ├── Maps/
|
||||
│ │ ├── Blueprints/
|
||||
│ │ └── Materials/
|
||||
│ ├── Plugins/
|
||||
│ └── Source/
|
||||
│
|
||||
├── data/ # Static data files
|
||||
├── aiprovider/ # Model provider/protocol adapter service
|
||||
├── motion_agent/ # Motion capture protocol service
|
||||
├── deploy/helm/planet/ # Helm chart
|
||||
├── docs/ # Documentation
|
||||
├── scripts/ # Utility scripts
|
||||
├── scripts/ # Utility and harness scripts
|
||||
├── docker-compose.yml
|
||||
├── pyproject.toml
|
||||
├── uv.lock
|
||||
├── .env.example
|
||||
├── rules.md
|
||||
├── project_context.md
|
||||
├── agents.md
|
||||
├── AGENTS.md
|
||||
└── README.md
|
||||
```
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "planet"
|
||||
version = "0.71.0"
|
||||
version = "0.72.0"
|
||||
description = "智能星球计划 - 态势感知系统"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
source "$ROOT_DIR/scripts/harness/lib.sh"
|
||||
|
||||
main() {
|
||||
cd "$ROOT_DIR"
|
||||
local uv_bin
|
||||
uv_bin="$(harness_require_tool uv)"
|
||||
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python - <<'PY'
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
root = Path.cwd()
|
||||
failures: list[str] = []
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
failures.append(message)
|
||||
|
||||
|
||||
class BackendDebugCallVisitor(ast.NodeVisitor):
|
||||
def __init__(self, path: Path) -> None:
|
||||
self.path = path
|
||||
|
||||
def visit_Call(self, node: ast.Call) -> None:
|
||||
if isinstance(node.func, ast.Name) and node.func.id in {"print", "breakpoint"}:
|
||||
fail(f"{self.path}:{node.lineno}: backend app code must use structured logging, not {node.func.id}()")
|
||||
if (
|
||||
isinstance(node.func, ast.Attribute)
|
||||
and node.func.attr == "set_trace"
|
||||
and isinstance(node.func.value, ast.Name)
|
||||
and node.func.value.id == "pdb"
|
||||
):
|
||||
fail(f"{self.path}:{node.lineno}: remove pdb.set_trace() from backend app code")
|
||||
self.generic_visit(node)
|
||||
|
||||
|
||||
for path in sorted((root / "backend/app").rglob("*.py")):
|
||||
rel = path.relative_to(root)
|
||||
try:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(rel))
|
||||
except SyntaxError as exc:
|
||||
fail(f"{rel}:{exc.lineno}: Python syntax error: {exc.msg}")
|
||||
continue
|
||||
BackendDebugCallVisitor(rel).visit(tree)
|
||||
|
||||
if failures:
|
||||
for message in failures:
|
||||
print(f"fail: {message}")
|
||||
raise SystemExit(f"backend rules check failed: {len(failures)} failure(s)")
|
||||
|
||||
print("backend rules check passed")
|
||||
PY
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+645
@@ -0,0 +1,645 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
source "$ROOT_DIR/scripts/harness/lib.sh"
|
||||
|
||||
main() {
|
||||
cd "$ROOT_DIR"
|
||||
local uv_bin
|
||||
uv_bin="$(harness_require_tool uv)"
|
||||
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python - <<'PY'
|
||||
import ast
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
root = Path.cwd()
|
||||
failures: list[str] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
failures.append(message)
|
||||
|
||||
|
||||
def warn(message: str) -> None:
|
||||
warnings.append(message)
|
||||
|
||||
|
||||
def read_text(path: str) -> str:
|
||||
return (root / path).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def literal_assignment(path: str, name: str) -> object:
|
||||
tree = ast.parse(read_text(path))
|
||||
for node in tree.body:
|
||||
if not isinstance(node, ast.Assign):
|
||||
continue
|
||||
if not any(isinstance(target, ast.Name) and target.id == name for target in node.targets):
|
||||
continue
|
||||
return ast.literal_eval(node.value)
|
||||
raise ValueError(f"could not find literal assignment {name} in {path}")
|
||||
|
||||
|
||||
def slug_from_filename(filename: str) -> str:
|
||||
return "overview" if filename == "README.md" else filename.removesuffix(".md")
|
||||
|
||||
|
||||
def frontend_docs_metadata() -> dict[str, dict[str, object]]:
|
||||
text = read_text("frontend/src/pages/Docs/docs-content.ts")
|
||||
entries: dict[str, dict[str, object]] = {}
|
||||
pattern = re.compile(
|
||||
r"(?:\[(?P<constant>DOCS_README_FILENAME)\]|'(?P<filename>[^']+\.md)'):\s*\{\s*"
|
||||
r"zh:\s*\{\s*title:\s*'(?P<zh_title>[^']+)',\s*group:\s*'(?P<zh_group>[^']+)',\s*order:\s*(?P<zh_order>\d+)\s*\},\s*"
|
||||
r"en:\s*\{\s*title:\s*'(?P<en_title>[^']+)',\s*group:\s*'(?P<en_group>[^']+)',\s*order:\s*(?P<en_order>\d+)\s*\}",
|
||||
re.S,
|
||||
)
|
||||
for match in pattern.finditer(text):
|
||||
filename = "README.md" if match.group("constant") else match.group("filename")
|
||||
if filename in entries:
|
||||
fail(f"frontend Docs metadata registers {filename} more than once")
|
||||
continue
|
||||
entries[filename] = {
|
||||
"slug": slug_from_filename(filename),
|
||||
"zh_title": match.group("zh_title"),
|
||||
"en_title": match.group("en_title"),
|
||||
"zh_group": match.group("zh_group"),
|
||||
"en_group": match.group("en_group"),
|
||||
"zh_order": int(match.group("zh_order")),
|
||||
"en_order": int(match.group("en_order")),
|
||||
}
|
||||
return entries
|
||||
|
||||
|
||||
def backend_docs_metadata() -> dict[str, dict[str, object]]:
|
||||
tree = ast.parse(read_text("backend/app/services/docs_gatekeeper.py"))
|
||||
constants: dict[str, object] = {}
|
||||
|
||||
for node in tree.body:
|
||||
if not isinstance(node, ast.Assign) or len(node.targets) != 1:
|
||||
continue
|
||||
target = node.targets[0]
|
||||
if isinstance(target, ast.Name) and isinstance(node.value, ast.Constant):
|
||||
constants[target.id] = node.value.value
|
||||
|
||||
def read_arg(node: ast.AST) -> object:
|
||||
if isinstance(node, ast.Constant):
|
||||
return node.value
|
||||
if isinstance(node, ast.Name) and node.id in constants:
|
||||
return constants[node.id]
|
||||
raise ValueError(f"unsupported DocsMetadata argument: {ast.dump(node)}")
|
||||
|
||||
entries: dict[str, dict[str, object]] = {}
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
if not isinstance(node.func, ast.Name) or node.func.id != "DocsMetadata":
|
||||
continue
|
||||
if len(node.args) != 7:
|
||||
fail("backend DocsMetadata entries must keep the expected seven positional fields")
|
||||
continue
|
||||
filename, slug, access, group, order, zh_title, en_title = [read_arg(arg) for arg in node.args]
|
||||
if not isinstance(filename, str):
|
||||
fail("backend DocsMetadata filename must be a string")
|
||||
continue
|
||||
if filename in entries:
|
||||
fail(f"backend Docs metadata registers {filename} more than once")
|
||||
continue
|
||||
entries[filename] = {
|
||||
"slug": slug,
|
||||
"access": access,
|
||||
"group": group,
|
||||
"order": order,
|
||||
"zh_title": zh_title,
|
||||
"en_title": en_title,
|
||||
}
|
||||
return entries
|
||||
|
||||
|
||||
def docs_metadata_filenames() -> set[str]:
|
||||
return set(frontend_docs_metadata())
|
||||
|
||||
|
||||
def check_docs_metadata_alignment() -> None:
|
||||
frontend = frontend_docs_metadata()
|
||||
backend = backend_docs_metadata()
|
||||
|
||||
if not frontend:
|
||||
fail("frontend Docs metadata must expose at least one document")
|
||||
if not backend:
|
||||
fail("backend Gatekeeper Docs metadata must expose at least one document")
|
||||
|
||||
frontend_only = sorted(set(frontend) - set(backend))
|
||||
backend_only = sorted(set(backend) - set(frontend))
|
||||
if frontend_only:
|
||||
fail("frontend Docs metadata has files missing from backend Gatekeeper metadata: " + ", ".join(frontend_only))
|
||||
if backend_only:
|
||||
fail("backend Gatekeeper metadata has files missing from frontend Docs metadata: " + ", ".join(backend_only))
|
||||
|
||||
for filename in sorted(set(frontend) & set(backend)):
|
||||
frontend_entry = frontend[filename]
|
||||
backend_entry = backend[filename]
|
||||
if frontend_entry["zh_group"] != frontend_entry["en_group"]:
|
||||
fail(f"frontend Docs metadata group differs by language for {filename}")
|
||||
if frontend_entry["zh_order"] != frontend_entry["en_order"]:
|
||||
fail(f"frontend Docs metadata order differs by language for {filename}")
|
||||
|
||||
expected = {
|
||||
"slug": frontend_entry["slug"],
|
||||
"group": frontend_entry["zh_group"],
|
||||
"order": frontend_entry["zh_order"],
|
||||
"zh_title": frontend_entry["zh_title"],
|
||||
"en_title": frontend_entry["en_title"],
|
||||
}
|
||||
actual = {key: backend_entry[key] for key in expected}
|
||||
if actual != expected:
|
||||
fail(f"{filename}: frontend Docs metadata and backend Gatekeeper metadata differ; frontend={expected}, backend={actual}")
|
||||
|
||||
|
||||
def check_public_docs_registry() -> None:
|
||||
filenames = docs_metadata_filenames()
|
||||
for filename in sorted(filenames):
|
||||
for lang in ("zh", "en"):
|
||||
path = root / "docs/technical" / lang / filename
|
||||
if not path.exists():
|
||||
fail(f"public docs metadata references missing file: {path.relative_to(root)}")
|
||||
|
||||
for readme in (root / "docs/technical/zh/README.md", root / "docs/technical/en/README.md"):
|
||||
if not readme.exists():
|
||||
continue
|
||||
for href in re.findall(r"\]\(([^)]+\.md)\)", readme.read_text(encoding="utf-8")):
|
||||
if "docs/technical/" not in href:
|
||||
continue
|
||||
filename = Path(href).name
|
||||
if filename not in filenames:
|
||||
fail(f"{readme.relative_to(root)} links {filename}, but DOCS_METADATA does not expose it")
|
||||
|
||||
|
||||
def check_all_technical_docs_have_bilingual_pairs() -> None:
|
||||
zh_dir = root / "docs/technical/zh"
|
||||
en_dir = root / "docs/technical/en"
|
||||
zh_files = {path.name for path in zh_dir.glob("*.md")}
|
||||
en_files = {path.name for path in en_dir.glob("*.md")}
|
||||
|
||||
zh_only = sorted(zh_files - en_files)
|
||||
en_only = sorted(en_files - zh_files)
|
||||
if zh_only:
|
||||
fail("technical docs missing English counterparts: " + ", ".join(zh_only))
|
||||
if en_only:
|
||||
fail("technical docs missing Chinese counterparts: " + ", ".join(en_only))
|
||||
|
||||
|
||||
def check_bilingual_docs_are_not_copies() -> None:
|
||||
same: list[str] = []
|
||||
for en in sorted((root / "docs/technical/en").glob("*.md")):
|
||||
zh = root / "docs/technical/zh" / en.name
|
||||
if zh.exists() and en.read_text(encoding="utf-8") == zh.read_text(encoding="utf-8"):
|
||||
same.append(en.name)
|
||||
if same:
|
||||
fail("identical en/zh technical docs: " + ", ".join(same))
|
||||
|
||||
|
||||
def check_public_doc_links_exist() -> None:
|
||||
repo_prefix = f"{root}/"
|
||||
for doc in sorted((root / "docs/technical").glob("*/*.md")):
|
||||
text = doc.read_text(encoding="utf-8")
|
||||
for href in re.findall(r"\]\(([^)#]+\.md)(?:#[^)]+)?\)", text):
|
||||
if not href.startswith(repo_prefix):
|
||||
continue
|
||||
target = Path(href)
|
||||
if not target.exists():
|
||||
fail(f"{doc.relative_to(root)} links missing markdown file: {href}")
|
||||
|
||||
|
||||
def check_language_scoped_technical_links() -> None:
|
||||
technical_docs_prefix = re.escape(str(root / "docs/technical"))
|
||||
pattern = re.compile(rf"{technical_docs_prefix}/(?!zh/|en/)[^)#\s]+")
|
||||
for doc in sorted((root / "docs/technical").glob("*/*.md")):
|
||||
text = doc.read_text(encoding="utf-8")
|
||||
for match in pattern.finditer(text):
|
||||
line_no = text.count("\n", 0, match.start()) + 1
|
||||
fail(
|
||||
f"{doc.relative_to(root)}:{line_no}: technical doc link must include "
|
||||
f"the language directory: {match.group(0)}"
|
||||
)
|
||||
|
||||
|
||||
def check_public_doc_link_titles() -> None:
|
||||
pattern = re.compile(r"\[([^]\n]+\.md)\]\(")
|
||||
for doc in sorted((root / "docs/technical").glob("*/*.md")):
|
||||
text = doc.read_text(encoding="utf-8")
|
||||
for match in pattern.finditer(text):
|
||||
line_no = text.count("\n", 0, match.start()) + 1
|
||||
fail(
|
||||
f"{doc.relative_to(root)}:{line_no}: public docs should use readable "
|
||||
f"link text instead of raw filename {match.group(1)!r}"
|
||||
)
|
||||
|
||||
|
||||
def check_credential_collector_contracts() -> None:
|
||||
defaults = literal_assignment("backend/app/core/datasource_defaults.py", "DEFAULT_DATASOURCES")
|
||||
if not isinstance(defaults, dict):
|
||||
fail("backend/app/core/datasource_defaults.py DEFAULT_DATASOURCES must stay a dict")
|
||||
return
|
||||
|
||||
supported_sources: dict[str, str] = {}
|
||||
for source, info in defaults.items():
|
||||
if not isinstance(info, dict):
|
||||
fail(f"DEFAULT_DATASOURCES entry {source!r} must be a dict")
|
||||
continue
|
||||
if not info.get("requires_credentials"):
|
||||
continue
|
||||
if info.get("credential_status") != "supported":
|
||||
continue
|
||||
provider = info.get("credential_provider")
|
||||
if not isinstance(provider, str) or not provider.strip():
|
||||
fail(f"{source}: supported credential collector is missing credential_provider")
|
||||
continue
|
||||
supported_sources[str(source)] = provider
|
||||
|
||||
if not supported_sources:
|
||||
return
|
||||
|
||||
guides_text = read_text("backend/app/services/credential_guides.py")
|
||||
default_guides = set(re.findall(r"CredentialGuideDefault\(\s*provider=\"([^\"]+)\"", guides_text))
|
||||
connectivity_providers = literal_assignment(
|
||||
"backend/app/services/datasource_connectivity.py",
|
||||
"SUPPORTED_CREDENTIAL_PROVIDERS",
|
||||
)
|
||||
if not isinstance(connectivity_providers, set):
|
||||
fail("SUPPORTED_CREDENTIAL_PROVIDERS must stay a literal set")
|
||||
connectivity_providers = set()
|
||||
|
||||
frontend_text = read_text("frontend/src/admin/pages/PlainResourcePages.tsx")
|
||||
tests_text = read_text("backend/tests/test_collectors.py")
|
||||
zh_doc = read_text("docs/technical/zh/datasource-collector-settings-connectivity.md")
|
||||
en_doc = read_text("docs/technical/en/datasource-collector-settings-connectivity.md")
|
||||
|
||||
if "test_supported_credential_collectors_have_guides_and_connectivity_provider" not in tests_text:
|
||||
fail("backend/tests/test_collectors.py must keep the supported credential collector contract test")
|
||||
|
||||
if "loadCredentialGuide" not in frontend_text or "credentialGuideProvider" not in frontend_text:
|
||||
fail("collector credential UI must keep guide-loading and provider-normalization helpers")
|
||||
|
||||
for source, provider in sorted(supported_sources.items()):
|
||||
if provider not in default_guides:
|
||||
fail(f"{source}: missing default credential guide for provider {provider}")
|
||||
if provider not in connectivity_providers:
|
||||
fail(f"{source}: missing supported connectivity provider {provider}")
|
||||
if provider not in frontend_text and source not in frontend_text:
|
||||
fail(f"{source}: collector credential UI does not mention provider/source {provider}")
|
||||
for doc_path, doc_text in (
|
||||
("docs/technical/zh/datasource-collector-settings-connectivity.md", zh_doc),
|
||||
("docs/technical/en/datasource-collector-settings-connectivity.md", en_doc),
|
||||
):
|
||||
if provider not in doc_text and source not in doc_text:
|
||||
fail(f"{doc_path}: missing supported credential collector provider/source {provider}/{source}")
|
||||
|
||||
|
||||
def known_frontend_routes() -> set[str]:
|
||||
app_text = read_text("frontend/src/App.tsx")
|
||||
admin_text = read_text("frontend/src/admin/AdminRoutes.tsx")
|
||||
manifest_text = read_text("frontend/src/admin/routes/manifest.tsx")
|
||||
routes = set(re.findall(r'<Route\s+path="([^"*][^"]*)"', app_text))
|
||||
routes.update(re.findall(r'<Route\s+path="([^"*][^"]*)"', admin_text))
|
||||
routes.update(re.findall(r"path:\s*'([^']+)'", manifest_text))
|
||||
routes.update({"/", "/playground", "/docs/:slug"})
|
||||
routes.discard("*")
|
||||
return routes
|
||||
|
||||
|
||||
def admin_manifest_routes() -> dict[str, str]:
|
||||
manifest_text = read_text("frontend/src/admin/routes/manifest.tsx")
|
||||
routes: dict[str, str] = {}
|
||||
pattern = re.compile(r"\{\s*path:\s*'([^']+)',\s*label:\s*'([^']+)'", re.S)
|
||||
for path, label in pattern.findall(manifest_text):
|
||||
routes[path] = label
|
||||
if not routes:
|
||||
fail("could not parse admin route manifest for manual coverage checks")
|
||||
return routes
|
||||
|
||||
|
||||
def manual_console_route_rows(doc_path: Path, heading: str) -> dict[str, str]:
|
||||
text = doc_path.read_text(encoding="utf-8")
|
||||
heading_index = text.find(heading)
|
||||
if heading_index == -1:
|
||||
fail(f"{doc_path.relative_to(root)} is missing {heading!r}")
|
||||
return {}
|
||||
next_heading = re.search(r"\n##\s+", text[heading_index + len(heading):])
|
||||
section = text[heading_index:] if not next_heading else text[heading_index:heading_index + len(heading) + next_heading.start()]
|
||||
rows: dict[str, str] = {}
|
||||
for line in section.splitlines():
|
||||
match = re.match(r"\|\s*([^|`][^|]*?)\s*\|\s*`([^`]+)`\s*\|", line)
|
||||
if not match:
|
||||
continue
|
||||
label = match.group(1).strip()
|
||||
path = match.group(2).strip()
|
||||
rows[path] = label
|
||||
return rows
|
||||
|
||||
|
||||
def normalize_zh_label(label: str) -> str:
|
||||
return re.sub(r"\s+", "", label)
|
||||
|
||||
|
||||
def check_manual_console_route_tables() -> None:
|
||||
manifest = admin_manifest_routes()
|
||||
zh_manual = root / "docs/technical/zh/manual.md"
|
||||
en_manual = root / "docs/technical/en/manual.md"
|
||||
manual_rows = {
|
||||
"zh": manual_console_route_rows(zh_manual, "## 控制台总览"),
|
||||
"en": manual_console_route_rows(en_manual, "## Console Overview"),
|
||||
}
|
||||
|
||||
for lang, rows in manual_rows.items():
|
||||
missing = sorted(set(manifest) - set(rows))
|
||||
extra = sorted(set(rows) - set(manifest))
|
||||
if missing:
|
||||
fail(f"docs/technical/{lang}/manual.md console overview misses admin manifest route(s): " + ", ".join(missing))
|
||||
if extra:
|
||||
fail(f"docs/technical/{lang}/manual.md console overview lists route(s) missing from admin manifest: " + ", ".join(extra))
|
||||
|
||||
zh_rows = manual_rows["zh"]
|
||||
for path, expected_label in manifest.items():
|
||||
actual = zh_rows.get(path)
|
||||
if actual is None:
|
||||
continue
|
||||
if normalize_zh_label(actual) != normalize_zh_label(expected_label):
|
||||
fail(
|
||||
"docs/technical/zh/manual.md console overview label mismatch for "
|
||||
f"{path}: expected {expected_label!r}, got {actual!r}"
|
||||
)
|
||||
|
||||
|
||||
def extract_balanced(text: str, start: int, open_char: str, close_char: str) -> str:
|
||||
depth = 0
|
||||
quote: str | None = None
|
||||
escape = False
|
||||
for index in range(start, len(text)):
|
||||
char = text[index]
|
||||
if quote:
|
||||
if escape:
|
||||
escape = False
|
||||
elif char == "\\":
|
||||
escape = True
|
||||
elif char == quote:
|
||||
quote = None
|
||||
continue
|
||||
if char in ("'", '"', "`"):
|
||||
quote = char
|
||||
continue
|
||||
if char == open_char:
|
||||
depth += 1
|
||||
elif char == close_char:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[start:index + 1]
|
||||
raise ValueError(f"could not find balanced {open_char}{close_char} block")
|
||||
|
||||
|
||||
def find_balanced_after(text: str, marker: str, open_char: str, close_char: str) -> str:
|
||||
marker_index = text.index(marker)
|
||||
start = text.index(open_char, marker_index)
|
||||
return extract_balanced(text, start, open_char, close_char)
|
||||
|
||||
|
||||
def nesting_depth(text: str, stop: int, open_char: str, close_char: str) -> int:
|
||||
depth = 0
|
||||
quote: str | None = None
|
||||
escape = False
|
||||
for char in text[:stop]:
|
||||
if quote:
|
||||
if escape:
|
||||
escape = False
|
||||
elif char == "\\":
|
||||
escape = True
|
||||
elif char == quote:
|
||||
quote = None
|
||||
continue
|
||||
if char in ("'", '"', "`"):
|
||||
quote = char
|
||||
continue
|
||||
if char == open_char:
|
||||
depth += 1
|
||||
elif char == close_char:
|
||||
depth -= 1
|
||||
return depth
|
||||
|
||||
|
||||
def top_level_config_blocks(configs_block: str) -> dict[str, str]:
|
||||
blocks: dict[str, str] = {}
|
||||
index = 1
|
||||
while index < len(configs_block) - 1:
|
||||
match = re.search(r"\b([A-Za-z][A-Za-z0-9_]*)\s*:\s*\{", configs_block[index:])
|
||||
if not match:
|
||||
break
|
||||
name = match.group(1)
|
||||
start = index + match.end() - 1
|
||||
if nesting_depth(configs_block, start, "{", "}") != 1:
|
||||
index = start + 1
|
||||
continue
|
||||
block = extract_balanced(configs_block, start, "{", "}")
|
||||
blocks[name] = block
|
||||
index = start + len(block)
|
||||
return blocks
|
||||
|
||||
|
||||
def direct_section_keys(config_block: str) -> set[str]:
|
||||
sections_match = re.search(r"\bsections\s*:\s*\[", config_block)
|
||||
if not sections_match:
|
||||
return set()
|
||||
sections_block = extract_balanced(config_block, sections_match.end() - 1, "[", "]")
|
||||
keys: set[str] = set()
|
||||
index = 1
|
||||
while index < len(sections_block) - 1:
|
||||
match = re.search(r"\{\s*key\s*:\s*'([^']+)'", sections_block[index:])
|
||||
if not match:
|
||||
break
|
||||
start = index + match.start()
|
||||
if (
|
||||
nesting_depth(sections_block, start, "[", "]") == 1
|
||||
and nesting_depth(sections_block, start, "{", "}") == 0
|
||||
):
|
||||
keys.add(match.group(1))
|
||||
block = extract_balanced(sections_block, start, "{", "}")
|
||||
index = start + len(block)
|
||||
else:
|
||||
index = start + 1
|
||||
return keys
|
||||
|
||||
|
||||
def known_admin_sections() -> dict[str, set[str]]:
|
||||
plain_text = read_text("frontend/src/admin/pages/PlainResourcePages.tsx")
|
||||
admin_text = read_text("frontend/src/admin/AdminRoutes.tsx")
|
||||
|
||||
configs_block = find_balanced_after(plain_text, "const configs =", "{", "}")
|
||||
configs = top_level_config_blocks(configs_block)
|
||||
component_to_config = dict(re.findall(
|
||||
r"export function (\w+)\(\) \{\s*return <ModuleConsole config=\{configs\.([A-Za-z0-9_]+)\} />\s*\}",
|
||||
plain_text,
|
||||
))
|
||||
path_to_component = dict(re.findall(
|
||||
r'<Route\s+path="([^"]+)"\s+element=\{<([A-Za-z0-9_]+)\s*/>\}',
|
||||
admin_text,
|
||||
))
|
||||
|
||||
section_map: dict[str, set[str]] = {}
|
||||
for path, component in path_to_component.items():
|
||||
config_key = component_to_config.get(component)
|
||||
if not config_key:
|
||||
continue
|
||||
if config_key not in configs:
|
||||
fail(f"Admin route {path} uses unknown PlainResourcePages config: {config_key}")
|
||||
continue
|
||||
section_map[path] = direct_section_keys(configs[config_key])
|
||||
return section_map
|
||||
|
||||
|
||||
def check_documented_section_deep_links() -> None:
|
||||
section_map = known_admin_sections()
|
||||
pattern = re.compile(r"/[a-z][a-z0-9/-]*\?section=[a-z0-9_/-]+")
|
||||
docs = [
|
||||
*sorted((root / "docs/technical").glob("*/*.md")),
|
||||
*sorted((root / "docs/plans").glob("*.md")),
|
||||
]
|
||||
for doc in docs:
|
||||
text = doc.read_text(encoding="utf-8")
|
||||
for match in pattern.finditer(text):
|
||||
value = match.group(0)
|
||||
parsed = urlsplit(value)
|
||||
section = parse_qs(parsed.query).get("section", [""])[0]
|
||||
if parsed.path not in section_map:
|
||||
line_no = text.count("\n", 0, match.start()) + 1
|
||||
fail(f"{doc.relative_to(root)}:{line_no}: documented section link uses a route with no known sections: {value}")
|
||||
continue
|
||||
if section not in section_map[parsed.path]:
|
||||
line_no = text.count("\n", 0, match.start()) + 1
|
||||
known = ", ".join(sorted(section_map[parsed.path]))
|
||||
fail(f"{doc.relative_to(root)}:{line_no}: documented section link {value} is not a known section; expected one of: {known}")
|
||||
|
||||
|
||||
def check_documented_ui_routes() -> None:
|
||||
routes = known_frontend_routes()
|
||||
allowed_prefixes = (
|
||||
"/api/",
|
||||
"/ws",
|
||||
"/health",
|
||||
"/legacy/",
|
||||
"/earth/",
|
||||
"/docs/",
|
||||
"/assets/",
|
||||
"/components/",
|
||||
"/dev/",
|
||||
"/etc/",
|
||||
"/home/",
|
||||
"/tmp/",
|
||||
"/root",
|
||||
"/app/",
|
||||
"/planet",
|
||||
"/localhost",
|
||||
"/example",
|
||||
"/your-",
|
||||
)
|
||||
route_docs = [
|
||||
root / "docs/technical/zh/README.md",
|
||||
root / "docs/technical/en/README.md",
|
||||
root / "docs/technical/zh/manual.md",
|
||||
root / "docs/technical/en/manual.md",
|
||||
root / "docs/technical/zh/quickstart.md",
|
||||
root / "docs/technical/en/quickstart.md",
|
||||
root / "docs/technical/zh/frontend-admin-frontend-context.md",
|
||||
root / "docs/technical/en/frontend-admin-frontend-context.md",
|
||||
]
|
||||
route_pattern = re.compile(r"(?<![\w:_}-])/(?:[a-z][a-z0-9-]*)(?:/[a-z0-9:_-]+)*")
|
||||
for doc in route_docs:
|
||||
if not doc.exists():
|
||||
continue
|
||||
text = doc.read_text(encoding="utf-8")
|
||||
for candidate in sorted(set(route_pattern.findall(text))):
|
||||
if candidate in routes:
|
||||
continue
|
||||
if candidate.startswith(allowed_prefixes):
|
||||
continue
|
||||
if re.search(r"/(start|stop|restart|reset|status|stream|generate|cancel|tasks?|task-status|events)$", candidate):
|
||||
continue
|
||||
if re.fullmatch(r"/[a-z]{2,3}", candidate):
|
||||
continue
|
||||
if candidate == "/admin-next" or candidate.startswith("/admin-next/"):
|
||||
fail(f"{doc.relative_to(root)} references stale admin-next route {candidate}")
|
||||
elif candidate.startswith("/") and candidate.count("/") <= 2:
|
||||
warn(f"{doc.relative_to(root)} references route-like path not in current frontend routes: {candidate}")
|
||||
|
||||
|
||||
def check_stale_admin_doc_terms() -> None:
|
||||
stale_patterns = [
|
||||
(re.compile(r"React\s*\+\s*Ant Design"), "console frontend is no longer React + Ant Design"),
|
||||
(re.compile(r"Ant Design Pro"), "console frontend is no longer Ant Design Pro"),
|
||||
(re.compile(r"Old AntD legacy pages"), "old AntD legacy pages are not part of the active frontend"),
|
||||
(re.compile(r"Task Queue:\s*Celery"), "Celery is not part of the active local task stack"),
|
||||
(re.compile(r"Message Queue:\s*Kafka"), "Kafka is not part of the active local message stack"),
|
||||
(re.compile(r"UI Library:\s*Ant Design Pro"), "console frontend is no longer Ant Design Pro"),
|
||||
(re.compile(r"├── unreal/"), "UE5 is not an active checked-in local project tree"),
|
||||
(re.compile(r"Unreal Engine 5 3D visualization"), "UE5 is future/optional, not the active local visualization shell"),
|
||||
(re.compile(r"Polarized 3D large display \(4K, 120Hz\)"), "physical display work is future/optional, not the active local loop"),
|
||||
(re.compile(r"\?tab="), "admin deep links use ?section=, not ?tab="),
|
||||
]
|
||||
docs = [
|
||||
root / "AGENTS.md",
|
||||
root / "README.md",
|
||||
root / "project_context.md",
|
||||
*sorted((root / "docs/technical").glob("*/*.md")),
|
||||
*sorted((root / "docs/plans").glob("*.md")),
|
||||
]
|
||||
for doc in docs:
|
||||
text = doc.read_text(encoding="utf-8")
|
||||
for pattern, reason in stale_patterns:
|
||||
for match in pattern.finditer(text):
|
||||
line_no = text.count("\n", 0, match.start()) + 1
|
||||
fail(f"{doc.relative_to(root)}:{line_no}: stale admin documentation: {reason}")
|
||||
|
||||
|
||||
def check_harness_rule_coverage_notes() -> None:
|
||||
harness_doc = read_text("docs/HARNESS.md")
|
||||
audit_doc = read_text("docs/harness-audit.md")
|
||||
if "Rules Coverage Evidence" not in harness_doc:
|
||||
fail("docs/HARNESS.md must point frontend/docs audits to the Rules Coverage Evidence section")
|
||||
if "## Rules Coverage Evidence" not in audit_doc:
|
||||
fail("docs/harness-audit.md must keep the Rules Coverage Evidence section")
|
||||
|
||||
for module in ("core", "security", "workflow", "docs", "uiux", "frontend", "earth"):
|
||||
if f"| `{module}` |" not in audit_doc:
|
||||
fail(f"docs/harness-audit.md Rules Coverage Evidence must include the `{module}` rules module")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
check_docs_metadata_alignment()
|
||||
check_public_docs_registry()
|
||||
check_all_technical_docs_have_bilingual_pairs()
|
||||
check_bilingual_docs_are_not_copies()
|
||||
check_public_doc_links_exist()
|
||||
check_language_scoped_technical_links()
|
||||
check_public_doc_link_titles()
|
||||
check_credential_collector_contracts()
|
||||
check_manual_console_route_tables()
|
||||
check_documented_section_deep_links()
|
||||
check_documented_ui_routes()
|
||||
check_stale_admin_doc_terms()
|
||||
check_harness_rule_coverage_notes()
|
||||
|
||||
for message in warnings:
|
||||
print(f"warn: {message}")
|
||||
if failures:
|
||||
for message in failures:
|
||||
print(f"fail: {message}")
|
||||
raise SystemExit(f"docs consistency check failed: {len(failures)} failure(s), {len(warnings)} warning(s)")
|
||||
print(f"docs consistency check passed: {len(warnings)} warning(s)")
|
||||
|
||||
|
||||
main()
|
||||
PY
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
source "$ROOT_DIR/scripts/harness/lib.sh"
|
||||
|
||||
failures=0
|
||||
warnings=0
|
||||
|
||||
ok() {
|
||||
printf "ok: %s\n" "$1"
|
||||
}
|
||||
|
||||
warn() {
|
||||
warnings=$((warnings + 1))
|
||||
printf "warn: %s\n" "$1"
|
||||
}
|
||||
|
||||
fail() {
|
||||
failures=$((failures + 1))
|
||||
printf "fail: %s\n" "$1"
|
||||
}
|
||||
|
||||
check_cmd() {
|
||||
local cmd="$1"
|
||||
local found
|
||||
if found="$(harness_find_cmd "$cmd")"; then
|
||||
harness_prepend_tool_dir "$found"
|
||||
ok "found command: $cmd ($found)"
|
||||
else
|
||||
fail "missing required command: $cmd"
|
||||
fi
|
||||
}
|
||||
|
||||
check_optional_cmd() {
|
||||
local cmd="$1"
|
||||
local reason="$2"
|
||||
local found
|
||||
if found="$(harness_find_cmd "$cmd")"; then
|
||||
harness_prepend_tool_dir "$found"
|
||||
ok "found optional command: $cmd ($found)"
|
||||
else
|
||||
warn "missing optional command: $cmd ($reason)"
|
||||
fi
|
||||
}
|
||||
|
||||
check_file() {
|
||||
local path="$1"
|
||||
if [ -e "$ROOT_DIR/$path" ]; then
|
||||
ok "found file: $path"
|
||||
else
|
||||
fail "missing required file: $path"
|
||||
fi
|
||||
}
|
||||
|
||||
check_absent() {
|
||||
local path="$1"
|
||||
local reason="$2"
|
||||
if [ -e "$ROOT_DIR/$path" ]; then
|
||||
fail "unexpected file: $path ($reason)"
|
||||
else
|
||||
ok "absent as expected: $path"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
check_file README.md
|
||||
check_file rules.md
|
||||
check_file project_context.md
|
||||
check_file AGENTS.md
|
||||
check_file CODEMAP.md
|
||||
check_file docs/HARNESS.md
|
||||
check_file docs/harness-audit.md
|
||||
check_file docs/documentation-coverage-rules.md
|
||||
check_file planet.sh
|
||||
check_file pyproject.toml
|
||||
check_file frontend/package.json
|
||||
check_file scripts/harness/security-check.sh
|
||||
check_file scripts/harness/backend-rules-check.sh
|
||||
check_file scripts/harness/frontend-rules-check.sh
|
||||
check_file scripts/harness/docs-consistency-check.sh
|
||||
check_file scripts/harness/frontend-smoke.mjs
|
||||
check_file .gitea/workflows/ci.yaml
|
||||
|
||||
check_cmd git
|
||||
check_cmd zsh
|
||||
check_cmd uv
|
||||
check_cmd bun
|
||||
|
||||
check_optional_cmd docker "needed for local stack and optional image smoke builds"
|
||||
check_optional_cmd helm "needed for optional Helm delivery smoke checks"
|
||||
|
||||
check_absent frontend/package-lock.json "frontend package management is Bun-only"
|
||||
check_absent frontend/pnpm-lock.yaml "frontend package management is Bun-only"
|
||||
check_absent frontend/yarn.lock "frontend package management is Bun-only"
|
||||
check_absent agents.md "AGENTS.md is the single agent guide"
|
||||
|
||||
if [ ! -x "$ROOT_DIR/planet.sh" ]; then
|
||||
warn "planet.sh is not executable; run it with zsh or restore executable bit"
|
||||
else
|
||||
ok "planet.sh is executable"
|
||||
fi
|
||||
|
||||
if [ "$failures" -gt 0 ]; then
|
||||
printf "harness doctor failed: %d failure(s), %d warning(s)\n" "$failures" "$warnings"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf "harness doctor passed: %d warning(s)\n" "$warnings"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+465
@@ -0,0 +1,465 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
source "$ROOT_DIR/scripts/harness/lib.sh"
|
||||
|
||||
main() {
|
||||
cd "$ROOT_DIR"
|
||||
local uv_bin
|
||||
uv_bin="$(harness_require_tool uv)"
|
||||
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python - <<'PY'
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
root = Path.cwd()
|
||||
failures: list[str] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
failures.append(message)
|
||||
|
||||
|
||||
def warn(message: str) -> None:
|
||||
warnings.append(message)
|
||||
|
||||
|
||||
def read_text(path: str) -> str:
|
||||
return (root / path).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def check_package_manager() -> None:
|
||||
for path in ("package.json", "frontend/package.json"):
|
||||
payload = json.loads(read_text(path))
|
||||
package_manager = payload.get("packageManager", "")
|
||||
if not str(package_manager).startswith("bun@"):
|
||||
fail(f"{path}: packageManager must stay Bun-only, got {package_manager!r}")
|
||||
for script_name, command in payload.get("scripts", {}).items():
|
||||
if re.search(r"\b(npm|pnpm|yarn)\b", command):
|
||||
fail(f"{path} script {script_name!r} uses a forbidden package manager: {command}")
|
||||
|
||||
forbidden_lockfiles = [
|
||||
"frontend/package-lock.json",
|
||||
"frontend/pnpm-lock.yaml",
|
||||
"frontend/yarn.lock",
|
||||
]
|
||||
for path in forbidden_lockfiles:
|
||||
if (root / path).exists():
|
||||
fail(f"{path}: forbidden frontend lockfile; frontend package management is Bun-only")
|
||||
|
||||
|
||||
def extract_admin_routes() -> tuple[set[str], set[str]]:
|
||||
admin_routes_text = read_text("frontend/src/admin/AdminRoutes.tsx")
|
||||
manifest_text = read_text("frontend/src/admin/routes/manifest.tsx")
|
||||
route_paths = set(re.findall(r'<Route\s+path="([^"*][^"]*)"', admin_routes_text))
|
||||
route_paths.discard("*")
|
||||
manifest_paths = set(re.findall(r"path:\s*'([^']+)'", manifest_text))
|
||||
return route_paths, manifest_paths
|
||||
|
||||
|
||||
def check_route_manifest_consistency() -> None:
|
||||
route_paths, manifest_paths = extract_admin_routes()
|
||||
public_manifest_paths = {"/earth", "/docs"}
|
||||
redirect_only_routes = {"/alerts"}
|
||||
|
||||
missing_routes = sorted(manifest_paths - route_paths - public_manifest_paths)
|
||||
if missing_routes:
|
||||
fail(
|
||||
"admin route manifest points to paths that AdminRoutes does not render: "
|
||||
+ ", ".join(missing_routes)
|
||||
)
|
||||
|
||||
missing_manifest = sorted(route_paths - manifest_paths - redirect_only_routes)
|
||||
if missing_manifest:
|
||||
fail(
|
||||
"AdminRoutes renders paths that are missing from admin route manifest: "
|
||||
+ ", ".join(missing_manifest)
|
||||
)
|
||||
|
||||
|
||||
def known_frontend_routes() -> set[str]:
|
||||
app_text = read_text("frontend/src/App.tsx")
|
||||
admin_text = read_text("frontend/src/admin/AdminRoutes.tsx")
|
||||
manifest_text = read_text("frontend/src/admin/routes/manifest.tsx")
|
||||
routes = set(re.findall(r'<Route\s+path="([^"*][^"]*)"', app_text))
|
||||
routes.update(re.findall(r'<Route\s+path="([^"*][^"]*)"', admin_text))
|
||||
routes.update(re.findall(r"path:\s*'([^']+)'", manifest_text))
|
||||
routes.update({"/", "/docs/:slug"})
|
||||
routes.discard("*")
|
||||
routes.discard("/*")
|
||||
return routes
|
||||
|
||||
|
||||
def check_literal_internal_links() -> None:
|
||||
routes = known_frontend_routes()
|
||||
allowed_prefixes = (
|
||||
"/api/",
|
||||
"/ws",
|
||||
"/assets/",
|
||||
"/earth/",
|
||||
)
|
||||
literal_link_pattern = re.compile(r"\b(?:to|href)\s*=\s*['\"](/[^'\"#]+(?:#[^'\"]*)?)['\"]")
|
||||
for path in (root / "frontend/src").rglob("*.tsx"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
for match in literal_link_pattern.finditer(text):
|
||||
href = match.group(1)
|
||||
route_path = urlsplit(href).path
|
||||
if route_path in routes:
|
||||
continue
|
||||
if route_path.startswith("/docs/"):
|
||||
continue
|
||||
if any(route_path.startswith(prefix) for prefix in allowed_prefixes):
|
||||
continue
|
||||
line_no = jsx_line_number(text, match.start())
|
||||
fail(f"{rel}:{line_no}: literal internal link points to an unknown frontend route: {href}")
|
||||
|
||||
|
||||
def check_admin_search_route_targets() -> None:
|
||||
routes = known_frontend_routes()
|
||||
text = read_text("frontend/src/admin/search/indexers.ts")
|
||||
for match in re.finditer(r"\broutePath:\s*'([^']+)'", text):
|
||||
route_path = match.group(1)
|
||||
if route_path in routes:
|
||||
continue
|
||||
line_no = jsx_line_number(text, match.start())
|
||||
fail(
|
||||
"frontend/src/admin/search/indexers.ts:"
|
||||
f"{line_no}: admin search routePath points to an unknown frontend route: {route_path}"
|
||||
)
|
||||
|
||||
|
||||
def iter_frontend_src_files() -> list[Path]:
|
||||
return [
|
||||
path
|
||||
for path in (root / "frontend/src").rglob("*")
|
||||
if path.is_file() and path.suffix in {".ts", ".tsx", ".js", ".jsx", ".css"}
|
||||
]
|
||||
|
||||
|
||||
def collect_inline_style_context(lines: list[str], start_index: int) -> str:
|
||||
block = []
|
||||
for line in lines[start_index:start_index + 8]:
|
||||
block.append(line.strip())
|
||||
if "}}" in line or "} as CSSProperties" in line:
|
||||
break
|
||||
return " ".join(block)
|
||||
|
||||
|
||||
def inline_style_is_dynamic(context: str) -> bool:
|
||||
dynamic_needles = (
|
||||
"--",
|
||||
"CSSProperties",
|
||||
"transform:",
|
||||
"translate",
|
||||
"scale(",
|
||||
"width:",
|
||||
"height:",
|
||||
"thumbSize",
|
||||
"thumbOffset",
|
||||
"trackSize",
|
||||
"header.getSize",
|
||||
"summaryWidth",
|
||||
"detailWidth",
|
||||
"progress",
|
||||
"pan.x",
|
||||
"pan.y",
|
||||
"zoom",
|
||||
)
|
||||
return any(needle in context for needle in dynamic_needles)
|
||||
|
||||
|
||||
def iter_css_blocks(text: str) -> list[tuple[int, str, str]]:
|
||||
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
|
||||
blocks = []
|
||||
start_line = 1
|
||||
selector_lines = []
|
||||
body_lines = []
|
||||
in_block = False
|
||||
for line_no, line in enumerate(text.splitlines(), 1):
|
||||
if not in_block:
|
||||
selector_lines.append(line)
|
||||
if "{" in line:
|
||||
in_block = True
|
||||
start_line = line_no
|
||||
before, after = line.split("{", 1)
|
||||
selector_lines[-1] = before
|
||||
body_lines = [after]
|
||||
continue
|
||||
|
||||
if "}" in line:
|
||||
before, _after = line.split("}", 1)
|
||||
body_lines.append(before)
|
||||
blocks.append((start_line, " ".join(selector_lines).strip(), "\n".join(body_lines)))
|
||||
selector_lines = []
|
||||
body_lines = []
|
||||
in_block = False
|
||||
else:
|
||||
body_lines.append(line)
|
||||
return blocks
|
||||
|
||||
|
||||
def overflow_hidden_has_explicit_owner(selector: str, body: str) -> bool:
|
||||
owner_needles = (
|
||||
"min-height: 0",
|
||||
"height: 100%",
|
||||
"height: 100vh",
|
||||
"display: grid",
|
||||
"display: flex",
|
||||
"text-overflow: ellipsis",
|
||||
"border-radius:",
|
||||
"position: fixed",
|
||||
"position: absolute",
|
||||
"scrollbar",
|
||||
)
|
||||
selector_needles = (
|
||||
"html",
|
||||
"body",
|
||||
"#root",
|
||||
"tui-scrollbar",
|
||||
"table-scroll",
|
||||
"segmented-control__label",
|
||||
"docs-page",
|
||||
"docs-shell",
|
||||
"docs-content-layout",
|
||||
"docs-toc",
|
||||
"admin",
|
||||
"an-page",
|
||||
"an-resource",
|
||||
"an-data",
|
||||
"an-panel",
|
||||
"an-playground",
|
||||
"markdown-renderer",
|
||||
"meta",
|
||||
"select",
|
||||
)
|
||||
return any(needle in body for needle in owner_needles) or any(
|
||||
needle in selector for needle in selector_needles
|
||||
)
|
||||
|
||||
|
||||
def check_debug_output() -> None:
|
||||
for path in iter_frontend_src_files():
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
for line_no, line in enumerate(text.splitlines(), 1):
|
||||
if "console.log(" in line or re.search(r"\bdebugger\b", line):
|
||||
fail(f"{rel}:{line_no}: remove console.log/debugger from frontend source")
|
||||
if "console." in line and "token" in line.lower():
|
||||
fail(f"{rel}:{line_no}: console output must not include token material")
|
||||
|
||||
|
||||
def jsx_line_number(text: str, index: int) -> int:
|
||||
return text.count("\n", 0, index) + 1
|
||||
|
||||
|
||||
def iter_opening_tags(text: str, tag_name: str) -> list[tuple[int, str]]:
|
||||
tags: list[tuple[int, str]] = []
|
||||
needle = f"<{tag_name}"
|
||||
index = 0
|
||||
while True:
|
||||
start = text.find(needle, index)
|
||||
if start == -1:
|
||||
return tags
|
||||
next_char_index = start + len(needle)
|
||||
if next_char_index < len(text) and (text[next_char_index].isalnum() or text[next_char_index] in "_-"):
|
||||
index = next_char_index
|
||||
continue
|
||||
|
||||
quote: str | None = None
|
||||
brace_depth = 0
|
||||
cursor = next_char_index
|
||||
while cursor < len(text):
|
||||
char = text[cursor]
|
||||
if quote:
|
||||
if char == "\\":
|
||||
cursor += 2
|
||||
continue
|
||||
if char == quote:
|
||||
quote = None
|
||||
cursor += 1
|
||||
continue
|
||||
if char in ('"', "'", "`"):
|
||||
quote = char
|
||||
elif char == "{":
|
||||
brace_depth += 1
|
||||
elif char == "}":
|
||||
brace_depth = max(0, brace_depth - 1)
|
||||
elif char == ">" and brace_depth == 0:
|
||||
tags.append((start, text[start:cursor + 1]))
|
||||
index = cursor + 1
|
||||
break
|
||||
cursor += 1
|
||||
else:
|
||||
return tags
|
||||
|
||||
|
||||
def check_native_button_safety() -> None:
|
||||
for path in (root / "frontend/src").rglob("*.tsx"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
for start, tag in iter_opening_tags(text, "button"):
|
||||
line_no = jsx_line_number(text, start)
|
||||
if not re.search(r"\btype\s*=", tag):
|
||||
fail(f"{rel}:{line_no}: native <button> must declare an explicit type")
|
||||
if re.search(r"\bdisabled\s*=", tag) and re.search(r"\{\s*\.\.\.", tag):
|
||||
spread_index = tag.find("{...")
|
||||
disabled_index = tag.find("disabled")
|
||||
if disabled_index < spread_index:
|
||||
fail(
|
||||
f"{rel}:{line_no}: button disabled state can be overridden by a later props spread"
|
||||
)
|
||||
|
||||
|
||||
def check_icon_button_accessibility() -> None:
|
||||
for path in (root / "frontend/src").rglob("*.tsx"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
for start, tag in iter_opening_tags(text, "Button"):
|
||||
if not re.search(r"\bsize\s*=\s*['\"]icon['\"]", tag):
|
||||
continue
|
||||
if "aria-label" not in tag and "ariaLabel" not in tag:
|
||||
fail(f"{rel}:{jsx_line_number(text, start)}: icon Button must include aria-label")
|
||||
if not re.search(r"\btitle\s*=", tag):
|
||||
fail(f"{rel}:{jsx_line_number(text, start)}: icon Button must include title")
|
||||
|
||||
|
||||
def check_no_nested_cards() -> None:
|
||||
for path in (root / "frontend/src").rglob("*.tsx"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
depth = 0
|
||||
for match in re.finditer(r"</?Card\b", text):
|
||||
token = match.group(0)
|
||||
if token.startswith("</"):
|
||||
depth = max(0, depth - 1)
|
||||
continue
|
||||
line_no = jsx_line_number(text, match.start())
|
||||
if depth > 0:
|
||||
fail(f"{rel}:{line_no}: do not nest Card components inside other Cards")
|
||||
tag_end = text.find(">", match.start())
|
||||
tag = text[match.start():tag_end + 1] if tag_end != -1 else ""
|
||||
if not tag.rstrip().endswith("/>"):
|
||||
depth += 1
|
||||
|
||||
|
||||
def check_no_antd_layout_primitives() -> None:
|
||||
for path in (root / "frontend/src").rglob("*.tsx"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
if re.search(r"\bfrom\s+['\"]antd['\"]", text):
|
||||
fail(f"{rel}: active frontend must not import AntD; use Tactile UI/Radix project components")
|
||||
for match in re.finditer(r"<Space\b", text):
|
||||
line_no = jsx_line_number(text, match.start())
|
||||
fail(f"{rel}:{line_no}: avoid implicit Space layout primitives in height-critical UI")
|
||||
|
||||
|
||||
def check_connection_test_input_pattern() -> None:
|
||||
text = read_text("frontend/src/admin/pages/PlainResourcePages.tsx")
|
||||
if "function ConnectionTestInput" not in text:
|
||||
fail("AI/WebSearch connection tests must use the shared ConnectionTestInput pattern")
|
||||
|
||||
for label in ("测试 AI Provider 连通性", "测试 Web Search 连通性"):
|
||||
if re.search(rf"<Button\b(?=[^>]*\btitle=['\"]{re.escape(label)}['\"])", text):
|
||||
fail(f"{label}: connection test must be attached to the Base URL input suffix, not a standalone Button")
|
||||
|
||||
provider_pattern = re.compile(
|
||||
r"key:\s*'base_url'[\s\S]{0,260}inputAction:[\s\S]{0,260}"
|
||||
r"title:\s*'测试 AI Provider 连通性'",
|
||||
)
|
||||
if not provider_pattern.search(text):
|
||||
fail("AI Provider Base URL field must expose its connection test through inputAction")
|
||||
|
||||
web_pattern = re.compile(
|
||||
r"key:\s*'base_url'[\s\S]{0,320}disabled:\s*webSearchDisabled[\s\S]{0,260}"
|
||||
r"title:\s*'测试 Web Search 连通性'",
|
||||
)
|
||||
if not web_pattern.search(text):
|
||||
fail("WebSearch Base URL field must expose a disabled-aware connection test through inputAction")
|
||||
|
||||
|
||||
def check_uiux_static_warnings() -> None:
|
||||
viewport_font_pattern = re.compile(r"\b(?:font-size|fontSize)\s*[:=]\s*[^;\n}]*(?:vw|vmin|vmax|cqw|cqi)")
|
||||
letter_spacing_pattern = re.compile(r"\b(?:letter-spacing|letterSpacing)\s*[:=]\s*([^;\n}]+)")
|
||||
shell_viewport_height_pattern = re.compile(r"\b(?:height|min-height)\s*:\s*100v[hw]\s*;")
|
||||
for path in iter_frontend_src_files():
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
for match in viewport_font_pattern.finditer(text):
|
||||
line_no = jsx_line_number(text, match.start())
|
||||
fail(f"{rel}:{line_no}: font size must not scale with viewport width units under uiux rules")
|
||||
for match in letter_spacing_pattern.finditer(text):
|
||||
value = match.group(1).strip().strip("'\"")
|
||||
allowed = (
|
||||
value in {"0", "0em", "0rem", "normal", "inherit", "initial", "unset"}
|
||||
or re.fullmatch(r"var\([^,]+,\s*0(?:em|rem)?\s*\)", value)
|
||||
)
|
||||
if allowed:
|
||||
continue
|
||||
line_no = jsx_line_number(text, match.start())
|
||||
fail(f"{rel}:{line_no}: letter spacing must stay 0 under uiux rules, got {value!r}")
|
||||
if str(rel) in {"frontend/src/admin/styles.css", "frontend/src/pages/Docs/Docs.css"}:
|
||||
for match in shell_viewport_height_pattern.finditer(text):
|
||||
line_no = jsx_line_number(text, match.start())
|
||||
fail(
|
||||
f"{rel}:{line_no}: admin/docs shells must use the root 100% height chain, "
|
||||
"not exact 100vh/100vw sizing"
|
||||
)
|
||||
|
||||
if path.suffix == ".css":
|
||||
continue
|
||||
lines = text.splitlines()
|
||||
for line_no, line in enumerate(lines, 1):
|
||||
if "style={{" not in line:
|
||||
continue
|
||||
context = collect_inline_style_context(lines, line_no - 1)
|
||||
if not inline_style_is_dynamic(context):
|
||||
warn(f"{rel}:{line_no}: inline style found; rules prefer CSS classes unless values are truly dynamic")
|
||||
if re.search(r"\bas\s+any\b|<any>", text):
|
||||
warn(f"{rel}: broad TypeScript cast found; prefer specific types where practical")
|
||||
|
||||
for path in (root / "frontend/src").rglob("*.css"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
rel = path.relative_to(root)
|
||||
for line_no, selector, body in iter_css_blocks(text):
|
||||
if "overflow: hidden" not in body:
|
||||
continue
|
||||
if not overflow_hidden_has_explicit_owner(selector, body):
|
||||
warn(
|
||||
f"{rel}:{line_no}: overflow:hidden needs an explicit child scroll owner "
|
||||
f"or a documented clipping reason under uiux rules"
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
check_package_manager()
|
||||
check_route_manifest_consistency()
|
||||
check_literal_internal_links()
|
||||
check_admin_search_route_targets()
|
||||
check_debug_output()
|
||||
check_native_button_safety()
|
||||
check_icon_button_accessibility()
|
||||
check_no_nested_cards()
|
||||
check_no_antd_layout_primitives()
|
||||
check_connection_test_input_pattern()
|
||||
check_uiux_static_warnings()
|
||||
|
||||
for message in warnings:
|
||||
print(f"warn: {message}")
|
||||
if failures:
|
||||
for message in failures:
|
||||
print(f"fail: {message}")
|
||||
raise SystemExit(f"frontend rules check failed: {len(failures)} failure(s), {len(warnings)} warning(s)")
|
||||
print(f"frontend rules check passed: {len(warnings)} warning(s)")
|
||||
|
||||
|
||||
main()
|
||||
PY
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+1232
File diff suppressed because it is too large.
Load diff
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
harness_candidate_shells() {
|
||||
local shell
|
||||
local -a shells=()
|
||||
if [ -n "${SHELL:-}" ]; then
|
||||
shells+=("$SHELL")
|
||||
fi
|
||||
shells+=(zsh bash)
|
||||
|
||||
local seen=""
|
||||
for shell in "${shells[@]}"; do
|
||||
if [ -z "$shell" ]; then
|
||||
continue
|
||||
fi
|
||||
if ! command -v "$shell" >/dev/null 2>&1; then
|
||||
continue
|
||||
fi
|
||||
shell="$(command -v "$shell")"
|
||||
case ":$seen:" in
|
||||
*":$shell:"*) continue ;;
|
||||
esac
|
||||
seen="${seen:+$seen:}$shell"
|
||||
printf "%s\n" "$shell"
|
||||
done
|
||||
}
|
||||
|
||||
harness_find_cmd() {
|
||||
local cmd="$1"
|
||||
if [[ ! "$cmd" =~ ^[A-Za-z0-9_.+-]+$ ]]; then
|
||||
printf "invalid command name: %s\n" "$cmd" >&2
|
||||
return 2
|
||||
fi
|
||||
|
||||
local found=""
|
||||
found="$(command -v "$cmd" 2>/dev/null || true)"
|
||||
if [ -n "$found" ] && [ -x "$found" ]; then
|
||||
printf "%s\n" "$found"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local shell
|
||||
while IFS= read -r shell; do
|
||||
found="$("$shell" -lic "command -v $cmd" 2>/dev/null | sed -n '1p' || true)"
|
||||
if [ -n "$found" ] && [ -x "$found" ]; then
|
||||
printf "%s\n" "$found"
|
||||
return 0
|
||||
fi
|
||||
done < <(harness_candidate_shells)
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
harness_require_tool() {
|
||||
local cmd="$1"
|
||||
local found
|
||||
if ! found="$(harness_find_cmd "$cmd")"; then
|
||||
printf "missing required command: %s\n" "$cmd" >&2
|
||||
printf "looked in the current non-interactive PATH and login interactive shells\n" >&2
|
||||
return 1
|
||||
fi
|
||||
harness_prepend_tool_dir "$found"
|
||||
printf "%s\n" "$found"
|
||||
}
|
||||
|
||||
harness_prepend_tool_dir() {
|
||||
local path="$1"
|
||||
local dir
|
||||
dir="$(dirname "$path")"
|
||||
case ":$PATH:" in
|
||||
*":$dir:"*) ;;
|
||||
*)
|
||||
PATH="$dir:$PATH"
|
||||
export PATH
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
harness_run() {
|
||||
printf "+ %s\n" "$*" >&2
|
||||
"$@"
|
||||
}
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
source "$ROOT_DIR/scripts/harness/lib.sh"
|
||||
|
||||
main() {
|
||||
cd "$ROOT_DIR"
|
||||
local uv_bin
|
||||
uv_bin="$(harness_require_tool uv)"
|
||||
|
||||
harness_run scripts/harness/doctor.sh
|
||||
harness_run git diff --check
|
||||
harness_run zsh -n planet.sh
|
||||
harness_run bash -n scripts/bootstrap-dev.sh
|
||||
harness_run bash -n scripts/harness/lib.sh
|
||||
harness_run bash -n scripts/harness/doctor.sh
|
||||
harness_run bash -n scripts/harness/quick-check.sh
|
||||
harness_run bash -n scripts/harness/validate.sh
|
||||
harness_run bash -n scripts/harness/security-check.sh
|
||||
harness_run bash -n scripts/harness/backend-rules-check.sh
|
||||
harness_run bash -n scripts/harness/frontend-rules-check.sh
|
||||
harness_run bash -n scripts/harness/docs-consistency-check.sh
|
||||
harness_run scripts/harness/security-check.sh
|
||||
harness_run scripts/harness/backend-rules-check.sh
|
||||
harness_run scripts/harness/frontend-rules-check.sh
|
||||
harness_run scripts/harness/docs-consistency-check.sh
|
||||
|
||||
(
|
||||
cd "$ROOT_DIR/backend"
|
||||
harness_run "$uv_bin" run --frozen --group dev --project "$ROOT_DIR" python -m pytest -s \
|
||||
tests/test_api.py \
|
||||
tests/test_realtime_sources.py \
|
||||
-q
|
||||
)
|
||||
|
||||
printf "harness quick check passed\n"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
main() {
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
python - <<'PY'
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
root = Path.cwd()
|
||||
failures: list[str] = []
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
failures.append(message)
|
||||
|
||||
|
||||
tracked = subprocess.check_output(["git", "ls-files"], text=True).splitlines()
|
||||
for path in tracked:
|
||||
name = Path(path).name
|
||||
if name == ".env" or (name.startswith(".env.") and name not in {".env.example"}):
|
||||
fail(f"{path}: environment files must not be tracked")
|
||||
if re.search(r"\.(pem|key|p12|pfx)$", name):
|
||||
fail(f"{path}: private key/certificate material must not be tracked")
|
||||
|
||||
secret_patterns = [
|
||||
("private key block", re.compile(r"BEGIN [A-Z ]*PRIVATE KEY")),
|
||||
("AWS access key", re.compile(r"AKIA[0-9A-Z]{16}")),
|
||||
("Google API key", re.compile(r"AIza[0-9A-Za-z_-]{35}")),
|
||||
("OpenAI-style secret key", re.compile(r"sk-[A-Za-z0-9]{32,}")),
|
||||
("Slack token", re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}")),
|
||||
("GitHub token", re.compile(r"gh[pousr]_[A-Za-z0-9_]{30,}")),
|
||||
]
|
||||
skip_parts = {
|
||||
".git",
|
||||
".venv",
|
||||
"node_modules",
|
||||
"dist",
|
||||
"build",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
"__pycache__",
|
||||
}
|
||||
|
||||
for path in root.rglob("*"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
if skip_parts.intersection(path.relative_to(root).parts):
|
||||
continue
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
rel = path.relative_to(root)
|
||||
for label, pattern in secret_patterns:
|
||||
for match in pattern.finditer(text):
|
||||
line_no = text.count("\n", 0, match.start()) + 1
|
||||
fail(f"{rel}:{line_no}: possible {label} committed to repository")
|
||||
|
||||
if failures:
|
||||
for message in failures:
|
||||
print(f"fail: {message}")
|
||||
raise SystemExit(f"security check failed: {len(failures)} failure(s)")
|
||||
|
||||
print("security check passed")
|
||||
PY
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+119
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
source "$ROOT_DIR/scripts/harness/lib.sh"
|
||||
|
||||
DOCKER_SMOKE="${PLANET_HARNESS_DOCKER_SMOKE:-0}"
|
||||
FRONTEND_SMOKE="${PLANET_HARNESS_FRONTEND_SMOKE:-1}"
|
||||
FRONTEND_SMOKE_PORT="${PLANET_HARNESS_FRONTEND_SMOKE_PORT:-4173}"
|
||||
|
||||
run_helm_smoke_if_available() {
|
||||
local helm_bin
|
||||
if ! helm_bin="$(harness_find_cmd helm)"; then
|
||||
printf "warn: helm not found; skipping Helm lint/template smoke\n"
|
||||
return 0
|
||||
fi
|
||||
|
||||
harness_run "$helm_bin" lint deploy/helm/planet
|
||||
harness_run "$helm_bin" template planet-staging deploy/helm/planet \
|
||||
--namespace planet-staging \
|
||||
-f deploy/helm/planet/values.single-node.yaml \
|
||||
--set image.tag=harness-smoke >/tmp/planet-harness-rendered.yaml
|
||||
}
|
||||
|
||||
run_docker_smoke_if_requested() {
|
||||
case "$DOCKER_SMOKE" in
|
||||
1|true|yes|on)
|
||||
;;
|
||||
*)
|
||||
printf "info: Docker image smoke skipped; set PLANET_HARNESS_DOCKER_SMOKE=1 to enable\n"
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
local docker_bin
|
||||
if ! docker_bin="$(harness_find_cmd docker)"; then
|
||||
printf "fail: docker not found; cannot run requested image smoke builds\n"
|
||||
return 1
|
||||
fi
|
||||
|
||||
harness_run "$docker_bin" build -t planet-harness/frontend:smoke ./frontend
|
||||
harness_run "$docker_bin" build -t planet-harness/backend:smoke -f backend/Dockerfile .
|
||||
harness_run "$docker_bin" build -t planet-harness/aiprovider:smoke -f aiprovider/Dockerfile .
|
||||
}
|
||||
|
||||
wait_for_frontend_preview() {
|
||||
local bun_bin="$1"
|
||||
local url="$2"
|
||||
local attempts=60
|
||||
local index=0
|
||||
while [ "$index" -lt "$attempts" ]; do
|
||||
if PLANET_FRONTEND_SMOKE_URL="$url" "$bun_bin" -e \
|
||||
'fetch(process.env.PLANET_FRONTEND_SMOKE_URL).then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))' \
|
||||
>/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
index=$((index + 1))
|
||||
sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
run_frontend_smoke_if_enabled() {
|
||||
local bun_bin="$1"
|
||||
case "$FRONTEND_SMOKE" in
|
||||
0|false|no|off)
|
||||
printf "info: frontend Playwright smoke skipped; set PLANET_HARNESS_FRONTEND_SMOKE=1 to enable\n"
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
local url="http://127.0.0.1:${FRONTEND_SMOKE_PORT}"
|
||||
local log_path="/tmp/planet-harness-frontend-preview.log"
|
||||
(
|
||||
cd "$ROOT_DIR/frontend"
|
||||
"$bun_bin" ./node_modules/vite/bin/vite.js preview \
|
||||
--host 127.0.0.1 \
|
||||
--port "$FRONTEND_SMOKE_PORT" \
|
||||
--strictPort
|
||||
) >"$log_path" 2>&1 &
|
||||
local preview_pid=$!
|
||||
|
||||
if ! wait_for_frontend_preview "$bun_bin" "$url"; then
|
||||
printf "fail: frontend preview did not become ready at %s\n" "$url"
|
||||
printf "preview log: %s\n" "$log_path"
|
||||
kill "$preview_pid" >/dev/null 2>&1 || true
|
||||
wait "$preview_pid" >/dev/null 2>&1 || true
|
||||
return 1
|
||||
fi
|
||||
|
||||
local smoke_status=0
|
||||
PLANET_FRONTEND_SMOKE_URL="$url" harness_run "$bun_bin" "$ROOT_DIR/scripts/harness/frontend-smoke.mjs" || smoke_status=$?
|
||||
kill "$preview_pid" >/dev/null 2>&1 || true
|
||||
wait "$preview_pid" >/dev/null 2>&1 || true
|
||||
return "$smoke_status"
|
||||
}
|
||||
|
||||
main() {
|
||||
cd "$ROOT_DIR"
|
||||
local bun_bin
|
||||
bun_bin="$(harness_require_tool bun)"
|
||||
|
||||
harness_run scripts/harness/quick-check.sh
|
||||
|
||||
(
|
||||
cd "$ROOT_DIR/frontend"
|
||||
harness_run "$bun_bin" install --frozen-lockfile
|
||||
harness_run "$bun_bin" run build
|
||||
)
|
||||
|
||||
run_frontend_smoke_if_enabled "$bun_bin"
|
||||
run_helm_smoke_if_available
|
||||
run_docker_smoke_if_requested
|
||||
|
||||
printf "harness validation passed\n"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Reference in new issue
Block a user