Files
planet/docs/technical/en/frontend-admin-frontend-context.md
linkong fbecf30513
Some checks failed
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
ci / delivery (push) Has been cancelled
release / images (push) Has been cancelled
release: bump version to 0.73.0
2026-06-29 17:04:05 +08:00

24 KiB

Admin Frontend Context

This document describes the current real structure of the console frontend. The goal is to help future page development, table refactoring, layout governance, and state consolidation quickly find the right entry points.

Related references:

Current Goal

The console frontend is a backend workbench, not a display-style dashboard. Current constraints:

  • Pages default to a single-screen work area
  • Primary interaction happens through in-module scrolling, not relying on the whole page growing infinitely
  • Lists, tables, and analysis pages prioritize keeping the main work area visible
  • Common layout, scrollbar, and table scroll behavior should be reused across pages

Current Route Entry Points

Main entry point:

Admin now owns the official admin routes:

  • /admin
  • /users
  • /datasources
  • /data
  • /alerts/system
  • /alerts/bgp
  • /alerts/situational
  • /bgp
  • /ai
  • /earth-content
  • /collection-management
  • /settings

These routes render AdminRoutes.tsx. Page metadata and menu entries come from manifest.tsx. Admin is the only console entry point; there is no parallel console or rollback route.

/earth is a standalone display page and is not part of the console shell.

Current Page Shell

The official admin shell is at:

Responsibilities:

  • Left navigation, grouped collapse, and mobile drawer
  • Current account, version, logout, and theme switching
  • Top search, breadcrumbs, and page shortcuts
  • Single-screen content-area height closure
  • Coordination for Admin internal scrolling, tables, detail panels, and mobile detail views

Future official admin pages should adapt to AdminLayout and Admin page patterns; do not reintroduce a parallel admin shell.

Admin Section Loading

Multi-tab pages are currently coordinated by PlainResourcePages.tsx, which hosts the current management and information workbench patterns. Section loading follows these rules:

  • Initial page load requests only the active tab; it does not prefetch every tab endpoint.
  • Switching tabs lazily loads that tab. Loaded tabs stay cached in local states, so returning to a tab reuses the previous data.
  • Explicit actions such as refresh, save, test, upload, and credential-guide generation refresh only the current section instead of fanning out to unrelated sections.
  • Datasource directory filter changes clear the built-in-source section cache and reload the current section with the new filters.
  • Top summary metrics count loaded sections only, so unopened tabs are not reported as failed interfaces.

This keeps Earth, AI, collection management, and other multi-section pages from flooding backend APIs on cold start while preserving a fast cached tab-switching experience. Full health checks should use backend health endpoints or explicit refresh flows rather than relying on page initialization to touch every business endpoint.

Datasource Collection Queue

The Admin datasource page routes single-source trigger, table-selected trigger, and trigger-all into a browser-download-list style collection queue:

  • Queue state is managed by PlainResourcePages.tsx. It is a current-session visibility layer and does not fake task history in localStorage.
  • Progress first consumes the /ws datasource_tasks channel. If the socket is unavailable or stale, the page polls /api/v1/datasources/{id}/task-status.
  • Trigger responses immediately insert triggered, skipped, and failed items. After a refresh, the queue restores only real backend rows that are still running, pending, or queued.
  • The Built-in Sources section uses the table selection column for selected-source triggering. With no rows selected, the primary button is Trigger All; after selection, the same button becomes Trigger Selected N, replacing the old manual-ID batch button.
  • The expanded queue no longer lives in the page content flow, so trigger-all cannot squeeze the table and detail panel. The top-right actions area uses the existing Button styling; the empty state shows a ListChecks icon, and active queues show only a pure circular total-progress indicator. Clicking it opens a floating panel grouped by running, failed, completed, and skipped.
  • Queue rows can jump to the datasource detail panel, and failed rows can retry. The detail panel's task summary only reports the selected source's latest task; it does not save configuration.
  • While a single-source collection is running, the action button becomes Stop Collection; unfinished queue rows expose a cancel action on the right. Cancellation calls /api/v1/datasources/{source_id}/tasks/{task_id}/cancel; the backend keeps committed batches and rolls back unfinished work.
  • Clearing database data and clearing display cache enter the same queue. The frontend shows task state and does not assume the API completed synchronously.

This queue is a user-perception layer. Backend task status remains the only source of truth for running, completion, failure, and skipped decisions.

Admin Theme Slider

The Admin sidebar theme switcher still reuses shared SegmentedControl.tsx, while styles.css overrides the segment variables by data-theme:

  • Light mode uses --d-segment-bg: #eef3f9, a white slider, and a light external shadow.
  • Dark mode uses the same dark base, #202938 slider, and dark external shadow semantics as Docs.
  • Product code only hides the text label and keeps icon + tooltip behavior; it should not recreate the private slider DOM.

Admin Status Colors

Admin status labels should use StatusText or Badge. Color variables come from styles.css. New states should map to an existing tone instead of adding page-local hex colors.

StatusText is an indicator-light pill: the pill background and border stay on the component base color, while only the dot and text use the status color. Badge does not carry the indicator-light meaning, so it may use a light same-tone background and border for stronger hierarchy.

Status indicators must show the full state word. In lists, hierarchy groups, and detail headers, the title/description area should shrink or wrap while the status pill keeps content-sized width and does not get compressed by flex/grid layout; do not truncate state words such as Configured or Available just to save horizontal space.

Tone Color variable Meaning Examples
success --an-success available, successful, connected, enabled log source Available, collection Success
warning --an-warning needs attention but is not necessarily failed missing log file, degraded or skipped state
danger --an-danger failed, unavailable, permission/connection error Docker unavailable, endpoint failure
info / running --an-info in progress, syncing, informational Following, Syncing
neutral --an-muted empty, disabled, not reported yet, unknown No reports yet, disabled
ai fixed purple AI-specific emphasis AI generation or model action

The log source list follows the same rule: ok is success; empty means the source exists but has not reported yet and is neutral; missing means an expected log file is not present and is warning; docker_unavailable / source_unavailable are danger.

Admin Runtime Logs

Admin runtime errors are reported through runtimeLogs.ts to /api/v1/system/logs/admin-client. The reporter only runs on Admin routes and skips /earth, /docs, login, and registration pages so public-page noise does not enter the Admin client log source.

AdminErrorBoundary.tsx catches React render failures and reuses the same reporter; global error and unhandledrejection events use that channel as well. Reporting failures must stay silent, because the logging path must not create another frontend error.

The Logs page follows log increments through the /ws logs_tail channel. File logs and database logs are both normalized into line events by the backend. When adding a new log source, wire it through the backend source registry and tail manager instead of adding a page-local poller.

The Logs page now opens in the grouped view by default. It reads /api/v1/system/logs/observability/groups, groups Earth, Admin, and service runtime reports by fingerprint, and then reads /api/v1/system/logs/observability/groups/{fingerprint}/events when an operator opens one group. Raw logs and audit logs remain separate views; only the raw-log view can follow WebSocket updates. Frontend reporters coalesce repeated errors in a short window and submit occurrence_count, while the backend writes both system_logs and observability_events / observability_event_groups, so the page should not add another browser-side aggregation pass over identical messages.

The datasource task queue View Logs action opens /logs?source=system-db&search=task_id=<id>. Backend database-log search indexes must expand simple JSON context fields into key=value aliases such as task_id=26906 and datasource_id=20, so historical task logs remain discoverable without rerunning the task.

Current Shared Components

1. Scrollbar

File:

Purpose:

  • Ordinary content containers like the console sidebar
  • Internally manages visibility, thumb size, drag, and dual-axis overflow detection

Current constraint:

  • The scrollbar must be a floating overlay that does not participate in layout
  • Should leave no visible trace when there is no overflow
  • Real scrolling is still handled by the native container; only the visible layer and interaction layer are replaced

2. ScrollbarOverlay

File:

Purpose:

  • Areas like Ant Table that already have an internal scroll container
  • Does not take over scroll semantics; only adds a new scrollbar visible layer

Current usage:

  • Admin data sources, collected data, collection management, logs, alerts, and BGP pages

3. TableScrollRegion

File:

Purpose:

  • Provides a unified wrapper for table scroll areas
  • New table pages should reuse this rather than repeating the "table area + overlay scrollbar" boilerplate

4. TactileButton / TactileSwitch / ControlGroup

Files:

Purpose:

  • Admin global tool buttons and detail-panel toolbars
  • Icon-only ordinary actions with tooltips
  • Strong-intent actions such as save, create, confirm, delete, and stop
  • Compact switches aligned with the Docs theme slider

Current constraints:

  • Neutral buttons default to a white tactile surface with external shadow
  • Unambiguous actions prefer icon + tooltip; strong-intent actions like save may keep text
  • Feature pages should customize through props and CSS variables, not by rewriting core button CSS

5. SegmentedControl

Files:

Purpose:

  • Segmented controls for language, theme, mode, or other 2 to 3 option settings
  • Settings that need the shared animated slider, active state, and compact button layout
  • The /docs footer language switcher and theme switcher already reuse it

Interface semantics:

  • options: each option contains value and label, with optional icon and title
  • value: current active value
  • onChange: called when the selected option changes
  • ariaLabel: accessible name for the control
  • className: page-level hook for size or local style overrides

Current constraints:

  • The component owns slider count, position, and spring-like transition
  • Feature pages should only pass options and state, not recreate private slider DOM
  • Prefer CSS variable overrides for colors instead of hard-coding theme colors in feature components
  • Best for a small set of mutually exclusive choices; do not use it as a long list, navigation menu, or select replacement

6. Console i18n

Files:

Purpose:

  • Share one zh-CN / en-US language state across the console, auth pages, and Docs UI
  • Store the language preference in planet-locale while keeping compatibility with the old docs-lang
  • Keep Docs API requests mapped to the backend's existing zh / en document interface
  • Provide language switchers in the console sidebar preferences panel and auth panel

Current constraints:

  • New console copy should be added to resources.ts, then consumed with useTranslation() or useLocale()
  • Routes, menus, search indexes, and shared components must use explicit translation keys
  • LegacyI18nBridge is transitional and only handles exact static text and attributes inside admin/auth containers
  • Business data, raw logs, API field names, provider ids, commands, and Markdown body content are not translated by the legacy bridge
  • Future large-page migrations should shrink the legacy dictionary rather than grow it

7. MarkdownRenderer

File:

Purpose:

  • Renders Markdown content for /docs
  • Supports headings, lists, blockquotes, code blocks, tables, and basic inline formatting
  • Code blocks and tables reuse Scrollbar so horizontal content does not blow out the docs page
  • Docs content is returned by backend /api/v1/docs/... endpoints according to Gatekeeper permissions; the frontend only renders content visible to the current user

Current constraints:

  • It is not a full GitHub Markdown engine; it only covers the syntax currently needed by project docs
  • Internal document links should be converted to /docs/:slug through transformLink
  • Heading anchors are injected through getHeadingId, keeping route state outside the renderer

7. Admin UI Primitives

Files:

Use:

  • Global tool buttons, detail actions, confirmation dialogs, and binary settings.
  • Aligned with Tactile UI tokens so Admin controls keep consistent size, hover, disabled, and dark-mode behavior.
  • Row actions should prefer icon buttons plus tooltip/title; do not reintroduce a separate action-menu component.

Current State Sources

1. Auth State

File:

Responsibilities:

  • Token
  • Current user
  • Gatekeeper groups
  • Login / logout

App.tsx uses it to decide whether to redirect to the login page. /docs remains a public route, but the backend decides the visible catalog and content from the token; anonymous visitors only receive public docs.

2. AI

File:

Responsibilities:

  • /ai now owns LLM Provider, AI Tool configuration, and Playground instead of nesting them under /settings
  • The 模型供应商 section manages default provider, model, base URL, provider key, local aiprovider proxy, and connection test; provider and model fields use editable comboboxes so users can manually enter new providers/models if the models.dev catalog stops updating
  • The 工具调用 section first selects a tool from a dropdown menu, then renders that tool's configuration; it currently includes WebSearch and OCR
  • WebSearch configuration includes provider, search key, base URL, timeout, result count, and advanced provider options
  • OCR configuration includes provider, Base URL, API key, model/engine, languages, timeout, file-size limit, and output format
  • The Playground section embeds the former Playground real session, preset prompts, and AI Provider status debugging
  • The page reuses the Settings single-screen section, panel card, and internal scrolling style
  • AI Provider and WebSearch connection tests use ConnectionTestInput, with the connector icon fixed at the end of the Base URL input; when WebSearch is disabled, every configuration field and the test entry point are greyed out except the switch

AI configuration no longer lives under /settings; /playground should redirect to /ai?section=playground.

3. Business Data Gateway

AI / situational awareness related services are currently in:

Constraints:

  • Pages must not scatter URL construction directly
  • Define boundaries through port/types first
  • Then implement via http/mock gateway

Current Page Layer Recommendations

1. Dashboard and Summary Pages

Example:

Priority goals:

  • Stable header
  • Summary cards compact first
  • Main work area occupies primary height

2. Table Pages

Examples:

Constraints:

  • Prefer internal scrolling
  • Do not let tables blow out the full page
  • New table areas should reuse TableScrollRegion / ScrollbarOverlay

Datasource Directory Page

DataSources.tsx is the datasource directory and collection operation page. It should not grow back into a configuration editor.

Current page boundary:

  • Built-in and custom sources are merged as UnifiedDataSource.
  • The list shows type, state, last run, collection progress, and actions.
  • Clicking a name opens a read-only drawer.
  • Endpoint, headers, and config are displayed here, not edited.
  • Credential-bearing collectors point users to Collection Management -> Collectors.

Keep this boundary: do not put custom datasource editing, built-in endpoint overrides, or credential forms back into /datasources. Those configuration entry points live at /collection-management?section=collector_credentials.

Collectors Page

Settings.tsx has three route modes: /settings for System Settings, /earth-content for Earth Content, and /collection-management for Collection Management. The collector_credentials section is shown as Collectors under /collection-management.

The System Display section under /settings includes the Demo Mode switch. When enabled, Earth OOBE ignores existing current collected data and the local browse first temporary skip state, then opens the initialization guide directly. This switch is only for demos and acceptance checks; it does not change datasources, collection queues, or Earth content resources.

Current boundary:

  • The dropdown selects built-in collectors.
  • The plug icon beside the dropdown runs the health check.
  • Credential-bearing collectors place credential forms above base config.
  • Free collectors show endpoint, default endpoint, headers, timeout, and retry.
  • BarentsWatch AIS keeps its dedicated credential form.

Earth Content Page

/earth-content reuses the same single-screen tab container from Settings.tsx, but its ownership is separate from System Settings:

  • TV Livestream owns the Earth media-panel source configuration.
  • Boundary Precision owns the Earth static boundary asset state: provider, low-precision fallback, high-precision manifest/PMTiles, source JSON, and build action.
  • Base Map, Layer Resources, 3D Assets, and News Anchor Strategy are placeholders only. They show module status and do not invent fake APIs or fake data.

Do not add Earth experience resources or collection-lifecycle tabs back into /settings; collection belongs to /collection-management, and Earth display resources belong to /earth-content.

3. Complex Workspace Pages

Examples:

Constraints:

  • Tab content must not share the same height logic
  • Table tabs, Markdown tabs, and config tabs each need their own scroll responsibility
  • AI result areas and long text areas should maintain a minimum readable height

Current Layout Constraints

These principles have been repeatedly validated in the project:

  1. Parent container height chain must close
  2. min-height: 0 must not be omitted
  3. Overflow responsibility must be explicit
  4. Do not use overflow: hidden to mask structural issues
  5. Do not compress the main work area to make summary cards show completely
  6. Custom scrollbars must be floating overlays; they must not squeeze content width
  7. The Admin shell relies on the root height: 100% chain and should not use exact 100vh sizing at the workspace root

For detailed experience, see:

For future console page changes:

  1. Confirm whether the page is a summary page, table page, or complex workspace
  2. Integrate into the existing shell and scroll semantics first
  3. Reuse shared scroll components
  4. Handle visual and detail interactions last

Do not write local CSS patches first, then retrofit the structure.

Current Clear Boundary

The console frontend and the Earth frontend are not the same system:

  • Console frontend: React + Tactile UI / Radix primitives / lucide workbench
  • Earth frontend: independent native HUD system under public/earth

Therefore:

  • Do not move Earth's HUD / animations / state machine directly into the console
  • Do not force the console's table / scroll strategy onto the Earth HUD

For Earth-related structure, see: