Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(console): address PR 2132 review on platform K8s and archive logs
刘祺祥4d27a49762d6
diff --git a/console/bff/app/k8s_probe.py b/console/bff/app/k8s_probe.pyindex 750e9c59d..29e31821f 100644--- a/console/bff/app/k8s_probe.py+++ b/console/bff/app/k8s_probe.py@@ -51,12 +51,16 @@ async def probe_node_agent(settings: Settings) -> dict[str, Any]:namespace=settings.bff_k8s_node_agent_namespace,label_selector=settings.bff_k8s_node_agent_label_selector,)- out: list[dict[str, str]] = []+ out: list[dict[str, str | None]] = []for pod in pods.items:- ip = pod.status.pod_ip- if not ip:- continue- out.append({"name": pod.metadata.name, "node": pod.spec.node_name or "", "ip": ip})+ ip = pod.status.pod_ip if pod.status else None+ out.append(+ {+ "name": pod.metadata.name,+ "node": pod.spec.node_name or "",+ "ip": ip,+ }+ )return outtry:@@ -74,12 +78,17 @@ async def probe_node_agent(settings: Settings) -> dict[str, Any]:"totalPods": 0,}- probes = await asyncio.gather(- *[- _probe_pod_readyz(p["ip"], settings.bff_k8s_node_agent_probe_port, settings.bff_http_timeout_seconds)- for p in pod_refs- ],- )+ async def _probe_one(pod_ref: dict[str, str | None]) -> dict[str, Any]:+ ip = pod_ref.get("ip")+ if not ip:+ return {"ready": False, "reasons": ["no-pod-ip"]}+ return await _probe_pod_readyz(+ ip,+ settings.bff_k8s_node_agent_probe_port,+ settings.bff_http_timeout_seconds,+ )++ probes = await asyncio.gather(*[_probe_one(p) for p in pod_refs])ready_count = sum(1 for p in probes if p.get("ready"))sample_reasons: list[str] = []for p in probes:diff --git a/console/bff/app/k8s_resources.py b/console/bff/app/k8s_resources.pyindex 93d031dd1..670d913b1 100644--- a/console/bff/app/k8s_resources.py+++ b/console/bff/app/k8s_resources.py@@ -17,6 +17,9 @@ from __future__ import annotationsimport asynciofrom typing import Any+from kubernetes.client.exceptions import ApiException+from kubernetes.config.config_exception import ConfigException+from app.config import Settingsfrom app.k8s_client import load_core_v1from app.tenants import load_tenants@@ -113,6 +116,72 @@ def _list_workloads_sync(return rows+def _k8s_list_error(exc: Exception) -> dict[str, Any]:+ if isinstance(exc, ConfigException):+ return {+ "items": [],+ "message": str(exc),+ "errorCode": "K8S_CONFIG",+ }+ if isinstance(exc, ApiException):+ body = exc.body if isinstance(exc.body, str) else str(exc.body or exc.reason or exc)+ return {+ "items": [],+ "message": body,+ "errorCode": "K8S_API_ERROR",+ }+ return {+ "items": [],+ "message": str(exc),+ "errorCode": "K8S_ERROR",+ }+++def _event_sort_key(ev: Any) -> Any:+ return ev.last_timestamp or ev.event_time or ev.metadata.creation_timestamp+++def _list_namespace_events(v1: Any, namespace: str, *, page_size: int, max_pages: int) -> list[Any]:+ collected: list[Any] = []+ continue_token: str | None = None+ for _ in range(max_pages):+ resp = v1.list_namespaced_event(+ namespace=namespace,+ limit=page_size,+ _continue=continue_token,+ )+ collected.extend(resp.items)+ continue_token = resp.metadata._continue+ if not continue_token:+ break+ collected.sort(key=_event_sort_key, reverse=True)+ return collected+++def _pod_names_for_sandbox(v1: Any, namespace: str, sandbox_id: str) -> set[str]:+ names = set(pod_name_candidates_for_sandbox(sandbox_id))+ try:+ pods = v1.list_namespaced_pod(+ namespace=namespace,+ label_selector=f"{SANDBOX_ID_LABEL}={sandbox_id}",+ )+ for pod in pods.items:+ if pod.metadata.name:+ names.add(pod.metadata.name)+ except ApiException:+ raise+ except Exception:+ pass+ return names+++def _event_matches_sandbox(ev: Any, pod_names: set[str]) -> bool:+ obj = ev.involved_object+ if not obj or obj.kind != "Pod" or not obj.name:+ return False+ return obj.name in pod_names++def _event_row(ev: Any, tenant: str, namespace: str) -> dict[str, Any]:obj = ev.involved_objectreturn {@@ -141,26 +210,18 @@ def _list_events_sync() -> list[dict[str, Any]]:v1 = load_core_v1()rows: list[dict[str, Any]] = []+ page_size = min(max(limit, 50), 300)+ max_pages = 8for tenant_name, namespace in _target_namespaces(settings, tenant_filter):if namespace_filter and namespace != namespace_filter:continue- field_selector = None+ pod_names: set[str] | None = Noneif sandbox_id:- # Events don't index by sandbox label; filter client-side on pod name prefix if needed- pass- events = v1.list_namespaced_event(namespace=namespace, field_selector=field_selector, limit=limit)- for ev in sorted(events.items, key=lambda e: e.last_timestamp or e.event_time or e.metadata.creation_timestamp, reverse=True):- if sandbox_id:- obj = ev.involved_object- if obj and obj.kind == "Pod":- try:- pod = v1.read_namespaced_pod(name=obj.name, namespace=namespace)- if (pod.metadata.labels or {}).get(SANDBOX_ID_LABEL) != sandbox_id:- continue- except Exception:- continue- else:- continue+ pod_names = _pod_names_for_sandbox(v1, namespace, sandbox_id)+ events = _list_namespace_events(v1, namespace, page_size=page_size, max_pages=max_pages)+ for ev in events:+ if pod_names is not None and not _event_matches_sandbox(ev, pod_names):+ continuerows.append(_event_row(ev, tenant_name, namespace))if len(rows) >= limit:return rows@@ -181,14 +242,20 @@ async def list_workloads("disabled": True,"message": "Set BFF_K8S_PROBE_ENABLED=true and configure RBAC",}- items = await asyncio.to_thread(- _list_workloads_sync,- settings,- tenant_filter=tenant,- namespace_filter=namespace,- sandbox_id=sandbox_id,- limit=min(limit, 500),- )+ capped = min(limit, 500)+ try:+ items = await asyncio.to_thread(+ _list_workloads_sync,+ settings,+ tenant_filter=tenant,+ namespace_filter=namespace,+ sandbox_id=sandbox_id,+ limit=capped,+ )+ except (ConfigException, ApiException, RuntimeError) as exc:+ return {**_k8s_list_error(exc), "totalItems": 0}+ except Exception as exc:+ return {**_k8s_list_error(exc), "totalItems": 0}return {"items": items, "totalItems": len(items)}@@ -206,12 +273,18 @@ async def list_events("disabled": True,"message": "Set BFF_K8S_PROBE_ENABLED=true and configure RBAC",}- items = await asyncio.to_thread(- _list_events_sync,- settings,- tenant_filter=tenant,- namespace_filter=namespace,- sandbox_id=sandbox_id,- limit=min(limit, 300),- )+ capped = min(limit, 300)+ try:+ items = await asyncio.to_thread(+ _list_events_sync,+ settings,+ tenant_filter=tenant,+ namespace_filter=namespace,+ sandbox_id=sandbox_id,+ limit=capped,+ )+ except (ConfigException, ApiException, RuntimeError) as exc:+ return {**_k8s_list_error(exc), "totalItems": 0}+ except Exception as exc:+ return {**_k8s_list_error(exc), "totalItems": 0}return {"items": items, "totalItems": len(items)}diff --git a/console/bff/app/nodeagent_archive.py b/console/bff/app/nodeagent_archive.pyindex 445e2c0ae..a745a10aa 100644--- a/console/bff/app/nodeagent_archive.py+++ b/console/bff/app/nodeagent_archive.py@@ -55,13 +55,14 @@ def _read_archive_sync(auth = oss2.Auth(settings.bff_nodeagent_oss_access_key_id, settings.bff_nodeagent_oss_access_key_secret)bucket = oss2.Bucket(auth, settings.bff_nodeagent_oss_endpoint, settings.bff_nodeagent_oss_bucket)- log_objects: list[tuple[str, Any]] = []+ log_objects: list[tuple[str, Any, int]] = []marker_objects: list[tuple[str, int, Any]] = []for obj in oss2.ObjectIterator(bucket, prefix=prefix):key = obj.keyif _LOG_OBJECT_RE.search(key):- log_objects.append((key, obj.last_modified))+ size = int(getattr(obj, "size", 0) or 0)+ log_objects.append((key, obj.last_modified, size))marker_match = _MARKER_RE.search(key)if marker_match:marker_objects.append((key, int(marker_match.group(1)), obj.last_modified))@@ -76,7 +77,7 @@ def _read_archive_sync()log_objects.sort(key=lambda x: x[1], reverse=True)- chosen_key = log_objects[0][0]+ chosen_key, _, object_size = log_objects[0]marker_status: str | None = Nonemarker_warnings: list[str] = []@@ -89,20 +90,33 @@ def _read_archive_sync(marker_status = str(marker_doc.get("status") or "")if marker_doc.get("warnings"):marker_warnings = [str(w) for w in marker_doc["warnings"]]+ except oss2.exceptions.NoSuchKey:+ marker_status = "unknown"except Exception:marker_status = "unknown"- obj = bucket.get_object(chosen_key)- data = obj.read()+ effective_max = max(1, max_bytes)truncated = False- if len(data) > max_bytes:- data = data[-max_bytes:]- truncated = True-try:- content = data.decode("utf-8", errors="replace")- except Exception:- content = data.decode("latin-1", errors="replace")+ if object_size and object_size > effective_max:+ start = object_size - effective_max+ data = bucket.get_object(chosen_key, byte_range=(start, object_size - 1)).read()+ truncated = True+ else:+ data = bucket.get_object(chosen_key).read()+ if len(data) > effective_max:+ data = data[-effective_max:]+ truncated = True+ except oss2.exceptions.NoSuchKey as exc:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail={+ "code": "ARCHIVE_NOT_FOUND",+ "message": f"Log object {chosen_key!r} no longer exists",+ },+ ) from exc++ content = data.decode("utf-8", errors="replace")warnings: list[str] = ["Source: node-agent durable store (OSS). Live tail still uses Lifecycle diagnostics.",@@ -152,7 +166,11 @@ async def fetch_archive_logs(},)- limit = max_bytes if max_bytes is not None else settings.bff_nodeagent_archive_max_bytes+ cap = max(1, settings.bff_nodeagent_archive_max_bytes)+ if max_bytes is None:+ limit = cap+ else:+ limit = max(1, min(max_bytes, cap))import asyncioreturn await asyncio.to_thread(diff --git a/console/bff/app/query_params.py b/console/bff/app/query_params.pynew file mode 100644index 000000000..5bd4a55ea--- /dev/null+++ b/console/bff/app/query_params.py@@ -0,0 +1,66 @@+# Copyright 2026 The OpenSandbox Authors+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++from __future__ import annotations++from fastapi import HTTPException, status+++def parse_query_int(+ raw: str | None,+ *,+ field: str,+ default: int,+ minimum: int = 1,+ maximum: int,+) -> int:+ if raw is None or str(raw).strip() == "":+ value = default+ else:+ try:+ value = int(str(raw).strip())+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "code": "INVALID_QUERY",+ "message": f"{field} must be an integer",+ },+ ) from exc+ if value < minimum:+ value = minimum+ if value > maximum:+ value = maximum+ return value+++def parse_archive_max_bytes(raw: str | None, *, cap: int) -> int:+ """Parse maxBytes query; always clamp to operator cap (1..cap)."""+ if cap < 1:+ cap = 1+ if raw is None or str(raw).strip() == "":+ return cap+ try:+ value = int(str(raw).strip())+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "code": "INVALID_QUERY",+ "message": "maxBytes must be an integer",+ },+ ) from exc+ if value < 1:+ value = 1+ return min(value, cap)diff --git a/console/bff/app/routes/admin.py b/console/bff/app/routes/admin.pyindex 81b0478e5..45481bd35 100644--- a/console/bff/app/routes/admin.py+++ b/console/bff/app/routes/admin.py@@ -27,6 +27,7 @@ from app.k8s_platform import probe_platform_deploymentfrom app.k8s_probe import probe_node_agentfrom app.k8s_resources import list_events, list_workloadsfrom app.nodeagent_archive import fetch_archive_logs+from app.query_params import parse_archive_max_bytes, parse_query_intfrom app.routes.proxy_utils import passthrough_jsonfrom app.routes.admin_proxy import admin_get_sandbox, admin_lifecycle_requestfrom app.routes.session_keys import api_key_for_tenant_name, tenant_namespace_for_name@@ -231,7 +232,7 @@ async def admin_k8s_workloads(require_admin_session(payload)settings = get_settings()qp = request.query_params- limit = int(qp.get("limit", 200) or 200)+ limit = parse_query_int(qp.get("limit"), field="limit", default=200, maximum=500)return await list_workloads(settings,tenant=qp.get("tenant"),@@ -249,7 +250,7 @@ async def admin_k8s_events(require_admin_session(payload)settings = get_settings()qp = request.query_params- limit = int(qp.get("limit", 100) or 100)+ limit = parse_query_int(qp.get("limit"), field="limit", default=100, maximum=300)return await list_events(settings,tenant=qp.get("tenant"),@@ -377,10 +378,14 @@ async def admin_sandbox_archive_logs(require_admin_session(payload)tenant = _require_tenant_query(request)namespace = tenant_namespace_for_name(tenant)- max_bytes = request.query_params.get("maxBytes")+ settings = get_settings()+ max_bytes = parse_archive_max_bytes(+ request.query_params.get("maxBytes"),+ cap=settings.bff_nodeagent_archive_max_bytes,+ )return await fetch_archive_logs(- get_settings(),+ settings,namespace,sandbox_id,- max_bytes=int(max_bytes) if max_bytes else None,+ max_bytes=max_bytes,)diff --git a/console/bff/app/routes/sandboxes.py b/console/bff/app/routes/sandboxes.pyindex f7cb46ecf..058d633d4 100644--- a/console/bff/app/routes/sandboxes.py+++ b/console/bff/app/routes/sandboxes.py@@ -23,6 +23,7 @@ from app.deps import get_session_payload, require_tenant_sessionfrom app.lifecycle import LifecycleClientfrom app.runtime import attach_runtime_summaryfrom app.nodeagent_archive import fetch_archive_logs+from app.query_params import parse_archive_max_bytesfrom app.routes.proxy_utils import passthrough_jsonfrom app.routes.session_keys import tenant_api_key, tenant_namespace_for_session@@ -162,12 +163,16 @@ async def get_sandbox_archive_logs() -> Any:require_tenant_session(payload)namespace = tenant_namespace_for_session(payload)- max_bytes = request.query_params.get("maxBytes")+ settings = get_settings()+ max_bytes = parse_archive_max_bytes(+ request.query_params.get("maxBytes"),+ cap=settings.bff_nodeagent_archive_max_bytes,+ )return await fetch_archive_logs(- get_settings(),+ settings,namespace,sandbox_id,- max_bytes=int(max_bytes) if max_bytes else None,+ max_bytes=max_bytes,)diff --git a/console/bff/tests/test_k8s_event_filter.py b/console/bff/tests/test_k8s_event_filter.pynew file mode 100644index 000000000..194747eb0--- /dev/null+++ b/console/bff/tests/test_k8s_event_filter.py@@ -0,0 +1,33 @@+# Copyright 2026 The OpenSandbox Authors+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++from types import SimpleNamespace++from app.k8s_resources import _event_matches_sandbox, pod_name_candidates_for_sandbox+++def test_pod_name_candidates_include_batch_suffix():+ assert pod_name_candidates_for_sandbox("abc") == ["abc-0", "abc"]+++def test_event_matches_pooled_pod_name():+ ev = SimpleNamespace(+ involved_object=SimpleNamespace(kind="Pod", name="abc-0"),+ )+ names = set(pod_name_candidates_for_sandbox("abc"))+ assert _event_matches_sandbox(ev, names)+ assert not _event_matches_sandbox(+ SimpleNamespace(involved_object=SimpleNamespace(kind="Pod", name="other-0")),+ names,+ )diff --git a/console/bff/tests/test_query_params.py b/console/bff/tests/test_query_params.pynew file mode 100644index 000000000..26fc69f21--- /dev/null+++ b/console/bff/tests/test_query_params.py@@ -0,0 +1,38 @@+# Copyright 2026 The OpenSandbox Authors+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++import pytest+from fastapi import HTTPException++from app.query_params import parse_archive_max_bytes, parse_query_int+++def test_parse_query_int_defaults_and_clamps():+ assert parse_query_int(None, field="limit", default=100, maximum=500) == 100+ assert parse_query_int("", field="limit", default=100, maximum=500) == 100+ assert parse_query_int("0", field="limit", default=100, minimum=1, maximum=500) == 1+ assert parse_query_int("9999", field="limit", default=100, maximum=500) == 500+++def test_parse_query_int_rejects_garbage():+ with pytest.raises(HTTPException) as exc:+ parse_query_int("abc", field="limit", default=100, maximum=500)+ assert exc.value.detail["code"] == "INVALID_QUERY"+++def test_parse_archive_max_bytes_clamps_to_cap():+ assert parse_archive_max_bytes(None, cap=512_288) == 512_288+ assert parse_archive_max_bytes("9999999", cap=512_288) == 512_288+ assert parse_archive_max_bytes("0", cap=512_288) == 1+ assert parse_archive_max_bytes("-5", cap=512_288) == 1diff --git a/console/web/src/api/types.ts b/console/web/src/api/types.tsindex 6554a8abf..bc94667f6 100644--- a/console/web/src/api/types.ts+++ b/console/web/src/api/types.ts@@ -113,6 +113,7 @@ export interface K8sListResponse<T> {totalItems?: number;disabled?: boolean;message?: string;+ errorCode?: string;}export interface PoolListResponse {diff --git a/console/web/src/components/SandboxArchiveLogPanel.tsx b/console/web/src/components/SandboxArchiveLogPanel.tsxindex 52da872cc..e84df1d37 100644--- a/console/web/src/components/SandboxArchiveLogPanel.tsx+++ b/console/web/src/components/SandboxArchiveLogPanel.tsx@@ -1,11 +1,11 @@// Copyright 2026 The OpenSandbox Authors-//+//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at-//+//// http://www.apache.org/licenses/LICENSE-2.0-//+//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -13,9 +13,9 @@// limitations under the License.import { Alert, Button, Space, Typography, message } from 'antd';-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';-import { adminApi, sandboxApi } from '../api/client';+import { ApiError, adminApi, sandboxApi } from '../api/client';import type { DiagnosticContentResponse } from '../api/types';import { useAuth } from '../auth/AuthContext';import { SandboxColoredLogViewer } from './SandboxColoredLogViewer';@@ -27,6 +27,11 @@ type Props = {maxHeight?: number;};+const ARCHIVE_DISABLED_CODES = new Set([+ 'NODEAGENT_ARCHIVE_DISABLED',+ 'NODEAGENT_OSS_NOT_CONFIGURED',+]);+export function SandboxArchiveLogPanel({sandboxId,tenant,@@ -34,6 +39,8 @@ export function SandboxArchiveLogPanel({maxHeight = 420,}: Props) {const { user } = useAuth();+ const requestSeq = useRef(0);+ const [contentVersion, setContentVersion] = useState(0);const [data, setData] = useState<DiagnosticContentResponse | null>(null);const [loading, setLoading] = useState(false);const [disabledNote, setDisabledNote] = useState<string | null>(null);@@ -44,6 +51,7 @@ export function SandboxArchiveLogPanel({message.warning('Admin 查看归档日志需指定 tenant');return;}+ const seq = ++requestSeq.current;setLoading(true);setDisabledNote(null);try {@@ -51,23 +59,25 @@ export function SandboxArchiveLogPanel({user?.role === 'admin' && tenant? await adminApi.archiveLogs(sandboxId.trim(), tenant): await sandboxApi.archiveLogs(sandboxId.trim());+ if (seq !== requestSeq.current) return;setData(result);+ setContentVersion((v) => v + 1);} catch (e) {+ if (seq !== requestSeq.current) return;setData(null);- const msg = e instanceof Error ? e.message : '加载归档失败';- if (msg.includes('NODEAGENT') || msg.includes('DISABLED') || msg.includes('OSS')) {- setDisabledNote(msg);+ if (e instanceof ApiError && ARCHIVE_DISABLED_CODES.has(e.code)) {+ setDisabledNote(e.message);} else {- message.error(msg);+ message.error(e instanceof Error ? e.message : '加载归档失败');}} finally {- setLoading(false);+ if (seq === requestSeq.current) setLoading(false);}}, [sandboxId, tenant, user?.role]);useEffect(() => {if (autoLoad && sandboxId) void fetchArchive();- }, [autoLoad, sandboxId, fetchArchive]);+ }, [autoLoad, sandboxId, tenant, fetchArchive]);if (disabledNote) {return (@@ -83,6 +93,11 @@ export function SandboxArchiveLogPanel({</Typography.Paragraph></>}+ action={+ <Button size="small" onClick={() => void fetchArchive()}>+ 重试+ </Button>+ }/>);}@@ -99,8 +114,8 @@ export function SandboxArchiveLogPanel({</Typography.Text>)}</Space>- {data?.warnings?.map((w) => (- <Alert key={w} type="info" showIcon message={w} style={{ marginBottom: 8 }} />+ {data?.warnings?.map((w, i) => (+ <Alert key={`${i}-${w.slice(0, 40)}`} type="info" showIcon message={w} style={{ marginBottom: 8 }} />))}{data?.truncated && (<Alert@@ -117,7 +132,7 @@ export function SandboxArchiveLogPanel({<SandboxColoredLogViewercontent={data.content}maxHeight={maxHeight}- contentKey={`archive-${data.content.length}-${loading ? 'loading' : 'idle'}`}+ contentKey={`archive-${contentVersion}`}/>)}</div>diff --git a/console/web/src/layout/AppLayout.tsx b/console/web/src/layout/AppLayout.tsxindex 18b17b77e..030bb0efc 100644--- a/console/web/src/layout/AppLayout.tsx+++ b/console/web/src/layout/AppLayout.tsx@@ -55,8 +55,12 @@ export function AppLayout() {children: [{ key: '/platform/health', label: '组件健康' },{ key: '/platform/version', label: '版本' },- { key: '/platform/k8s/workloads', label: 'K8s 工作负载' },- { key: '/platform/k8s/events', label: 'K8s 事件' },+ ...(isAdmin+ ? [+ { key: '/platform/k8s/workloads', label: 'K8s 工作负载' },+ { key: '/platform/k8s/events', label: 'K8s 事件' },+ ]+ : []),],},];diff --git a/console/web/src/pages/platform/ComponentHealthPage.tsx b/console/web/src/pages/platform/ComponentHealthPage.tsxindex 4eca6cc0e..822a9d032 100644--- a/console/web/src/pages/platform/ComponentHealthPage.tsx+++ b/console/web/src/pages/platform/ComponentHealthPage.tsx@@ -25,10 +25,12 @@ export function ComponentHealthPage() {const [bffHealth, setBffHealth] = useState<{ status?: string } | null>(null);const [loading, setLoading] = useState(true);const [usedFallback, setUsedFallback] = useState(false);+ const [loadError, setLoadError] = useState<string | null>(null);useEffect(() => {void (async () => {setLoading(true);+ setLoadError(null);try {if (user?.role === 'admin') {setSummary(await adminApi.platformSummary());@@ -37,12 +39,17 @@ export function ComponentHealthPage() {setUsedFallback(true);setBffHealth(await platformApi.bffHealth());}- } catch {+ } catch (err) {setUsedFallback(true);+ const primary = err instanceof Error ? err.message : '加载平台摘要失败';try {setBffHealth(await platformApi.bffHealth());- } catch {+ setLoadError(primary);+ } catch (fallbackErr) {setBffHealth(null);+ const secondary =+ fallbackErr instanceof Error ? fallbackErr.message : 'BFF /health 不可用';+ setLoadError(`${primary};${secondary}`);}} finally {setLoading(false);@@ -55,6 +62,9 @@ export function ComponentHealthPage() {return (<div><Typography.Title level={4}>组件健康</Typography.Title>+ {loadError && (+ <Alert type="warning" showIcon message={loadError} style={{ marginBottom: 16 }} />+ )}{usedFallback && (<Alerttype="info"diff --git a/console/web/src/pages/platform/K8sEventsPage.tsx b/console/web/src/pages/platform/K8sEventsPage.tsxindex d4ba051a4..2123b4e13 100644--- a/console/web/src/pages/platform/K8sEventsPage.tsx+++ b/console/web/src/pages/platform/K8sEventsPage.tsx@@ -1,20 +1,20 @@// Copyright 2026 The OpenSandbox Authors-//+//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at-//+//// http://www.apache.org/licenses/LICENSE-2.0-//+//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.-import { Alert, Input, Space, Table, Typography } from 'antd';+import { Alert, Input, Space, Table, Typography, message } from 'antd';import type { ColumnsType } from 'antd/es/table';-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { adminApi } from '../../api/client';import type { K8sEventRow } from '../../api/types';@@ -22,6 +22,7 @@ import { useAuth } from '../../auth/AuthContext';export function K8sEventsPage() {const { user } = useAuth();+ const requestSeq = useRef(0);const [loading, setLoading] = useState(false);const [items, setItems] = useState<K8sEventRow[]>([]);const [disabledMsg, setDisabledMsg] = useState<string | null>(null);@@ -29,20 +30,29 @@ export function K8sEventsPage() {const load = async () => {if (user?.role !== 'admin') return;+ const seq = ++requestSeq.current;setLoading(true);setDisabledMsg(null);try {const data = await adminApi.k8sEvents({sandboxId: sandboxId.trim() || undefined,});+ if (seq !== requestSeq.current) return;if (data.disabled) {setDisabledMsg(data.message ?? 'K8s API 未启用');setItems([]);+ } else if (data.errorCode) {+ setDisabledMsg(data.message ?? 'K8s API 错误');+ setItems([]);} else {setItems(data.items ?? []);}+ } catch (e) {+ if (seq !== requestSeq.current) return;+ message.error(e instanceof Error ? e.message : '加载 K8s 事件失败');+ setItems([]);} finally {- setLoading(false);+ if (seq === requestSeq.current) setLoading(false);}};@@ -78,7 +88,12 @@ export function K8sEventsPage() {/><Typography.Link onClick={() => void load()}>刷新</Typography.Link></Space>- <Table rowKey={(r, i) => `${r.namespace}-${r.lastTimestamp}-${i}`} loading={loading} columns={columns} dataSource={items} />+ <Table+ rowKey={(r) => `${r.namespace}-${r.lastTimestamp}-${r.reason}-${r.involvedObject?.name ?? ''}`}+ loading={loading}+ columns={columns}+ dataSource={items}+ /></div>);}diff --git a/console/web/src/pages/platform/K8sPlaceholderPage.tsx b/console/web/src/pages/platform/K8sPlaceholderPage.tsxdeleted file mode 100644index 82ec10f15..000000000--- a/console/web/src/pages/platform/K8sPlaceholderPage.tsx+++ /dev/null@@ -1,39 +0,0 @@-// Copyright 2026 The OpenSandbox Authors-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--import { Alert, Typography } from 'antd';--type Props = {- title: string;-};--export function K8sPlaceholderPage({ title }: Props) {- return (- <div>- <Typography.Title level={4}>{title}</Typography.Title>- <Alert- type="warning"- showIcon- message="Phase 2 — 需要 K8s RBAC"- description={- <ul>- <li>BFF 需配置只读 ServiceAccount(list/watch Pods、Events 等)。</li>- <li>当前版本未实现 K8s API 代理;本页为结构化占位,避免误导为已联通集群。</li>- <li>上线后在此展示按 namespace 过滤的工作负载或事件表格。</li>- </ul>- }- />- </div>- );-}diff --git a/console/web/src/pages/platform/K8sWorkloadsPage.tsx b/console/web/src/pages/platform/K8sWorkloadsPage.tsxindex f844dcb33..7aa8ff597 100644--- a/console/web/src/pages/platform/K8sWorkloadsPage.tsx+++ b/console/web/src/pages/platform/K8sWorkloadsPage.tsx@@ -1,20 +1,20 @@// Copyright 2026 The OpenSandbox Authors-//+//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at-//+//// http://www.apache.org/licenses/LICENSE-2.0-//+//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.-import { Alert, Input, Select, Space, Table, Tag, Typography } from 'antd';+import { Alert, Input, Select, Space, Table, Tag, Typography, message } from 'antd';import type { ColumnsType } from 'antd/es/table';-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { TenantTag } from '../../components/SemanticTags';import { adminApi } from '../../api/client';@@ -23,14 +23,17 @@ import { useAuth } from '../../auth/AuthContext';export function K8sWorkloadsPage() {const { user } = useAuth();+ const requestSeq = useRef(0);const [loading, setLoading] = useState(false);const [items, setItems] = useState<K8sWorkloadRow[]>([]);+ const [tenantOptions, setTenantOptions] = useState<string[]>([]);const [disabledMsg, setDisabledMsg] = useState<string | null>(null);const [tenant, setTenant] = useState<string>();const [sandboxId, setSandboxId] = useState('');const load = async () => {if (user?.role !== 'admin') return;+ const seq = ++requestSeq.current;setLoading(true);setDisabledMsg(null);try {@@ -38,17 +41,38 @@ export function K8sWorkloadsPage() {tenant,sandboxId: sandboxId.trim() || undefined,});+ if (seq !== requestSeq.current) return;if (data.disabled) {setDisabledMsg(data.message ?? 'K8s API 未启用');setItems([]);+ } else if (data.errorCode) {+ setDisabledMsg(data.message ?? 'K8s API 错误');+ setItems([]);} else {setItems(data.items ?? []);}+ } catch (e) {+ if (seq !== requestSeq.current) return;+ message.error(e instanceof Error ? e.message : '加载 K8s 工作负载失败');+ setItems([]);} finally {- setLoading(false);+ if (seq === requestSeq.current) setLoading(false);}};+ useEffect(() => {+ if (user?.role !== 'admin') return;+ void (async () => {+ try {+ const data = await adminApi.k8sWorkloads({});+ const names = [...new Set((data.items ?? []).map((i) => i.tenant).filter(Boolean))] as string[];+ setTenantOptions(names);+ } catch {+ /* tenant filter is optional */+ }+ })();+ }, [user?.role]);+useEffect(() => {void load();}, [user?.role, tenant]);@@ -90,9 +114,9 @@ export function K8sWorkloadsPage() {style={{ width: 140 }}value={tenant}onChange={setTenant}- options={[...new Set(items.map((i) => i.tenant).filter(Boolean))].map((t) => ({+ options={tenantOptions.map((t) => ({label: t,- value: t!,+ value: t,}))}/><Typography.Link onClick={() => void load()}>刷新</Typography.Link>