Compare commits

..
2 Commits
Author SHA1 Message Date
linkong 2c439b7235 release: bump version to 0.80.2
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-30 11:06:33 +08:00
linkong 4b2004b7d8 release: bump version to 0.80.1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-26 19:41:17 +08:00
43 changed files with 3155 additions and 375 deletions

No files matched your search

+14 -5
View File
@@ -180,13 +180,22 @@ Push to remote:
When remote publication is requested, verify the remote tag points to the
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
using the command below. The publisher builds the three production images and
the desktop packages from the tag. A published stable release triggers the
server's two-minute Compose deployment check. The workstation can go offline
after publication. Check the live update manifest and the running image digests
before reporting production deployment complete.
using the command below. The publisher inspects changed files against the previous
stable release (`scripts/release_scope.py`), writes `release-manifest.json`, and
builds/uploads **only** the affected targets:
- `admin` / `backend` / `aiprovider`-only changes: builds/pushes only the changed
service image(s), skips desktop packaging and client hotfix updates, and deploys
only the changed container(s) on production.
- `frontend/public/earth/**`-only changes: emits only the L1 Earth hotfix bundle
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`.
- `client/**` changes: builds cross-platform desktop installers (`--all`) plus the
L1 hotfix bundle.
Use `--scope auto` (default) or override explicitly with `--scope admin`,
`--scope hotfix`, `--scope backend,admin`, or `--scope full`:
```bash
python3 scripts/release_publish.py --tag vx.x.x --dry-run
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
```
+6
View File
@@ -98,6 +98,12 @@ the user's login interactive shell instead of assuming a specific dotfile.
one-screen (`一屏` / `首屏`) height chain: route roots use `height: 100%`,
intermediate wrappers keep `min-height: 0`, and only the intended child owns
scrolling.
- **Admin Control Design Contract**: Inline controls in the same row must share
a `rules.md` density tier (`--an-control-xs/sm/md/lg`, e.g., `32px` filter bar
with `0px` height jump on filter reset), centered table selection/switch
columns, rounded-square shadowless `.tui-switch`, labeled `操作` columns, and
`.an-detail-link` navigation cues; enforced by
`scripts/harness/frontend-rules-check.sh` and `scripts/harness/frontend-smoke.mjs`.
- **Existing-UI Context Inspection Before Editing**: Whenever changing or
extending an existing interface (any non-new screen, such as `/earth/` HUD
overlays or existing Admin/Docs pages), inspect surrounding sibling controls,
+1 -1
View File
@@ -1 +1 @@
0.80.0
0.80.2
+161 -18
View File
@@ -7,7 +7,7 @@ from sqlalchemy import func, or_, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.core.enums import JobStatus, SnapshotStatus
from app.core.enums import JobStatus, SnapshotStatus, UserRole
from app.core.time import to_iso8601_utc
from app.core.security import get_current_user
from app.core.data_sources import get_data_sources_config
@@ -39,6 +39,7 @@ from app.services.business_logs import emit_business_log
router = APIRouter()
logger = get_logger(__name__, service="api")
STALE_RUNNING_TASK_TIMEOUT_MINUTES = 90
DATASOURCE_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
@@ -65,6 +66,20 @@ class DatasourceBatchTriggerRequest(BaseModel):
q: Optional[str] = None
class DatasourceBatchStatusRequest(BaseModel):
source_ids: list[int] = Field(min_length=1, max_length=500)
is_active: bool
def _require_datasource_admin(current_user: User) -> None:
role = getattr(current_user.role, "value", current_user.role)
if role not in DATASOURCE_ADMIN_ROLES:
raise HTTPException(
status_code=403,
detail="Only administrators can change datasource scheduling",
)
def format_frequency_label(minutes: int) -> str:
if minutes % 1440 == 0:
return f"{minutes // 1440}d"
@@ -353,6 +368,78 @@ def serialize_datasource_row(
return row
async def _serialize_datasource_rows(
db: AsyncSession,
datasources: list[DataSource],
) -> list[dict]:
if not datasources:
return []
config = get_data_sources_config()
running_tasks, latest_tasks, endpoint_overrides = await _load_datasource_list_context(
db,
datasources,
include_endpoint=False,
)
record_counts = await _load_collected_record_counts(
db, [datasource.source for datasource in datasources]
)
return [
serialize_datasource_row(
datasource,
running_tasks=running_tasks,
latest_tasks=latest_tasks,
record_counts=record_counts,
endpoint_overrides=endpoint_overrides,
config=config,
include_endpoint=False,
)
for datasource in datasources
]
async def _load_datasource_status_counts(db: AsyncSession) -> dict[str, int]:
result = await db.execute(
select(DataSource.is_active, func.count(DataSource.id)).group_by(DataSource.is_active)
)
active = 0
inactive = 0
for is_active, count in result.all():
if is_active:
active += int(count or 0)
else:
inactive += int(count or 0)
return {"all": active + inactive, "active": active, "inactive": inactive}
async def _apply_datasource_activation(
db: AsyncSession,
datasources: list[DataSource],
is_active: bool,
) -> tuple[list[DataSource], list[int]]:
"""Persist scheduling state, then reconcile scheduler jobs for changed rows only."""
changed = [datasource for datasource in datasources if bool(datasource.is_active) != is_active]
for datasource in changed:
datasource.is_active = is_active
if changed:
await db.commit()
sync_failed: list[int] = []
for datasource in changed:
try:
await sync_datasource_job(datasource.id)
except Exception as exc:
sync_failed.append(datasource.id)
logger.warning_event(
"Datasource scheduler sync failed",
event="collector.schedule.sync_failed",
context={
"datasource_id": datasource.id,
"source": datasource.source,
"error_type": type(exc).__name__,
},
)
return changed, sync_failed
def _apply_datasource_query_filters(
query,
*,
@@ -817,7 +904,55 @@ async def list_datasources(
)
)
return {"total": len(collector_list), "data": collector_list}
return {
"total": len(collector_list),
"data": collector_list,
"counts": await _load_datasource_status_counts(db),
}
@router.post("/batch-status")
async def update_datasource_batch_status(
payload: DatasourceBatchStatusRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_datasource_admin(current_user)
requested_ids = list(dict.fromkeys(payload.source_ids))
result = await db.execute(
select(DataSource)
.where(DataSource.id.in_(requested_ids))
.order_by(DataSource.module, DataSource.id)
)
datasources = list(result.scalars().all())
found_ids = {datasource.id for datasource in datasources}
changed, sync_failed = await _apply_datasource_activation(db, datasources, payload.is_active)
changed_ids = {datasource.id for datasource in changed}
await emit_business_log(
logger,
event="collector.schedule.batch_status",
message="Datasource scheduling batch update completed",
category="collector",
service="api",
module=__name__,
user_id=current_user.id,
context={
"is_active": payload.is_active,
"requested_count": len(requested_ids),
"updated_count": len(changed),
"sync_failed_count": len(sync_failed),
},
)
return {
"is_active": payload.is_active,
"updated": await _serialize_datasource_rows(db, changed),
"unchanged": [
datasource.id for datasource in datasources if datasource.id not in changed_ids
],
"not_found": [source_id for source_id in requested_ids if source_id not in found_ids],
"sync_failed": sync_failed,
"counts": await _load_datasource_status_counts(db),
}
@router.post("/trigger-all")
@@ -987,20 +1122,35 @@ async def get_datasource_row(
}
async def _set_single_datasource_active(
db: AsyncSession,
source_id: str,
current_user: User,
is_active: bool,
) -> dict:
_require_datasource_admin(current_user)
datasource = await get_datasource_record(db, source_id)
if not datasource:
raise HTTPException(status_code=404, detail="Data source not found")
_changed, sync_failed = await _apply_datasource_activation(db, [datasource], is_active)
rows = await _serialize_datasource_rows(db, [datasource])
return {
"status": "enabled" if is_active else "disabled",
"source_id": datasource.id,
"data": rows[0] if rows else None,
"sync_failed": bool(sync_failed),
"counts": await _load_datasource_status_counts(db),
}
@router.post("/{source_id}/enable")
async def enable_datasource(
source_id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
datasource = await get_datasource_record(db, source_id)
if not datasource:
raise HTTPException(status_code=404, detail="Data source not found")
datasource.is_active = True
await db.commit()
await sync_datasource_job(datasource.id)
return {"status": "enabled", "source_id": datasource.id}
return await _set_single_datasource_active(db, source_id, current_user, True)
@router.post("/{source_id}/disable")
@@ -1009,14 +1159,7 @@ async def disable_datasource(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
datasource = await get_datasource_record(db, source_id)
if not datasource:
raise HTTPException(status_code=404, detail="Data source not found")
datasource.is_active = False
await db.commit()
await sync_datasource_job(datasource.id)
return {"status": "disabled", "source_id": datasource.id}
return await _set_single_datasource_active(db, source_id, current_user, False)
@router.get("/{source_id}/stats")
+129
View File
@@ -1,6 +1,10 @@
import asyncio
import inspect
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from app.api.v1 import datasources as datasources_api
from app.models.datasource import DataSource
@@ -219,3 +223,128 @@ def test_trigger_datasource_batch_skips_disabled_and_frequency_window(monkeypatc
assert queued_sources == ["ris_live_bgp"]
asyncio.run(run())
class _CommitDb:
def __init__(self, datasources=None):
self.commits = 0
self.datasources = list(datasources or [])
async def commit(self):
self.commits += 1
async def execute(self, _query):
datasources = self.datasources
class _Result:
def scalars(self):
return self
def all(self):
return datasources
return _Result()
def _patch_row_helpers(monkeypatch, synced: list[int]):
async def fake_sync(datasource_id):
synced.append(datasource_id)
async def fake_rows(_db, datasources):
return [{"id": item.id, "source": item.source, "is_active": item.is_active} for item in datasources]
async def fake_counts(_db):
return {"all": 3, "active": 2, "inactive": 1}
monkeypatch.setattr(datasources_api, "sync_datasource_job", fake_sync)
monkeypatch.setattr(datasources_api, "_serialize_datasource_rows", fake_rows)
monkeypatch.setattr(datasources_api, "_load_datasource_status_counts", fake_counts)
def test_activation_only_commits_and_syncs_changed_sources(monkeypatch):
async def run():
synced: list[int] = []
_patch_row_helpers(monkeypatch, synced)
db = _CommitDb()
enabled = make_datasource(1, "arcgis_cables", is_active=True)
disabled = make_datasource(2, "ris_live_bgp", is_active=False)
changed, failed = await datasources_api._apply_datasource_activation(db, [enabled, disabled], True)
assert [item.id for item in changed] == [2]
assert disabled.is_active is True
assert failed == []
assert synced == [2]
assert db.commits == 1
unchanged, _ = await datasources_api._apply_datasource_activation(db, [enabled], True)
assert unchanged == []
assert db.commits == 1
asyncio.run(run())
def test_batch_status_reports_updated_unchanged_and_missing(monkeypatch):
async def run():
synced: list[int] = []
_patch_row_helpers(monkeypatch, synced)
already = make_datasource(1, "arcgis_cables", is_active=True)
target = make_datasource(2, "ris_live_bgp", is_active=False)
db = _CommitDb([already, target])
admin = SimpleNamespace(id=9, role="admin")
result = await datasources_api.update_datasource_batch_status(
datasources_api.DatasourceBatchStatusRequest(source_ids=[1, 2, 2, 99], is_active=True),
current_user=admin,
db=db,
)
assert [row["id"] for row in result["updated"]] == [2]
assert result["updated"][0]["is_active"] is True
assert result["unchanged"] == [1]
assert result["not_found"] == [99]
assert result["sync_failed"] == []
assert result["counts"] == {"all": 3, "active": 2, "inactive": 1}
assert synced == [2]
asyncio.run(run())
def test_scheduling_changes_require_admin(monkeypatch):
async def run():
_patch_row_helpers(monkeypatch, [])
viewer = SimpleNamespace(id=5, role="viewer")
with pytest.raises(HTTPException) as batch_error:
await datasources_api.update_datasource_batch_status(
datasources_api.DatasourceBatchStatusRequest(source_ids=[1], is_active=False),
current_user=viewer,
db=_CommitDb(),
)
with pytest.raises(HTTPException) as single_error:
await datasources_api.enable_datasource("1", current_user=viewer, db=_CommitDb())
assert batch_error.value.status_code == 403
assert single_error.value.status_code == 403
asyncio.run(run())
def test_single_toggle_returns_row_and_counts(monkeypatch):
async def run():
synced: list[int] = []
_patch_row_helpers(monkeypatch, synced)
datasource = make_datasource(4, "ris_live_bgp", is_active=False)
async def fake_record(_db, _source_id):
return datasource
monkeypatch.setattr(datasources_api, "get_datasource_record", fake_record)
result = await datasources_api.enable_datasource(
"4", current_user=SimpleNamespace(id=1, role="super_admin"), db=_CommitDb()
)
assert result["status"] == "enabled"
assert result["data"] == {"id": 4, "source": "ris_live_bgp", "is_active": True}
assert result["counts"]["active"] == 2
assert synced == [4]
asyncio.run(run())
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-client",
"version": "0.80.0",
"version": "0.80.2",
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true,
"packageManager": "bun@1",
@@ -37,6 +37,7 @@
"start": "bun run build && bun ./scripts/launch-electron.mjs",
"dev": "bun run build && bun ./scripts/launch-electron.mjs --devtools",
"dist:dir": "bun run build && bun ./scripts/dist-target.mjs --dir",
"dist:hotfix": "bun run build:earth",
"dist:win": "bun run build && bun ./scripts/dist-target.mjs --win",
"dist:linux": "bun run build && bun ./scripts/dist-target.mjs --linux",
"dist:mac": "bun run build && bun ./scripts/dist-target.mjs --mac",
+82 -30
View File
@@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process'
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
@@ -129,43 +130,87 @@ function resolveLinuxTargets() {
return targets
}
function runWinViaWindowsHost() {
if (!isWsl()) return false
const winProbeScript = [
'$candidates = @(',
' (Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),',
' (Join-Path $env:USERPROFILE ".bun\\bin\\bun.exe"),',
' (Join-Path $env:USERPROFILE "scoop\\shims\\bun.exe"),',
' (Join-Path $env:LOCALAPPDATA "bun\\bin\\bun.exe")',
') | Where-Object { $_ -and (Test-Path -LiteralPath $_) }',
'$candidates | Select-Object -First 1',
].join('; ')
const winBunCheck = spawnSync('powershell.exe', ['-NoProfile', '-Command', winProbeScript], { encoding: 'utf8' })
const winBunPath = (winBunCheck.stdout || '').trim().split(/\r?\n/)[0]?.trim() || ''
const winPathRes = spawnSync('wslpath', ['-w', desktopRoot], { encoding: 'utf8' })
const winDesktopRoot = (winPathRes.stdout || '').trim()
if (winBunCheck.status !== 0 || !winBunPath || !winDesktopRoot) return false
console.log(`WSL2 detected; building Windows NSIS + portable installers via Windows host Bun (${winBunPath})...`)
const psScript = [
"$ErrorActionPreference = 'Stop'",
`$env:ELECTRON_MIRROR = '${env.ELECTRON_MIRROR}'`,
`$env:ELECTRON_BUILDER_BINARIES_MIRROR = '${env.ELECTRON_BUILDER_BINARIES_MIRROR}'`,
`Set-Location -LiteralPath '${winDesktopRoot.replace(/'/g, "''")}'`,
`& '${winBunPath.replace(/'/g, "''")}' x electron-builder --win nsis portable --publish never`,
].join('; ')
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], { stdio: 'inherit' })
return (winRun.status ?? 1) === 0
}
function runWinViaDockerWine() {
if (!hasCommand('docker')) return false
const image = process.env.PLANET_ELECTRON_BUILDER_IMAGE || 'electronuserland/builder:wine'
const home = homedir()
const electronCache = join(home, '.cache', 'electron')
const builderCache = join(home, '.cache', 'electron-builder')
mkdirSync(electronCache, { recursive: true })
mkdirSync(builderCache, { recursive: true })
const uid = typeof process.getuid === 'function' ? process.getuid() : 0
const gid = typeof process.getgid === 'function' ? process.getgid() : 0
console.log(`Building Windows NSIS + portable installers via Docker Wine (${image})...`)
const dockerCmd = [
'run', '--rm',
'-v', `${desktopRoot}:/project`,
'-v', `${electronCache}:/root/.cache/electron`,
'-v', `${builderCache}:/root/.cache/electron-builder`,
'-e', `ELECTRON_MIRROR=${env.ELECTRON_MIRROR}`,
'-e', `ELECTRON_BUILDER_BINARIES_MIRROR=${env.ELECTRON_BUILDER_BINARIES_MIRROR}`,
'-w', '/project',
image,
'bash', '-lc',
`./node_modules/.bin/electron-builder --win nsis portable --publish never; status=$?; chown -R ${uid}:${gid} /project/release 2>/dev/null || true; exit $status`,
]
const res = spawnSync('docker', dockerCmd, { stdio: 'inherit' })
return (res.status ?? 1) === 0
}
function runWinBuild() {
if (process.platform === 'win32' || hasCommand('wine') || hasCommand('wine64')) {
runBuilder(['--win', 'nsis', 'portable'])
return
}
if (isWsl()) {
const winBunCheck = spawnSync(
'powershell.exe',
['-NoProfile', '-Command', 'Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source'],
{ encoding: 'utf8' },
)
const winBunPath = (winBunCheck.stdout || '').trim()
const winPathRes = spawnSync('wslpath', ['-w', desktopRoot], { encoding: 'utf8' })
const winDesktopRoot = (winPathRes.stdout || '').trim()
if (winBunCheck.status === 0 && winBunPath && winDesktopRoot) {
console.log('WSL2 detected without Wine; building Windows installers via Windows host toolchain...')
const psScript = [
"$ErrorActionPreference = 'Stop'",
`$env:ELECTRON_MIRROR = '${env.ELECTRON_MIRROR}'`,
`$env:ELECTRON_BUILDER_BINARIES_MIRROR = '${env.ELECTRON_BUILDER_BINARIES_MIRROR}'`,
`Set-Location -LiteralPath '${winDesktopRoot.replace(/'/g, "''")}'`,
'bun x electron-builder --win nsis portable --publish never',
].join('; ')
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], {
stdio: 'inherit',
})
if ((winRun.status ?? 1) === 0) {
return
}
console.warn('Windows host build fell back to unpacked/zip cross-build without Wine.')
}
} else {
console.warn('Wine not available on Linux host: building standalone Windows zip bundle (win-unpacked + zip).')
if (runWinViaWindowsHost()) {
return
}
runBuilder(['--win', 'zip', '--config.win.signAndEditExecutable=false'])
if (runWinViaDockerWine()) {
return
}
if (process.env.PLANET_ALLOW_WIN_ZIP_FALLBACK === '1') {
console.warn('PLANET_ALLOW_WIN_ZIP_FALLBACK=1 set without Wine/Docker/Windows Bun: building win zip without NSIS .exe.')
runBuilder(['--win', 'zip', '--config.win.signAndEditExecutable=false'])
return
}
console.error(
'Unable to build Windows NSIS (.exe) installer: install Wine (wine64), enable Docker (electronuserland/builder:wine), or install Windows bun.exe (or set PLANET_ALLOW_WIN_ZIP_FALLBACK=1 for zip-only).',
)
process.exit(1)
}
function runMacBuild() {
@@ -177,7 +222,14 @@ function runMacBuild() {
}
}
if (mode === '--dir') {
if (mode === '--hotfix') {
const result = spawnSync(process.execPath, [join(__dirname, 'build-earth-bundle.mjs')], {
cwd: desktopRoot,
env,
stdio: 'inherit',
})
process.exit(result.status ?? 1)
} else if (mode === '--dir') {
runBuilder(['--dir'])
} else if (mode === '--linux') {
runBuilder(['--linux', ...resolveLinuxTargets()])
+23
View File
@@ -8,6 +8,29 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [0.80.2] — 2026-11-30
Released: 2026-11-30
### Highlights
- Admin standardizes control density/radius CSS tokens (`--an-control-*`), aligns datasource filter bars (`32px` with `0px` reset jump), selection checkboxes, and shadowless rounded-square switches, and enforces the layout contract in static + Playwright harness checks.
- Desktop client local packaging aligns cross-platform Windows `.exe` builds (`dist-target.mjs` 3-tier detection + `--hotfix` bundle), while release publishing and production deployment classify changes by scope (`release_scope.py` + `release-manifest.json`) so Admin/Backend/AIProvider rollouts never trigger unnecessary client rebuilds.
---
## [0.80.1] — 2026-11-26
Released: 2026-11-26
### Highlights
- Admin supports enabling or disabling schedules for selected data sources. Changing a schedule leaves manual collection as a separate action.
- The data source list remembers filters and updates rows and counts in place. At narrow desktop widths, opening a detail panel switches views to preserve space for the table.
- Earth information, compute and regional news cards use overlay scrollbars. The AI workbench preserves the conversation scroll position while rendering updates and retries a failed turn in place.
---
## [0.80.0] — 2026-11-26
Released: 2026-11-26
+9 -4
View File
@@ -94,7 +94,7 @@ elevated restart; report that separately when it has not been exercised.
| 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, Earth HUD baseline shell/glow/translucency/focus-stack alignment, and high-signal UI rule warnings. |
| 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, Admin control design contract (`--an-control-*`, checkbox centering, switch `box-shadow: none`, segmented transparent borders, `DataTable` `data-column-id`), viewport-scaled font sizes, zero letter spacing, Earth HUD baseline shell/glow/translucency/focus-stack alignment, 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, and documented `?section=` deep-link validity against the actual admin section config in technical docs and active plan docs. |
| Quick | `scripts/harness/quick-check.sh` | Runs doctor, whitespace diff check, shell syntax checks, isolated Docker bootstrap/proxy and startup tests, error-catalog consistency tests, 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. |
@@ -327,9 +327,14 @@ No automatic hooks are installed in this phase. Manual reminders:
### 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.
Use `.codex/skills/release/SKILL.md`, `scripts/release_scope.py`,
`scripts/release_publish.py`, and `.gitea/workflows/` files. Tagged releases
classify changed paths into scoped images (`admin`, `backend`, `aiprovider`)
and client modes (`none`, `hotfix`, `full`) in `release-manifest.json`, so
admin-only or backend-only releases never rebuild desktop clients or restart
unchanged services. Harness validation can smoke-check Helm and Docker locally,
and `scripts/harness/test_production_release.py` covers scoped release/deploy
logic without replacing the release process.
## Implementation Notes
+6
View File
@@ -464,6 +464,12 @@ POST /api/v1/datasources/trigger-batch
The request body may pass `source_ids` for selected rows. Without `source_ids`, the backend filters by `product`, `module`, `is_active`, `run_status`, `collected`, `credential_status`, and `q`. The endpoint skips disabled sources, sources already running without `force`, and sources still inside their frequency window, then returns `triggered`, `skipped`, and `failed` groups.
### Scheduling switch
`POST /api/v1/datasources/{id}/enable` and `/disable` change only whether the scheduler runs a source; they never start a collection. `POST /api/v1/datasources/batch-status` takes `{source_ids, is_active}` and returns `updated` rows, `unchanged` and `not_found` IDs, `sync_failed` scheduler IDs, and global `counts`. All three require admin or super_admin. Only rows whose state actually changes are committed and resynchronized with the scheduler; running tasks continue after a disable. The list endpoint also returns `counts: {all, active, inactive}`, unaffected by filters.
Admin applies these responses to the affected rows without reloading the list. Rows that stop matching the current filter stay dimmed until the next reload. Collection Management uses the same switch in the scheduling panel heading, while draft saves only change frequency, priority, and storage policy.
**Core file**: `backend/app/api/v1/datasources.py`
## Compute source contracts and topic APIs
+6
View File
@@ -494,6 +494,12 @@ POST /api/v1/datasources/trigger-batch
请求体可以传 `source_ids` 精确触发选中项;如果不传 `source_ids`,后端按 `product`、`module`、`is_active`、`run_status`、`collected`、`credential_status` 和 `q` 过滤后触发。接口会跳过禁用源、正在运行且未 `force` 的源,以及未到频率窗口的源,并返回 `triggered`、`skipped`、`failed` 三组结果。
### 调度开关
`POST /api/v1/datasources/{id}/enable` 与 `/disable` 只改变数据源是否参与定时调度,不会立即发起采集。`POST /api/v1/datasources/batch-status` 接收 `{source_ids, is_active}`,返回 `updated`(最新行数据)、`unchanged`、`not_found`、`sync_failed`(调度同步失败的 ID)以及全局 `counts`。三个接口都需要 admin 或 super_admin。只有状态确实变化的数据源会提交并重新同步调度器;停用不会中断运行中的任务。列表接口同时返回不受筛选影响的 `counts: {all, active, inactive}`。
控制台用这些响应原地更新受影响的行,不重新加载列表;不再符合当前筛选的行变暗保留,下次刷新时移出。采集管理的“采集调度”在面板标题处使用同一开关,草稿保存只修改频率、优先级和存储策略。
**核心文件**: `backend/app/api/v1/datasources.py`
## 算力来源合同与专题接口
+3 -1
View File
@@ -16,12 +16,14 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.80.0`
- `dev` 当前开发分支历史推导到:`0.80.2`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `0.80.2` | improvement | `dev` | `v0.80.2` | 统一 Admin 控件设计参数与 Harness 校验,支持本地客户端全平台打包及按改动范围分层发版部署 |
| `0.80.1` | improvement | `dev` | `v0.80.1` | 数据源支持批量启停调度、保留筛选和就地更新,优化 Earth 卡片与 AI 对话滚动 |
| `0.80.0` | feature | `dev` | `v0.80.0` | Earth AI 工作台支持流式多轮对话和本地会话,新增单摄手势控制与公共模型目录批量刷新 |
| `0.79.2` | improvement | `dev` | `v0.79.2` | 卫星目录支持紧凑传输、本地缓存和后台校验,改进桌面客户端启动时的窗口尺寸恢复 |
| `0.79.1` | improvement | `dev` | `v0.79.1` | Windows 根据显存与帧率自动切换显卡,保留 45 秒切换冷却与窗口状态,统一 IMI 英文名称 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.80.0",
"version": "0.80.2",
"private": true,
"packageManager": "bun@1",
"dependencies": {
@@ -770,9 +770,17 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
padding: 0 calc(14px * var(--hud-scale)) calc(12px * var(--hud-scale));
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: none;
-ms-overflow-style: none;
max-height: min(var(--hud-body-content-height, calc(460px * var(--hud-scale))), calc(100vh - calc(252px * var(--hud-scale))));
}
.compute-card__body::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
.compute-card.hud-panel--collapsed {
min-height: calc(154px * var(--hud-scale));
height: auto !important;
+1 -1
View File
@@ -5073,7 +5073,7 @@ label.is-disabled.earth-mobile-settings-card {
.satellite-map-label small { font-size:10px; font-weight:400; color:#cbd5e1; }
/* Only aggregate/expanded points use DOM; ordinary markers stay GPU-batched. */
.map-clusters { position:absolute; inset:0; pointer-events:none; z-index:8; }
.map-clusters { position:absolute; inset:0; pointer-events:none; z-index:5; }
.map-clusters__legs { position:absolute; inset:0; width:100%; height:100%; overflow:visible; pointer-events:none; }
.map-clusters__legs line { stroke:#94a3b8; stroke-width:1; }
.map-cluster-badge { position:absolute; width:26px; height:26px; padding:0; display:grid; place-items:center;
+44 -12
View File
@@ -250,11 +250,11 @@
opacity: 0;
pointer-events: none;
transition: opacity 0.22s ease;
z-index: 6;
z-index: 9;
}
.callout-connector.is-rear {
z-index: 4;
z-index: 7;
}
.callout-connector polyline {
@@ -410,24 +410,56 @@ body[data-callout-line-style="bold"] .callout-connector circle {
.info-card-content {
padding: calc(8px * var(--hud-scale)) calc(12px * var(--hud-scale));
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: rgba(160, 186, 216, 0.34) transparent;
scrollbar-width: none;
-ms-overflow-style: none;
pointer-events: auto;
user-select: none;
-webkit-user-select: none;
}
.info-card-content::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
/* Hover-only zero-width overlay scrollbar restricted to Earth cards */
.card-overlay-scrollbar {
position: absolute;
top: 4px;
right: 2px;
width: 6px;
z-index: 6;
opacity: 0;
pointer-events: none;
transition: opacity 0.18s ease;
}
.info-card:hover .card-overlay-scrollbar.has-overflow,
.news-region-card:hover .card-overlay-scrollbar.has-overflow,
.compute-card:hover .card-overlay-scrollbar.has-overflow,
.card-overlay-scrollbar.has-overflow.is-scrolling,
.card-overlay-scrollbar.has-overflow.is-dragging {
opacity: 1;
pointer-events: auto;
}
.card-overlay-scrollbar__thumb {
position: absolute;
top: 0;
right: 1px;
width: 4px;
}
.info-card-content::-webkit-scrollbar-track {
background: transparent;
}
.info-card-content::-webkit-scrollbar-thumb {
background: linear-gradient(180deg, rgba(210, 225, 242, 0.2), rgba(126, 154, 185, 0.28));
min-height: 24px;
border-radius: 999px;
background: rgba(176, 206, 238, 0.34);
cursor: pointer;
transition: background 0.16s ease, width 0.16s ease;
}
.card-overlay-scrollbar:hover .card-overlay-scrollbar__thumb,
.card-overlay-scrollbar.is-dragging .card-overlay-scrollbar__thumb {
width: 5px;
background: rgba(198, 224, 252, 0.56);
}
.info-card-property {
@@ -175,12 +175,14 @@ body:not(.layout-mode-mobile) .news-region-card.is-spotlight:hover:not(.is-dragg
0 0 32px rgba(110, 190, 255, 0.24);
}
.news-region-card .info-card-header { flex-shrink:0; }
.news-region-card__body { --hud-body-collapse-gap:0px; --hud-body-max-height:calc(100vh - 24px); display:flex; flex:1 1 auto; flex-direction:column; min-height:0; overflow:hidden; }
.news-region-card__body { --hud-body-collapse-gap:0px; --hud-body-max-height:calc(100vh - 24px); position:relative; display:flex; flex:1 1 auto; flex-direction:column; min-height:0; overflow:hidden; }
.news-region-card.hud-panel--collapsed { height:auto !important; }
.news-region-card__content {
flex:1 1 auto; max-height:calc(100vh - 110px * var(--hud-scale)); height:auto;
overflow:auto; min-height:0;
scrollbar-width:none; -ms-overflow-style:none;
}
.news-region-card__content::-webkit-scrollbar { display:none; width:0; height:0; }
.news-region-card__footer { display:flex; align-items:center; gap:calc(4px * var(--hud-scale)); padding:calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale)); flex-shrink:0; border-top:1px solid var(--hud-border); }
.news-region-card__footer a { margin-left:auto; color:var(--hud-accent,#91baff); font-size:var(--hud-font-size-sm); text-decoration:none; white-space:nowrap; }
.news-region-card__count { min-width:calc(36px * var(--hud-scale)); text-align:center; font-size:var(--hud-font-size-sm); }
@@ -0,0 +1,209 @@
const MIN_THUMB_PX = 24;
const TRACK_INSET_PX = 4;
const SCROLL_IDLE_HIDE_MS = 700;
/**
* Mount a zero-width overlay scrollbar that reveals on hover/scroll/drag
* without taking layout width from the card's scroll container.
*/
export function mountCardOverlayScrollbar(
scrollEl,
{ hostEl = scrollEl?.parentElement, hoverTarget = hostEl } = {},
) {
if (!scrollEl || !hostEl || typeof document === "undefined" || typeof document.createElement !== "function") {
return { update() {}, destroy() {} };
}
const track = document.createElement("div");
track.className = "card-overlay-scrollbar";
track.setAttribute("aria-hidden", "true");
const thumb = document.createElement("div");
thumb.className = "card-overlay-scrollbar__thumb";
track.append(thumb);
hostEl.append(track);
let rafId = null;
let scrollHideTimer = null;
let dragState = null;
let destroyed = false;
const scheduleUpdate = () => {
if (destroyed || rafId !== null) return;
if (typeof requestAnimationFrame === "function") {
rafId = requestAnimationFrame(() => {
rafId = null;
update();
});
} else {
update();
}
};
function getMetrics() {
const clientHeight = Number(scrollEl.clientHeight) || 0;
const scrollHeight = Number(scrollEl.scrollHeight) || 0;
const scrollTop = Number(scrollEl.scrollTop) || 0;
const offsetTop = Number(scrollEl.offsetTop) || 0;
const maxScroll = Math.max(0, scrollHeight - clientHeight);
const trackHeight = Math.max(0, clientHeight - TRACK_INSET_PX * 2);
const hasOverflow = clientHeight > 0 && maxScroll > 1 && trackHeight > 0;
if (!hasOverflow) {
return { hasOverflow: false, clientHeight, scrollHeight, scrollTop, offsetTop, maxScroll, trackHeight, thumbHeight: 0, thumbTop: 0, maxTravel: 0 };
}
const rawThumbHeight = (clientHeight / scrollHeight) * trackHeight;
const thumbHeight = Math.max(Math.min(MIN_THUMB_PX, trackHeight), Math.min(trackHeight, rawThumbHeight));
const maxTravel = Math.max(0, trackHeight - thumbHeight);
const ratio = maxScroll > 0 ? Math.max(0, Math.min(1, scrollTop / maxScroll)) : 0;
const thumbTop = ratio * maxTravel;
return { hasOverflow, clientHeight, scrollHeight, scrollTop, offsetTop, maxScroll, trackHeight, thumbHeight, thumbTop, maxTravel };
}
function update() {
if (destroyed) return;
const m = getMetrics();
track.classList?.toggle?.("has-overflow", m.hasOverflow);
if (!m.hasOverflow) {
thumb.style.height = "";
thumb.style.transform = "";
return;
}
track.style.top = `${m.offsetTop + TRACK_INSET_PX}px`;
track.style.height = `${m.trackHeight}px`;
thumb.style.height = `${m.thumbHeight}px`;
thumb.style.transform = `translateY(${m.thumbTop}px)`;
}
const onScroll = () => {
if (destroyed) return;
update();
track.classList?.add?.("is-scrolling");
if (scrollHideTimer !== null) clearTimeout(scrollHideTimer);
scrollHideTimer = setTimeout(() => {
scrollHideTimer = null;
track.classList?.remove?.("is-scrolling");
}, SCROLL_IDLE_HIDE_MS);
};
const stopDrag = (event) => {
if (!dragState) return;
if (event && dragState.pointerId !== null && "pointerId" in event && event.pointerId !== dragState.pointerId) {
return;
}
if (dragState.pointerId !== null && typeof thumb.releasePointerCapture === "function") {
try {
thumb.releasePointerCapture(dragState.pointerId);
} catch {
// Ignore capture release errors on detached nodes.
}
}
dragState = null;
track.classList?.remove?.("is-dragging");
};
const onPointerMove = (event) => {
if (!dragState) return;
if (dragState.pointerId !== null && "pointerId" in event && event.pointerId !== dragState.pointerId) {
return;
}
event.preventDefault();
const m = getMetrics();
if (!m.hasOverflow || m.maxTravel <= 0) return;
const deltaY = event.clientY - dragState.startY;
scrollEl.scrollTop = dragState.startScrollTop + (deltaY / m.maxTravel) * m.maxScroll;
update();
};
const onThumbPointerDown = (event) => {
if (event.button !== undefined && event.button !== 0) return;
const m = getMetrics();
if (!m.hasOverflow) return;
event.preventDefault();
event.stopPropagation();
dragState = {
pointerId: "pointerId" in event ? event.pointerId : null,
startY: event.clientY,
startScrollTop: m.scrollTop,
};
track.classList?.add?.("is-dragging");
if (dragState.pointerId !== null && typeof thumb.setPointerCapture === "function") {
try {
thumb.setPointerCapture(dragState.pointerId);
} catch {
// Ignore if element cannot capture pointer.
}
}
};
const onTrackPointerDown = (event) => {
if (event.target === thumb) return;
const m = getMetrics();
if (!m.hasOverflow || typeof track.getBoundingClientRect !== "function") return;
event.preventDefault();
event.stopPropagation();
const rect = track.getBoundingClientRect();
const clickY = event.clientY - rect.top - m.thumbHeight / 2;
const ratio = m.maxTravel > 0 ? Math.max(0, Math.min(1, clickY / m.maxTravel)) : 0;
scrollEl.scrollTop = ratio * m.maxScroll;
update();
};
const onHoverEnter = () => update();
scrollEl.addEventListener?.("scroll", onScroll, { passive: true });
scrollEl.addEventListener?.("transitionend", scheduleUpdate, { passive: true });
hoverTarget?.addEventListener?.("pointerenter", onHoverEnter, { passive: true });
thumb.addEventListener?.("pointerdown", onThumbPointerDown);
track.addEventListener?.("pointerdown", onTrackPointerDown);
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
window.addEventListener("pointermove", onPointerMove, { passive: false, capture: true });
window.addEventListener("pointerup", stopDrag, { capture: true });
window.addEventListener("pointercancel", stopDrag, { capture: true });
}
thumb.addEventListener?.("lostpointercapture", stopDrag);
let resizeObserver = null;
if (typeof ResizeObserver === "function") {
resizeObserver = new ResizeObserver(scheduleUpdate);
resizeObserver.observe(scrollEl);
if (hostEl !== scrollEl) resizeObserver.observe(hostEl);
}
let mutationObserver = null;
if (typeof MutationObserver === "function") {
mutationObserver = new MutationObserver(scheduleUpdate);
mutationObserver.observe(scrollEl, { childList: true, subtree: true, characterData: true });
}
update();
return {
update,
destroy() {
destroyed = true;
if (rafId !== null && typeof cancelAnimationFrame === "function") {
cancelAnimationFrame(rafId);
rafId = null;
}
if (scrollHideTimer !== null) {
clearTimeout(scrollHideTimer);
scrollHideTimer = null;
}
stopDrag();
resizeObserver?.disconnect();
mutationObserver?.disconnect();
scrollEl.removeEventListener?.("scroll", onScroll);
scrollEl.removeEventListener?.("transitionend", scheduleUpdate);
hoverTarget?.removeEventListener?.("pointerenter", onHoverEnter);
thumb.removeEventListener?.("pointerdown", onThumbPointerDown);
track.removeEventListener?.("pointerdown", onTrackPointerDown);
thumb.removeEventListener?.("lostpointercapture", stopDrag);
if (typeof window !== "undefined" && typeof window.removeEventListener === "function") {
window.removeEventListener("pointermove", onPointerMove, { capture: true });
window.removeEventListener("pointerup", stopDrag, { capture: true });
window.removeEventListener("pointercancel", stopDrag, { capture: true });
}
track.remove?.();
},
};
}
@@ -0,0 +1,125 @@
import { describe, expect, it } from "bun:test";
import { readFileSync } from "node:fs";
import { mountCardOverlayScrollbar } from "./card-overlay-scrollbar.js";
function createScrollbarDomStub({ clientHeight = 200, scrollHeight = 500, offsetTop = 0 } = {}) {
const scrollListeners = new Map();
const trackClasses = new Set();
let trackNode = null;
let thumbNode = null;
const makeEl = (tag) => {
const node = {
tagName: tag.toUpperCase(),
className: "",
style: {},
children: [],
attributes: new Map(),
listeners: new Map(),
classList: {
add: (...names) => names.forEach((n) => trackClasses.add(n)),
remove: (...names) => names.forEach((n) => trackClasses.delete(n)),
toggle: (name, force) => {
const next = force === undefined ? !trackClasses.has(name) : Boolean(force);
if (next) trackClasses.add(name);
else trackClasses.delete(name);
return next;
},
contains: (name) => trackClasses.has(name),
},
setAttribute: (k, v) => node.attributes.set(k, String(v)),
getAttribute: (k) => node.attributes.get(k) ?? null,
addEventListener: (t, fn) => node.listeners.set(t, fn),
removeEventListener: (t) => node.listeners.delete(t),
append: (...children) => node.children.push(...children),
remove: () => {
hostEl.children = hostEl.children.filter((c) => c !== node);
},
};
if (!trackNode) trackNode = node;
else thumbNode = node;
return node;
};
const scrollEl = {
clientHeight,
scrollHeight,
scrollTop: 0,
offsetTop,
addEventListener: (type, fn) => {
if (!scrollListeners.has(type)) scrollListeners.set(type, []);
scrollListeners.get(type).push(fn);
},
removeEventListener: (type, fn) => {
const list = scrollListeners.get(type) || [];
scrollListeners.set(type, list.filter((f) => f !== fn));
},
};
const hostEl = {
children: [],
append: (node) => hostEl.children.push(node),
addEventListener: () => {},
removeEventListener: () => {},
};
return { makeEl, scrollEl, hostEl, scrollListeners, getTrack: () => trackNode, getThumb: () => thumbNode };
}
describe("card-overlay-scrollbar", () => {
it("toggles overflow class, updates thumb geometry proportionally, and cleans up on destroy", () => {
const origDoc = globalThis.document;
const origWin = globalThis.window;
const stub = createScrollbarDomStub({ clientHeight: 200, scrollHeight: 500, offsetTop: 12 });
globalThis.document = { createElement: (tag) => stub.makeEl(tag) };
globalThis.window = { addEventListener() {}, removeEventListener() {} };
try {
const ctrl = mountCardOverlayScrollbar(stub.scrollEl, {
hostEl: stub.hostEl,
hoverTarget: stub.hostEl,
});
const track = stub.getTrack();
const thumb = stub.getThumb();
expect(stub.hostEl.children).toHaveLength(1);
expect(track.classList.contains("has-overflow")).toBe(true);
expect(track.style.top).toBe("16px"); // offsetTop (12) + inset (4)
expect(track.style.height).toBe("192px"); // 200 - 8
// Scroll halfway down: maxScroll = 300 -> scrollTop = 150
stub.scrollEl.scrollTop = 150;
for (const fn of stub.scrollListeners.get("scroll") || []) fn();
const thumbH = parseFloat(thumb.style.height);
const expectedTravel = (192 - thumbH) * 0.5;
expect(thumb.style.transform).toBe(`translateY(${expectedTravel}px)`);
// No overflow hides thumb
stub.scrollEl.scrollHeight = 180;
ctrl.update();
expect(track.classList.contains("has-overflow")).toBe(false);
// Cleanup removes track
ctrl.destroy();
expect(stub.hostEl.children).toHaveLength(0);
} finally {
globalThis.document = origDoc;
globalThis.window = origWin;
}
});
it("hides native scrollbars only on cards while leaving other scroll regions untouched", () => {
const hudCss = readFileSync(new URL("../css/hud.css", import.meta.url), "utf8");
const infoCss = readFileSync(new URL("../css/info-panel.css", import.meta.url), "utf8");
const regionCss = readFileSync(new URL("../css/news-region-cards.css", import.meta.url), "utf8");
const computeCss = readFileSync(new URL("../css/compute-topic.css", import.meta.url), "utf8");
expect(hudCss).toContain(".hud-scroll-region");
expect(hudCss).toContain("scrollbar-width: thin;");
expect(infoCss).toContain(".info-card:hover .card-overlay-scrollbar.has-overflow");
expect(infoCss).toContain(".info-card-content::-webkit-scrollbar {\n display: none;");
expect(regionCss).toContain(".news-region-card__content::-webkit-scrollbar { display:none; width:0; height:0; }");
expect(computeCss).toContain(".compute-card__body::-webkit-scrollbar {");
expect(computeCss).toContain(".situational-copilot__messages");
});
});
@@ -163,4 +163,19 @@ describe("card workbench header actions & mountCardImage compatibility", () => {
expect(computeTopicSrc).toContain('data-action="open-copilot"');
expect(computeTopicSrc).toContain(">forum<");
});
it("keeps callout-connector z-index above map-clusters and below HUD panels", () => {
const hudCss = readFileSync(new URL("../css/hud.css", import.meta.url), "utf8");
const infoCss = readFileSync(new URL("../css/info-panel.css", import.meta.url), "utf8");
const clusterZ = Number(hudCss.match(/\.map-clusters\s*\{[^}]*z-index:\s*(\d+)/)?.[1]);
const connectorRearZ = Number(infoCss.match(/\.callout-connector\.is-rear\s*\{[^}]*z-index:\s*(\d+)/)?.[1]);
const connectorZ = Number(infoCss.match(/\.callout-connector\s*\{[^}]*z-index:\s*(\d+)/)?.[1]);
const infoPanelZ = Number(infoCss.match(/\.hud-panel-info\s*\{[^}]*z-index:\s*(\d+)/)?.[1]);
expect(clusterZ).toBeGreaterThan(0);
expect(connectorRearZ).toBeGreaterThan(clusterZ);
expect(connectorZ).toBeGreaterThan(connectorRearZ);
expect(infoPanelZ).toBeGreaterThan(connectorZ);
});
});
+14
View File
@@ -1,3 +1,4 @@
import { mountCardOverlayScrollbar } from "./card-overlay-scrollbar.js";
import {
buildBilateralDuelSummary,
buildDenominatorAttributionSummary,
@@ -108,6 +109,7 @@ export function initComputeTopic({
const cards = new Map();
const cardMarkup = new WeakMap();
const cardPanels = new Map();
const cardScrollbars = new Map();
const mobileCardPanels = new Map();
const expandedCards = new Set(["CN", "US"]);
let mobileView = "overview";
@@ -926,6 +928,7 @@ export function initComputeTopic({
function attachCardPanel(code, element) {
cardPanels.get(code)?.destroy();
cardScrollbars.get(code)?.destroy();
const controller = createHUDPanel({
panel: element,
header: element.querySelector(".hud-panel__header"),
@@ -936,6 +939,13 @@ export function initComputeTopic({
});
controller.setCollapsed(!expandedCards.has(code));
cardPanels.set(code, controller);
const bodyEl = element.querySelector(".compute-card__body");
if (bodyEl) {
cardScrollbars.set(code, mountCardOverlayScrollbar(bodyEl, {
hostEl: element,
hoverTarget: element,
}));
}
}
function renderCards() {
@@ -953,6 +963,8 @@ export function initComputeTopic({
if (keys.has(code)) continue;
cardPanels.get(code)?.destroy();
cardPanels.delete(code);
cardScrollbars.get(code)?.destroy();
cardScrollbars.delete(code);
element.remove();
cards.delete(code);
}
@@ -1551,6 +1563,8 @@ export function initComputeTopic({
document.body.classList.remove("compute-topic-open");
for (const controller of cardPanels.values()) controller.destroy();
cardPanels.clear();
for (const sb of cardScrollbars.values()) sb.destroy();
cardScrollbars.clear();
destroyMobileCardPanels();
spatial.destroy();
layoutObserver.disconnect();
+11
View File
@@ -1,3 +1,4 @@
import { mountCardOverlayScrollbar } from "./card-overlay-scrollbar.js";
import { COMPUTE_SITE_TYPES, isComputeSiteType } from "./compute-site-types.js";
import { cardImageIdentity, mountCardImage, createCardImagePresenter } from "./card-images.js";
import { sharedHudFocusStack } from "./hud-focus-stack.js";
@@ -17,6 +18,7 @@ import {
} from './news-locale.js';
let cardMounted = false;
let desktopCardImage = null;
let desktopCardScrollbar = null;
let mobileCardImage = null;
let activeWorkbenchAction = null;
const infoCardTypewriter = createTypewriter();
@@ -2160,6 +2162,10 @@ function mountCard() {
const content = panel.querySelector('#info-card-content');
desktopCardImage = mountCardImage(content, card.querySelector(".info-card-header"));
desktopCardScrollbar = mountCardOverlayScrollbar(content, {
hostEl: content.parentElement,
hoverTarget: card,
});
// Prevent pointer events from reaching the earth canvas
const stopEvent = (event) => { event.stopPropagation(); };
@@ -2408,6 +2414,10 @@ export function showInfoCard(type, data, options = {}) {
}
void desktopCardImage.show(cardImageIdentity(type, data));
showPanel(options.x, options.y, options);
desktopCardScrollbar?.update();
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => desktopCardScrollbar?.update());
}
}
export function hideInfoCard() {
@@ -2415,6 +2425,7 @@ export function hideInfoCard() {
const workbenchBtn = document.getElementById('info-card-workbench');
if (workbenchBtn) workbenchBtn.hidden = true;
desktopCardImage?.hide();
desktopCardScrollbar?.update();
mobileCardImage?.hide();
getMobileDetailsImagePresenter()?.hide();
stopTypewriterAnimation();
@@ -1,3 +1,4 @@
import { mountCardOverlayScrollbar } from "./card-overlay-scrollbar.js";
import { createTypewriter } from "./typewriter.js";
import { CRUISE_CONFIG } from "./constants.js";
import { getEarthLocale } from "./i18n.js";
@@ -74,6 +75,7 @@ export function initNewsRegionCards({ rootParent, spatial }) {
if (!card.source.hidden) card.source.href = url; else card.source.removeAttribute("href");
card.source.textContent = text("阅读原文 ↗","Read source ↗");
if (card.analyze) card.analyze.disabled = !card.currentStory;
card.scrollbar?.update();
}
card.count.textContent = snapshot.count ? `${snapshot.index+1} / ${snapshot.count}` : "0 / 0";
card.previous.disabled = card.next.disabled = snapshot.count < 2;
@@ -95,6 +97,7 @@ export function initNewsRegionCards({ rootParent, spatial }) {
previous:element.querySelector('[data-action="news-prev"]'),next:element.querySelector('[data-action="news-next"]'),play:element.querySelector('[data-action="news-play"]'),analyze:element.querySelector('[data-action="news-analyze"]'),
};
card.panel=createHUDPanel({panel:element,header:element.querySelector("header"),body:element.querySelector(".news-region-card__body"),collapseBtn:element.querySelector('[data-action="card-collapse"]'),expandLabel:text("展开新闻","Expand news"),collapseLabel:text("折叠新闻","Collapse news")});
card.scrollbar=mountCardOverlayScrollbar(card.content,{hostEl:element.querySelector(".news-region-card__body"),hoverTarget:element});
element.addEventListener("pointerenter",()=>{card.hovered=true;});
element.addEventListener("pointerleave",()=>{card.hovered=false;});
element.addEventListener("click",event=>{
@@ -209,7 +212,7 @@ export function initNewsRegionCards({ rootParent, spatial }) {
},
destroy() {
destroyed=true;spatial.destroy();layoutObserver.disconnect();
cards.forEach(card=>{card.writer.stop();card.animation?.cancel();card.panel.destroy();});cards.clear();
cards.forEach(card=>{card.writer.stop();card.animation?.cancel();card.scrollbar?.destroy();card.panel.destroy();});cards.clear();
toggles.forEach(button=>button.removeEventListener("click",toggle));
window.removeEventListener("earth:news-payload-updated",syncItems);
window.removeEventListener("earth:locale-change",locale);
@@ -954,6 +954,7 @@ export function initSituationalCopilot({
let suppressJumpButtonUntilBottom = false;
let lastMsgScrollTop = 0;
let streamAutoFollow = true;
function syncJumpLatestButton(msgContainer) {
const btn = panel.querySelector('[data-copilot-action="jump-latest"]');
@@ -985,12 +986,15 @@ export function initSituationalCopilot({
const msgContainer = panel.querySelector(".situational-copilot__messages");
if (!msgContainer) return;
const btn = panel.querySelector('[data-copilot-action="jump-latest"]');
streamAutoFollow = true;
lastMsgScrollTop = msgContainer.scrollTop || 0;
if (typeof msgContainer.scrollTo === "function") {
suppressJumpButtonUntilBottom = true;
if (btn) btn.hidden = true;
msgContainer.scrollTo({ top: msgContainer.scrollHeight, behavior: "smooth" });
} else {
msgContainer.scrollTop = msgContainer.scrollHeight;
lastMsgScrollTop = msgContainer.scrollTop;
syncJumpLatestButton(msgContainer);
}
}
@@ -1211,12 +1215,10 @@ export function initSituationalCopilot({
if (!msgContainer || typeof msgContainer.querySelector !== "function") return false;
const turnEl = msgContainer.querySelector(`[data-turn="${turn.id}"]`);
if (!turnEl) return false;
const prevTop = msgContainer.scrollTop;
turnEl.innerHTML = renderTurnInnerHtml(turn);
if (followBottom) {
msgContainer.scrollTop = msgContainer.scrollHeight;
} else {
msgContainer.scrollTop = prevTop;
lastMsgScrollTop = msgContainer.scrollTop;
}
syncJumpLatestButton(msgContainer);
return true;
@@ -1664,6 +1666,7 @@ export function initSituationalCopilot({
runId: clientRunId,
domain: ctx.domain || "compute",
question: trimmed,
newsContext: activeNewsContext || null,
status: "loading",
stageText: sessionId
? text("正在连接 AI 参谋并核验上下文…", "Connecting AI copilot and verifying telemetry…")
@@ -1688,6 +1691,8 @@ export function initSituationalCopilot({
errorIcon: "error",
errorText: "",
};
streamAutoFollow = true;
suppressJumpButtonUntilBottom = false;
turns.push(turn);
if (turns.length > MAX_TURNS) {
turns = turns.slice(-MAX_TURNS);
@@ -1696,7 +1701,6 @@ export function initSituationalCopilot({
let streamRenderTimer = null;
let slowHintTimer = null;
let streamAutoFollow = true;
const clearStreamRenderTimer = () => {
if (streamRenderTimer !== null) {
clearTimeout(streamRenderTimer);
@@ -1712,6 +1716,9 @@ export function initSituationalCopilot({
const isNearBottom = () => {
const msgBox = panel.querySelector(".situational-copilot__messages");
if (!msgBox || msgBox.clientHeight <= 0) return true;
if (suppressJumpButtonUntilBottom && streamAutoFollow) {
return true;
}
const remaining = msgBox.scrollHeight - msgBox.scrollTop - msgBox.clientHeight;
if (msgBox.scrollTop < lastMsgScrollTop - 2 && remaining > 16) {
streamAutoFollow = false;
@@ -2292,9 +2299,12 @@ export function initSituationalCopilot({
const retryTurnBtn = event.target.closest("[data-copilot-retry-turn]");
if (retryTurnBtn) {
const targetTurn = turns.find((t) => t.id === retryTurnBtn.dataset.copilotRetryTurn);
const targetIndex = turns.findIndex((t) => t.id === retryTurnBtn.dataset.copilotRetryTurn);
const targetTurn = targetIndex >= 0 ? turns[targetIndex] : null;
if (targetTurn?.question) {
void askQuestion(targetTurn.question);
const { question, newsContext } = targetTurn;
turns = turns.slice(0, targetIndex);
void askQuestion(question, { newsContextOverride: newsContext ?? undefined });
}
return;
}
@@ -1632,4 +1632,140 @@ describe("Shared HUD Select Menu for Time Basis", () => {
globalThis.window = prevWin;
}
});
it("truncates an earlier failed turn and subsequent retries when clicking Retry and supports jump-latest mid-SSE", async () => {
const prevDoc = globalThis.document;
const prevWin = globalThis.window;
const env = createMockDomEnv();
const panelListeners = new Map();
const turnElStub = { innerHTML: "" };
const jumpBtnStub = { hidden: true };
const msgBoxStub = {
scrollHeight: 1400,
clientHeight: 320,
scrollTop: 1080,
scrollToCalls: [],
addEventListener() {},
removeEventListener() {},
querySelector: (sel) => (String(sel).startsWith("[data-turn=") ? turnElStub : null),
querySelectorAll: () => [],
scrollTo(opts) {
this.scrollToCalls.push(opts);
// Simulate mid-animation partial progress on smooth scroll
this.scrollTop = Math.max(this.scrollTop, Math.round(opts.top * 0.7));
},
};
const panelStub = {
tagName: "ASIDE",
id: "situational-copilot",
className: "",
hidden: false,
innerHTML: "",
dataset: {},
style: { setProperty() {} },
classList: { add() {}, remove() {}, toggle() {}, contains: () => false },
append() {},
remove() {},
addEventListener(type, fn) {
if (!panelListeners.has(type)) panelListeners.set(type, []);
panelListeners.get(type).push(fn);
},
removeEventListener() {},
querySelector(sel) {
if (sel === ".situational-copilot__messages") return msgBoxStub;
if (sel === '[data-copilot-action="jump-latest"]') return jumpBtnStub;
return null;
},
querySelectorAll: () => [],
getBoundingClientRect: () => ({ top: 100, bottom: 980, left: 1200, right: 1900, width: 396, height: 556 }),
children: [],
};
let createdCount = 0;
const origCreateElement = env.mockDoc.createElement.bind(env.mockDoc);
env.mockDoc.createElement = (tag) => {
createdCount += 1;
return createdCount === 1 ? panelStub : origCreateElement(tag);
};
globalThis.document = env.mockDoc;
globalThis.window = env.mockWin;
let failMode = true;
let releaseTailChunk;
const tailChunkGate = new Promise((r) => { releaseTailChunk = r; });
const mockFetch = async (url) => {
if (String(url).endsWith("/sessions")) {
return { ok: true, status: 200, json: async () => ({ session_id: "s-retry-trunc", session_token: "tok-retry" }) };
}
if (failMode) {
return { ok: false, status: 405 };
}
if (String(url).includes("/turns/stream")) {
const enc = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
controller.enqueue(enc.encode('event: meta\ndata: {"run_id":"r-ok","model":"MiniMax-M3.1-Flash"}\n\n'));
controller.enqueue(enc.encode('event: text\ndata: {"delta":"前半段重试内容"}\n\n'));
await tailChunkGate;
controller.enqueue(enc.encode('event: text\ndata: {"delta":"与后半段成功结果"}\n\n'));
controller.enqueue(enc.encode('event: done\ndata: {"generation_mode":"llm_verified","zero_token":false,"model":"MiniMax-M3.1-Flash","answer_markdown":"前半段重试内容与后半段成功结果"}\n\n'));
controller.close();
},
});
return {
ok: true,
status: 200,
headers: new Headers({ "content-type": "text/event-stream" }),
body: stream,
};
}
return { ok: true, status: 200, json: async () => ({}) };
};
try {
const copilot = initSituationalCopilot({
rootParent: env.root,
requestTimeouts: { sessionMs: 200, streamMs: 200, turnMs: 200, slowHintMs: 0, maxRetries: 0, retryDelayMs: 5 },
fetchImpl: mockFetch,
});
copilot.open({ domain: "global", autoAsk: false });
await copilot.ask("首次失败提问");
await copilot.ask("第二次失败提问");
expect(copilot.getState().turnsCount).toBe(2);
// Server recovers; user clicks Retry on the FIRST failed turn ("turn-1")
failMode = false;
const retryNode = { dataset: { copilotRetryTurn: "turn-1" } };
for (const fn of panelListeners.get("click") || []) {
fn({ target: { closest: (sel) => (sel === "[data-copilot-retry-turn]" ? retryNode : null) } });
}
await new Promise((r) => setTimeout(r, 80));
// Turn-1 + Turn-2 were truncated and replaced by the live retried turn (only 1 turn in list!)
expect(copilot.getState().turnsCount).toBe(1);
expect(panelStub.innerHTML).toContain("首次失败提问");
expect(panelStub.innerHTML).not.toContain("第二次失败提问");
// Simulate scrolling up then clicking jump-latest mid-SSE: should smooth-scroll and resume bottom follow
msgBoxStub.scrollTop = 200;
const jumpAction = { dataset: { copilotAction: "jump-latest" } };
for (const fn of panelListeners.get("click") || []) {
fn({ target: { closest: (sel) => (sel === "[data-copilot-action]" ? jumpAction : null) } });
}
expect(msgBoxStub.scrollToCalls).toHaveLength(1);
expect(jumpBtnStub.hidden).toBe(true);
releaseTailChunk();
await new Promise((r) => setTimeout(r, 80));
expect(panelStub.innerHTML).toContain("前半段重试内容与后半段成功结果");
expect(panelStub.innerHTML).not.toContain("copilot-error");
expect(msgBoxStub.scrollTop).toBe(1400);
copilot.destroy();
} finally {
globalThis.document = prevDoc;
globalThis.window = prevWin;
}
});
});
@@ -90,7 +90,7 @@ export function DataTable<TData>({
const sorted = header.column.getIsSorted()
const stickyEnd = header.column.id === 'actions' || header.column.id === 'action'
return (
<th key={header.id} style={{ width: header.getSize() }} data-sticky-end={stickyEnd || undefined}>
<th key={header.id} style={{ width: header.getSize() }} data-column-id={header.column.id} data-sticky-end={stickyEnd || undefined}>
{header.isPlaceholder ? null : (
<button
type="button"
@@ -142,7 +142,7 @@ export function DataTable<TData>({
</td>
) : null}
{row.getVisibleCells().map((cell) => (
<td key={cell.id} data-sticky-end={cell.column.id === 'actions' || cell.column.id === 'action' || undefined}>
<td key={cell.id} data-column-id={cell.column.id} data-sticky-end={cell.column.id === 'actions' || cell.column.id === 'action' || undefined}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
@@ -0,0 +1,92 @@
import { Square, ToggleLeft, ToggleRight, X } from 'lucide-react'
import { Button } from '../ui/button'
export type DatasourceBatchAction = '' | 'enable' | 'disable' | 'trigger' | 'stop'
interface DatasourceBatchBarProps {
selectedCount: number
enableCount: number
disableCount: number
triggerCount: number
stopCount: number
busy: DatasourceBatchAction
translate: (value: string) => string
onEnable: () => void
onDisable: () => void
onTrigger: () => void
onStop: () => void
onClear: () => void
}
export function DatasourceBatchBar({
selectedCount,
enableCount,
disableCount,
triggerCount,
stopCount,
busy,
translate,
onEnable,
onDisable,
onTrigger,
onStop,
onClear,
}: DatasourceBatchBarProps) {
const locked = Boolean(busy)
return (
<div className="an-batch-bar" role="toolbar" aria-label={translate('批量操作')}>
<span className="an-batch-bar__count">
<strong>{selectedCount}</strong>
{translate('已选择')}
</span>
<Button
size="sm"
variant="subtle"
onClick={onEnable}
disabled={locked || !enableCount}
loading={busy === 'enable'}
title={translate('启用调度')}
>
<ToggleRight size={15} aria-hidden="true" />
{translate('启用')}
<span className="an-batch-bar__num">{enableCount}</span>
</Button>
<Button
size="sm"
variant="subtle"
onClick={onDisable}
disabled={locked || !disableCount}
loading={busy === 'disable'}
title={translate('停用调度')}
>
<ToggleLeft size={15} aria-hidden="true" />
{translate('停用')}
<span className="an-batch-bar__num">{disableCount}</span>
</Button>
{stopCount ? (
<Button size="sm" variant="danger" onClick={onStop} disabled={locked} loading={busy === 'stop'} title={translate('停止采集')}>
<Square size={14} aria-hidden="true" />
{translate('停止')}
<span className="an-batch-bar__num">{stopCount}</span>
</Button>
) : (
<Button
size="sm"
variant="primary"
icon="trigger"
onClick={onTrigger}
disabled={locked || !triggerCount}
loading={busy === 'trigger'}
title={translate('立即采集')}
>
{translate('立即采集')}
<span className="an-batch-bar__num">{triggerCount}</span>
</Button>
)}
<Button size="icon" variant="subtle" onClick={onClear} disabled={locked} title={translate('清除选择')} aria-label={translate('清除选择')}>
<X size={15} />
</Button>
</div>
)
}
+431 -158
View File
@@ -3,15 +3,18 @@ import axios from 'axios'
import {
AlertTriangle,
ArrowLeft,
ArrowUpRight,
Bot,
BrushCleaning,
CheckCircle2,
ChevronRight,
CircleHelp,
Copy,
Database,
DatabaseZap,
Eye,
FileText,
FilterX,
Globe2,
History,
ImageUp,
@@ -41,6 +44,7 @@ import { legacyUiTextEnUS } from '../../i18n/legacy-ui'
import { useLocale, type SupportedLocale } from '../../i18n/locale'
import { AdminLayout } from '../components/layout/AdminLayout'
import { DataTable } from '../components/data-table/DataTable'
import { DatasourceBatchBar, type DatasourceBatchAction } from '../components/datasources/DatasourceBatchBar'
import { Button, type ButtonProps } from '../components/ui/button'
import { ConfirmDialog, Dialog } from '../components/ui/dialog'
import { Textarea } from '../components/ui/input'
@@ -126,12 +130,13 @@ type BrandAssetTargetKey = 'logo_src' | 'title_src'
const DEFAULT_DATASOURCE_FILTERS: DatasourceFilters = {
product: '',
module: '',
isActive: 'true',
isActive: '',
runStatus: '',
dataStatus: '',
}
const DATASOURCE_FILTER_STORAGE_KEY = 'planet.admin.datasource.filters'
// v2: the default scheduling filter changed from "enabled only" to "all".
const DATASOURCE_FILTER_STORAGE_KEY = 'planet.admin.datasource.filters.v2'
const DATASOURCE_FILTER_QUERY_KEYS = ['product', 'module', 'is_active', 'run_status', 'data_status']
const DATASOURCE_TERMINAL_STATUSES = new Set(['success', 'completed', 'failed', 'cancelled', 'canceled', 'stopped'])
const TASK_ACTIVE_STATUSES = new Set(['queued', 'pending', 'running', 'cancelling'])
@@ -749,6 +754,7 @@ function ModuleTable({
columns,
selection,
loading,
className = '',
}: {
rows: TableRecord[]
selected: TableRecord | null
@@ -762,16 +768,20 @@ function ModuleTable({
isRowSelectable?: (row: TableRecord) => boolean
}
loading?: boolean
className?: string
}) {
const { locale } = useLocale()
const tableColumns = useMemo(() => columns || defaultColumns(onSelect, locale), [columns, locale, onSelect])
return (
<DataTable
className="an-resource-table"
className={`an-resource-table${className ? ` ${className}` : ''}`}
columns={tableColumns}
data={rows}
emptyText={localizeAdminText('当前模块暂无数据', locale)}
getRowClassName={(row) => row.__rowId === selected?.__rowId ? 'is-selected' : undefined}
getRowClassName={(row) => [
row.__rowId === selected?.__rowId ? 'is-selected' : '',
row.__filterStale ? 'is-filter-stale' : '',
].filter(Boolean).join(' ') || undefined}
getRowId={(row) => row.__rowId}
loading={loading}
onRowClick={onSelect}
@@ -2975,6 +2985,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const [loading, setLoading] = useState(false)
const [actionLoading, setActionLoading] = useState(false)
const [rowActionLoading, setRowActionLoading] = useState<Record<string, boolean>>({})
const [datasourceBatchAction, setDatasourceBatchAction] = useState<DatasourceBatchAction>('')
const [collectionQueue, setCollectionQueue] = useState<CollectionQueueItem[]>([])
const [collectionQueueOpen, setCollectionQueueOpen] = useState(false)
const collectionQueueRef = useRef<HTMLDivElement>(null)
@@ -3066,10 +3077,14 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
}, [collectionQueueOpen])
const loadRef = useRef<((sectionKey?: string) => Promise<void>) | null>(null)
useEffect(() => {
const changed = !datasourceFiltersEqual(datasourceFiltersRef.current, datasourceFilters)
datasourceFiltersRef.current = datasourceFilters
if (config === configs.datasources) {
setStates((current) => current.filter((state) => state.section.key !== 'builtin'))
// Keep the current rows visible while the filtered list reloads.
if (config === configs.datasources && changed) {
void loadRef.current?.('builtin')
}
}, [config, datasourceFilters])
@@ -3190,6 +3205,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
setLoading(false)
}
}, [activeSectionKey, config.sections, sectionRequestParams])
loadRef.current = load
const datasourceBuiltinSection = useMemo(
() => config.sections.find((section) => section.key === 'builtin') || config.sections[0],
@@ -3261,7 +3277,8 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const updateDatasourceRow = useCallback((row: AnyRecord, options: { removeIfFilteredOut?: boolean } = {}) => {
if (config !== configs.datasources) return
const normalized = normalizeDatasourceTableRecord(row)
const shouldKeep = !options.removeIfFilteredOut || datasourceRowMatchesFilters(normalized, datasourceFiltersRef.current)
const matchesFilters = datasourceRowMatchesFilters(normalized, datasourceFiltersRef.current)
const shouldKeep = !options.removeIfFilteredOut || matchesFilters
setStates((currentStates) => currentStates.map((state) => {
if (state.section.key !== 'builtin') return state
let matched = false
@@ -3270,7 +3287,8 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return [existing]
}
matched = true
return shouldKeep ? [{ ...existing, ...normalized }] : []
// Rows that stop matching the filter stay in place (dimmed) until the next reload.
return shouldKeep ? [{ ...existing, ...normalized, __filterStale: !matchesFilters }] : []
})
if (!matched && shouldKeep) rows.push(normalized)
return { ...state, rows, raw: isObjectRecord(state.raw) ? { ...state.raw, data: rows, total: rows.length } : state.raw }
@@ -3459,12 +3477,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
() => isDatasourceBuiltinSection ? rows.filter((row) => datasourceSelectedRowIds.has(row.__rowId)) : [],
[datasourceSelectedRowIds, isDatasourceBuiltinSection, rows],
)
const selectedDatasourceIds = useMemo(
() => selectedDatasourceRows
.map((row) => Number(row.id))
.filter((id) => Number.isFinite(id) && id > 0),
[selectedDatasourceRows],
)
const toggleDatasourceSelection = useCallback((rowId: string) => {
setDatasourceSelectedRowIds((current) => {
const next = new Set(current)
@@ -3756,37 +3768,151 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
}
const triggerSelectedDatasources = async () => {
const sourceIds = selectedDatasourceIds
if (!sourceIds.length) {
toast({ title: '请先勾选数据源', description: '勾选内置源后,主触发按钮会只触发所选数据源。', tone: 'error' })
const applyDatasourceCounts = (counts: unknown) => {
if (!isObjectRecord(counts)) return
setStates((current) => current.map((state) => (
state.section.key === 'builtin' && isObjectRecord(state.raw)
? { ...state, raw: { ...state.raw, counts } }
: state
)))
}
const postDatasourceActive = async (id: string, nextActive: boolean): Promise<AnyRecord> => {
const response = await axios.post(apiPath(`/datasources/${encodeURIComponent(id)}/${nextActive ? 'enable' : 'disable'}`))
return isObjectRecord(response.data) ? response.data : {}
}
const toastDatasourceActiveResult = (name: string, nextActive: boolean, result: AnyRecord | null, error?: unknown) => {
if (error !== undefined) {
toast({
title: localizeAdminText(nextActive ? '启用调度失败' : '停用调度失败', locale),
description: localizeAdminText(actionErrorMessage(error), locale),
tone: 'error',
})
return
}
setActionLoading(true)
toast({
title: localizeAdminText(nextActive ? '已启用调度' : '已停用调度', locale),
description: localizeDisplayValue(name, locale) || undefined,
tone: result?.sync_failed ? 'error' : 'success',
})
}
const setDatasourceActive = async (record: TableRecord, nextActive: boolean) => {
const id = pick(record, ['id', 'source_id', 'key', 'name'], '')
if (!id) return
setRowActionLoading((current) => ({ ...current, [id]: true }))
try {
const result = await postDatasourceActive(id, nextActive)
const row = objectAt(result, 'data')
updateDatasourceRow(Object.keys(row).length ? row : { ...record, is_active: nextActive })
applyDatasourceCounts(result.counts)
toastDatasourceActiveResult(recordTitle(record), nextActive, result)
} catch (error) {
toastDatasourceActiveResult(recordTitle(record), nextActive, null, error)
} finally {
setRowActionLoading((current) => ({ ...current, [id]: false }))
}
}
const setCollectorActive = async (record: AnyRecord, nextActive: boolean) => {
const id = text(record.id, '')
if (!id) return
setRowActionLoading((current) => ({ ...current, [id]: true }))
try {
const result = await postDatasourceActive(id, nextActive)
const saved = objectAt(result, 'data').is_active
const resolved = typeof saved === 'boolean' ? saved : nextActive
setStates((current) => current.map((state) => (
state.section.key !== 'collectors'
? state
: { ...state, rows: state.rows.map((row) => (text(row.id, '') === id ? { ...row, is_active: resolved, __status: String(resolved) } : row)) }
)))
toastDatasourceActiveResult(recordTitle(record), nextActive, result)
} catch (error) {
toastDatasourceActiveResult(recordTitle(record), nextActive, null, error)
} finally {
setRowActionLoading((current) => ({ ...current, [id]: false }))
}
}
const setSelectedDatasourcesActive = async (nextActive: boolean) => {
const sourceIds = selectedDatasourceRows
.filter((row) => (row.is_active !== false) !== nextActive)
.map((row) => Number(row.id))
.filter((id) => Number.isFinite(id) && id > 0)
if (!sourceIds.length) return
setDatasourceBatchAction(nextActive ? 'enable' : 'disable')
try {
const response = await axios.post(apiPath('/datasources/batch-status'), { source_ids: sourceIds, is_active: nextActive })
const updated = arrayAt(response.data, 'updated')
updated.forEach((row) => updateDatasourceRow(row))
applyDatasourceCounts(response.data?.counts)
const missing = Array.isArray(response.data?.not_found) ? response.data.not_found.length : 0
const syncFailed = Array.isArray(response.data?.sync_failed) ? response.data.sync_failed.length : 0
const issues = [
missing ? `${localizeAdminText('数据源不存在', locale)} · ${missing}` : '',
syncFailed ? `${localizeAdminText('调度同步失败', locale)} · ${syncFailed}` : '',
].filter(Boolean).join(' / ')
toast({
title: `${localizeAdminText(nextActive ? '已启用调度' : '已停用调度', locale)} · ${updated.length}`,
description: issues || undefined,
tone: issues ? 'error' : 'success',
})
} catch (error) {
toast({
title: localizeAdminText(nextActive ? '启用调度失败' : '停用调度失败', locale),
description: localizeAdminText(actionErrorMessage(error), locale),
tone: 'error',
})
} finally {
setDatasourceBatchAction('')
}
}
const confirmDisableSelectedDatasources = () => {
const count = selectedDatasourceRows.filter((row) => row.is_active !== false).length
if (!count) return
setConfirmAction({
title: '停用调度',
description: `停用 ${count} 个数据源的定时调度,运行中的任务不受影响。`,
danger: true,
confirmLabel: '停用',
run: () => setSelectedDatasourcesActive(false),
})
}
const triggerSelectedDatasources = async () => {
const sourceIds = selectedDatasourceRows
.filter((row) => row.is_active !== false)
.map((row) => Number(row.id))
.filter((id) => Number.isFinite(id) && id > 0)
if (!sourceIds.length) return
setDatasourceBatchAction('trigger')
try {
const response = await axios.post(apiPath('/datasources/trigger-batch'), {
source_ids: sourceIds,
force: false,
})
addBatchQueueResult(response.data)
arrayAt(response.data, 'triggered').forEach((item) => {
const triggered = arrayAt(response.data, 'triggered')
triggered.forEach((item) => {
const sourceId = text(item.id || item.source_id || item.datasource_id, '')
const record = rows.find((row) => text(row.id, '') === sourceId || text(row.source, '') === text(item.source, ''))
if (record) scheduleDatasourceTaskPoll(record, item.task_id as number | string | null | undefined)
})
replaceSelectedWithPayload('trigger-batch', '批量触发结果', [{
...response.data,
__title: '批量触发结果',
__module: '批量任务',
__status: '已提交',
__metric: `${sourceIds.length} 个数据源`,
}])
const skipped = arrayAt(response.data, 'skipped').length
const failed = arrayAt(response.data, 'failed').length
setDatasourceSelectedRowIds(new Set())
toast({ title: '已触发所选数据源', description: `${sourceIds.length} 个数据源已提交。`, tone: 'success' })
toast({
title: `${localizeAdminText('已提交采集', locale)} · ${triggered.length}`,
description: [skipped ? `跳过 ${skipped}(未到采集间隔或任务运行中)` : '', failed ? `失败 ${failed}` : ''].filter(Boolean).join(',') || undefined,
tone: failed || !triggered.length ? 'error' : 'success',
})
} catch (error) {
toast({ title: '触发已选失败', description: error instanceof Error ? error.message : '接口请求失败', tone: 'error' })
toast({ title: localizeAdminText('触发采集失败', locale), description: localizeAdminText(actionErrorMessage(error), locale), tone: 'error' })
} finally {
setActionLoading(false)
setDatasourceBatchAction('')
}
}
@@ -3826,41 +3952,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
}
const triggerDatasourcePrimaryAction = async () => {
if (selectedDatasourceIds.length && selectedActiveCollectQueueItems.length) {
await cancelCollectionQueueItems(selectedActiveCollectQueueItems, '停止已选')
return
}
if (!selectedDatasourceIds.length && activeCollectQueueItems.length) {
await cancelCollectionQueueItems(activeCollectQueueItems, '停止采集')
return
}
if (selectedDatasourceIds.length) {
await triggerSelectedDatasources()
return
}
await triggerAllDatasources()
}
const triggerAllDatasources = async () => {
setActionLoading(true)
try {
toast({ title: '正在提交采集队列', description: '触发全部会按后端调度规则跳过未到采集间隔的源。' })
const response = await axios.post(apiPath('/datasources/trigger-all'))
addBatchQueueResult(response.data)
arrayAt(response.data, 'triggered').forEach((item) => {
const sourceId = text(item.id || item.source_id || item.datasource_id, '')
const record = rows.find((row) => text(row.id, '') === sourceId || text(row.source, '') === text(item.source, ''))
if (record) scheduleDatasourceTaskPoll(record, item.task_id as number | string | null | undefined)
})
toast({ title: '采集队列已提交', description: `${arrayAt(response.data, 'triggered').length} 个任务已进入队列。`, tone: 'success' })
} catch (error) {
toast({ title: '触发全部失败', description: actionErrorMessage(error), tone: 'error' })
} finally {
setActionLoading(false)
}
}
const scheduleDatasourceTaskPoll = (record: TableRecord, taskId?: number | string | null) => {
const id = pick(record, ['id', 'source_id', 'key', 'name'], '')
if (!id) return
@@ -4096,7 +4187,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
source: text(record.source || response.data?.collector_name, ''),
taskType: 'collect',
}))
setCollectionQueueOpen(true)
completedDatasourceTasksRef.current.delete(pendingKey)
updateDatasourceRow({
...record,
@@ -4112,14 +4202,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
progress: 0,
error_message: null,
})
replaceSelectedWithPayload('task-status', '任务状态', [{
...response.data,
__title: `${recordTitle(record)} 任务状态`,
__module: '任务状态',
__status: '已提交',
__metric: response.data?.task_id || '-',
}])
toast({ title: force ? '已强制重新触发' : '任务已触发', tone: 'success' })
toast({
title: localizeAdminText(force ? '已强制重新触发' : '已提交采集', locale),
description: localizeDisplayValue(recordTitle(record), locale) || undefined,
tone: 'success',
})
scheduleDatasourceTaskPoll(record, taskId)
} catch (error) {
toast({ title: '触发采集失败', description: actionErrorMessage(error), tone: 'error' })
@@ -5609,7 +5696,10 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
),
}
})
: fields
: config === configs.collection && activeSection.key === 'collectors'
// Scheduling is toggled immediately from the panel heading, not saved with the draft.
? fields.filter((field) => field.key !== 'is_active')
: fields
const renderNewsFeedEditor = () => {
if (!activeGroup) return null
const currentSource = draftRecord(hierarchyDraft, activeGroup.record)
@@ -6008,7 +6098,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
if (activeSection.key === 'collectors' && id) {
const globalSingleLocked = Boolean(collectorStoragePolicy?.global_single_lock || activeGroup.record.snapshot_locked === true)
await saveHierarchySettings(`/settings/collectors/${encodeURIComponent(id)}`, {
is_active: Boolean(payload.is_active),
is_active: activeGroup.record.is_active !== false,
priority: text(payload.priority, 'P1'),
frequency_minutes: Number(payload.frequency_minutes || 60),
snapshot_mode: globalSingleLocked ? 'single' : text(payload.snapshot_mode, 'single'),
@@ -6279,6 +6369,17 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<p>{localizeDisplayValue(activeGroup?.description || '选择左侧父级后编辑它的子配置。', locale)}</p>
</div>
<div className="an-toolbar">
{config === configs.collection && activeSection.key === 'collectors' && activeGroup ? (
<span className="an-inline-switch" title={localizeAdminText('定时调度', locale)}>
<AdminSwitch
checked={activeGroup.record.is_active !== false}
disabled={Boolean(rowActionLoading[text(activeGroup.record.id, '')])}
label={localizeAdminText(activeGroup.record.is_active !== false ? '停用调度' : '启用调度', locale)}
onCheckedChange={(next) => void setCollectorActive(activeGroup.record, next)}
/>
<span>{localizeAdminText('定时调度', locale)}</span>
</span>
) : null}
{config === configs.earthContent && activeSection.key === 'brand' ? (
<>
<Button size="icon" variant="subtle" title="重置品牌配置" aria-label="重置品牌配置" onClick={() => setConfirmAction({
@@ -6723,53 +6824,39 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const id = pick(selected, ['config_id', 'id', 'source_id', 'key', 'name'], '')
if (config === configs.datasources && endpointKey === 'builtin' && id) {
const isDatasourceActive = selected.is_active !== false
const toggle = isDatasourceActive ? 'disable' : 'enable'
const toggleLabel = isDatasourceActive ? '停用数据源调度' : '启用数据源调度'
const rowLoading = Boolean(rowActionLoading[id])
const sourceId = text(selected.id || selected.source_id, '')
const source = text(selected.source || selected.collector_name, '')
const queueItem = collectionQueue.find((item) => isSameDatasourceRow(selected, item.sourceId || '', item.source || '') && isActiveQueueStatus(item.status))
const activeCollectItem = queueItem?.taskType === 'collect' ? queueItem : null
const activeDeleteItem = queueItem?.taskType === 'clear_data' ? queueItem : null
const activeTaskId = queueItem?.taskId || selected.task_id
const isCollecting = isCollectTaskActive(selected) || Boolean(activeCollectItem)
actions.push(
<Button key="load-detail" size="icon" variant="subtle" icon="detail" onClick={() => void loadDatasourceDetail(selected)} loading={actionLoading} title="详情/统计" aria-label="详情/统计" />,
isCollecting && (activeCollectItem?.taskId || activeTaskId) ? (
<Button key="trigger" variant="danger" onClick={() => void cancelQueueItem(queueItemFromDatasourceRow(selected, (activeCollectItem?.taskId || activeTaskId) as number | string, {
taskType: 'collect',
status: activeCollectItem?.status || 'running',
phase: text(selected.phase, queueItem?.phase || 'running'),
phaseMessage: text(selected.phase_message, queueItem?.phaseMessage || '后端任务仍在运行'),
progress: typeof selected.progress === 'number' ? selected.progress : queueItem?.progress,
createdAt: queueItem?.createdAt || Date.now(),
updatedAt: Date.now(),
}))} loading={rowLoading}>
<Square size={14} />
停止采集
</Button>
) : (
<Button key="trigger" variant="primary" icon="trigger" onClick={() => void triggerDatasourceWithPrecheck(selected)} loading={rowLoading}>触发采集</Button>
),
<Button key="toggle" size="icon" variant={toggle === 'enable' ? 'subtle' : 'danger'} icon={toggle === 'enable' ? 'start' : 'stop'} onClick={() => void requestAction(toggleLabel, 'post', `/datasources/${encodeURIComponent(id)}/${toggle}`)} loading={actionLoading} title={toggleLabel} aria-label={toggleLabel} />,
<Button key="task-status" size="icon" variant="subtle" icon="status" onClick={() => void loadTaskStatus(selected)} loading={actionLoading} title="任务状态" aria-label="任务状态" />,
<Button key="clear-cache" size="icon" variant="subtle" onClick={() => setConfirmAction({
title: '清理数据源缓存',
description: `确认清理 ${recordTitle(selected)} 的智能星球展示缓存?这不会删除数据库里的采集数据。`,
danger: false,
confirmLabel: '清理缓存',
run: () => clearDatasourceCache(selected),
})} loading={actionLoading} title="清理缓存" aria-label="清理缓存"><BrushCleaning size={15} /></Button>,
activeDeleteItem ? (
<Button key="delete-data" size="icon" variant="subtle" onClick={() => void cancelQueueItem(activeDeleteItem)} loading={actionLoading} title="停止删除" aria-label="停止删除"><X size={15} /></Button>
) : (
<Button key="delete-data" size="icon" variant="danger" onClick={() => setConfirmAction({
title: '清理数据库数据',
description: `确认删除 ${recordTitle(selected)} 的已采集数据库记录?这不会清理智能星球展示缓存,此操作不可恢复。`,
danger: true,
confirmLabel: '删除数据',
run: () => clearDatasourceData(selected),
})} loading={actionLoading} title="清理数据库数据" aria-label="清理数据库数据"><Trash2 size={15} /></Button>
),
const taskId = text(queueItem?.taskId || selected.task_id, '')
return (
<nav className="an-detail-links" aria-label={localizeAdminText('数据源详情', locale)}>
<button
type="button"
className="an-detail-link"
disabled={actionLoading}
onClick={() => void loadDatasourceDetail(selected)}
>
<span>{localizeAdminText('详情与统计', locale)}</span>
<ChevronRight size={14} aria-hidden="true" />
</button>
<button
type="button"
className="an-detail-link"
disabled={actionLoading}
onClick={() => void loadTaskStatus(selected)}
>
<span>{localizeAdminText('任务状态', locale)}</span>
<ChevronRight size={14} aria-hidden="true" />
</button>
<button
type="button"
className="an-detail-link an-detail-link--external"
onClick={() => openLogsForTask({ taskId, sourceId, source })}
>
<span>{localizeAdminText('查看日志', locale)}</span>
<ArrowUpRight size={14} aria-hidden="true" />
</button>
</nav>
)
}
@@ -6962,27 +7049,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const renderModuleActions = () => {
const actions: ReactNode[] = []
if (config === configs.datasources) {
const selectedCount = selectedDatasourceIds.length
const selectedRunningCount = selectedActiveCollectQueueItems.length
const allRunningCount = activeCollectQueueItems.length
const isStopAction = selectedCount ? selectedRunningCount > 0 : allRunningCount > 0
const label = isStopAction
? selectedCount ? `停止已选 ${selectedRunningCount}` : '停止采集'
: selectedCount ? `触发已选 ${selectedCount}` : '触发全部'
const title = isStopAction
? selectedCount ? `停止已选中的 ${selectedRunningCount} 个采集任务` : `停止 ${allRunningCount} 个采集任务`
: selectedCount ? `触发已选 ${selectedCount} 个数据源` : '触发全部数据源'
if (config === configs.datasources && activeCollectQueueItems.length > 0) {
const runningCount = activeCollectQueueItems.length
actions.push(
<Button
key="trigger-primary"
variant="primary"
onClick={() => void triggerDatasourcePrimaryAction()}
key="stop-all-active"
variant="danger"
onClick={() => void cancelCollectionQueueItems(activeCollectQueueItems, '停止采集')}
loading={actionLoading}
title={title}
title={localizeAdminText('停止采集', locale)}
>
{isStopAction ? <Square size={15} /> : <Radio size={15} />}
{label}
<Square size={15} />
{`${localizeAdminText('停止采集', locale)} ${runningCount}`}
</Button>,
)
}
@@ -7049,8 +7127,30 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const renderDatasourceFilters = () => {
if (config !== configs.datasources || activeSection?.key !== 'builtin') return null
const counts = objectAt(activeState?.raw, 'counts')
const countOf = (key: string) => (typeof counts[key] === 'number' ? counts[key] as number : null)
const scheduleOptions = [
{ value: '', label: '全部调度', count: countOf('all') },
{ value: 'true', label: '已启用', count: countOf('active') },
{ value: 'false', label: '已停用', count: countOf('inactive') },
]
const filtersDirty = !datasourceFiltersEqual(datasourceFilters, DEFAULT_DATASOURCE_FILTERS)
return (
<div className="an-filter-grid an-filter-grid--datasources">
<div className="an-segmented an-segmented--counted" role="group" aria-label={localizeAdminText('定时调度', locale)}>
{scheduleOptions.map((option) => (
<button
key={option.value || 'all'}
type="button"
className={datasourceFilters.isActive === option.value ? 'is-active' : undefined}
aria-pressed={datasourceFilters.isActive === option.value}
onClick={() => setDatasourceFilter('isActive', option.value)}
>
{localizeAdminText(option.label, locale)}
{option.count !== null ? <span className="an-segmented__count">{option.count}</span> : null}
</button>
))}
</div>
<label className="an-field an-field--inline-filter">
<select className="an-input" value={datasourceFilters.product} onChange={(event) => setDatasourceFilter('product', event.target.value)}>
<option value="">全部产品域</option>
@@ -7073,13 +7173,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<option value="L4">L4</option>
</select>
</label>
<label className="an-field an-field--inline-filter">
<select className="an-input" value={datasourceFilters.isActive} onChange={(event) => setDatasourceFilter('isActive', event.target.value)}>
<option value="">全部启用状态</option>
<option value="true">已启用</option>
<option value="false">已停用</option>
</select>
</label>
<label className="an-field an-field--inline-filter">
<select className="an-input" value={datasourceFilters.runStatus} onChange={(event) => setDatasourceFilter('runStatus', event.target.value)}>
<option value="">全部执行状态</option>
@@ -7097,6 +7190,23 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<option value="uncollected">未采集</option>
</select>
</label>
{filtersDirty ? (
<Button
size="icon"
variant="subtle"
onClick={() => {
const next = { ...DEFAULT_DATASOURCE_FILTERS }
setDatasourceSelectedRowIds(new Set())
setDatasourceFilters(next)
storeDatasourceFilters(next)
navigate({ pathname: location.pathname, search: datasourceFiltersSearch(next) }, { replace: true })
}}
title={localizeAdminText('重置筛选', locale)}
aria-label={localizeAdminText('重置筛选', locale)}
>
<FilterX size={15} />
</Button>
) : null}
</div>
)
}
@@ -7106,7 +7216,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const sourceId = text(selected.id || selected.source_id, '')
const source = text(selected.source || selected.collector_name, '')
const queueItem = collectionQueue.find((item) => isSameDatasourceRow(selected, item.sourceId || '', item.source || '') && isActiveQueueStatus(item.status))
const status = queueItem?.status || datasourceStatus(selected)
const taskId = text(queueItem?.taskId || selected.task_id, '')
return (
<section className="an-task-summary">
@@ -7114,19 +7223,13 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<strong>采集任务</strong>
<p>{queueItem?.phaseMessage || text(selected.last_status || selected.phase_message, '当前没有运行中的任务。')}</p>
</div>
<StatusText tone={statusTone(status)}>{queueStatusLabel(status, queueItem?.taskType || text(selected.task_type, 'collect'))}</StatusText>
{queueItem ? <span className="an-task-summary__progress">{queueProgress(queueItem)}%</span> : null}
<dl>
<dt>数据源</dt><dd>{source || sourceId || '-'}</dd>
<dt>任务</dt><dd>{text(taskId, '-')}</dd>
<dt>进度</dt><dd>{queueItem ? `${queueProgress(queueItem)}%` : '-'}</dd>
<dt>更新时间</dt><dd>{queueItem?.updatedAt ? new Date(queueItem.updatedAt).toLocaleTimeString() : text(selected.last_run_at, '-')}</dd>
</dl>
<div className="an-task-summary__actions">
<Button size="sm" variant="subtle" onClick={() => openLogsForTask({ taskId, sourceId, source })}>
<FileText size={14} />
查看日志
</Button>
</div>
</section>
)
}
@@ -7207,6 +7310,170 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
await cancelCollectionQueueItems([item], `停止${taskTypeLabel(item.taskType)}`)
}
const activeCollectQueueItemFor = (record: AnyRecord) => activeCollectQueueItems.find((item) => isSameDatasourceRow(record, item.sourceId || '', item.source || ''))
const stopDatasourceCollection = (record: AnyRecord) => {
const queueItem = activeCollectQueueItemFor(record)
const taskId = (queueItem?.taskId || record.task_id) as number | string | null | undefined
if (!taskId) return
void cancelQueueItem(queueItemFromDatasourceRow(record, taskId, {
taskType: 'collect',
status: queueItem?.status || 'running',
phase: text(record.phase, queueItem?.phase || 'running'),
phaseMessage: text(record.phase_message, queueItem?.phaseMessage || '后端任务仍在运行'),
progress: typeof record.progress === 'number' ? record.progress : queueItem?.progress,
createdAt: queueItem?.createdAt || Date.now(),
updatedAt: Date.now(),
}))
}
const datasourceColumns: Array<ColumnDef<TableRecord>> = [
{
id: 'name',
header: localizeAdminText('名称', locale),
size: 148,
cell: ({ row }) => (
<button type="button" className="an-table-link" onClick={() => openResourceDetail(row.original)}>
{localizeDisplayValue(recordTitle(row.original), locale)}
</button>
),
},
{
id: 'schedule',
header: localizeAdminText('定时调度', locale),
size: 64,
enableSorting: false,
cell: ({ row }) => {
const record = row.original
const id = pick(record, ['id', 'source_id', 'key', 'name'], '')
const active = record.is_active !== false
return (
<span className="an-table-switch" onClick={(event) => event.stopPropagation()}>
<AdminSwitch
checked={active}
disabled={Boolean(rowActionLoading[id])}
label={localizeAdminText(active ? '停用调度' : '启用调度', locale)}
onCheckedChange={(next) => void setDatasourceActive(record, next)}
/>
</span>
)
},
},
{ id: 'module', header: localizeAdminText('模块', locale), size: 54, cell: ({ row }) => localizeDisplayValue(row.original.__module, locale) },
{
id: 'status',
header: localizeAdminText('状态', locale),
size: 96,
cell: ({ row }) => {
const status = recordDisplayStatus(row.original)
return <StatusText tone={statusTone(status)}>{localizeDisplayValue(status, locale)}</StatusText>
},
},
{ id: 'metric', header: localizeAdminText('指标', locale), size: 72, cell: ({ row }) => <span className="an-muted-text">{localizeDisplayValue(semanticLabel(recordMetric(row.original)), locale)}</span> },
{ id: 'updated', header: localizeAdminText('更新时间', locale), size: 152, cell: ({ row }) => localizeDisplayValue(row.original.__time, locale) },
{
id: 'actions',
header: localizeAdminText('操作', locale),
size: 104,
enableSorting: false,
cell: ({ row }) => {
const record = row.original
const id = pick(record, ['id', 'source_id', 'key', 'name'], '')
const active = record.is_active !== false
const loadingRow = Boolean(rowActionLoading[id])
const collecting = isCollectTaskActive(record) || Boolean(activeCollectQueueItemFor(record))
const activeDeleteItem = collectionQueue.find(
(item) => isSameDatasourceRow(record, item.sourceId || '', item.source || '') && item.taskType === 'clear_data' && isActiveQueueStatus(item.status),
)
return (
<span className="an-table-actions" onClick={(event) => event.stopPropagation()}>
{collecting ? (
<Button size="icon" variant="danger" onClick={() => stopDatasourceCollection(record)} loading={loadingRow} title={localizeAdminText('停止采集', locale)} aria-label={localizeAdminText('停止采集', locale)}>
<Square size={14} />
</Button>
) : (
<Button
size="icon"
variant="ghost"
icon="trigger"
onClick={() => void triggerDatasourceWithPrecheck(record)}
loading={loadingRow}
disabled={!active}
title={localizeAdminText(active ? '立即采集' : '调度已停用', locale)}
aria-label={localizeAdminText('立即采集', locale)}
/>
)}
<Button
size="icon"
variant="ghost"
onClick={() => setConfirmAction({
title: '清理数据源缓存',
description: `确认清理 ${recordTitle(record)} 的智能星球展示缓存?这不会删除数据库里的采集数据。`,
danger: false,
confirmLabel: '清理缓存',
run: () => clearDatasourceCache(record),
})}
disabled={actionLoading}
title={localizeAdminText('清理缓存', locale)}
aria-label={localizeAdminText('清理缓存', locale)}
>
<BrushCleaning size={14} />
</Button>
{activeDeleteItem ? (
<Button
size="icon"
variant="ghost"
onClick={() => void cancelQueueItem(activeDeleteItem)}
disabled={actionLoading}
title={localizeAdminText('停止删除', locale)}
aria-label={localizeAdminText('停止删除', locale)}
>
<X size={14} />
</Button>
) : (
<Button
size="icon"
variant="ghost"
className="an-table-action--danger"
onClick={() => setConfirmAction({
title: '清理数据库数据',
description: `确认删除 ${recordTitle(record)} 的已采集数据库记录?这不会清理智能星球展示缓存,此操作不可恢复。`,
danger: true,
confirmLabel: '删除数据',
run: () => clearDatasourceData(record),
})}
disabled={actionLoading}
title={localizeAdminText('清理数据库数据', locale)}
aria-label={localizeAdminText('清理数据库数据', locale)}
>
<Trash2 size={14} />
</Button>
)}
</span>
)
},
},
]
const selectedInactiveCount = selectedDatasourceRows.filter((row) => row.is_active === false).length
const selectedActiveCount = selectedDatasourceRows.length - selectedInactiveCount
const renderDatasourceBatchBar = () => (
<DatasourceBatchBar
selectedCount={selectedDatasourceRows.length}
enableCount={selectedInactiveCount}
disableCount={selectedActiveCount}
triggerCount={selectedActiveCount}
stopCount={selectedActiveCollectQueueItems.length}
busy={datasourceBatchAction}
translate={(value) => localizeAdminText(value, locale)}
onEnable={() => void setSelectedDatasourcesActive(true)}
onDisable={confirmDisableSelectedDatasources}
onTrigger={() => void triggerSelectedDatasources()}
onStop={() => void cancelCollectionQueueItems(selectedActiveCollectQueueItems, '停止已选')}
onClear={() => setDatasourceSelectedRowIds(new Set())}
/>
)
const renderCollectionQueuePanel = () => {
if (config !== configs.datasources) return null
const groups: Array<{ key: string; title: string; items: CollectionQueueItem[] }> = [
@@ -7370,23 +7637,29 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
) : isHierarchySection ? (
config === configs.ai ? renderAIHierarchy() : renderConfigHierarchy()
) : (
<div className={`an-resource-layout${mobileResourceDetailOpen ? ' is-mobile-detail-open' : ''}`} style={{ '--an-detail-width': `${detailWidth}px` } as CSSProperties}>
<div
className={`an-resource-layout${isDatasourceBuiltinSection ? ' an-resource-layout--datasources' : ''}${mobileResourceDetailOpen ? ' is-mobile-detail-open' : ''}`}
style={{ '--an-detail-width': `${detailWidth}px` } as CSSProperties}
>
<Panel className="an-resource-main">
<div className="an-panel-heading">
<div>
<h2>{localizeAdminText(activeSection?.label || config.listTitle, locale)}</h2>
<p>{localizeAdminText(config.listDescription, locale)}</p>
</div>
<StatusText tone={loading ? 'running' : activeState?.ok === false ? 'danger' : 'success'}>{localizeAdminText(loading ? '同步中' : activeState?.ok === false ? '接口失败' : '已就绪', locale)}</StatusText>
{isDatasourceBuiltinSection && selectedDatasourceRows.length ? renderDatasourceBatchBar() : (
<StatusText tone={loading ? 'running' : activeState?.ok === false ? 'danger' : 'success'}>{localizeAdminText(loading ? '同步中' : activeState?.ok === false ? '接口失败' : '已就绪', locale)}</StatusText>
)}
</div>
<div className="an-panel-body">
{loading || rows.length > 0 ? (
<ModuleTable
className={isDatasourceBuiltinSection ? 'an-data-table--datasources' : undefined}
rows={rows}
selected={selected}
onSelect={openResourceDetail}
columns={config.columns}
loading={loading}
columns={isDatasourceBuiltinSection ? datasourceColumns : config.columns}
loading={loading && rows.length === 0}
selection={isDatasourceBuiltinSection ? {
selectedRowIds: datasourceSelectedRowIds,
onToggleAllVisible: toggleAllVisibleDatasourceSelection,
+436 -35
View File
@@ -6,6 +6,12 @@
--an-page-padding: 16px;
--an-section-gap: 16px;
--an-panel-gap: 12px;
--an-control-xs: 28px;
--an-control-sm: 32px;
--an-control-md: 34px;
--an-control-lg: 38px;
--an-control-radius: 6px;
--an-control-radius-md: 7px;
--an-bg: #f6f8fb;
--an-surface: #ffffff;
--an-surface-alt: #f9fbfd;
@@ -754,6 +760,19 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
min-width: 0;
}
.an-task-summary strong {
font-size: 13px;
font-weight: 650;
}
.an-task-summary__progress {
align-self: start;
font-size: 12px;
font-weight: 650;
font-variant-numeric: tabular-nums;
color: var(--an-accent);
}
.an-task-summary p {
margin: 3px 0 0;
color: var(--an-muted);
@@ -793,10 +812,9 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
white-space: nowrap;
}
.an-task-summary__actions {
grid-column: 1 / -1;
display: flex;
justify-content: flex-end;
.an-task-summary dt:nth-last-child(-n+4),
.an-task-summary dd:nth-last-child(-n+4) {
border-bottom: 0;
}
.admin__content {
@@ -1061,15 +1079,15 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
.an-toolbar > .tui-button {
align-self: stretch;
height: 34px;
height: var(--an-control-md);
}
.an-toolbar .an-status-pill {
align-self: stretch;
height: 34px;
height: var(--an-control-md);
min-width: 0;
padding: 0 12px;
border-radius: 7px;
border-radius: var(--an-control-radius-md);
line-height: 1;
}
@@ -1362,7 +1380,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
.an-detail-title {
display: flex;
align-items: flex-start;
align-items: center;
justify-content: space-between;
gap: 10px;
}
@@ -1386,6 +1404,62 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
gap: 8px;
}
.an-detail-links {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 16px;
padding-bottom: 10px;
border-bottom: 1px solid var(--an-border);
}
.an-detail-link {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 2px 0;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--an-accent);
font: inherit;
font-size: 13px;
font-weight: 500;
line-height: 1.4;
cursor: pointer;
transition: color 0.14s ease, opacity 0.14s ease;
}
.an-detail-link svg {
flex: 0 0 auto;
opacity: 0.72;
transition: transform 0.14s ease, opacity 0.14s ease;
}
.an-detail-link:hover:not(:disabled) {
text-decoration: underline;
text-underline-offset: 3px;
}
.an-detail-link:hover:not(:disabled) svg {
opacity: 1;
transform: translateX(2px);
}
.an-detail-link--external:hover:not(:disabled) svg {
transform: translate(1px, -1px);
}
.an-detail-link:focus-visible {
outline: 2px solid color-mix(in srgb, var(--an-accent) 78%, white);
outline-offset: -2px;
}
.an-detail-link:disabled {
cursor: not-allowed;
opacity: 0.52;
}
.an-detail-list {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -2806,10 +2880,10 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
.an-input,
.an-select {
width: 100%;
height: 32px;
height: var(--an-control-sm);
min-width: 0;
border: 1px solid var(--an-border);
border-radius: 6px;
border-radius: var(--an-control-radius);
background: var(--an-surface);
color: var(--an-text);
padding: 0 10px;
@@ -3185,20 +3259,74 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
white-space: nowrap;
}
.an-data-table__selection-cell {
width: 42px;
min-width: 42px;
max-width: 42px;
.an-data-table th.an-data-table__selection-cell,
.an-data-table td.an-data-table__selection-cell {
width: 40px;
min-width: 40px;
max-width: 40px;
padding: 0;
text-align: center;
vertical-align: middle;
}
.an-data-table__selection-cell input {
width: 15px;
height: 15px;
margin: 0;
accent-color: var(--an-accent);
.an-data-table__selection-cell input[type='checkbox'] {
position: relative;
box-sizing: border-box;
appearance: none;
-webkit-appearance: none;
display: block;
width: 16px;
height: 16px;
margin: 0 auto;
border: 1.5px solid color-mix(in srgb, var(--an-muted) 56%, var(--an-border));
border-radius: 4px;
background: var(--an-surface);
cursor: pointer;
transition: border-color 0.14s ease, background 0.14s ease;
}
.an-data-table__selection-cell input[type='checkbox']:hover:not(:disabled) {
border-color: var(--an-accent);
}
.an-data-table__selection-cell input[type='checkbox']:checked,
.an-data-table__selection-cell input[type='checkbox']:indeterminate {
border-color: var(--an-accent);
background: var(--an-accent);
}
.an-data-table__selection-cell input[type='checkbox']:checked::after {
content: '';
position: absolute;
box-sizing: border-box;
left: 4px;
top: 1px;
width: 5px;
height: 9px;
border: solid #ffffff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
.an-data-table__selection-cell input[type='checkbox']:indeterminate::after {
content: '';
position: absolute;
left: 3px;
top: 5.5px;
width: 7px;
height: 2px;
border-radius: 1px;
background: #ffffff;
}
.an-data-table__selection-cell input[type='checkbox']:focus-visible {
outline: 2px solid color-mix(in srgb, var(--an-accent) 78%, white);
outline-offset: 0;
}
.an-data-table__selection-cell input[type='checkbox']:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.an-data-table th {
@@ -3878,8 +4006,174 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
}
.an-filter-grid--datasources {
grid-template-columns: repeat(5, minmax(128px, 1fr));
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.an-filter-grid--datasources > .an-segmented--counted {
flex: 0 0 auto;
max-width: 100%;
height: var(--an-control-sm);
}
.an-filter-grid--datasources > .an-field--inline-filter {
flex: 1 1 116px;
min-width: 116px;
}
.an-filter-grid--datasources > .tui-button,
.an-filter-grid--datasources > .tui-button.tui-button--tactile {
flex: 0 0 auto;
width: var(--an-control-sm);
height: var(--an-control-sm);
border-radius: var(--an-control-radius);
box-shadow: none;
}
.an-segmented--counted button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 5px;
}
.an-segmented__count {
font-variant-numeric: tabular-nums;
font-size: 12px;
font-weight: 500;
color: color-mix(in srgb, var(--an-text) 56%, var(--an-muted));
}
.an-segmented--counted button.is-active .an-segmented__count {
color: var(--an-accent);
font-weight: 650;
}
.an-batch-bar {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
flex-wrap: wrap;
justify-content: flex-end;
}
.an-batch-bar__count {
display: inline-flex;
align-items: baseline;
gap: 4px;
padding-right: 4px;
color: var(--an-muted);
font-size: 12px;
white-space: nowrap;
}
.an-batch-bar__count strong {
color: var(--an-text);
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.an-batch-bar__num {
font-variant-numeric: tabular-nums;
opacity: 0.72;
}
.an-table-switch,
.an-table-actions,
.an-inline-switch {
display: inline-flex;
align-items: center;
}
.an-table-switch {
justify-content: center;
}
.an-table-actions {
gap: 2px;
justify-content: center;
}
.an-table-actions .tui-button--icon {
width: var(--an-control-xs);
height: var(--an-control-xs);
border-radius: var(--an-control-radius);
color: var(--an-muted);
}
.an-table-actions .tui-button--icon:hover:not(:disabled) {
color: var(--an-text);
}
.an-table-actions .tui-button--danger {
color: #fff;
}
.an-table-actions .an-table-action--danger:hover:not(:disabled),
.an-table-actions .an-table-action--danger:focus-visible {
color: var(--an-danger);
background: color-mix(in srgb, var(--an-danger) 12%, transparent);
}
.an-inline-switch {
gap: 6px;
height: 32px;
color: var(--an-muted);
font-size: 12px;
white-space: nowrap;
}
.an-data-table tr.is-filter-stale td {
opacity: 0.48;
}
.an-data-table--datasources .an-data-table__table {
min-width: 730px;
}
.an-data-table--datasources th,
.an-data-table--datasources td {
padding: 0 10px;
}
.an-data-table--datasources th.an-data-table__selection-cell,
.an-data-table--datasources td.an-data-table__selection-cell {
width: 40px;
min-width: 40px;
max-width: 40px;
padding: 0;
text-align: center;
}
.an-data-table--datasources th[data-column-id='schedule'],
.an-data-table--datasources td[data-column-id='schedule'] {
text-align: center;
}
.an-data-table--datasources th[data-column-id='schedule'] .an-data-table__sort {
justify-content: center;
cursor: default;
}
.an-data-table--datasources th[data-sticky-end='true'],
.an-data-table--datasources td[data-sticky-end='true'] {
padding: 0 8px;
text-align: center;
}
.an-data-table--datasources th[data-sticky-end='true'] .an-data-table__sort {
justify-content: center;
cursor: default;
}
.an-data-table--datasources .an-table-link {
max-width: 148px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.an-field--inline-filter .an-input {
@@ -4362,29 +4656,51 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
.an-segmented {
height: 30px;
display: inline-flex;
align-items: stretch;
gap: 2px;
border: 1px solid var(--an-border);
border-radius: 6px;
border-radius: var(--an-control-radius);
padding: 2px;
background: var(--an-surface-alt);
background: color-mix(in srgb, var(--an-border) 34%, var(--an-surface-alt));
}
.admin-theme-root[data-theme='dark'] .an-segmented {
background: color-mix(in srgb, #000 28%, var(--an-surface-alt));
}
.an-segmented button {
min-width: 0;
border: 0;
border: 1px solid transparent;
background: transparent;
color: var(--an-muted);
color: color-mix(in srgb, var(--an-text) 68%, var(--an-muted));
border-radius: 4px;
padding: 0 10px;
font: inherit;
font-size: 13px;
font-weight: 500;
line-height: 1;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
transition: background 0.14s ease, color 0.14s ease, border-color 0.14s ease, box-shadow 0.14s ease;
}
.an-segmented button:hover:not(:disabled):not(.is-active) {
color: var(--an-text);
}
.an-segmented button.is-active {
background: var(--an-surface);
color: var(--an-text);
border: 1px solid var(--an-border);
font-weight: 600;
border-color: color-mix(in srgb, var(--an-border) 88%, transparent);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
}
.admin-theme-root[data-theme='dark'] .an-segmented button.is-active {
background: color-mix(in srgb, var(--an-surface) 92%, #ffffff);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.35);
}
.an-segmented button:focus-visible {
@@ -4535,8 +4851,28 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
grid-template-columns: 1fr;
}
.an-filter-grid--datasources {
grid-template-columns: repeat(3, minmax(112px, 1fr));
.an-filter-grid--datasources > .an-segmented--counted {
flex: 1 0 100%;
}
.an-segmented--counted button {
flex: 1 1 0;
}
}
@media (900px < width <= 1100px) {
.an-resource-layout--datasources .an-resource-side,
.an-resource-layout--datasources.is-mobile-detail-open .an-resource-main {
display: none;
}
.an-resource-layout--datasources.is-mobile-detail-open .an-resource-side {
display: grid;
grid-template-rows: auto minmax(0, 1fr);
}
.an-resource-layout--datasources .an-mobile-detail-bar {
display: flex;
}
}
@@ -4638,15 +4974,65 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
padding: 12px;
}
.an-page {
gap: 8px;
}
.an-page__header {
display: grid;
gap: 8px;
}
.an-page__header h1 {
font-size: 19px;
}
.an-page-grid,
.an-resource-page .an-page__body {
gap: 8px;
}
.an-toolbar {
justify-content: flex-start;
}
.an-summary-strip,
.an-summary-strip {
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 6px;
}
.an-summary-strip .an-stat-cell {
padding: 8px 10px;
gap: 2px;
}
.an-summary-strip .an-stat-cell strong {
font-size: 18px;
}
.an-summary-strip .an-stat-cell span,
.an-summary-strip .an-stat-cell small {
font-size: 11px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.an-panel-heading {
min-height: 40px;
padding: 8px 12px;
flex-wrap: wrap;
gap: 8px;
}
.an-panel-body {
padding: 8px;
}
.an-batch-bar {
justify-content: flex-start;
}
.an-kpi-grid,
.an-summary-kpis,
.an-detail-list,
@@ -4663,7 +5049,12 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
}
.an-filter-grid--datasources {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px;
}
.an-filter-grid--datasources > .an-field--inline-filter {
flex: 1 1 calc(42% - 6px);
min-width: 0;
}
.an-collection-queue__bar {
@@ -4688,6 +5079,22 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.an-task-summary dt:nth-last-child(-n+4),
.an-task-summary dd:nth-last-child(-n+4) {
border-bottom: 1px solid var(--an-border);
}
.an-task-summary dt:nth-last-child(-n+2),
.an-task-summary dd:nth-last-child(-n+2) {
border-bottom: 0;
}
.an-data-table--datasources th[data-sticky-end='true'],
.an-data-table--datasources td[data-sticky-end='true'] {
position: static;
box-shadow: none;
}
.an-logs-filters {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@@ -4743,9 +5150,3 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
grid-template-columns: 1fr;
}
}
@media (max-width: 420px) {
.an-filter-grid--datasources {
grid-template-columns: 1fr;
}
}
@@ -169,7 +169,7 @@ body[data-admin-theme='dark'] .tui-tooltip {
.tui-switch {
width: var(--tui-control-width, 38px);
height: var(--tui-control-height, 20px);
border: 1px solid var(--tui-border-soft);
border: 1px solid var(--tui-border);
border-radius: var(--tui-control-radius, 8px);
margin: var(--tui-control-margin, 0);
padding: 2px;
@@ -178,9 +178,9 @@ body[data-admin-theme='dark'] .tui-tooltip {
justify-content: flex-start;
flex: 0 0 auto;
background: var(--tui-control-bg, linear-gradient(180deg, var(--tui-surface), var(--tui-surface-soft)));
box-shadow: var(--tui-control-shadow, 0 2px 5px rgba(15, 23, 42, 0.13), 0 8px 18px rgba(15, 23, 42, 0.07));
box-shadow: none;
cursor: pointer;
transition: border-color 0.16s ease, background 0.16s ease, box-shadow 0.16s ease;
transition: border-color 0.16s ease, background 0.16s ease;
}
.tui-switch span {
@@ -188,7 +188,7 @@ body[data-admin-theme='dark'] .tui-tooltip {
height: 14px;
border-radius: 6px;
background: linear-gradient(180deg, #ffffff, #dbeafe);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.2);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.18);
transition: transform 0.18s ease, background 0.16s ease;
}
+21
View File
@@ -899,4 +899,25 @@ export const legacyUiTextEnUS: Record<string, string> = {
'发件邮箱': 'Sender email',
'发件人名称': 'Sender name',
'个历史快照,选择后查看该版本详情。': 'historical snapshots. Select one to view that version.',
'批量操作': 'Bulk actions',
'已选择': 'selected',
'定时调度': 'Schedule',
'启用调度': 'Enable schedule',
'停用调度': 'Disable schedule',
'已启用调度': 'Schedule enabled',
'已停用调度': 'Schedule disabled',
'启用调度失败': 'Failed to enable schedule',
'停用调度失败': 'Failed to disable schedule',
'数据源不存在': 'Data sources not found',
'调度同步失败': 'Schedule sync failed',
'调度已停用': 'Schedule is disabled',
'立即采集': 'Collect now',
'已提交采集': 'Collection submitted',
'触发采集失败': 'Failed to trigger collection',
'已强制重新触发': 'Collection restarted',
'清除选择': 'Clear selection',
'重置筛选': 'Reset filters',
'操作': 'Actions',
'详情与统计': 'Details & stats',
'全部调度': 'All schedules',
}
+4 -4
View File
@@ -5372,7 +5372,7 @@ bundle_command() {
case "$target" in
-h|--help|help)
log_note "用法: ./planet.sh bundle [--win|--linux|--mac|--dir|--all]"
log_note "用法: ./planet.sh bundle [--win|--linux|--mac|--dir|--hotfix|--all]"
return 0
;;
"" )
@@ -5384,11 +5384,11 @@ bundle_command() {
target="--linux"
fi
;;
--win|--linux|--mac|--dir|--all)
--win|--linux|--mac|--dir|--hotfix|--all)
;;
*)
log_error "未知打包目标: ${target}"
printf "${DIM} %s${NC}\n" "支持: --win, --linux, --mac, --dir, --all" >&2
printf "${DIM} %s${NC}\n" "支持: --win, --linux, --mac, --dir, --hotfix, --all" >&2
exit 1
;;
esac
@@ -5418,7 +5418,7 @@ start / restart 可加 --no-build:仅使用本地已有镜像,缺少镜像
start 启动服务;默认启动 Web 全量前端;加 --admin 用轻量 Admin 容器替代 Vite,--admin-only 仅启动后端+Admin 容器,--no-frontend 不启动 Web
admin 单独管理 Admin 轻量容器: ./planet.sh admin {start|stop|restart|health|log}
earth 启动 Electron Earth 桌面端 (WSL2 优先拉起原生 Windows 客户端,加 --linux 强制 Linux)
bundle 打包跨平台独立客户端: ./planet.sh bundle {--win|--linux|--mac|--dir|--all}
bundle 打包跨平台独立客户端: ./planet.sh bundle {--win|--linux|--mac|--dir|--hotfix|--all}
deploy 生产编排管理: ./planet.sh deploy {up|down|restart|status|logs|init-env} [--split] [--no-build] [--env-file <path>]
backup 执行 PostgreSQL 滚动压缩备份: ./planet.sh backup [--mode full|core] [--retention-days 14]
migrate 数据库版本迁移: ./planet.sh migrate {status|upgrade|stamp <version>} [--container [name]]
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.80.0"
version = "0.80.2"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+23
View File
@@ -363,10 +363,28 @@ Backend/admin pages are compact single-screen workspaces (`一屏` / `首屏`):
- Connection-test actions for endpoint/Base URL inputs must use the shared `ConnectionTestInput` pattern: a single plug/connector icon at the input suffix, no adjacent text button; disabled integrations should grey out the field and its test action.
- Do not put cards inside cards.
- Do not use visible in-app text to explain obvious UI features or styling.
- Let layout explain: state, grouping and available actions must be readable from control type, placement and alignment (switches for persistent state, buttons for actions, contextual toolbars that appear with a selection, dimmed rows for out-of-filter items). Fix an unclear layout instead of adding helper captions, hint paragraphs or inline instructions.
- Text must fit within its parent on mobile and desktop.
- Do not scale font size with viewport width.
- Letter spacing should usually be `0`.
### Admin Control Design Contract (Mandatory Baseline)
- **Control Density Tiers**: `.admin-theme-root` defines and components reuse 4 explicit height/radius tiers so controls sharing a horizontal row stay optically flush and never cause row-height jumps when dynamic buttons mount or unmount (`heightDelta === 0`):
- `--an-control-xs` (`28px`, radius `6px`, `12px`/`500`, `14px` icon): table row `操作` icon buttons (`.an-table-actions .tui-button--icon`) and compact inline micro-actions.
- `--an-control-sm` (`32px`, radius `6px`, `13px`/`500` and `600` active, `14–15px` icon): filter-bar controls (segmented bars, `<select>`, `.an-input`, search box, filter-reset button), form fields, contextual batch bar, and table pagination. Any dynamic icon button inside a `32px` filter row must override `.tui-button--tactile`'s `34px` preset down to `--an-control-sm` (`box-shadow: none`).
- `--an-control-md` (`34px`, radius `7px`, `13px`/`650`, `15px` icon): page-header `.an-toolbar` buttons and status pills.
- `--an-control-lg` (`38px`, radius `7px`, `14px`/`650`, `16px` icon): auth / standalone emphasis primary buttons.
- **Button Hierarchy & Semantic Links**:
- At most one `primary` button per toolbar/panel; use `subtle` for secondary actions, `ghost` for table-row actions (resting muted tint, hover/focus `--an-danger` + `12%` red tint for destructive icons), and `danger` only for confirmation modals or emergency stop of active tasks.
- Drill-down sub-views and cross-page navigation inside detail inspectors must use semantic link controls (`.an-detail-link` with `>` / upper-right arrow cues), never crowded button strips.
- **Filter Bars, Segmented Controls, Switches, Checkboxes & Tables**:
- Filter toolbars use wrap-safe Flexbox (`flex-wrap: wrap; align-items: center`) with `min-width`-bounded inputs/selects rather than rigid grid tracks that crush controls on mobile/zoom.
- `.an-segmented button` reserves a `1px solid transparent` idle border (preventing `1px` active-state jitter), maintains distinct trough contrast in light and dark themes, and renders counts in `12px` `tabular-nums`.
- Binary scheduling/setting switches keep the rounded-square `.tui-switch` geometry (`38×20px`, `8px`/`6px` radius, `1px solid var(--tui-border)` rim, `box-shadow: none`), centered under matching `data-column-id` table headers.
- Table selection checkboxes declare high-specificity `.an-data-table th/td.an-data-table__selection-cell` centering inside `40px` cells; table action columns carry an explicit centered header (`操作` / `Actions`) and unpin sticky-end on `<=760px` mobile; detail panels show at most one status pill per entity.
- Enforced statically by `scripts/harness/frontend-rules-check.sh` (`check_admin_control_design_contract`) and visually/geometrically by `scripts/harness/frontend-smoke.mjs`.
### Earth HUD Baseline & Creative Space (Shell Unified, Interior Expressive)
Earth HUD cards and floating panels follow **“壳层统一、内景自由”**: align outer shell, liquid-glass material, shared controls, and focus/pin mechanics so new features feel native to the HUD, while keeping interior visualizations and domain layouts open to creative design.
@@ -650,6 +668,11 @@ release-oriented change.
- Before committing a release, verify target version consistency.
- Before pushing a release, run the smallest relevant validation for the changed scope and report what was or was not validated.
- Do not include generated runtime output directories in release commits.
- **Scoped Release & Deployment Classification**: Releases resolve changed paths (`scripts/release_scope.py`) against the previous stable tag and record exact service image digests plus `client.mode` (`none` | `hotfix` | `full`) in `release-manifest.json`:
- `admin`-only, `backend`-only, or `aiprovider`-only changes build/push/roll out **only** the affected container image(s) and must **not** package desktop clients or publish client update manifests.
- `frontend/public/earth/**` (without `client/**`) emits only the lightweight L1 Earth hotfix bundle (`--hotfix`) while preserving the prior `shell_version`.
- `client/**` triggers full multi-platform desktop installer builds (`--all`, producing `.exe`/`.zip`, `.AppImage`/`.deb`, `.zip`) plus the L1 hotfix bundle.
- Docs/harness-only changes do not trigger production rollouts.
### Verify
+71
View File
@@ -692,6 +692,76 @@ def check_connection_test_input_pattern() -> None:
fail("WebSearch Base URL field must expose a disabled-aware connection test through inputAction")
def check_admin_control_design_contract() -> None:
admin_css = read_text("frontend/src/admin/styles.css")
tactile_css = read_text("frontend/src/components/tactile-ui/styles.css")
data_table_tsx = read_text("frontend/src/admin/components/data-table/DataTable.tsx")
theme_root = css_block_for_selector(admin_css, ".admin-theme-root")
for token in ("--an-control-xs", "--an-control-sm", "--an-control-md", "--an-control-radius"):
if theme_root is None or not css_has_declaration(theme_root[1], token, r"[^;]+"):
fail(f"frontend/src/admin/styles.css: .admin-theme-root must define Admin control token {token}")
selection_block = css_block_for_selector(
admin_css,
".an-data-table th.an-data-table__selection-cell",
)
if selection_block is None:
fail(
"frontend/src/admin/styles.css: table selection cells must declare "
".an-data-table th.an-data-table__selection-cell / td.an-data-table__selection-cell "
"so centering beats generic td rules"
)
else:
line_no, body = selection_block
if not css_has_declaration(body, "text-align", r"center"):
fail(
f"frontend/src/admin/styles.css:{line_no}: selection cell rule must declare text-align: center"
)
filter_reset_block = css_block_for_selector(
admin_css,
".an-filter-grid--datasources > .tui-button.tui-button--tactile",
)
if filter_reset_block is None or not css_has_declaration(
filter_reset_block[1],
"height",
r"(?:var\(--an-control-sm\)|32px)",
):
fail(
"frontend/src/admin/styles.css: .an-filter-grid--datasources > .tui-button.tui-button--tactile "
"must lock height to var(--an-control-sm) so filter reset never shifts row height"
)
segmented_btn = css_block_for_selector(admin_css, ".an-segmented button")
if segmented_btn is None or not css_has_declaration(
segmented_btn[1],
"border",
r"1px\s+solid\s+transparent",
):
fail(
"frontend/src/admin/styles.css: .an-segmented button must reserve 1px solid transparent "
"border to prevent active-state jitter"
)
switch_blocks = [
body
for _line_no, selector, body in iter_css_blocks(tactile_css)
if ".tui-switch" in [item.strip() for item in selector.split(",")]
]
if not switch_blocks or not any(css_has_declaration(body, "box-shadow", r"none") for body in switch_blocks):
fail(
"frontend/src/components/tactile-ui/styles.css: .tui-switch must declare box-shadow: none "
"for shadowless table/form clarity"
)
if "data-column-id={header.column.id}" not in data_table_tsx or "data-column-id={cell.column.id}" not in data_table_tsx:
fail(
"frontend/src/admin/components/data-table/DataTable.tsx: th and td must expose data-column-id "
"for column-level alignment rules"
)
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}]+)")
@@ -976,6 +1046,7 @@ def main() -> None:
check_connection_test_input_pattern()
check_admin_shell_height_chain()
check_admin_header_and_focus_safety()
check_admin_control_design_contract()
check_earth_hud_baseline()
check_earth_icon_consistency()
check_uiux_static_warnings()
+120 -5
View File
@@ -835,6 +835,19 @@ const datasource = {
retry_attempts: 2,
}
const disabledDatasource = {
...datasource,
id: 2,
source_id: 'ris_live_bgp',
name: 'ris_live_bgp',
display_name: 'RIPE RIS Live BGP',
source: 'ris_live_bgp',
collected_records: 0,
is_active: false,
}
const datasourceCounts = { all: 2, active: 1, inactive: 1 }
const integrationSettings = {
integrations: {
ai_provider: {
@@ -990,7 +1003,22 @@ function apiPayloadFor(requestUrl, method) {
if (path === '/collected/types') return jsonResponse({ data_types: ['bgp_event'] })
if (path === '/collected/countries') return jsonResponse({ countries: ['CN'] })
if (path === '/datasources') return jsonResponse([datasource])
const datasourceToggle = method === 'POST' ? path.match(/^\/datasources\/(\d+)\/(enable|disable)$/) : null
if (datasourceToggle) {
const isActive = datasourceToggle[2] === 'enable'
const sourceId = Number(datasourceToggle[1])
const base = sourceId === disabledDatasource.id ? disabledDatasource : datasource
return jsonResponse({
status: isActive ? 'enabled' : 'disabled',
source_id: sourceId,
data: { ...base, is_active: isActive },
counts: datasourceCounts,
})
}
if (method === 'POST' && path === '/datasources/batch-status') {
return jsonResponse({ is_active: true, updated: [], unchanged: [], not_found: [], sync_failed: [], counts: datasourceCounts })
}
if (path === '/datasources') return jsonResponse({ total: 2, data: [datasource, disabledDatasource], counts: datasourceCounts })
if (path === '/datasources/configs') return jsonResponse([datasource])
if (path === '/datasources/configs/all') return jsonResponse([datasource])
if (path === '/datasources/mappings') return jsonResponse({ mappings: [{ id: 1, name: 'Default Mapping', target_schema: 'collected_data', validation_status: 'valid' }] })
@@ -1695,6 +1723,88 @@ async function runAIModelCatalogChecks(browser, failures, consoleErrors) {
}
}
async function runDatasourceSchedulingChecks(browser, failures, consoleErrors) {
for (const viewport of [desktopViewport, mobileViewport]) {
const context = await browser.newContext({ viewport })
await installApiMocks(context)
bindConsoleCollection(context, consoleErrors)
const page = await context.newPage()
await seedAuthenticatedState(page)
let listRequests = 0
const toggles = []
page.on('request', (request) => {
const { pathname } = new URL(request.url())
if (request.method() === 'GET' && pathname.endsWith('/api/v1/datasources')) listRequests += 1
if (request.method() === 'POST' && /\/datasources\/\d+\/(enable|disable)$/.test(pathname)) toggles.push(pathname)
})
try {
smokeProgress(`datasource scheduling ${viewport.width}px`)
await page.goto(urlFor('/datasources'), { waitUntil: 'domcontentloaded' })
const enableSwitch = page.getByRole('switch', { name: '启用调度', exact: true })
await enableSwitch.first().waitFor({ state: 'visible' })
assert.equal(await page.getByRole('button', { name: '触发全部' }).count(), 0, 'idle datasources toolbar must not show redundant trigger-all button')
assert.equal(await page.locator('thead th', { hasText: '操作' }).count(), 1, 'datasources table must label its actions column')
const filterHeightBefore = await page.evaluate(() => Math.round(document.querySelector('.an-filter-grid--datasources')?.getBoundingClientRect().height || 0))
await page.locator('.an-segmented--counted button', { hasText: '已启用' }).click()
await page.getByRole('button', { name: '重置筛选' }).waitFor({ state: 'visible' })
const filterMetricsDirty = await page.evaluate(() => {
const grid = document.querySelector('.an-filter-grid--datasources')?.getBoundingClientRect()
const seg = document.querySelector('.an-filter-grid--datasources > .an-segmented--counted')?.getBoundingClientRect()
const sel = document.querySelector('.an-filter-grid--datasources select')?.getBoundingClientRect()
const resetBtn = document.querySelector('.an-filter-grid--datasources > button')?.getBoundingClientRect()
return {
gridH: grid ? Math.round(grid.height) : 0,
segH: seg ? Math.round(seg.height) : 0,
selH: sel ? Math.round(sel.height) : 0,
resetH: resetBtn ? Math.round(resetBtn.height) : 0,
}
})
assert.equal(filterMetricsDirty.gridH, filterHeightBefore, 'mounting filter reset button must not change filter row height')
assert.equal(filterMetricsDirty.segH, 32, 'segmented filter control must stay 32px tall')
assert.equal(filterMetricsDirty.selH, 32, 'filter select control must stay 32px tall')
assert.equal(filterMetricsDirty.resetH, 32, 'filter reset button must stay 32px tall')
await page.getByRole('button', { name: '重置筛选' }).click()
const alignment = await page.evaluate(() => {
const cb = document.querySelector('thead th.an-data-table__selection-cell input')?.getBoundingClientRect()
const cell = document.querySelector('thead th.an-data-table__selection-cell')?.getBoundingClientRect()
const schedTh = document.querySelector('thead th[data-column-id="schedule"]')?.getBoundingClientRect()
const schedSwitch = document.querySelector('tbody td[data-column-id="schedule"] [role="switch"]')?.getBoundingClientRect()
return {
checkboxDelta: cb && cell ? Math.abs((cb.left - cell.left) - (cell.right - cb.right)) : null,
scheduleDelta: schedTh && schedSwitch ? Math.abs(((schedTh.left + schedTh.right) / 2) - ((schedSwitch.left + schedSwitch.right) / 2)) : null,
}
})
assert.ok(alignment.checkboxDelta !== null && alignment.checkboxDelta <= 1.5, `selection checkbox must be centered, got delta=${alignment.checkboxDelta}`)
assert.ok(alignment.scheduleDelta !== null && alignment.scheduleDelta <= 1.5, `schedule switch must align with header center, got delta=${alignment.scheduleDelta}`)
const listRequestsBeforeToggle = listRequests
await enableSwitch.first().click()
await page.locator('.an-toast--success').first().waitFor({ state: 'visible' })
assert.deepEqual(toggles, ['/api/v1/datasources/2/enable'], 'row switch must call the single enable endpoint')
assert.equal(listRequests, listRequestsBeforeToggle, 'toggling scheduling must not reload the datasource list')
assert.equal(await page.getByRole('switch', { name: '停用调度', exact: true }).count(), 2, 'toggled row must update in place')
await page.locator('tbody .an-data-table__selection-cell input').first().check()
await page.locator('.an-batch-bar').waitFor({ state: 'visible' })
if (viewport.width >= 1024) {
await page.locator('.an-table-link', { hasText: 'open_bgp' }).click()
await page.locator('.an-detail-links').waitFor({ state: 'visible' })
assert.equal(await page.locator('.an-detail-links .an-detail-link', { hasText: '详情与统计' }).count(), 1)
assert.equal(await page.locator('.an-detail-links .an-detail-link', { hasText: '任务状态' }).count(), 1)
assert.equal(await page.locator('.an-detail-links .an-detail-link', { hasText: '查看日志' }).count(), 1)
assert.equal(await page.locator('.an-detail-content .an-status-pill').count(), 1, 'datasource detail panel must not duplicate the status pill')
}
if (process.env.PLANET_DATASOURCE_SCREENSHOT_DIR) {
await page.screenshot({ path: `${process.env.PLANET_DATASOURCE_SCREENSHOT_DIR}/datasources-${viewport.width}.png`, fullPage: false })
}
await checkNoFrameworkOverlay(page, 'datasource scheduling')
await checkNoGlobalHorizontalOverflow(page, 'datasource scheduling')
} catch (error) {
failures.push(`datasource scheduling ${viewport.width}px: ${formatSmokeError(error)}`)
} finally {
await context.close()
}
}
}
async function runDocsInteractionChecks(browser, failures, consoleErrors) {
const context = await browser.newContext({ viewport: desktopViewport })
await installApiMocks(context)
@@ -1930,11 +2040,13 @@ async function runEarthNewsRefreshChecks(browser, failures) {
await frame.waitForFunction(() => !document.getElementById('news-refresh')?.disabled, null, { timeout: 5000 })
assert.equal(await buttonsAreReady(), true, 'retry did not restore refresh buttons')
await checkNoFrameworkOverlay(page, 'earth manual news refresh lifecycle')
await page.close()
smokeProgress('earth mobile news refresh')
await page.setViewportSize(mobileViewport)
await page.goto(urlFor('/earth'), { waitUntil: 'domcontentloaded' })
const mobileFrame = await getEarthFrame(page, 'earth mobile news refresh')
const mobilePage = await context.newPage()
await mobilePage.setViewportSize(mobileViewport)
await mobilePage.goto(urlFor('/earth'), { waitUntil: 'domcontentloaded' })
const mobileFrame = await getEarthFrame(mobilePage, 'earth mobile news refresh')
await mobileFrame.waitForFunction(() => (
document.getElementById('mobile-news-board-list')?.children.length > 0
), null, { timeout: SMOKE_RENDER_TIMEOUT_MS })
@@ -1957,7 +2069,7 @@ async function runEarthNewsRefreshChecks(browser, failures) {
const mobileStatus = await mobileFrame.evaluate(() => document.getElementById('mobile-news-board-status')?.innerText || '')
assert.ok(mobileStatus.includes('态势新闻已刷新'), 'mobile refresh did not show completed status')
assert.deepEqual(runtimeErrors, [], 'news refresh emitted uncaught page errors')
await checkNoFrameworkOverlay(page, 'earth mobile news refresh')
await checkNoFrameworkOverlay(mobilePage, 'earth mobile news refresh')
} catch (error) {
failures.push(formatSmokeError(error))
} finally {
@@ -2588,6 +2700,8 @@ async function main() {
failures.push(formatSmokeError(error))
}
await context.close()
await runAuthenticatedAdminChecks(browser, failures, consoleErrors, {
label: 'desktop',
viewport: desktopViewport,
@@ -2611,6 +2725,7 @@ async function main() {
}
await runAdminInteractionChecks(browser, failures, consoleErrors)
await runAIModelCatalogChecks(browser, failures, consoleErrors)
await runDatasourceSchedulingChecks(browser, failures, consoleErrors)
await runDocsInteractionChecks(browser, failures, consoleErrors)
await runAuthInteractionChecks(browser, failures, consoleErrors)
await runEarthNewsRefreshChecks(browser, failures)
+241 -1
View File
@@ -5,7 +5,7 @@ import sys
import tarfile
import tempfile
import unittest
from contextlib import ExitStack
from contextlib import ExitStack, redirect_stdout
from pathlib import Path
from unittest.mock import patch
@@ -13,6 +13,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import production_deploy as deploy
import production_registry as registry
import production_release as publisher
import release_publish as publish
import release_scope as scope
def hotfix(tag):
@@ -235,5 +237,243 @@ class ImageTests(unittest.TestCase):
registry.release_bundle(release, tag)
class ScopedReleaseTests(unittest.TestCase):
def test_classify_changed_paths_scopes_independently(self):
admin_only = scope.classify_changed_paths(
["frontend/src/admin/styles.css", "docs/CHANGELOG.md", "rules.md"]
)
self.assertEqual(admin_only.services, ("admin",))
self.assertEqual(admin_only.client_mode, "none")
self.assertEqual(admin_only.components, ("admin",))
backend_only = scope.classify_changed_paths(["backend/app/api/v1/datasources.py"])
self.assertEqual(backend_only.services, ("backend",))
self.assertEqual(backend_only.client_mode, "none")
provider_only = scope.classify_changed_paths(["aiprovider/main.py"])
self.assertEqual(provider_only.services, ("aiprovider",))
self.assertEqual(provider_only.client_mode, "none")
hotfix_only = scope.classify_changed_paths(["frontend/public/earth/js/main.js"])
self.assertEqual(hotfix_only.services, ())
self.assertEqual(hotfix_only.client_mode, "hotfix")
self.assertEqual(hotfix_only.components, ("earth-hotfix",))
cards_manifest = scope.classify_changed_paths(
["frontend/public/earth/assets/cards/manifest.json"]
)
self.assertEqual(cards_manifest.services, ("backend",))
self.assertEqual(cards_manifest.client_mode, "hotfix")
shell_release = scope.classify_changed_paths(["client/src/main/index.ts", "frontend/src/admin/styles.css"])
self.assertEqual(shell_release.services, ("admin",))
self.assertEqual(shell_release.client_mode, "full")
docs_only = scope.classify_changed_paths(["docs/HARNESS.md", "scripts/harness/doctor.sh"])
self.assertEqual(docs_only.services, ())
self.assertEqual(docs_only.client_mode, "none")
self.assertEqual(docs_only.components, ("metadata",))
tooling_only = scope.classify_changed_paths(
["planet.sh", "client/scripts/dist-target.mjs", "client/tests/update.test.ts"]
)
self.assertEqual(tooling_only.services, ())
self.assertEqual(tooling_only.client_mode, "none")
self.assertEqual(tooling_only.components, ("metadata",))
after_pack = scope.classify_changed_paths(["client/scripts/after-pack.cjs"])
self.assertEqual(after_pack.client_mode, "full")
def test_scope_override_and_previous_stable_tag(self):
self.assertEqual(
scope.previous_stable_tag("v0.80.2", ["v0.79.9", "v0.80.0", "v0.80.1", "v0.80.2", "v1.0.0-rc1"]),
"v0.80.1",
)
parsed = scope.parse_scope_override("backend,admin")
self.assertEqual(parsed.services, ("backend", "admin"))
self.assertEqual(parsed.client_mode, "none")
hotfix_override = scope.parse_scope_override("hotfix")
self.assertEqual(hotfix_override.services, ())
self.assertEqual(hotfix_override.client_mode, "hotfix")
def test_ensure_images_scoped_reuses_unchanged_pins_and_select_packages_modes(self):
prev_pins = {
"aiprovider": "gitea.rclaw.top/linkong/planet/aiprovider:v1.0.0@sha256:" + "1" * 64,
"backend": "gitea.rclaw.top/linkong/planet/backend:v1.0.0@sha256:" + "2" * 64,
"admin": "gitea.rclaw.top/linkong/planet/admin:v1.0.0@sha256:" + "3" * 64,
}
new_admin = "gitea.rclaw.top/linkong/planet/admin:v1.1.0@sha256:" + "4" * 64
with (
tempfile.TemporaryDirectory() as temp,
patch.object(publisher, "resolve_image", side_effect=[None, new_admin]),
patch.object(publisher.subprocess, "run") as run,
):
pins = publisher.ensure_images(
Path(temp),
"v1.1.0",
"a" * 40,
services=("admin",),
previous_services=prev_pins,
)
run.assert_called_once()
self.assertEqual(pins["aiprovider"], prev_pins["aiprovider"])
self.assertEqual(pins["backend"], prev_pins["backend"])
self.assertEqual(pins["admin"], new_admin)
root = Path(temp)
self.assertEqual(publisher.select_packages(root, "v1.1.0", (".zip", ".tar.gz"), client_mode="none"), [])
bundle = root / "planet-earth-bundle-1.1.0.tar.gz"
bundle.write_bytes(hotfix("v1.1.0"))
self.assertEqual(
publisher.select_packages(root, "v1.1.0", (".zip", ".tar.gz"), client_mode="hotfix"),
[bundle],
)
self.assertEqual(
publisher.select_packages(root, "v1.1.0", (".zip", ".tar.gz"), client_mode="full"),
[],
)
def test_admin_only_deploy_restarts_only_admin_and_skips_hotfix(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
host = deploy.Host(base / "host", base / "settings", base / "state")
host.state.mkdir()
(host.directory("v1.0.0")).mkdir(parents=True)
for name in deploy.HOST_FILES:
(host.directory("v1.0.0") / name).write_text("host-managed")
deploy.point_current(host, "v1.0.0")
old_refs = {
"aiprovider": f"gitea.rclaw.top/linkong/planet/aiprovider:v1.0.0@sha256:{'1' * 64}",
"backend": f"gitea.rclaw.top/linkong/planet/backend:v1.0.0@sha256:{'2' * 64}",
"admin": f"gitea.rclaw.top/linkong/planet/admin:v1.0.0@sha256:{'3' * 64}",
}
new_admin = f"gitea.rclaw.top/linkong/planet/admin:v1.1.0@sha256:{'4' * 64}"
new_refs = {**old_refs, "admin": new_admin}
manifest = {
"schema_version": 1,
"tag": "v1.1.0",
"commit": "f" * 40,
"previous_tag": "v1.0.0",
"components": ["admin"],
"changed_services": ["admin"],
"services": new_refs,
"client": {"mode": "none", "shell_version": "1.0.0", "min_shell_version": "1.0.0"},
}
host.env.write_text(
"\n".join([f"{registry.SERVICES[k]}={v}" for k, v in old_refs.items()] + ["LIMIT=500m"]) + "\n"
)
live_manifest = base / "manifest.json"
original_live = b'{"bundle":{"version":"1.0.0","sha256":"keep"}}'
live_manifest.write_bytes(original_live)
running = old_refs.copy()
rolled = []
with (
patch.object(deploy, "read_url", return_value=json.dumps({"tag_name": "v1.1.0", "draft": False, "prerelease": False}).encode()),
patch.object(deploy, "tag_commit", return_value="f" * 40),
patch.object(deploy, "release_manifest", return_value=manifest),
patch.object(deploy, "resolved_images", return_value=new_refs),
patch.object(deploy, "inspect", side_effect=lambda name: {"Config": {"Image": running[name]}}),
patch.object(deploy, "data_containers", return_value={"postgres": "same", "redis": "same"}),
patch.object(deploy, "live_manifest_path", return_value=live_manifest),
patch.object(deploy, "docker") as docker_mock,
patch.object(deploy, "backup_database", side_effect=lambda p: p.write_bytes(b"ok")),
patch.object(deploy, "rollout_services", side_effect=lambda _h, _t, imgs, services=None: (rolled.append(tuple(services or ())), running.update({s: imgs[s] for s in (services or ())}))) as rollout_mock,
patch.object(deploy, "check_routes") as routes_mock,
patch.object(deploy, "publish_hotfix_bundle") as hotfix_mock,
patch.object(deploy, "check_hotfix") as check_hotfix_mock,
):
deploy.reconcile(host)
self.assertEqual(host.current(), "v1.1.0")
self.assertEqual(rolled, [("admin",)])
self.assertEqual(docker_mock.call_count, 1)
self.assertIn(new_admin, docker_mock.call_args.args)
routes_mock.assert_called_once()
rollout_mock.assert_called_once()
hotfix_mock.assert_not_called()
check_hotfix_mock.assert_not_called()
self.assertEqual(live_manifest.read_bytes(), original_live)
def test_earth_hotfix_only_deploy_preserves_shell_version_and_skips_containers(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
host = deploy.Host(base / "host", base / "settings", base / "state")
host.state.mkdir()
(host.directory("v1.0.0")).mkdir(parents=True)
for name in deploy.HOST_FILES:
(host.directory("v1.0.0") / name).write_text("host-managed")
deploy.point_current(host, "v1.0.0")
old_refs = {
"aiprovider": f"gitea.rclaw.top/linkong/planet/aiprovider:v1.0.0@sha256:{'1' * 64}",
"backend": f"gitea.rclaw.top/linkong/planet/backend:v1.0.0@sha256:{'2' * 64}",
"admin": f"gitea.rclaw.top/linkong/planet/admin:v1.0.0@sha256:{'3' * 64}",
}
bundle_data = hotfix("v1.1.0")
bundle_sha = hashlib.sha256(bundle_data).hexdigest()
manifest = {
"schema_version": 1,
"tag": "v1.1.0",
"commit": "f" * 40,
"previous_tag": "v1.0.0",
"components": ["earth-hotfix"],
"changed_services": [],
"services": old_refs,
"client": {"mode": "hotfix", "shell_version": "1.0.0", "min_shell_version": "1.0.0"},
}
host.env.write_text(
"\n".join(
[f"{registry.SERVICES[k]}={v}" for k, v in old_refs.items()] + ["CLIENT_UPDATE_PUBLISH_TOKEN=tok"]
) + "\n"
)
live_manifest = base / "manifest.json"
live_manifest.write_bytes(b"{}")
with (
patch.object(deploy, "read_url", return_value=json.dumps({"tag_name": "v1.1.0", "draft": False, "prerelease": False}).encode()),
patch.object(deploy, "tag_commit", return_value="f" * 40),
patch.object(deploy, "release_manifest", return_value=manifest),
patch.object(deploy, "resolved_images", return_value=old_refs),
patch.object(deploy, "release_bundle", return_value=("planet-earth-bundle-1.1.0.tar.gz", bundle_data, bundle_sha)),
patch.object(deploy, "inspect", side_effect=lambda name: {"Config": {"Image": old_refs[name]}}),
patch.object(deploy, "data_containers", return_value={"postgres": "same", "redis": "same"}),
patch.object(deploy, "live_manifest_path", return_value=live_manifest),
patch.object(deploy, "docker") as docker_mock,
patch.object(deploy, "backup_database", side_effect=lambda p: p.write_bytes(b"ok")),
patch.object(deploy, "rollout_services") as rollout_mock,
patch.object(deploy, "check_routes"),
patch.object(deploy, "publish_hotfix_bundle") as hotfix_mock,
patch.object(deploy, "check_hotfix") as check_hotfix_mock,
):
deploy.reconcile(host)
docker_mock.assert_not_called()
rollout_mock.assert_not_called()
self.assertEqual(hotfix_mock.call_args.kwargs["shell_version"], "1.0.0")
check_hotfix_mock.assert_called_once_with("v1.1.0", bundle_sha, shell_version="1.0.0")
def test_release_publish_dry_run_hotfix_filters_assets_and_stays_read_only(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
(root / "Planet-0.80.1.exe").write_bytes(b"exe")
(root / "Planet-0.80.1.AppImage").write_bytes(b"appimage")
(root / "planet-earth-bundle-0.80.1.tar.gz").write_bytes(hotfix("v0.80.1"))
out = io.StringIO()
with redirect_stdout(out):
rc = publish.main(
["--tag", "v0.80.1", "--scope", "hotfix", "--assets-dir", str(root), "--dry-run"]
)
self.assertEqual(rc, 0)
stdout = out.getvalue()
self.assertIn("scope_client_mode: hotfix", stdout)
self.assertIn("assets_count: 1", stdout)
self.assertIn("planet-earth-bundle-0.80.1.tar.gz", stdout)
self.assertNotIn("Planet-0.80.1.exe", stdout)
self.assertNotIn("Planet-0.80.1.AppImage", stdout)
self.assertFalse((root / "SHA256SUMS.txt").exists())
if __name__ == "__main__":
unittest.main()
+109 -45
View File
@@ -26,7 +26,9 @@ if __package__:
SERVICES,
read_url,
release_bundle,
release_manifest,
resolve_image,
resolve_service_ref,
tag_commit,
version,
)
@@ -39,7 +41,9 @@ else:
SERVICES,
read_url,
release_bundle,
release_manifest,
resolve_image,
resolve_service_ref,
tag_commit,
version,
)
@@ -167,9 +171,10 @@ def stage_config(host, previous, tag):
return target
def rollout_services(host, tag, images):
def rollout_services(host, tag, images, services=None):
directory = host.directory(tag)
for name in SERVICES:
targets = tuple(SERVICES) if services is None else tuple(services)
for name in targets:
print(f"Starting {name} from {images[name]}", flush=True)
docker(
"compose",
@@ -293,12 +298,17 @@ def rollback(host):
pending = host.state / "pending"
journal = json.loads((pending / "release.json").read_text())
previous = journal["previous"]
client_mode = journal.get("client_mode", "full")
print(f"Restoring {previous} after interrupted or unsuccessful {journal['tag']}", flush=True)
manifest = Path(journal["manifest"])
old = pending / "previous-manifest.json"
before = old.read_bytes() if old.exists() else None
current = manifest.read_bytes() if manifest.exists() else None
if current != before:
if client_mode == "none":
raise RuntimeError(
"Hotfix manifest changed independently; preserved the transaction for review"
)
bundle = json.loads(current or b"{}").get("bundle") or {}
if bundle.get("version") != journal["tag"][1:] or bundle.get("sha256") != journal["sha"]:
raise RuntimeError(
@@ -309,11 +319,18 @@ def rollback(host):
sync_directory(manifest.parent)
else:
atomic_file(manifest, before, 0o644)
set_images(host, journal["old_images"])
rollout_services(host, previous, journal["old_images"])
old_images = journal["old_images"]
rolled_services = [
name for name in SERVICES if inspect(name)["Config"]["Image"] != old_images[name]
]
set_images(host, old_images)
if not rolled_services or set(rolled_services) == set(SERVICES):
rollout_services(host, previous, old_images)
else:
rollout_services(host, previous, old_images, services=rolled_services)
point_current(host, previous)
check_routes()
if before:
if before and client_mode != "none":
old_manifest = json.loads(before)
bundle = old_manifest.get("bundle")
if bundle:
@@ -326,33 +343,64 @@ def rollback(host):
print(f"Rollback to {previous} verified", flush=True)
def resolved_images(tag, commit):
def resolved_images(tag, commit, manifest=None):
images = {}
if manifest is None:
for service in SERVICES:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
images[service] = ref
return images
changed_services = set(manifest.get("changed_services") or [])
for service in SERVICES:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
images[service] = ref
pinned = manifest["services"][service]
if service in changed_services:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
if ref != pinned:
raise ValueError(f"{service}:{tag} digest does not match release manifest")
images[service] = ref
else:
images[service] = resolve_service_ref(service, pinned)
return images
def deploy(host, release, previous, tag, images, commit):
name, data, sha = release_bundle(release, tag)
minimum = minimum_shell(data, tag)
def deploy(host, release, previous, tag, images, commit, *, manifest=None):
client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full"
client_info = (manifest or {}).get("client") or {}
if client_mode == "none":
name, data, sha = None, None, None
minimum = None
shell_version = client_info.get("shell_version")
else:
name, data, sha = release_bundle(release, tag)
minimum = client_info.get("min_shell_version") or minimum_shell(data, tag)
shell_version = client_info.get("shell_version") or tag[1:]
settings = env_settings(host)
token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022")
if not token:
raise RuntimeError("Production hotfix publisher credential is missing")
old_images = {n: settings[k].strip("'\u0022") for n, k in SERVICES.items()}
for service, ref in images.items():
docker("pull", "--platform", "linux/amd64", ref)
changed_services = [service for service in SERVICES if images[service] != old_images[service]]
token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022")
if client_mode != "none" and not token:
raise RuntimeError("Production hotfix publisher credential is missing")
for service in changed_services:
docker("pull", "--platform", "linux/amd64", images[service])
for service in SERVICES:
if inspect(service)["Config"]["Image"] != old_images[service]:
raise RuntimeError("Running image differs from the host configuration: " + service)
stage_config(host, previous, tag)
manifest = live_manifest_path()
bundle_path = manifest.parent / name
if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha:
raise RuntimeError("Existing versioned hotfix file has different contents")
manifest_file = live_manifest_path()
if client_mode != "none":
bundle_path = manifest_file.parent / name
if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha:
raise RuntimeError("Existing versioned hotfix file has different contents")
original_stores = data_containers()
save_journal(
host,
@@ -360,38 +408,48 @@ def deploy(host, release, previous, tag, images, commit):
tag=tag,
previous=previous,
old_images=old_images,
manifest=str(manifest),
manifest=str(manifest_file),
sha=sha,
client_mode=client_mode,
commit=commit,
),
manifest,
manifest_file,
)
try:
set_images(host, images)
rollout_services(host, tag, images)
if changed_services:
set_images(host, images)
if set(changed_services) == set(SERVICES):
rollout_services(host, tag, images)
else:
rollout_services(host, tag, images, services=changed_services)
check_routes()
if data_containers() != original_stores:
raise RuntimeError("PostgreSQL or Redis container identity changed")
with tempfile.TemporaryDirectory(dir=host.state) as tmp:
archive = Path(tmp) / name
archive.write_bytes(data)
publish_hotfix_bundle(
publish_url=PUBLIC,
publish_token=token,
tag=tag,
notes=release.get("body") or "",
release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}",
assets=[(archive, sha)],
min_shell_version=minimum,
)
check_hotfix(tag, sha)
if client_mode != "none":
with tempfile.TemporaryDirectory(dir=host.state) as tmp:
archive = Path(tmp) / name
archive.write_bytes(data)
publish_hotfix_bundle(
publish_url=PUBLIC,
publish_token=token,
tag=tag,
notes=release.get("body") or "",
release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}",
assets=[(archive, sha)],
min_shell_version=minimum,
shell_version=shell_version,
)
check_hotfix(tag, sha, shell_version=shell_version)
point_current(host, tag)
finish_journal(host, "last-success")
except Exception as exc:
print(f"Deploying {tag} failed: {exc}", file=sys.stderr, flush=True)
rollback(host)
raise
print(f"Deployed {tag} at {commit}", flush=True)
print(
f"Deployed {tag} at {commit} (services={','.join(changed_services) or 'none'}, client={client_mode})",
flush=True,
)
def reconcile(host, *, check=False, retry=False):
@@ -424,10 +482,15 @@ def reconcile(host, *, check=False, retry=False):
):
print(f"{tag} previously rolled back; waiting for a new release or --retry", flush=True)
return
images = resolved_images(tag, commit)
manifest = release_manifest(release, tag)
images = resolved_images(tag, commit, manifest=manifest)
if check:
_, data, sha = release_bundle(release, tag)
minimum_shell(data, tag)
client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full"
sha = None
shell_version = (manifest or {}).get("client", {}).get("shell_version") if manifest else tag[1:]
if client_mode != "none":
_, data, sha = release_bundle(release, tag)
minimum_shell(data, tag)
if tag == previous:
for name, ref in images.items():
container = inspect(name)
@@ -437,10 +500,11 @@ def reconcile(host, *, check=False, retry=False):
):
raise RuntimeError("Active service differs from the release: " + name)
check_routes()
check_hotfix(tag, sha)
if client_mode != "none":
check_hotfix(tag, sha, shell_version=shell_version)
print(f"Verified {tag} at {commit}; active release {previous}", flush=True)
return
deploy(host, release, previous, tag, images, commit)
deploy(host, release, previous, tag, images, commit, manifest=manifest)
def main():
+52 -6
View File
@@ -14,6 +14,7 @@ SERVER = "https://gitea.rclaw.top"
REPO = "linkong/planet"
REGISTRY = urllib.parse.urlsplit(SERVER).netloc
API = f"{SERVER}/api/v1/repos/{REPO}"
MANIFEST_NAME = "release-manifest.json"
SERVICES = {
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
"backend": "BACKEND_IMAGE_NAME",
@@ -69,8 +70,8 @@ def tag_commit(tag):
return commit
def release_bundle(release, tag):
"""Read the published hotfix and check it against the release checksum file."""
def _verified_release_asset(release, tag, name, *, limit, label):
"""Download and verify a release asset against SHA256SUMS.txt."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
@@ -78,19 +79,64 @@ def release_bundle(release, tag):
sizes = {entry["name"]: entry["size"] for entry in assets}
if len(assets) != len(sizes):
raise ValueError("Duplicate release attachment names")
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
base = f"{SERVER}/{REPO}/releases/download/{tag}"
if not 0 < sizes.get(name, 0) <= 32 * 1024 * 1024 or "SHA256SUMS.txt" not in sizes:
raise ValueError("Release has no complete Earth bundle and checksum list")
if not 0 < sizes.get(name, 0) <= limit or "SHA256SUMS.txt" not in sizes:
raise ValueError(f"Release has no complete {label} and checksum list")
sums = read_url(f"{base}/SHA256SUMS.txt", limit=128 * 1024).decode().splitlines()
hashes = [line.split(" ", 1)[0] for line in sums if line.endswith(" " + name)]
data = read_url(f"{base}/{name}", limit=sizes[name])
sha = hashlib.sha256(data).hexdigest()
if hashes != [sha] or len(data) != sizes[name]:
raise ValueError("Earth bundle failed release SHA-256 or size verification")
raise ValueError(f"{label} failed release SHA-256 or size verification")
return name, data, sha
def release_bundle(release, tag):
"""Read the published hotfix and check it against the release checksum file."""
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
return _verified_release_asset(release, tag, name, limit=32 * 1024 * 1024, label="Earth bundle")
def release_manifest(release, tag):
"""Read and validate optional release-manifest.json; returns None for legacy releases."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
assets = release.get("assets") or []
if not any(entry.get("name") == MANIFEST_NAME for entry in assets):
return None
_, data, _ = _verified_release_asset(
release, tag, MANIFEST_NAME, limit=512 * 1024, label="Release manifest"
)
manifest = json.loads(data.decode("utf-8"))
if not isinstance(manifest, dict) or manifest.get("schema_version") != 1:
raise ValueError("Unsupported release manifest schema version")
if manifest.get("tag") != tag:
raise ValueError("Release manifest tag differs from the published release")
services = manifest.get("services")
if not isinstance(services, dict) or set(services.keys()) != set(SERVICES.keys()):
raise ValueError("Release manifest must pin all production service images")
client = manifest.get("client")
if not isinstance(client, dict) or client.get("mode") not in ("none", "hotfix", "full"):
raise ValueError("Release manifest has an invalid client mode")
return manifest
def resolve_service_ref(service, ref):
"""Verify an explicit ``image:tag@sha256:...`` pin against Gitea registry."""
prefix = image_name(service) + ":"
if not isinstance(ref, str) or not ref.startswith(prefix) or "@" not in ref:
raise ValueError(f"Invalid image reference for {service}: {ref!r}")
ref_tag, ref_digest = ref[len(prefix) :].split("@", 1)
version(ref_tag)
if not re.fullmatch(r"sha256:[a-f0-9]{64}", ref_digest):
raise ValueError(f"Invalid image digest for {service}: {ref!r}")
resolved = resolve_image(service, ref_tag, tag_commit(ref_tag))
if resolved != ref:
raise ValueError(f"{service} image reference differs from registry ({resolved!r} != {ref!r})")
return resolved
def image_name(service):
if service not in SERVICES:
raise ValueError(f"Unexpected production service: {service}")
+148 -20
View File
@@ -16,24 +16,36 @@ from pathlib import Path
if __package__:
from .production_registry import (
API,
MANIFEST_NAME,
REPO,
SERVER,
SERVICES,
image_name,
read_url,
release_manifest,
resolve_image,
resolve_service_ref,
tag_commit,
version,
)
from .release_scope import resolve_release_scope
else:
from production_registry import (
API,
MANIFEST_NAME,
REPO,
SERVER,
SERVICES,
image_name,
read_url,
release_manifest,
resolve_image,
resolve_service_ref,
tag_commit,
version,
)
from release_scope import resolve_release_scope
def git(*args, cwd=None):
@@ -58,8 +70,19 @@ def docker_config():
)
def ensure_images(source, tag, commit):
def ensure_images(source, tag, commit, *, services=None, previous_services=None):
target_services = set(SERVICES if services is None else services)
resolved_pins = {}
for service in SERVICES:
if service not in target_services:
prev_ref = (previous_services or {}).get(service)
if not prev_ref:
raise RuntimeError(
f"Cannot reuse unchanged {service} image without a verified previous release pin"
)
resolved_pins[service] = prev_ref
print(f"Reused {prev_ref}", flush=True)
continue
pin = resolve_image(service, tag, commit)
if not pin:
context = source / "frontend" if service == "admin" else source
@@ -103,10 +126,14 @@ def ensure_images(source, tag, commit):
pin = resolve_image(service, tag, commit)
if not pin:
raise RuntimeError(f"Pushed image is not visible: {service}:{tag}")
resolved_pins[service] = pin
print(f"Verified {pin}", flush=True)
return resolved_pins
def select_packages(directory, tag, suffixes):
def select_packages(directory, tag, suffixes, *, client_mode="full"):
if client_mode == "none":
return []
number = re.compile(rf"(?<![\d.]){re.escape(tag[1:])}(?!\d|\.\d)")
paths = (
[
@@ -117,15 +144,22 @@ def select_packages(directory, tag, suffixes):
if directory.is_dir()
else []
)
names = [p.name.lower() for p in paths]
if not (
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
and any(n.endswith((".appimage", ".deb")) for n in names)
and f"planet-earth-bundle-{tag[1:]}.tar.gz" in names
):
return []
bundle = directory / f"planet-earth-bundle-{tag[1:]}.tar.gz"
if not bundle.is_file():
return []
if client_mode == "full":
names = [p.name.lower() for p in paths]
if not (
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
and any(n.endswith((".appimage", ".deb")) for n in names)
):
return []
elif client_mode == "hotfix":
paths = [bundle]
else:
raise ValueError(f"Unsupported client_mode: {client_mode!r}")
with tarfile.open(bundle, "r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 8192:
@@ -155,12 +189,15 @@ def package_hash(path):
return hashlib.file_digest(stream, "sha256").hexdigest()
def cached_packages(source, supplied, cache, tag, suffixes):
def cached_packages(source, supplied, cache, tag, suffixes, *, client_mode="full"):
if client_mode == "none":
return []
if not cache.exists():
if supplied is None:
subprocess.run(["./planet.sh", "bundle", "--all"], cwd=source, check=True)
bundle_flag = "--hotfix" if client_mode == "hotfix" else "--all"
subprocess.run(["./planet.sh", "bundle", bundle_flag], cwd=source, check=True)
supplied = source / "client/release"
packages = select_packages(supplied, tag, suffixes)
packages = select_packages(supplied, tag, suffixes, client_mode=client_mode)
if not packages:
raise RuntimeError(f"Missing tagged desktop clients or Earth hotfix in {supplied}")
with tempfile.TemporaryDirectory(dir=cache.parent) as tmp:
@@ -171,21 +208,86 @@ def cached_packages(source, supplied, cache, tag, suffixes):
sums = {p.name: package_hash(p) for p in stage.iterdir()}
(stage / "checksums.json").write_text(json.dumps(sums))
os.rename(stage, cache)
packages = select_packages(cache, tag, suffixes)
packages = select_packages(cache, tag, suffixes, client_mode=client_mode)
expected = json.loads((cache / "checksums.json").read_text())
if not packages or {p.name: package_hash(p) for p in packages} != expected:
raise ValueError("The saved release artifacts differ from the original build")
return packages
def resolve_previous_release_state(previous_tag):
"""Fetch verified service image refs and active desktop shell version from ``previous_tag``."""
if not previous_tag:
return {}, None, None
release = json.loads(read_url(f"{API}/releases/tags/{previous_tag}"))
manifest = release_manifest(release, previous_tag)
if manifest is not None:
pins = {
service: resolve_service_ref(service, ref)
for service, ref in manifest["services"].items()
}
client = manifest.get("client") or {}
return pins, client.get("shell_version"), client.get("min_shell_version")
prev_commit = tag_commit(previous_tag)
pins = {}
for service in SERVICES:
pin = resolve_image(service, previous_tag, prev_commit)
if not pin:
raise RuntimeError(f"Missing {service}:{previous_tag} image in previous release")
pins[service] = pin
return pins, previous_tag[1:], previous_tag[1:]
def build_release_manifest(tag, commit, scope, service_refs, packages, *, shell_version=None, min_shell_version=None):
ver = tag[1:]
bundle_name = f"planet-earth-bundle-{ver}.tar.gz"
bundle_path = next((p for p in packages if p.name == bundle_name), None)
if scope.client_mode == "full":
resolved_shell = ver
resolved_min_shell = ver
else:
resolved_shell = shell_version or ver
resolved_min_shell = min_shell_version or resolved_shell
return {
"schema_version": 1,
"tag": tag,
"commit": commit,
"previous_tag": scope.previous_tag,
"components": list(scope.components),
"changed_services": list(scope.services),
"services": dict(service_refs),
"client": {
"mode": scope.client_mode,
"shell_version": resolved_shell,
"min_shell_version": resolved_min_shell,
"bundle": bundle_path.name if bundle_path else None,
"bundle_sha256": package_hash(bundle_path) if bundle_path else None,
},
}
@contextmanager
def prepare(tag, assets_dir, suffixes, *, already_published=False):
def prepare(tag, assets_dir, suffixes, *, already_published=False, scope_override=None):
version(tag)
commit = verified_tag(tag)
scope = resolve_release_scope(tag, commit, override=scope_override)
state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
state = state / "planet-releases" / tag / "publisher"
state.mkdir(mode=0o700, parents=True, exist_ok=True)
cache = state / commit
cache_key = f"{commit}-{scope.client_mode}"
cache = state / cache_key
prev_services = {}
prev_shell_version = None
prev_min_shell_version = None
if len(scope.services) < len(SERVICES) or scope.client_mode != "full":
if scope.previous_tag:
prev_services, prev_shell_version, prev_min_shell_version = resolve_previous_release_state(
scope.previous_tag
)
elif len(scope.services) < len(SERVICES):
raise RuntimeError("No previous stable release found to reuse unchanged services")
with (
local_release_lock(state / "lock"),
tempfile.TemporaryDirectory(prefix="planet-publish-") as tmp,
@@ -195,15 +297,41 @@ def prepare(tag, assets_dir, suffixes, *, already_published=False):
["git", "worktree", "add", "--quiet", "--detach", str(worktree), commit], check=True
)
try:
ensure_images(worktree, tag, commit)
service_refs = ensure_images(
worktree,
tag,
commit,
services=scope.services,
previous_services=prev_services,
)
stage = Path(tmp) / "assets"
stage.mkdir()
if not already_published:
for package in cached_packages(worktree, assets_dir, cache, tag, suffixes):
staged_packages = []
for package in cached_packages(
worktree,
assets_dir,
cache,
tag,
suffixes,
client_mode=scope.client_mode,
):
dest = stage / package.name
try:
os.link(package, stage / package.name)
os.link(package, dest)
except OSError:
shutil.copy2(package, stage / package.name)
shutil.copy2(package, dest)
staged_packages.append(dest)
manifest = build_release_manifest(
tag,
commit,
scope,
service_refs,
staged_packages,
shell_version=prev_shell_version,
min_shell_version=prev_min_shell_version,
)
(stage / MANIFEST_NAME).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
yield stage, worktree / "docs/CHANGELOG.md"
# The verified public release now holds these bytes. Keep the cache on upload failure.
if cache.exists():
+67 -11
View File
@@ -148,7 +148,8 @@ def collect_release_assets(assets_dir: Path) -> list[tuple[Path, str]]:
(
entry
for entry in assets_dir.iterdir()
if entry.is_file() and entry.name.lower().endswith(ASSET_SUFFIXES)
if entry.is_file()
and (entry.name.lower().endswith(ASSET_SUFFIXES) or entry.name == "release-manifest.json")
),
key=lambda p: p.name,
)
@@ -297,6 +298,11 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
default="",
help="Optional X-Client-Update-Token matching CLIENT_UPDATE_PUBLISH_TOKEN on backend",
)
parser.add_argument(
"--scope",
default="auto",
help="Release scope: auto, full, none, or comma-separated components (aiprovider,backend,admin,hotfix,client-shell)",
)
return parser.parse_args(argv)
@@ -438,6 +444,7 @@ def publish_hotfix_bundle(
release_html_url: str,
assets: list[tuple[Path, str]],
min_shell_version: str | None = None,
shell_version: str | None = None,
) -> None:
hotfix_tar = next(
(
@@ -452,6 +459,8 @@ def publish_hotfix_bundle(
return
version = tag.lstrip("vV")
resolved_shell = shell_version or version
resolved_min_shell = min_shell_version or resolved_shell
endpoint = f"{publish_url.rstrip('/')}/api/v1/client/updates/bundle"
proc = subprocess.run(
[
@@ -473,9 +482,9 @@ def publish_hotfix_bundle(
"--form-string",
f"version={version}",
"--form-string",
f"min_shell_version={min_shell_version or version}",
f"min_shell_version={resolved_min_shell}",
"--form-string",
f"shell_version={version}",
f"shell_version={resolved_shell}",
"--form-string",
f"shell_download_url={release_html_url}",
"--form-string",
@@ -520,14 +529,53 @@ def main(argv: list[str] | None = None) -> int:
assets_dir = Path(args.assets_dir or "client/release")
if args.dry_run:
if __package__:
from .production_release import select_packages
from .release_scope import resolve_release_scope
else:
from production_release import select_packages
from release_scope import resolve_release_scope
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
commit_ref = args.tag
try:
commit_ref = subprocess.check_output(
["git", "rev-parse", "--verify", f"{args.tag}^{{commit}}"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
try:
commit_ref = subprocess.check_output(
["git", "rev-parse", "HEAD"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
commit_ref = "HEAD"
scope = resolve_release_scope(args.tag, commit_ref, override=args.scope)
if scope.client_mode == "none":
assets = []
else:
selected = (
select_packages(assets_dir, args.tag, ASSET_SUFFIXES, client_mode=scope.client_mode)
if assets_dir.is_dir()
else []
)
assets = [(path, compute_sha256(path)) for path in sorted(selected, key=lambda p: p.name)]
if not assets:
print(
f"error: no distributable assets matching client_mode={scope.client_mode} found in {assets_dir}",
file=sys.stderr,
)
return 1
print(f"server: {server}")
print(f"repo: {repo}")
print(f"tag: {args.tag}")
print(f"scope_components: {','.join(scope.components)}")
print(f"scope_services: {','.join(scope.services) or 'none'}")
print(f"scope_client_mode: {scope.client_mode}")
print(f"scope_previous_tag: {scope.previous_tag or 'none'}")
print(f"notes_length: {len(notes)}")
print(f"assets_count: {len(assets)}")
for path, sha in assets:
@@ -537,10 +585,10 @@ def main(argv: list[str] | None = None) -> int:
try:
if __package__:
from .production_registry import API, REPO, SERVER, release_bundle
from .production_registry import API, REPO, SERVER, release_bundle, release_manifest
from .production_release import prepare
else:
from production_registry import API, REPO, SERVER, release_bundle
from production_registry import API, REPO, SERVER, release_bundle, release_manifest
from production_release import prepare
production = (server, repo) == (SERVER, REPO) and re.fullmatch(r"v\d+\.\d+\.\d+", args.tag)
@@ -559,9 +607,17 @@ def main(argv: list[str] | None = None) -> int:
raise RuntimeError(f"Cannot inspect the release (HTTP {status})")
published = status == 200 and isinstance(public, dict) and public.get("draft") is False
supplied = assets_dir if args.assets_dir else None
with prepare(args.tag, supplied, ASSET_SUFFIXES, already_published=published) as (stage, changelog):
with prepare(
args.tag,
supplied,
ASSET_SUFFIXES,
already_published=published,
scope_override=args.scope,
) as (stage, changelog):
if published:
release_bundle(public, args.tag)
manifest = release_manifest(public, args.tag)
if manifest is None or manifest["client"]["mode"] != "none":
release_bundle(public, args.tag)
print(f"Verified published release {args.tag}; production follows stable releases")
else:
notes = extract_release_notes(changelog, args.tag)
+303
View File
@@ -0,0 +1,303 @@
"""Classify repository changes into scoped Planet release targets."""
from __future__ import annotations
import json
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
VALID_SERVICES = ("aiprovider", "backend", "admin")
VALID_CLIENT_MODES = ("none", "hotfix", "full")
CLIENT_MODE_RANK = {"none": 0, "hotfix": 1, "full": 2}
METADATA_EXACT = frozenset(
{
"AGENTS.md",
"CODEMAP.md",
"README.md",
"VERSION",
".editorconfig",
".gitattributes",
".gitignore",
"project_context.md",
"rules.md",
}
)
METADATA_PREFIXES = (
".codex/",
".gitea/",
".github/",
"client/tests/",
"docs/",
"scripts/harness/",
)
RELEASE_TOOLING_FILES = frozenset(
{
"client/scripts/dist-target.mjs",
"planet.sh",
"scripts/production_deploy.py",
"scripts/production_registry.py",
"scripts/production_release.py",
"scripts/release_publish.py",
"scripts/release_scope.py",
}
)
BACKEND_RUNTIME_FILES = frozenset(
{
"pyproject.toml",
"uv.lock",
"config/earth-boundary-pov-policy.china-v1.json",
"resources/earth/boundary-pov-geometry.china-v1.json",
"scripts/build_earth_boundary_china_pov_geojson.py",
"scripts/build_earth_boundary_pmtiles.py",
"scripts/db_migrate.py",
"scripts/earth_boundary_policy.py",
}
)
VERSION_ONLY_FILES = frozenset(
{
"client/package.json",
"frontend/package.json",
"pyproject.toml",
"uv.lock",
}
)
EARTH_CARDS_MANIFEST = "frontend/public/earth/assets/cards/manifest.json"
@dataclass(frozen=True)
class ReleaseScope:
"""Resolved container build targets and desktop client delivery mode."""
services: tuple[str, ...]
client_mode: str
components: tuple[str, ...]
previous_tag: str | None = None
changed_paths: tuple[str, ...] = ()
def to_dict(self) -> dict[str, object]:
return {
"services": list(self.services),
"client_mode": self.client_mode,
"components": list(self.components),
"previous_tag": self.previous_tag,
"changed_paths": list(self.changed_paths),
}
def _git(args: list[str], cwd: Path | None = None) -> str:
return subprocess.check_output(["git", *args], cwd=cwd, text=True)
def _git_show(revision: str, path: str, cwd: Path | None = None) -> str | None:
try:
return _git(["show", f"{revision}:{path}"], cwd=cwd)
except subprocess.CalledProcessError:
return None
def _parse_stable_version(tag: str) -> tuple[int, int, int] | None:
match = re.fullmatch(r"v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)", tag.strip())
if not match:
return None
return (int(match.group(1)), int(match.group(2)), int(match.group(3)))
def previous_stable_tag(tag: str, tags: Iterable[str]) -> str | None:
"""Return the highest stable release tag strictly lower than ``tag``."""
target = _parse_stable_version(tag)
if target is None:
return None
candidates: list[tuple[tuple[int, int, int], str]] = []
for raw in tags:
ver = _parse_stable_version(raw)
if ver is not None and ver < target:
candidates.append((ver, raw.strip()))
if not candidates:
return None
candidates.sort()
return candidates[-1][1]
def _normalize_package_json(raw: str) -> object | None:
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
if not isinstance(data, dict):
return None
return {k: v for k, v in data.items() if k != "version"}
def _normalize_pyproject(raw: str) -> str:
return re.sub(r'(?m)^version\s*=\s*["\'][^"\']*["\']\s*$', "version = <NORMALIZED>", raw)
def _normalize_uv_lock(raw: str) -> str:
return re.sub(
r'(\[\[package\]\]\s*\nname\s*=\s*"planet"\s*\nversion\s*=\s*)"[^"]+"',
r'\1"<NORMALIZED>"',
raw,
count=1,
)
def is_version_only_change(prev_ref: str, commit: str, path: str, cwd: Path | None = None) -> bool:
"""Return True when a version-bearing manifest only bumped the root Planet version."""
if path not in VERSION_ONLY_FILES:
return False
before = _git_show(prev_ref, path, cwd=cwd)
after = _git_show(commit, path, cwd=cwd)
if before is None or after is None:
return False
if path in ("client/package.json", "frontend/package.json"):
norm_before = _normalize_package_json(before)
norm_after = _normalize_package_json(after)
return norm_before is not None and norm_before == norm_after
if path == "pyproject.toml":
return _normalize_pyproject(before) == _normalize_pyproject(after)
if path == "uv.lock":
return _normalize_uv_lock(before) == _normalize_uv_lock(after)
return False
def _is_metadata_or_tooling(path: str) -> bool:
return (
path in METADATA_EXACT
or path in RELEASE_TOOLING_FILES
or any(path.startswith(prefix) for prefix in METADATA_PREFIXES)
)
def _derive_components(services: set[str], client_mode: str) -> tuple[str, ...]:
ordered: list[str] = [svc for svc in VALID_SERVICES if svc in services]
if client_mode == "hotfix":
ordered.append("earth-hotfix")
elif client_mode == "full":
ordered.append("client-shell")
if not ordered:
ordered.append("metadata")
return tuple(ordered)
def classify_changed_paths(
paths: Iterable[str],
*,
previous_tag: str | None = None,
) -> ReleaseScope:
"""Classify changed repository paths into service image builds and client mode."""
normalized_paths = tuple(
sorted({p.strip().lstrip("./").replace("\\", "/") for p in paths if p and p.strip()})
)
services: set[str] = set()
client_mode = "none"
for path in normalized_paths:
if _is_metadata_or_tooling(path):
continue
if path.startswith("aiprovider/"):
services.add("aiprovider")
continue
if path.startswith(("backend/", "alembic/")) or path in BACKEND_RUNTIME_FILES:
services.add("backend")
continue
if path.startswith("frontend/public/earth/"):
if CLIENT_MODE_RANK["hotfix"] > CLIENT_MODE_RANK[client_mode]:
client_mode = "hotfix"
if path == EARTH_CARDS_MANIFEST:
services.add("backend")
continue
if path.startswith("frontend/"):
services.add("admin")
continue
if path.startswith("client/"):
client_mode = "full"
continue
# Infra/compose/root or unknown paths fall back to rebuilding all services safely.
services.update(VALID_SERVICES)
ordered_services = tuple(svc for svc in VALID_SERVICES if svc in services)
return ReleaseScope(
services=ordered_services,
client_mode=client_mode,
components=_derive_components(services, client_mode),
previous_tag=previous_tag,
changed_paths=normalized_paths,
)
def parse_scope_override(raw: str | None, *, previous_tag: str | None = None) -> ReleaseScope | None:
"""Parse an explicit ``--scope`` value, or return None for auto-detection."""
if raw is None:
return None
text = raw.strip().lower()
if not text or text == "auto":
return None
if text == "full":
return ReleaseScope(
services=VALID_SERVICES,
client_mode="full",
components=_derive_components(set(VALID_SERVICES), "full"),
previous_tag=previous_tag,
)
services: set[str] = set()
client_mode = "none"
for token in (part.strip() for part in text.split(",") if part.strip()):
if token in VALID_SERVICES:
services.add(token)
elif token in ("hotfix", "earth", "earth-hotfix"):
if CLIENT_MODE_RANK["hotfix"] > CLIENT_MODE_RANK[client_mode]:
client_mode = "hotfix"
elif token in ("client", "client-shell", "desktop"):
client_mode = "full"
elif token in ("none", "metadata", "docs"):
continue
else:
raise ValueError(
f"Unsupported release scope token {token!r}; expected auto, full, none, "
"aiprovider, backend, admin, hotfix, or client-shell"
)
ordered_services = tuple(svc for svc in VALID_SERVICES if svc in services)
return ReleaseScope(
services=ordered_services,
client_mode=client_mode,
components=_derive_components(services, client_mode),
previous_tag=previous_tag,
)
def resolve_release_scope(
tag: str,
commit: str,
*,
override: str | None = None,
cwd: Path | None = None,
) -> ReleaseScope:
"""Determine scoped release targets from git history unless explicitly overridden."""
all_tags = _git(["tag", "--list", "v*"], cwd=cwd).splitlines()
prev_tag = previous_stable_tag(tag, all_tags)
explicit = parse_scope_override(override, previous_tag=prev_tag)
if explicit is not None:
return explicit
if prev_tag is None:
return ReleaseScope(
services=VALID_SERVICES,
client_mode="full",
components=_derive_components(set(VALID_SERVICES), "full"),
previous_tag=None,
)
raw_paths = _git(["diff", "--name-only", f"{prev_tag}..{commit}"], cwd=cwd).splitlines()
effective_paths = [
path
for path in raw_paths
if path.strip() and not is_version_only_change(prev_tag, commit, path.strip(), cwd=cwd)
]
return classify_changed_paths(effective_paths, previous_tag=prev_tag)
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.80.0"
version = "0.80.2"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },