Merge pull request #615 from AAEE86/main

feat: 健康监控仪表盘与关联下钻优化,完善使用记录展示
This commit is contained in:
fawney19
2026-06-21 12:48:13 +08:00
committed by GitHub
41 changed files with 4445 additions and 1602 deletions
@@ -21,6 +21,7 @@ pub(crate) fn mount_public_support_routes(router: Router<AppState>) -> Router<Ap
.route("/api/public/global-models", get(proxy_request))
.route("/api/public/health/api-formats", get(proxy_request))
.route("/api/public/health/models", get(proxy_request))
.route("/api/public/health/related", get(proxy_request))
.route("/api/modules/auth-status", get(proxy_request))
.route("/api/capabilities", get(proxy_request))
.route("/api/capabilities/user-configurable", get(proxy_request))
+1
View File
@@ -94,6 +94,7 @@ pub(crate) const RUST_FRONTDOOR_OWNED_ROUTE_PATTERNS: &[&str] = &[
"/api/public/global-models",
"/api/public/health/api-formats",
"/api/public/health/models",
"/api/public/health/related",
"/api/oauth/providers",
"/api/oauth/{provider_type}/authorize",
"/api/oauth/{provider_type}/callback",
@@ -81,6 +81,16 @@ pub(super) fn classify_admin_endpoints_family_route(
"admin:endpoints_health",
false,
))
} else if method == http::Method::GET
&& normalized_path == "/api/admin/endpoints/health/related"
{
Some(classified(
"admin_proxy",
"endpoints_health",
"health_related",
"admin:endpoints_health",
false,
))
} else if method == http::Method::GET
&& normalized_path.starts_with("/api/admin/endpoints/rpm/key/")
{
@@ -157,6 +157,7 @@ pub(super) fn classify_public_support_route(
| "/api/public/global-models"
| "/api/public/health/api-formats"
| "/api/public/health/models"
| "/api/public/health/related"
)
{
let route_kind = match normalized_path {
@@ -168,6 +169,7 @@ pub(super) fn classify_public_support_route(
"/api/public/global-models" => "global_models",
"/api/public/health/api-formats" => "health_api_formats",
"/api/public/health/models" => "health_models",
"/api/public/health/related" => "health_related",
_ => "site_info",
};
Some(classified(
@@ -140,6 +140,25 @@ fn classifies_admin_endpoint_health_providers_as_admin_proxy_route() {
assert!(!decision.is_execution_runtime_candidate());
}
#[test]
fn classifies_admin_endpoint_health_related_as_admin_proxy_route() {
let headers = headers(&[]);
let uri: Uri = "/api/admin/endpoints/health/related?dimension=model&value=gpt-5"
.parse()
.expect("uri should parse");
let decision =
classify_control_route(&http::Method::GET, &uri, &headers).expect("route should classify");
assert_eq!(decision.route_class.as_deref(), Some("admin_proxy"));
assert_eq!(decision.route_family.as_deref(), Some("endpoints_health"));
assert_eq!(decision.route_kind.as_deref(), Some("health_related"));
assert_eq!(
decision.auth_endpoint_signature.as_deref(),
Some("admin:endpoints_health")
);
assert!(!decision.is_execution_runtime_candidate());
}
#[test]
fn classifies_admin_endpoint_key_rpm_as_admin_proxy_route() {
let headers = headers(&[]);
@@ -757,6 +757,25 @@ fn classifies_public_catalog_health_models_as_public_support_route() {
assert!(!decision.is_execution_runtime_candidate());
}
#[test]
fn classifies_public_catalog_health_related_as_public_support_route() {
let headers = headers(&[]);
let uri: Uri = "/api/public/health/related?dimension=endpoint&value=openai%3Achat"
.parse()
.expect("uri should parse");
let decision =
classify_control_route(&http::Method::GET, &uri, &headers).expect("route should classify");
assert_eq!(decision.route_class.as_deref(), Some("public_support"));
assert_eq!(decision.route_family.as_deref(), Some("public_catalog"));
assert_eq!(decision.route_kind.as_deref(), Some("health_related"));
assert_eq!(
decision.auth_endpoint_signature.as_deref(),
Some("public:catalog")
);
assert!(!decision.is_execution_runtime_candidate());
}
#[test]
fn classifies_auth_registration_settings_as_public_support_route() {
let headers = headers(&[]);
@@ -1,7 +1,9 @@
use super::extractors::{admin_health_key_id, admin_recover_key_id};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::query_param_value;
use crate::handlers::public::{ApiFormatHealthMonitorOptions, ModelHealthMonitorOptions};
use crate::handlers::public::{
ApiFormatHealthMonitorOptions, HealthMonitorRelationDimension, ModelHealthMonitorOptions,
};
use crate::GatewayError;
use axum::{
body::Body,
@@ -22,6 +24,14 @@ fn build_admin_endpoint_health_data_unavailable_response() -> Response<Body> {
.into_response()
}
fn build_admin_endpoint_health_bad_request_response(detail: &str) -> Response<Body> {
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail })),
)
.into_response()
}
pub(super) async fn maybe_build_local_admin_endpoints_health_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
@@ -231,6 +241,55 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
return Ok(Some(Json(payload).into_response()));
}
if decision.route_family.as_deref() == Some("endpoints_health")
&& decision.route_kind.as_deref() == Some("health_related")
&& request_context.path() == "/api/admin/endpoints/health/related"
{
if !state.has_usage_data_reader() {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
}
let Some(dimension) = query_param_value(request_context.query_string(), "dimension")
.and_then(|value| HealthMonitorRelationDimension::parse(&value))
else {
return Ok(Some(build_admin_endpoint_health_bad_request_response(
"dimension 必须是 endpoint、model 或 provider",
)));
};
let Some(value) = query_param_value(request_context.query_string(), "value")
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
else {
return Ok(Some(build_admin_endpoint_health_bad_request_response(
"value 不能为空",
)));
};
let lookback_hours = query_param_value(request_context.query_string(), "lookback_hours")
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| (1..=72).contains(value))
.unwrap_or(6);
let related_limit = query_param_value(request_context.query_string(), "related_limit")
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| (1..=50).contains(value))
.unwrap_or(8);
let per_item_limit = query_param_value(request_context.query_string(), "per_item_limit")
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| (10..=200).contains(value))
.unwrap_or(100);
let Some(payload) = state
.build_related_health_monitor_payload(
lookback_hours,
dimension,
&value,
related_limit,
per_item_limit,
)
.await
else {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
};
return Ok(Some(Json(payload).into_response()));
}
if decision.route_family.as_deref() == Some("endpoints_health")
&& decision.route_kind.as_deref() == Some("health_status")
&& request_context.path() == "/api/admin/endpoints/health/status"
@@ -1,6 +1,8 @@
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::handlers::public::{api_format_display_name, build_public_health_timeline};
use crate::handlers::public::{
api_format_display_name, build_public_health_timeline, build_public_health_timeline_details,
};
use crate::handlers::shared::unix_ms_to_rfc3339;
use crate::provider_key_auth::provider_key_effective_api_formats;
use aether_data_contracts::repository::candidates::PublicHealthTimelineBucket;
@@ -11,6 +13,8 @@ use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
use std::time::{SystemTime, UNIX_EPOCH};
const ENDPOINT_HEALTH_TIMELINE_SEGMENTS: u32 = 60;
pub(crate) async fn build_admin_endpoint_health_status_payload(
state: &AdminAppState<'_>,
lookback_hours: u64,
@@ -124,7 +128,7 @@ pub(crate) async fn build_admin_endpoint_health_status_payload(
&all_endpoint_ids,
since_unix_secs,
now_unix_secs,
100,
ENDPOINT_HEALTH_TIMELINE_SEGMENTS,
)
.await
.ok()
@@ -171,7 +175,14 @@ pub(crate) async fn build_admin_endpoint_health_status_payload(
let empty_timeline = BTreeMap::new();
let timeline_source = timeline_by_format.get(&api_format).unwrap_or(&empty_timeline);
let (timeline, time_range_start, time_range_end) =
build_public_health_timeline(timeline_source, 100);
build_public_health_timeline(timeline_source, ENDPOINT_HEALTH_TIMELINE_SEGMENTS);
let timeline_details = build_public_health_timeline_details(
timeline_source,
since_unix_secs,
now_unix_secs,
ENDPOINT_HEALTH_TIMELINE_SEGMENTS,
&[],
);
let healthy_count = timeline.iter().filter(|status| **status == "healthy").count();
let warning_count = timeline.iter().filter(|status| **status == "warning").count();
let unhealthy_count = timeline.iter().filter(|status| **status == "unhealthy").count();
@@ -199,6 +210,7 @@ pub(crate) async fn build_admin_endpoint_health_status_payload(
"display_name": api_format_display_name(&api_format),
"health_score": health_score,
"timeline": timeline,
"timeline_details": timeline_details,
"time_range_start": time_range_start.and_then(unix_ms_to_rfc3339),
"time_range_end": time_range_end.map(|ms| unix_ms_to_rfc3339(ms)).unwrap_or_else(|| unix_secs_to_rfc3339(now_unix_secs)),
"total_endpoints": endpoint_ids.len(),
@@ -583,6 +583,7 @@ fn build_admin_usage_keyword_search_query(
client_family: base_query.client_family.clone(),
exclude_unknown_model_or_provider: base_query.exclude_unknown_model_or_provider,
statuses: base_query.statuses.clone(),
exclude_status_codes: base_query.exclude_status_codes.clone(),
is_stream: base_query.is_stream,
error_only: base_query.error_only,
keywords,
@@ -276,6 +276,26 @@ impl<'a> AdminAppState<'a> {
.await
}
pub(crate) async fn build_related_health_monitor_payload(
&self,
lookback_hours: u64,
dimension: crate::handlers::public::HealthMonitorRelationDimension,
value: &str,
related_limit: usize,
per_item_limit: usize,
) -> Option<serde_json::Value> {
crate::handlers::public::build_related_health_monitor_payload(
self.app,
lookback_hours,
dimension,
value,
related_limit,
per_item_limit,
true,
)
.await
}
pub(crate) async fn execute_execution_runtime_sync_plan(
&self,
trace_id: Option<&str>,
File diff suppressed because it is too large Load Diff
@@ -10,10 +10,11 @@ pub(crate) use self::catalog_helpers::{
admin_requested_force_stream, api_format_display_name, build_api_format_health_monitor_payload,
build_model_health_monitor_payload, build_provider_health_monitor_payload,
build_public_catalog_models_payload, build_public_catalog_search_models_payload,
build_public_health_timeline, build_public_providers_payload, normalize_admin_base_url,
build_public_health_timeline, build_public_health_timeline_details,
build_public_providers_payload, build_related_health_monitor_payload, normalize_admin_base_url,
provider_key_api_formats, request_candidate_event_unix_ms, request_candidate_status_label,
sanitize_public_model_config_for_user, ApiFormatHealthMonitorOptions,
ModelHealthMonitorOptions,
HealthMonitorRelationDimension, ModelHealthMonitorOptions,
};
pub(crate) use self::system_modules_helpers::{
build_admin_keys_grouped_by_format_payload, build_public_auth_modules_status_payload,
@@ -2,9 +2,10 @@ use super::{
build_api_format_health_monitor_payload, build_model_health_monitor_payload,
build_public_auth_modules_status_payload, build_public_catalog_models_payload,
build_public_catalog_search_models_payload, build_public_providers_payload,
capability_detail_by_name, ldap_module_config_is_valid, sanitize_public_model_config_for_user,
serialize_public_capability, supported_capability_names, ApiFormatHealthMonitorOptions,
ModelHealthMonitorOptions, PUBLIC_CAPABILITY_DEFINITIONS,
build_related_health_monitor_payload, capability_detail_by_name, ldap_module_config_is_valid,
sanitize_public_model_config_for_user, serialize_public_capability, supported_capability_names,
ApiFormatHealthMonitorOptions, HealthMonitorRelationDimension, ModelHealthMonitorOptions,
PUBLIC_CAPABILITY_DEFINITIONS,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::shared::{
@@ -477,6 +478,77 @@ pub(crate) async fn maybe_build_local_public_support_response(
.await?;
return Some(Json(payload).into_response());
}
if decision.route_kind.as_deref() == Some("health_related")
&& request_context.request_path == "/api/public/health/related"
{
let Some(dimension) =
query_param_value(request_context.request_query_string.as_deref(), "dimension")
.and_then(|value| HealthMonitorRelationDimension::parse(&value))
else {
return Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "dimension 必须是 endpoint 或 model" })),
)
.into_response(),
);
};
if matches!(dimension, HealthMonitorRelationDimension::Provider) {
return Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "公开健康监控不支持 provider 维度" })),
)
.into_response(),
);
}
let Some(value) =
query_param_value(request_context.request_query_string.as_deref(), "value")
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
else {
return Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "value 不能为空" })),
)
.into_response(),
);
};
let lookback_hours = query_param_value(
request_context.request_query_string.as_deref(),
"lookback_hours",
)
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| (1..=168).contains(value))
.unwrap_or(6);
let related_limit = query_param_value(
request_context.request_query_string.as_deref(),
"related_limit",
)
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| (1..=50).contains(value))
.unwrap_or(8);
let per_item_limit = query_param_value(
request_context.request_query_string.as_deref(),
"per_item_limit",
)
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| (10..=500).contains(value))
.unwrap_or(100);
let payload = build_related_health_monitor_payload(
state,
lookback_hours,
dimension,
&value,
related_limit,
per_item_limit,
false,
)
.await?;
return Some(Json(payload).into_response());
}
}
if decision.route_family.as_deref() == Some("capabilities") {
@@ -19,6 +19,10 @@ use chrono::Datelike;
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
const DASHBOARD_SITE_RATE_WINDOW_SECS: u64 = 60;
const DASHBOARD_ONLINE_USER_WINDOW_SECS: u64 = 300;
const DASHBOARD_ONLINE_USER_AGGREGATION_LIMIT: usize = 100_000;
#[derive(Debug, Clone, Copy)]
struct DashboardDateRange {
start_date: chrono::NaiveDate,
@@ -822,6 +826,22 @@ async fn dashboard_load_user_counts(
Ok((count, count))
}
async fn dashboard_load_online_user_count(
state: &AppState,
now_unix_secs: u64,
) -> Result<u64, GatewayError> {
let rows = state
.aggregate_usage_audits(&UsageAuditAggregationQuery {
created_from_unix_secs: now_unix_secs.saturating_sub(DASHBOARD_ONLINE_USER_WINDOW_SECS),
created_until_unix_secs: now_unix_secs.saturating_add(1),
group_by: UsageAuditAggregationGroupBy::User,
limit: DASHBOARD_ONLINE_USER_AGGREGATION_LIMIT,
exclude_reserved_provider_labels: false,
})
.await?;
Ok(rows.len() as u64)
}
fn dashboard_cache_savings_usd(summary: &StoredUsageCostSavingsSummary) -> f64 {
let estimated_full_cost =
if summary.estimated_full_cost_usd <= 0.0 && summary.cache_read_cost_usd > 0.0 {
@@ -966,6 +986,30 @@ pub(super) async fn handle_dashboard_stats_get(
});
if is_admin {
let now_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
let site_rate_summary = match dashboard_summary_for_unix_range_raw(
state,
now_unix_secs.saturating_sub(DASHBOARD_SITE_RATE_WINDOW_SECS),
now_unix_secs.saturating_add(1),
None,
"dashboard realtime site stats lookup failed",
)
.await
{
Ok(value) => value,
Err(response) => return response,
};
let site_rate_totals = dashboard_usage_totals_from_summary(&site_rate_summary);
let online_users = match dashboard_load_online_user_count(state, now_unix_secs).await {
Ok(value) => value,
Err(err) => {
return build_auth_error_response(
http::StatusCode::INTERNAL_SERVER_ERROR,
format!("dashboard online user stats lookup failed: {err:?}"),
false,
);
}
};
let (total_users, active_users) =
match dashboard_load_user_counts(state, summary_range).await {
Ok(value) => value,
@@ -1010,9 +1054,17 @@ pub(super) async fn handle_dashboard_stats_get(
};
let stats = json!([
{
"name": "今日请求",
"value": dashboard_format_integer(today_totals.requests),
"subValue": format!("成功率 {}", dashboard_format_percentage(success_rate)),
"name": "今日请求 / 费用",
"value": format!(
"{} / {}",
dashboard_format_integer(today_totals.requests),
dashboard_format_usd(today_totals.total_cost_usd)
),
"subValue": format!(
"成功率 {} / 节省 {}",
dashboard_format_percentage(success_rate),
dashboard_format_usd(today_cost_savings.max(0.0))
),
"icon": "Activity",
},
{
@@ -1022,15 +1074,26 @@ pub(super) async fn handle_dashboard_stats_get(
"icon": "Zap",
},
{
"name": "今日费用",
"value": dashboard_format_usd(today_totals.total_cost_usd),
"subValue": format!("节省 {}", dashboard_format_usd(today_cost_savings.max(0.0))),
"icon": "DollarSign",
"name": "全站 RPM / TPM",
"value": format!(
"{} / {}",
dashboard_format_integer(site_rate_totals.requests),
dashboard_format_token_compact(site_rate_totals.total_tokens)
),
"subValue": "最近 60 秒",
"icon": "Activity",
},
{
"name": "活跃用户",
"value": dashboard_format_integer(active_users),
"subValue": format!("总用户 {}", dashboard_format_integer(total_users)),
"name": "在线 / 启用用户",
"value": format!(
"{} / {}",
dashboard_format_integer(online_users),
dashboard_format_integer(active_users)
),
"subValue": format!(
"最近 5 分钟 / 总用户 {}",
dashboard_format_integer(total_users)
),
"icon": "Users",
}
]);
@@ -1060,6 +1123,7 @@ pub(super) async fn handle_dashboard_stats_get(
"users": {
"total": total_users,
"active": active_users,
"online": online_users,
},
"token_breakdown": token_breakdown,
});
@@ -965,6 +965,9 @@ pub(super) async fn handle_users_me_usage_get(
created_until_unix_secs,
user_id: Some(auth.user.id.clone()),
provider_name: None,
model: None,
api_format: None,
exclude_status_codes: Vec::new(),
group_by: UsageBreakdownGroupBy::Model,
})
.await
@@ -985,6 +988,9 @@ pub(super) async fn handle_users_me_usage_get(
created_until_unix_secs,
user_id: Some(auth.user.id.clone()),
provider_name: None,
model: None,
api_format: None,
exclude_status_codes: Vec::new(),
group_by: UsageBreakdownGroupBy::Provider,
})
.await
@@ -1005,6 +1011,9 @@ pub(super) async fn handle_users_me_usage_get(
created_until_unix_secs,
user_id: Some(auth.user.id.clone()),
provider_name: None,
model: None,
api_format: None,
exclude_status_codes: Vec::new(),
group_by: UsageBreakdownGroupBy::ApiFormat,
})
.await
@@ -1045,6 +1054,7 @@ pub(super) async fn handle_users_me_usage_get(
client_family: None,
exclude_unknown_model_or_provider: false,
statuses: None,
exclude_status_codes: Vec::new(),
is_stream: None,
error_only: false,
keywords,
@@ -1100,6 +1110,7 @@ pub(super) async fn handle_users_me_usage_get(
client_family: None,
exclude_unknown_model_or_provider: false,
statuses: None,
exclude_status_codes: Vec::new(),
is_stream: None,
error_only: false,
limit: None,
@@ -1128,6 +1139,7 @@ pub(super) async fn handle_users_me_usage_get(
client_family: None,
exclude_unknown_model_or_provider: false,
statuses: None,
exclude_status_codes: Vec::new(),
is_stream: None,
error_only: false,
limit: Some(limit),
@@ -1266,6 +1278,7 @@ pub(super) async fn handle_users_me_usage_active_get(
client_family: None,
exclude_unknown_model_or_provider: false,
statuses: Some(vec!["pending".to_string(), "streaming".to_string()]),
exclude_status_codes: Vec::new(),
is_stream: None,
error_only: false,
limit: Some(50),
@@ -800,7 +800,7 @@ async fn gateway_handles_admin_health_status_locally_with_trusted_admin_principa
.as_array()
.expect("timeline should be an array")
.len(),
100
60
);
assert!(formats[0]["time_range_start"].is_string());
assert!(formats[0]["time_range_end"].is_string());
@@ -1287,7 +1287,7 @@ async fn gateway_handles_public_health_api_formats_without_proxying_upstream() {
assert_eq!(formats[0]["total_attempts"], 1);
assert_eq!(formats[0]["success_rate"], 1.0);
assert_eq!(formats[0]["events"].as_array().map(Vec::len), Some(1));
assert_eq!(formats[0]["timeline"].as_array().map(Vec::len), Some(100));
assert_eq!(formats[0]["timeline"].as_array().map(Vec::len), Some(60));
assert_eq!(formats[1]["api_format"], "openai:chat");
assert_eq!(formats[1]["api_path"], "/v1/chat/completions");
assert_eq!(formats[1]["total_attempts"], 3);
@@ -1296,7 +1296,7 @@ async fn gateway_handles_public_health_api_formats_without_proxying_upstream() {
assert_eq!(formats[1]["skipped_count"], 1);
assert_eq!(formats[1]["success_rate"], 0.5);
assert_eq!(formats[1]["events"].as_array().map(Vec::len), Some(3));
assert_eq!(formats[1]["timeline"].as_array().map(Vec::len), Some(100));
assert_eq!(formats[1]["timeline"].as_array().map(Vec::len), Some(60));
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
gateway_handle.abort();
@@ -5389,12 +5389,12 @@ async fn gateway_handles_users_me_endpoint_status_locally_without_proxying_upstr
assert_eq!(items[0]["api_format"], "claude:messages");
assert_eq!(items[0]["display_name"], "Claude Messages");
assert_eq!(items[0]["health_score"], 1.0);
assert_eq!(items[0]["timeline"].as_array().map(Vec::len), Some(100));
assert_eq!(items[0]["timeline"].as_array().map(Vec::len), Some(60));
assert!(items[0].get("total_endpoints").is_none());
assert_eq!(items[1]["api_format"], "openai:chat");
assert_eq!(items[1]["display_name"], "OpenAI Chat");
assert_eq!(items[1]["health_score"], 0.5);
assert_eq!(items[1]["timeline"].as_array().map(Vec::len), Some(100));
assert_eq!(items[1]["timeline"].as_array().map(Vec::len), Some(60));
assert!(items[1].get("total_keys").is_none());
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
@@ -649,11 +649,24 @@ async fn gateway_handles_admin_dashboard_stats_locally_without_proxying_upstream
assert_eq!(payload["today"]["tokens"], 17_450);
assert_eq!(payload["today"]["cost"], json!(2.5));
assert_eq!(payload["cost_stats"]["cost_savings"], json!(0.025));
assert_eq!(payload["stats"][2]["subValue"], json!("节省 $0.01"));
assert_eq!(payload["stats"][0]["value"], json!("2"));
assert_eq!(payload["stats"][1]["value"], json!("17.4K"));
let stats = payload["stats"].as_array().expect("stats should be array");
assert_eq!(stats.len(), 4);
let today_request_stats = stats
.iter()
.find(|item| item["name"] == json!("今日请求 / 费用"))
.expect("today request stats card should exist");
assert_eq!(today_request_stats["value"], json!("2 / $2.50"));
assert_eq!(
payload["stats"][1]["subValue"],
today_request_stats["subValue"],
json!("成功率 100.0% / 节省 $0.01")
);
let today_token_stats = stats
.iter()
.find(|item| item["name"] == json!("今日 Token"))
.expect("today token stats card should exist");
assert_eq!(today_token_stats["value"], json!("17.4K"));
assert_eq!(
today_token_stats["subValue"],
json!("输入 12.1K / 输出 3.1K · 写缓存 1.25K / 读缓存 1K")
);
assert_eq!(payload["users"]["total"], 2);
@@ -733,6 +733,7 @@ pub struct UsageAuditListQuery {
pub client_family: Option<String>,
pub exclude_unknown_model_or_provider: bool,
pub statuses: Option<Vec<String>>,
pub exclude_status_codes: Vec<u16>,
pub is_stream: Option<bool>,
pub error_only: bool,
pub limit: Option<usize>,
@@ -751,6 +752,7 @@ pub struct UsageAuditKeywordSearchQuery {
pub client_family: Option<String>,
pub exclude_unknown_model_or_provider: bool,
pub statuses: Option<Vec<String>>,
pub exclude_status_codes: Vec<u16>,
pub is_stream: Option<bool>,
pub error_only: bool,
pub keywords: Vec<String>,
@@ -990,6 +992,9 @@ pub struct UsageBreakdownSummaryQuery {
pub created_until_unix_secs: u64,
pub user_id: Option<String>,
pub provider_name: Option<String>,
pub model: Option<String>,
pub api_format: Option<String>,
pub exclude_status_codes: Vec<u16>,
pub group_by: UsageBreakdownGroupBy,
}
@@ -297,6 +297,12 @@ fn usage_matches_list_query(item: &StoredRequestUsageAudit, query: &UsageAuditLi
return false;
}
}
if item
.status_code
.is_some_and(|status_code| query.exclude_status_codes.contains(&status_code))
{
return false;
}
if let Some(is_stream) = query.is_stream {
if item.is_stream != is_stream {
return false;
@@ -372,6 +378,12 @@ fn usage_matches_keyword_search_query(
return false;
}
}
if item
.status_code
.is_some_and(|status_code| query.exclude_status_codes.contains(&status_code))
{
return false;
}
if let Some(is_stream) = query.is_stream {
if item.is_stream != is_stream {
return false;
@@ -589,6 +601,22 @@ fn usage_matches_breakdown_summary_query(
return false;
}
}
if let Some(model) = query.model.as_deref() {
if item.model != model {
return false;
}
}
if let Some(api_format) = query.api_format.as_deref() {
if item.api_format.as_deref() != Some(api_format) {
return false;
}
}
if item
.status_code
.is_some_and(|status_code| query.exclude_status_codes.contains(&status_code))
{
return false;
}
match query.group_by {
UsageBreakdownGroupBy::Model | UsageBreakdownGroupBy::Provider => true,
UsageBreakdownGroupBy::ApiFormat => item.api_format.is_some(),
@@ -86,6 +86,24 @@ fn dashboard_utc_to_unix_secs(value: DateTime<Utc>) -> u64 {
value.timestamp().max(0) as u64
}
fn push_postgres_usage_excluded_status_codes(
builder: &mut QueryBuilder<'_, Postgres>,
has_where: &mut bool,
status_codes: &[u16],
) {
if status_codes.is_empty() {
return;
}
builder.push(if *has_where { " AND " } else { " WHERE " });
*has_where = true;
builder.push("(\"usage\".status_code IS NULL OR \"usage\".status_code NOT IN (");
let mut separated = builder.separated(", ");
for status_code in status_codes {
separated.push_bind(i32::from(*status_code));
}
separated.push_unseparated("))");
}
fn dashboard_utc_midnight(value: DateTime<Utc>) -> DateTime<Utc> {
DateTime::<Utc>::from_naive_utc_and_offset(
value
@@ -2631,6 +2649,11 @@ ORDER BY request_count DESC, "usage".provider_name ASC
separated.push_unseparated(")");
}
}
push_postgres_usage_excluded_status_codes(
&mut builder,
&mut has_where,
&query.exclude_status_codes,
);
if let Some(is_stream) = query.is_stream {
builder.push(if has_where { " AND " } else { " WHERE " });
has_where = true;
@@ -2738,6 +2761,11 @@ OR (\"usage\".error_message IS NOT NULL AND BTRIM(\"usage\".error_message) <> ''
separated.push_unseparated(")");
}
}
push_postgres_usage_excluded_status_codes(
&mut builder,
&mut has_where,
&query.exclude_status_codes,
);
if let Some(is_stream) = query.is_stream {
builder.push(if has_where { " AND " } else { " WHERE " });
has_where = true;
@@ -2926,6 +2954,11 @@ OR (\"usage\".error_message IS NOT NULL AND BTRIM(\"usage\".error_message) <> ''
separated.push_unseparated(")");
}
}
push_postgres_usage_excluded_status_codes(
&mut builder,
&mut has_where,
&query.exclude_status_codes,
);
if let Some(is_stream) = query.is_stream {
builder.push(if has_where { " AND " } else { " WHERE " });
has_where = true;
@@ -3022,6 +3055,11 @@ OR (\"usage\".error_message IS NOT NULL AND BTRIM(\"usage\".error_message) <> ''
separated.push_unseparated(")");
}
}
push_postgres_usage_excluded_status_codes(
&mut builder,
&mut has_where,
&query.exclude_status_codes,
);
if let Some(is_stream) = query.is_stream {
builder.push(if has_where { " AND " } else { " WHERE " });
has_where = true;
@@ -4897,6 +4935,23 @@ WITH filtered_usage AS (
.push("\"usage\".provider_name = ")
.push_bind(provider_name.to_string());
}
if let Some(model) = query.model.as_deref() {
builder.push(if has_where { " AND " } else { " WHERE " });
builder
.push("\"usage\".model = ")
.push_bind(model.to_string());
}
if let Some(api_format) = query.api_format.as_deref() {
builder.push(if has_where { " AND " } else { " WHERE " });
builder
.push("\"usage\".api_format = ")
.push_bind(api_format.to_string());
}
push_postgres_usage_excluded_status_codes(
&mut builder,
&mut has_where,
&query.exclude_status_codes,
);
builder.push(filtered_extra_where);
builder.push(
r#"
@@ -4989,9 +5044,18 @@ ORDER BY request_count DESC, group_key ASC
&self,
query: &UsageBreakdownSummaryQuery,
) -> Result<Vec<StoredUsageBreakdownSummaryRow>, DataLayerError> {
if !query.exclude_status_codes.is_empty() {
return self.summarize_usage_breakdown_raw(query).await;
}
if query.provider_name.is_some() {
return self.summarize_usage_breakdown_raw(query).await;
}
if query.model.is_some() {
return self.summarize_usage_breakdown_raw(query).await;
}
if query.api_format.is_some() {
return self.summarize_usage_breakdown_raw(query).await;
}
let Some(user_id) = query.user_id.as_deref() else {
return self.summarize_usage_breakdown_raw(query).await;
};
@@ -5014,6 +5078,9 @@ ORDER BY request_count DESC, group_key ASC
created_until_unix_secs: dashboard_utc_to_unix_secs(raw_end),
user_id: Some(user_id.to_string()),
provider_name: None,
model: None,
api_format: None,
exclude_status_codes: query.exclude_status_codes.clone(),
group_by: query.group_by,
})
.await?;
@@ -5037,6 +5104,9 @@ ORDER BY request_count DESC, group_key ASC
created_until_unix_secs: dashboard_utc_to_unix_secs(raw_end),
user_id: Some(user_id.to_string()),
provider_name: None,
model: None,
api_format: None,
exclude_status_codes: query.exclude_status_codes.clone(),
group_by: query.group_by,
})
.await?;
@@ -481,6 +481,7 @@ AND LOWER(TRIM(COALESCE(provider_name, ''))) NOT IN ('unknown', 'unknow'))",
separated.push_unseparated(")");
}
}
push_sqlite_usage_excluded_status_codes(builder, has_where, &query.exclude_status_codes);
if let Some(is_stream) = query.is_stream {
push_sqlite_usage_where(builder, has_where);
builder
@@ -497,6 +498,23 @@ OR (error_message IS NOT NULL AND TRIM(error_message) <> ''))",
}
}
fn push_sqlite_usage_excluded_status_codes(
builder: &mut QueryBuilder<'_, Sqlite>,
has_where: &mut bool,
status_codes: &[u16],
) {
if status_codes.is_empty() {
return;
}
push_sqlite_usage_where(builder, has_where);
builder.push("(status_code IS NULL OR status_code NOT IN (");
let mut separated = builder.separated(", ");
for status_code in status_codes {
separated.push_bind(i64::from(*status_code));
}
separated.push_unseparated("))");
}
fn push_sqlite_usage_keyword_filters(
builder: &mut QueryBuilder<'_, Sqlite>,
query: &UsageAuditKeywordSearchQuery,
@@ -514,6 +532,7 @@ fn push_sqlite_usage_keyword_filters(
client_family: query.client_family.clone(),
exclude_unknown_model_or_provider: query.exclude_unknown_model_or_provider,
statuses: query.statuses.clone(),
exclude_status_codes: query.exclude_status_codes.clone(),
is_stream: query.is_stream,
error_only: query.error_only,
limit: None,
@@ -2488,6 +2507,23 @@ FROM "usage"
"provider_name",
query.provider_name.as_deref(),
);
push_sqlite_usage_optional_text_filter(
&mut builder,
&mut has_where,
"model",
query.model.as_deref(),
);
push_sqlite_usage_optional_text_filter(
&mut builder,
&mut has_where,
"api_format",
query.api_format.as_deref(),
);
push_sqlite_usage_excluded_status_codes(
&mut builder,
&mut has_where,
&query.exclude_status_codes,
);
if matches!(query.group_by, UsageBreakdownGroupBy::ApiFormat) {
push_sqlite_usage_where(&mut builder, &mut has_where);
builder.push("api_format IS NOT NULL");
+1
View File
@@ -57,6 +57,7 @@ export interface CacheStats {
export interface UserStats {
total: number
active: number
online?: number
}
// Token 详细分类
+29 -1
View File
@@ -5,7 +5,9 @@ import type {
EndpointStatusMonitorResponse,
PublicEndpointStatusMonitorResponse,
ModelStatusMonitorResponse,
ProviderStatusMonitorResponse
ProviderStatusMonitorResponse,
HealthRelatedMonitorResponse,
HealthMonitorRelatedDimension
} from './types'
/**
@@ -136,3 +138,29 @@ export async function getProviderStatusMonitor(params?: {
})
return response.data
}
export async function getHealthRelatedMonitor(params: {
dimension: HealthMonitorRelatedDimension
value: string
lookback_hours?: number
related_limit?: number
per_item_limit?: number
}): Promise<HealthRelatedMonitorResponse> {
const response = await client.get('/api/admin/endpoints/health/related', {
params
})
return response.data
}
export async function getPublicHealthRelatedMonitor(params: {
dimension: Exclude<HealthMonitorRelatedDimension, 'provider'>
value: string
lookback_hours?: number
related_limit?: number
per_item_limit?: number
}): Promise<HealthRelatedMonitorResponse> {
const response = await client.get('/api/public/health/related', {
params
})
return response.data
}
@@ -563,6 +563,20 @@ export interface EndpointHealthEvent {
error_message?: string | null
}
export interface HealthTimelineDetail {
segment_index?: number
status?: string
time_range_start?: string | null
time_range_end?: string | null
total_attempts?: number | null
success_count?: number | null
failed_count?: number | null
success_rate?: number | null
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
}
export interface EndpointStatusMonitor {
api_format: string
total_attempts: number
@@ -570,11 +584,15 @@ export interface EndpointStatusMonitor {
failed_count: number
skipped_count: number
success_rate: number
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
provider_count: number
key_count: number
last_event_at?: string | null
events: EndpointHealthEvent[]
timeline?: string[]
timeline_details?: HealthTimelineDetail[]
time_range_start?: string | null
time_range_end?: string | null
}
@@ -602,9 +620,13 @@ export interface PublicEndpointStatusMonitor {
failed_count: number
skipped_count: number
success_rate: number
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
last_event_at?: string | null
events: PublicHealthEvent[]
timeline?: string[]
timeline_details?: HealthTimelineDetail[]
time_range_start?: string | null
time_range_end?: string | null
}
@@ -632,10 +654,12 @@ export interface ModelStatusMonitor {
success_rate: number
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
provider_count?: number
last_event_at?: string | null
events: ModelHealthEvent[]
timeline?: string[]
timeline_details?: HealthTimelineDetail[]
time_range_start?: string | null
time_range_end?: string | null
}
@@ -656,9 +680,11 @@ export interface ProviderStatusMonitor {
success_rate: number
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
model_count: number
last_event_at?: string | null
timeline?: string[]
timeline_details?: HealthTimelineDetail[]
time_range_start?: string | null
time_range_end?: string | null
models: ModelStatusMonitor[]
@@ -669,6 +695,36 @@ export interface ProviderStatusMonitorResponse {
providers: ProviderStatusMonitor[]
}
export type HealthMonitorRelatedDimension = 'endpoint' | 'model' | 'provider'
export interface HealthRelatedMonitor {
kind: HealthMonitorRelatedDimension
key: string
display_name: string
meta_text?: string | null
total_attempts: number
success_count: number
failed_count: number
success_rate: number
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
last_event_at?: string | null
timeline?: string[]
timeline_details?: HealthTimelineDetail[]
time_range_start?: string | null
time_range_end?: string | null
}
export interface HealthRelatedMonitorResponse {
generated_at: string
dimension: HealthMonitorRelatedDimension
value: string
related_endpoints: HealthRelatedMonitor[]
related_models: HealthRelatedMonitor[]
related_providers: HealthRelatedMonitor[]
}
export type ProviderType = 'custom' | 'claude_code' | 'codex' | 'chatgpt_web' | 'gemini_cli' | 'antigravity' | 'kiro' | 'grok' | 'windsurf' | 'vertex_ai'
export interface ClaudeCodeAdvancedConfig {
@@ -1,6 +1,19 @@
<template>
<div class="w-full space-y-1">
<!-- 时间线 -->
<HealthStatusTimeline
v-if="hasStatusTimeline"
:timeline="monitor?.timeline"
:timeline-details="monitor?.timeline_details"
:time-range-start="monitor?.time_range_start"
:time-range-end="monitor?.time_range_end"
:lookback-hours="lookbackHours"
:fallback-segments="segmentCount ?? GRID_COUNT"
entity-label="端点"
:entity-name="monitor?.api_format"
/>
<div
v-else
class="w-full space-y-1"
>
<div class="flex items-center gap-px h-6 w-full">
<TooltipProvider
v-for="(segment, index) in segments"
@@ -9,8 +22,10 @@
>
<Tooltip>
<TooltipTrigger as-child>
<div
class="flex-1 h-full rounded-sm transition-all duration-150 cursor-pointer hover:scale-y-110 hover:brightness-110"
<button
type="button"
:title="segment.tooltip"
class="h-full flex-1 cursor-pointer rounded-sm border-0 p-0 transition-all duration-150 hover:scale-y-110 hover:brightness-110 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
:class="segment.color"
/>
</TooltipTrigger>
@@ -26,7 +41,6 @@
</Tooltip>
</TooltipProvider>
</div>
<!-- 时间标签 -->
<div class="flex items-center justify-between text-[10px] text-muted-foreground">
<span>{{ earliestTime }}</span>
<span>{{ latestTime }}</span>
@@ -38,6 +52,8 @@
import { computed } from 'vue'
import type { EndpointStatusMonitor, EndpointHealthEvent, PublicEndpointStatusMonitor, PublicHealthEvent } from '@/api/endpoints'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import HealthStatusTimeline from './HealthStatusTimeline.vue'
import { formatTimestamp, formatTimelineTooltip } from './health-monitor-utils'
//
// - EndpointStatusMonitor: provider_count, key_count
@@ -49,40 +65,34 @@ const props = defineProps<{
}>()
//
const GRID_COUNT = 100
const GRID_COUNT = 60
const hasStatusTimeline = computed(() =>
Array.isArray(props.monitor?.timeline) && (props.monitor?.timeline?.length ?? 0) > 0
)
const segments = computed(() => {
const gridCount = props.segmentCount ?? GRID_COUNT
const lookbackHours = props.lookbackHours ?? 6
const usageTimeline = Array.isArray(props.monitor?.timeline)
? props.monitor?.timeline ?? []
: []
if (usageTimeline.length > 0) {
return buildUsageTimelineSegments(
usageTimeline,
props.monitor?.time_range_start ?? null,
props.monitor?.time_range_end ?? null,
lookbackHours
)
}
const events = props.monitor?.events ?? []
//
if (events.length === 0) {
return Array.from({ length: gridCount }, () => ({
color: 'bg-gray-300 dark:bg-gray-600',
tooltip: '暂无请求记录'
}))
}
// 使 UTC
const nowUtc = Date.now()
const startTimeUtc = nowUtc - lookbackHours * 60 * 60 * 1000
const timeRange = lookbackHours * 60 * 60 * 1000
const timePerGrid = timeRange / gridCount
//
if (events.length === 0) {
return Array.from({ length: gridCount }, (_, index) => {
const cellStartTime = new Date(startTimeUtc + index * timePerGrid)
const cellEndTime = new Date(startTimeUtc + (index + 1) * timePerGrid)
return {
color: 'bg-gray-300 dark:bg-gray-600',
tooltip: buildSegmentTooltip('unknown', cellStartTime, cellEndTime, [])
}
})
}
// 使 UTC
const gridEvents: Array<Array<EndpointHealthEvent | PublicHealthEvent>> = Array.from({ length: gridCount }, () => [])
for (const event of events) {
@@ -103,7 +113,7 @@ const segments = computed(() => {
if (cellEvents.length === 0) {
result.push({
color: 'bg-gray-300 dark:bg-gray-600',
tooltip: `${formatTimestamp(cellStartTime.toISOString())} - ${formatTimestamp(cellEndTime.toISOString())}\n暂无请求记录`
tooltip: buildSegmentTooltip('unknown', cellStartTime, cellEndTime, [])
})
continue
}
@@ -111,7 +121,12 @@ const segments = computed(() => {
if (cellEvents.length === 1) {
result.push({
color: getStatusColor(cellEvents[0].status),
tooltip: buildTooltip(cellEvents[0])
tooltip: buildSegmentTooltip(
getTimelineStatusFromEvents(cellEvents),
cellStartTime,
cellEndTime,
cellEvents
)
})
continue
}
@@ -134,11 +149,15 @@ const segments = computed(() => {
color = 'bg-gray-300 dark:bg-gray-600'
}
const firstTime = formatTimestamp(cellEvents[0]?.timestamp)
const lastTime = formatTimestamp(cellEvents[cellEvents.length - 1]?.timestamp)
const tooltip = `${firstTime} - ${lastTime}\n共 ${total} 次请求\n成功: ${successCount}, 失败: ${failedCount}, 跳过: ${skippedCount}`
result.push({ color, tooltip })
result.push({
color,
tooltip: buildSegmentTooltip(
getTimelineStatusFromEvents(cellEvents),
cellStartTime,
cellEndTime,
cellEvents
)
})
}
return result
@@ -159,42 +178,6 @@ function getStatusColor(status: string) {
}
}
function buildTooltip(event: EndpointHealthEvent | PublicHealthEvent) {
const time = formatTimestamp(event.timestamp)
const statusText = getStatusText(event.status)
const latency = event.latency_ms ? `${event.latency_ms}ms` : ''
const code = event.status_code ? `${event.status_code}` : ''
const error = event.error_type ? `${event.error_type}` : ''
return `${time} ${statusText}${latency}${code}${error}`
}
function getStatusText(status: string) {
switch (status) {
case 'success':
return '成功'
case 'failed':
return '失败'
case 'skipped':
return '跳过'
case 'started':
return '执行中'
default:
return '未知'
}
}
function formatTimestamp(timestamp?: string | null) {
if (!timestamp) return '未知时间'
const date = new Date(timestamp)
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
//
const earliestTime = computed(() => {
const explicitStart =
@@ -212,55 +195,51 @@ const latestTime = computed(() => {
return formatTimestamp(new Date().toISOString())
})
function buildUsageTimelineSegments(
statuses: string[],
timeRangeStart: string | null,
timeRangeEnd: string | null,
lookbackHours: number
function buildSegmentTooltip(
status: string,
cellStartTime: Date,
cellEndTime: Date,
cellEvents: Array<EndpointHealthEvent | PublicHealthEvent>
) {
const gridCount = statuses.length
const endTime = timeRangeEnd ? new Date(timeRangeEnd).getTime() : Date.now()
const startTime = timeRangeStart
? new Date(timeRangeStart).getTime()
: endTime - lookbackHours * 60 * 60 * 1000
const safeRange = Math.max(endTime - startTime, 1)
const interval = safeRange / gridCount
const successCount = cellEvents.filter(event => event.status === 'success').length
const failedCount = cellEvents.filter(event => event.status === 'failed').length
const completedCount = successCount + failedCount
const latencyValues = cellEvents
.map(event => event.latency_ms)
.filter((value): value is number => typeof value === 'number' && !Number.isNaN(value))
const avgLatencyMs = latencyValues.length > 0
? latencyValues.reduce((sum, value) => sum + value, 0) / latencyValues.length
: null
return statuses.map((status, index) => {
const cellStart = new Date(startTime + index * interval)
const cellEnd = new Date(startTime + (index + 1) * interval)
return {
color: getHealthTimelineColor(status),
tooltip: `${formatTimestamp(cellStart.toISOString())} - ${formatTimestamp(
cellEnd.toISOString()
)}\n状态${getHealthTimelineLabel(status)}`
}
return formatTimelineTooltip({
status,
timeRangeStart: cellStartTime.toISOString(),
timeRangeEnd: cellEndTime.toISOString(),
metrics: {
total_attempts: cellEvents.length,
success_count: successCount,
failed_count: failedCount,
success_rate: completedCount > 0 ? successCount / completedCount : null,
avg_latency_ms: avgLatencyMs,
avg_first_byte_ms: null,
avg_tps: null
},
entityLabel: '端点',
entityName: props.monitor?.api_format
})
}
function getHealthTimelineColor(status: string) {
switch (status) {
case 'healthy':
return 'bg-green-500/80 dark:bg-green-400/90'
case 'warning':
return 'bg-amber-400/80 dark:bg-amber-300/80'
case 'unhealthy':
return 'bg-red-500/80 dark:bg-red-400/90'
default:
return 'bg-gray-300 dark:bg-gray-600'
}
function getTimelineStatusFromEvents(
cellEvents: Array<EndpointHealthEvent | PublicHealthEvent>
) {
const successCount = cellEvents.filter(event => event.status === 'success').length
const failedCount = cellEvents.filter(event => event.status === 'failed').length
const completedCount = successCount + failedCount
if (completedCount === 0) return 'unknown'
const successRate = successCount / completedCount
if (successRate >= 0.95) return 'healthy'
if (successRate >= 0.7) return 'warning'
return 'unhealthy'
}
function getHealthTimelineLabel(status: string) {
switch (status) {
case 'healthy':
return '健康'
case 'warning':
return '警告'
case 'unhealthy':
return '异常'
default:
return '未知'
}
}
</script>
@@ -0,0 +1,65 @@
<template>
<div class="grid w-full grid-cols-2 gap-2 sm:grid-cols-4">
<div
v-for="metric in metrics"
:key="metric.label"
class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2"
>
<div class="text-[11px] leading-tight text-muted-foreground">
{{ metric.label }}
</div>
<div
class="mt-1 text-sm font-semibold tabular-nums"
:class="metric.valueClass"
>
{{ metric.value }}
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import {
formatAvailability,
formatMs,
formatTps,
getAvailabilityClass
} from './health-monitor-utils'
const props = defineProps<{
avgLatencyMs?: number | null
avgFirstByteMs?: number | null
avgTps?: number | null
totalAttempts: number
successRate: number
}>()
const availabilityItem = computed(() => ({
total_attempts: props.totalAttempts,
success_rate: props.successRate
}))
const metrics = computed(() => [
{
label: '平均耗时',
value: formatMs(props.avgLatencyMs),
valueClass: ''
},
{
label: '平均TTFB',
value: formatMs(props.avgFirstByteMs),
valueClass: ''
},
{
label: '平均速度',
value: formatTps(props.avgTps),
valueClass: ''
},
{
label: '可用率',
value: formatAvailability(availabilityItem.value),
valueClass: getAvailabilityClass(availabilityItem.value)
}
])
</script>
@@ -3,52 +3,14 @@
variant="default"
class="overflow-hidden"
>
<!-- 标题和筛选器 -->
<div class="px-6 py-3.5 border-b border-border/60">
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="text-base font-semibold">
{{ title }}
</h3>
<p class="mt-1 text-xs text-muted-foreground">
基于真实请求统计端点可用率请求成功率与健康历史
</p>
</div>
<div class="flex items-center gap-3">
<Label class="text-xs text-muted-foreground">回溯时间</Label>
<Select
v-model="lookbackHours"
>
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">
1 小时
</SelectItem>
<SelectItem value="6">
6 小时
</SelectItem>
<SelectItem value="12">
12 小时
</SelectItem>
<SelectItem value="24">
24 小时
</SelectItem>
<SelectItem value="48">
48 小时
</SelectItem>
</SelectContent>
</Select>
<RefreshButton
:loading="loading"
@click="refreshData"
/>
</div>
</div>
</div>
<HealthMonitorHeader
v-model:lookback-hours="lookbackHours"
:title="title"
description="基于真实请求统计端点可用率、平均耗时、平均TTFB 与平均速度"
:loading="loading"
@refresh="refreshData"
/>
<!-- 内容区域 -->
<div class="p-6">
<div
v-if="loadingMonitors"
@@ -59,7 +21,7 @@
</div>
<div
v-else-if="monitors.length === 0"
v-else-if="visibleMonitors.length === 0"
class="flex flex-col items-center justify-center py-12 text-muted-foreground"
>
<Activity class="w-12 h-12 mb-3 opacity-30" />
@@ -71,59 +33,70 @@
<div
v-else
class="space-y-3"
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
>
<div
v-for="monitor in monitors"
:key="monitor.api_format"
class="border border-border/60 rounded-lg p-4 hover:border-primary/50 transition-colors"
v-for="(monitor, index) in visibleMonitors"
:key="`${monitor.api_format}-${index}`"
class="relative overflow-hidden rounded-xl border border-border/60 bg-card/60 p-4 transition-colors hover:border-primary/50"
>
<!-- 响应式布局窄屏上下两行宽屏左右结构 -->
<div class="flex flex-col sm:flex-row sm:gap-6 sm:items-center">
<!-- 第一行/左侧信息区域 -->
<div class="sm:w-52 flex-shrink-0 space-y-1.5 mb-3 sm:mb-0">
<!-- API 格式标签和成功率 -->
<div class="flex items-center gap-2 flex-wrap">
<Badge
variant="outline"
class="font-mono text-xs whitespace-nowrap"
>
{{ formatApiFormat(monitor.api_format) }}
</Badge>
<Badge
v-if="monitor.total_attempts > 0"
:variant="getSuccessRateVariant(monitor.success_rate)"
class="text-xs whitespace-nowrap"
>
{{ (monitor.success_rate * 100).toFixed(0) }}%
</Badge>
<!-- 提供商信息仅管理员可见- 窄屏时显示在同一行 -->
<span
v-if="showProviderInfo && 'provider_count' in monitor"
class="text-xs text-muted-foreground sm:hidden"
>
{{ monitor.provider_count }} 个提供商 / {{ monitor.key_count }} 个密钥
</span>
</div>
<!-- 提供商信息仅管理员可见- 宽屏时显示在下方 -->
<div
class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent"
/>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-center gap-3">
<div
v-if="showProviderInfo && 'provider_count' in monitor"
class="text-xs text-muted-foreground hidden sm:block"
class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50"
>
{{ monitor.provider_count }} 个提供商 / {{ monitor.key_count }} 个密钥
<Activity class="h-5 w-5 text-muted-foreground" />
</div>
<div class="min-w-0">
<h4 class="truncate text-sm font-semibold">
{{ formatApiFormat(monitor.api_format) }}
</h4>
</div>
</div>
<Badge
:variant="getHealthBadgeVariant(monitor)"
class="shrink-0"
>
{{ getHealthLabel(monitor) }}
</Badge>
</div>
<!-- 第二行/右侧时间线区域 -->
<div class="flex-1 min-w-0 sm:flex sm:justify-end">
<div class="w-full sm:max-w-5xl">
<EndpointHealthTimeline
:monitor="monitor"
:lookback-hours="parseInt(lookbackHours)"
/>
</div>
</div>
<HealthMetricGrid
class="mt-4"
:avg-latency-ms="monitor.avg_latency_ms"
:avg-first-byte-ms="monitor.avg_first_byte_ms"
:avg-tps="monitor.avg_tps"
:total-attempts="monitor.total_attempts"
:success-rate="monitor.success_rate"
/>
<div
class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground"
>
<span>History (60pts)</span>
<span class="truncate normal-case tracking-normal">
{{ getEndpointMetaText(monitor) }}
</span>
</div>
<div class="mt-2">
<EndpointHealthTimeline
:monitor="monitor"
:lookback-hours="parseInt(lookbackHours)"
/>
</div>
<div class="mt-4 flex justify-end">
<Button
variant="outline"
size="sm"
@click="openDetails(monitor)"
>
查看详情
</Button>
</div>
</div>
</div>
@@ -132,23 +105,28 @@
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { computed, ref, onMounted, watch } from 'vue'
import { Activity, Loader2 } from 'lucide-vue-next'
import Card from '@/components/ui/card.vue'
import Badge from '@/components/ui/badge.vue'
import Label from '@/components/ui/label.vue'
import Select from '@/components/ui/select.vue'
import SelectTrigger from '@/components/ui/select-trigger.vue'
import SelectValue from '@/components/ui/select-value.vue'
import SelectContent from '@/components/ui/select-content.vue'
import SelectItem from '@/components/ui/select-item.vue'
import RefreshButton from '@/components/ui/refresh-button.vue'
import Button from '@/components/ui/button.vue'
import HealthMetricGrid from './HealthMetricGrid.vue'
import HealthMonitorHeader from './HealthMonitorHeader.vue'
import EndpointHealthTimeline from './EndpointHealthTimeline.vue'
import { getEndpointStatusMonitor, getPublicEndpointStatusMonitor } from '@/api/endpoints/health'
import type { EndpointStatusMonitor, PublicEndpointStatusMonitor } from '@/api/endpoints/types'
import type { HealthMonitorDetailTarget, HealthMonitorSectionSummary } from './health-monitor-utils'
import { useToast } from '@/composables/useToast'
import { parseApiError } from '@/utils/errorParser'
import { formatApiFormat } from '@/api/endpoints/types/api-format'
import {
formatCompactNumber,
getHealthBadgeVariant,
getHealthLabel,
summarizeHealthMonitorItems
} from './health-monitor-utils'
type EndpointMonitor = EndpointStatusMonitor | PublicEndpointStatusMonitor
const props = withDefaults(defineProps<{
title?: string
@@ -160,12 +138,18 @@ const props = withDefaults(defineProps<{
showProviderInfo: false
})
const emit = defineEmits<{
viewDetails: [target: HealthMonitorDetailTarget]
summaryUpdated: [summary: HealthMonitorSectionSummary]
}>()
const { error: showError } = useToast()
const loading = ref(false)
const loadingMonitors = ref(false)
const monitors = ref<(EndpointStatusMonitor | PublicEndpointStatusMonitor)[]>([])
const monitors = ref<EndpointMonitor[]>([])
const lookbackHours = ref('6')
const visibleMonitors = computed(() => monitors.value.filter(monitor => monitor.total_attempts > 0))
async function loadMonitors() {
loadingMonitors.value = true
@@ -182,6 +166,7 @@ async function loadMonitors() {
const data = await getPublicEndpointStatusMonitor(params)
monitors.value = data.formats || []
}
emitSummary()
} catch (err: unknown) {
showError(parseApiError(err, '加载健康监控数据失败'), '错误')
} finally {
@@ -198,10 +183,60 @@ async function refreshData() {
}
}
function getSuccessRateVariant(rate: number): 'default' | 'secondary' | 'destructive' | 'outline' {
if (rate >= 0.95) return 'default'
if (rate >= 0.8) return 'secondary'
return 'destructive'
function getEndpointMetaText(monitor: EndpointMonitor) {
const attempts = `${formatCompactNumber(monitor.total_attempts)} 次请求`
if (props.showProviderInfo && hasProviderInfo(monitor)) {
return `${monitor.provider_count} 个提供商 / ${monitor.key_count} 个密钥 / ${attempts}`
}
if (hasApiPath(monitor)) {
return `${monitor.api_path} / ${attempts}`
}
return attempts
}
function openDetails(monitor: EndpointMonitor) {
emit('viewDetails', {
lookbackHours: parseInt(lookbackHours.value),
source: {
kind: 'endpoint',
value: monitor.api_format,
title: formatApiFormat(monitor.api_format),
metaText: getEndpointDetailMetaText(monitor),
totalAttempts: monitor.total_attempts,
successCount: monitor.success_count,
failedCount: monitor.failed_count,
successRate: monitor.success_rate,
avgLatencyMs: monitor.avg_latency_ms,
avgFirstByteMs: monitor.avg_first_byte_ms,
avgTps: monitor.avg_tps,
timeline: monitor.timeline || null,
timelineDetails: monitor.timeline_details || null,
timeRangeStart: monitor.time_range_start || null,
timeRangeEnd: monitor.time_range_end || null
}
})
}
function getEndpointDetailMetaText(monitor: EndpointMonitor) {
if (props.showProviderInfo && hasProviderInfo(monitor)) {
return `${monitor.provider_count} 个提供商 / ${monitor.key_count} 个密钥`
}
if (hasApiPath(monitor)) {
return monitor.api_path
}
return null
}
function emitSummary() {
emit('summaryUpdated', summarizeHealthMonitorItems(visibleMonitors.value))
}
function hasProviderInfo(monitor: EndpointMonitor): monitor is EndpointStatusMonitor {
return 'provider_count' in monitor && typeof monitor.provider_count === 'number'
}
function hasApiPath(monitor: EndpointMonitor): monitor is PublicEndpointStatusMonitor {
return 'api_path' in monitor && typeof monitor.api_path === 'string' && monitor.api_path.length > 0
}
watch(lookbackHours, () => {
@@ -0,0 +1,306 @@
<template>
<Dialog
v-model:open="isOpen"
:title="dialogTitle"
:description="dialogDescription"
max-width="6xl"
no-padding
>
<template #header-actions>
<Button
variant="outline"
size="sm"
@click="isOpen = false"
>
关闭
</Button>
</template>
<div class="max-h-[78vh] overflow-y-auto px-4 py-4 sm:px-6">
<div
v-if="sourceMonitor"
class="space-y-6"
>
<section>
<div class="mb-3 flex items-center justify-between gap-3">
<div>
<h4 class="text-sm font-semibold">
当前健康
</h4>
<p class="text-xs text-muted-foreground">
当前卡片在相同回溯窗口内的健康概况
</p>
</div>
</div>
<HealthRelatedMonitorCard
:monitor="sourceMonitor"
:lookback-hours="target?.lookbackHours || 6"
:show-detail-button="false"
/>
</section>
<div
v-if="loading"
class="flex items-center justify-center rounded-xl border border-dashed border-border/60 py-12 text-muted-foreground"
>
<Loader2 class="h-5 w-5 animate-spin" />
<span class="ml-2 text-sm">加载关联健康...</span>
</div>
<div
v-else-if="errorMessage"
class="rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive"
>
<div class="flex items-start gap-2">
<AlertTriangle class="mt-0.5 h-4 w-4 flex-shrink-0" />
<div class="min-w-0">
<p class="font-medium">关联健康加载失败</p>
<p class="mt-1 text-xs">{{ errorMessage }}</p>
</div>
</div>
<Button
class="mt-3"
variant="outline"
size="sm"
@click="loadRelated"
>
重试
</Button>
</div>
<template v-else>
<section
v-for="section in relatedSections"
:key="section.key"
class="space-y-3"
>
<div>
<h4 class="text-sm font-semibold">
{{ section.title }}
</h4>
<p class="text-xs text-muted-foreground">
{{ section.description }}
</p>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<HealthRelatedMonitorCard
v-for="monitor in section.items"
:key="`${monitor.kind}-${monitor.key}`"
:monitor="monitor"
:lookback-hours="target?.lookbackHours || 6"
:generated-at="related?.generated_at || null"
@view-details="openRelatedDetails"
/>
</div>
</section>
<div
v-if="relatedSections.length === 0"
class="rounded-xl border border-dashed border-border/60 py-10 text-center text-sm text-muted-foreground"
>
当前时间范围内暂无关联健康数据
</div>
</template>
</div>
</div>
</Dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { AlertTriangle, Loader2 } from 'lucide-vue-next'
import Dialog from '@/components/ui/dialog/Dialog.vue'
import Button from '@/components/ui/button.vue'
import {
getHealthRelatedMonitor,
getPublicHealthRelatedMonitor
} from '@/api/endpoints/health'
import type {
HealthRelatedMonitor,
HealthRelatedMonitorResponse
} from '@/api/endpoints/types'
import { useToast } from '@/composables/useToast'
import { parseApiError } from '@/utils/errorParser'
import HealthRelatedMonitorCard from './HealthRelatedMonitorCard.vue'
import type {
HealthMonitorDetailSource,
HealthMonitorDetailTarget
} from './health-monitor-utils'
const props = defineProps<{
open: boolean
target: HealthMonitorDetailTarget | null
isAdmin: boolean
}>()
const emit = defineEmits<{
'update:open': [value: boolean]
viewDetails: [target: HealthMonitorDetailTarget]
}>()
const { error: showError } = useToast()
const related = ref<HealthRelatedMonitorResponse | null>(null)
const loading = ref(false)
const errorMessage = ref<string | null>(null)
let requestSeq = 0
const isOpen = computed({
get: () => props.open,
set: value => emit('update:open', value)
})
const dialogTitle = computed(() => {
if (!props.target) return '健康详情'
return `${props.target.source.title} 详情`
})
const dialogDescription = computed(() => {
if (!props.target) return '查看关联健康维度'
const dimensions = props.isAdmin ? '关联端点、模型与提供商健康' : '关联端点与模型健康'
return `${props.target.lookbackHours} 小时内的${dimensions}`
})
const sourceMonitor = computed<HealthRelatedMonitor | null>(() => {
const source = props.target?.source
if (!source) return null
return {
kind: source.kind,
key: source.value,
display_name: source.title,
meta_text: source.metaText || null,
total_attempts: source.totalAttempts,
success_count: source.successCount,
failed_count: source.failedCount,
success_rate: source.successRate,
avg_latency_ms: source.avgLatencyMs,
avg_first_byte_ms: source.avgFirstByteMs,
avg_tps: source.avgTps,
timeline: source.timeline || undefined,
timeline_details: source.timelineDetails || undefined,
time_range_start: source.timeRangeStart || null,
time_range_end: source.timeRangeEnd || null
}
})
const relatedSections = computed(() => {
const data = related.value
const targetKind = props.target?.source.kind
if (!data || !targetKind) return []
const sectionMap = {
endpoints: {
key: 'endpoints',
title: '关联端点健康',
description: '当前维度下实际请求涉及的端点健康',
items: data.related_endpoints || []
},
models: {
key: 'models',
title: '关联模型健康',
description: '当前维度下实际请求涉及的模型健康',
items: data.related_models || []
},
providers: {
key: 'providers',
title: '关联提供商健康',
description: '当前维度下实际请求涉及的提供商健康',
items: props.isAdmin ? (data.related_providers || []) : []
}
}
const orderByKind = {
endpoint: ['providers', 'models'],
provider: ['endpoints', 'models'],
model: ['providers', 'endpoints']
} as const
return orderByKind[targetKind]
.map(key => sectionMap[key])
.filter(section => section.items.length > 0)
})
async function loadRelated() {
const target = props.target
if (!props.open || !target) return
const seq = ++requestSeq
loading.value = true
errorMessage.value = null
try {
const params = {
dimension: target.source.kind,
value: target.source.value,
lookback_hours: target.lookbackHours,
related_limit: 8,
per_item_limit: 100
}
if (!props.isAdmin && target.source.kind === 'provider') {
throw new Error('公开健康监控不支持 provider 详情')
}
const data = props.isAdmin
? await getHealthRelatedMonitor(params)
: await getPublicHealthRelatedMonitor({
...params,
dimension: target.source.kind
})
if (seq === requestSeq) {
related.value = data
}
} catch (err: unknown) {
if (seq === requestSeq) {
const message = parseApiError(err, '加载关联健康失败')
errorMessage.value = message
showError(message, '错误')
}
} finally {
if (seq === requestSeq) {
loading.value = false
}
}
}
function openRelatedDetails(monitor: HealthRelatedMonitor) {
if (!props.isAdmin && monitor.kind === 'provider') return
emit('viewDetails', {
lookbackHours: props.target?.lookbackHours || 6,
source: buildSourceFromRelatedMonitor(monitor)
})
}
function buildSourceFromRelatedMonitor(monitor: HealthRelatedMonitor): HealthMonitorDetailSource {
return {
kind: monitor.kind,
value: monitor.key,
title: monitor.display_name || monitor.key,
metaText: buildRelatedMetaText(monitor),
totalAttempts: monitor.total_attempts,
successCount: monitor.success_count,
failedCount: monitor.failed_count,
successRate: monitor.success_rate,
avgLatencyMs: monitor.avg_latency_ms,
avgFirstByteMs: monitor.avg_first_byte_ms,
avgTps: monitor.avg_tps,
timeline: monitor.timeline || null,
timelineDetails: monitor.timeline_details || null,
timeRangeStart: monitor.time_range_start || null,
timeRangeEnd: monitor.time_range_end || null
}
}
function buildRelatedMetaText(monitor: HealthRelatedMonitor) {
return monitor.meta_text || null
}
watch([
() => props.open,
() => props.target?.source.kind,
() => props.target?.source.value,
() => props.target?.lookbackHours,
() => props.isAdmin
], ([open]) => {
if (open) {
loadRelated()
}
}, { immediate: true })
</script>
@@ -0,0 +1,71 @@
<template>
<div class="px-6 py-3.5 border-b border-border/60">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 class="text-base font-semibold">
{{ title }}
</h3>
<p class="mt-1 text-xs text-muted-foreground">
{{ description }}
</p>
</div>
<div class="flex items-center gap-3">
<Label class="text-xs text-muted-foreground">回溯时间</Label>
<Select v-model="selectedLookbackHours">
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">
1 小时
</SelectItem>
<SelectItem value="6">
6 小时
</SelectItem>
<SelectItem value="12">
12 小时
</SelectItem>
<SelectItem value="24">
24 小时
</SelectItem>
<SelectItem value="48">
48 小时
</SelectItem>
</SelectContent>
</Select>
<RefreshButton
:loading="loading"
@click="$emit('refresh')"
/>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import Label from '@/components/ui/label.vue'
import Select from '@/components/ui/select.vue'
import SelectTrigger from '@/components/ui/select-trigger.vue'
import SelectValue from '@/components/ui/select-value.vue'
import SelectContent from '@/components/ui/select-content.vue'
import SelectItem from '@/components/ui/select-item.vue'
import RefreshButton from '@/components/ui/refresh-button.vue'
const props = defineProps<{
title: string
description: string
lookbackHours: string
loading: boolean
}>()
const emit = defineEmits<{
'update:lookbackHours': [value: string]
refresh: []
}>()
const selectedLookbackHours = computed({
get: () => props.lookbackHours,
set: value => emit('update:lookbackHours', value)
})
</script>
@@ -0,0 +1,133 @@
<template>
<div class="relative overflow-hidden rounded-xl border border-border/60 bg-card/60 p-4 transition-colors hover:border-primary/50">
<div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-center gap-3">
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
<component
:is="iconComponent"
class="h-5 w-5 text-muted-foreground"
/>
</div>
<div class="min-w-0">
<h4 class="truncate text-sm font-semibold">
{{ monitor.display_name || monitor.key }}
</h4>
<p
v-if="monitor.meta_text"
class="mt-1 truncate text-xs text-muted-foreground"
>
{{ monitor.meta_text }}
</p>
</div>
</div>
<Badge
:variant="getHealthBadgeVariant(monitor)"
class="shrink-0"
>
{{ getHealthLabel(monitor) }}
</Badge>
</div>
<HealthMetricGrid
class="mt-4"
:avg-latency-ms="monitor.avg_latency_ms"
:avg-first-byte-ms="monitor.avg_first_byte_ms"
:avg-tps="monitor.avg_tps"
:total-attempts="monitor.total_attempts"
:success-rate="monitor.success_rate"
/>
<div class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground">
<span>History (60pts)</span>
<span class="truncate normal-case tracking-normal">
{{ metaText }}
</span>
</div>
<HealthStatusTimeline
class="mt-2"
:timeline="monitor.timeline"
:timeline-details="monitor.timeline_details"
:time-range-start="monitor.time_range_start"
:time-range-end="monitor.time_range_end"
:generated-at="generatedAt"
:lookback-hours="lookbackHours"
:entity-label="entityLabel"
:entity-name="monitor.key"
/>
<div
v-if="showDetailButton"
class="mt-4 flex justify-end"
>
<Button
variant="outline"
size="sm"
@click="$emit('viewDetails', monitor)"
>
查看详情
</Button>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { Activity, Bot, Server } from 'lucide-vue-next'
import Badge from '@/components/ui/badge.vue'
import Button from '@/components/ui/button.vue'
import type { HealthRelatedMonitor } from '@/api/endpoints/types'
import HealthMetricGrid from './HealthMetricGrid.vue'
import HealthStatusTimeline from './HealthStatusTimeline.vue'
import {
formatCompactNumber,
getHealthBadgeVariant,
getHealthLabel
} from './health-monitor-utils'
const props = withDefaults(defineProps<{
monitor: HealthRelatedMonitor
lookbackHours: number
generatedAt?: string | null
showDetailButton?: boolean
}>(), {
generatedAt: null,
showDetailButton: true
})
defineEmits<{
viewDetails: [monitor: HealthRelatedMonitor]
}>()
const iconComponent = computed(() => {
switch (props.monitor.kind) {
case 'model':
return Bot
case 'provider':
return Server
default:
return Activity
}
})
const entityLabel = computed(() => {
switch (props.monitor.kind) {
case 'model':
return '模型'
case 'provider':
return '提供商'
default:
return '端点'
}
})
const metaText = computed(() => {
const attempts = `${formatCompactNumber(props.monitor.total_attempts)} 次请求`
if (props.monitor.meta_text?.includes('次请求')) return props.monitor.meta_text
return props.monitor.meta_text
? `${props.monitor.meta_text} / ${attempts}`
: attempts
})
</script>
@@ -0,0 +1,128 @@
<template>
<div class="w-full space-y-1">
<div class="flex h-6 w-full items-center gap-px">
<TooltipProvider
v-for="(segment, index) in segments"
:key="index"
:delay-duration="100"
>
<Tooltip>
<TooltipTrigger as-child>
<button
type="button"
:title="segment.tooltip"
class="h-full flex-1 cursor-pointer rounded-sm border-0 p-0 transition-all duration-150 hover:scale-y-110 hover:brightness-110 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
:class="getTimelineColor(segment.status)"
/>
</TooltipTrigger>
<TooltipContent
side="top"
:side-offset="8"
class="max-w-xs"
>
<div class="text-xs whitespace-pre-line">
{{ segment.tooltip }}
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<div class="flex items-center justify-between text-[10px] text-muted-foreground">
<span>{{ startLabel }}</span>
<span>{{ endLabel }}</span>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import {
formatTimestamp,
formatTimelineTooltip,
getTimelineColor,
type HealthTimelineTooltipMetrics
} from './health-monitor-utils'
const props = withDefaults(defineProps<{
timeline?: string[] | null
timelineDetails?: HealthTimelineTooltipMetrics[] | null
timeRangeStart?: string | null
timeRangeEnd?: string | null
generatedAt?: string | null
lookbackHours?: number
fallbackSegments?: number
entityLabel?: string
entityName?: string | null
}>(), {
lookbackHours: 6,
fallbackSegments: 60,
entityLabel: '',
entityName: null
})
const statuses = computed(() => {
if (Array.isArray(props.timeline) && props.timeline.length > 0) {
return props.timeline
}
return Array.from({ length: props.fallbackSegments }, () => 'unknown')
})
const startMs = computed(() => {
const explicitStart = props.timeRangeStart
? new Date(props.timeRangeStart).getTime()
: NaN
if (!Number.isNaN(explicitStart)) return explicitStart
return endMs.value - props.lookbackHours * 60 * 60 * 1000
})
const endMs = computed(() => {
const explicitEnd = props.timeRangeEnd
? new Date(props.timeRangeEnd).getTime()
: NaN
if (!Number.isNaN(explicitEnd)) return explicitEnd
const generatedAt = props.generatedAt
? new Date(props.generatedAt).getTime()
: NaN
if (!Number.isNaN(generatedAt)) return generatedAt
return Date.now()
})
const startLabel = computed(() => formatTimestamp(new Date(startMs.value).toISOString()))
const endLabel = computed(() => formatTimestamp(new Date(endMs.value).toISOString()))
const segments = computed(() => {
const segmentStatuses = statuses.value
const safeRange = Math.max(endMs.value - startMs.value, 1)
const interval = safeRange / segmentStatuses.length
return segmentStatuses.map((status, index) => {
const cellStart = new Date(startMs.value + index * interval).toISOString()
const cellEnd = new Date(startMs.value + (index + 1) * interval).toISOString()
const detail = props.timelineDetails?.[index] ?? null
const timeRangeStart = detail?.time_range_start || cellStart
const timeRangeEnd = detail?.time_range_end || cellEnd
return {
status,
tooltip: buildTooltip(status, timeRangeStart, timeRangeEnd, detail)
}
})
})
function buildTooltip(
status: string,
cellStart: string,
cellEnd: string,
detail: HealthTimelineTooltipMetrics | null
) {
return formatTimelineTooltip({
status,
timeRangeStart: cellStart,
timeRangeEnd: cellEnd,
metrics: detail,
entityLabel: props.entityLabel,
entityName: props.entityName
})
}
</script>
@@ -1,49 +1,12 @@
<template>
<Card
variant="default"
class="overflow-hidden"
>
<div class="px-6 py-3.5 border-b border-border/60">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 class="text-base font-semibold">
{{ title }}
</h3>
<p class="mt-1 text-xs text-muted-foreground">
基于真实请求统计模型可用率响应延迟与首包延迟
</p>
</div>
<div class="flex items-center gap-3">
<Label class="text-xs text-muted-foreground">回溯时间</Label>
<Select v-model="lookbackHours">
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">
1 小时
</SelectItem>
<SelectItem value="6">
6 小时
</SelectItem>
<SelectItem value="12">
12 小时
</SelectItem>
<SelectItem value="24">
24 小时
</SelectItem>
<SelectItem value="48">
48 小时
</SelectItem>
</SelectContent>
</Select>
<RefreshButton
:loading="loading"
@click="refreshData"
/>
</div>
</div>
</div>
<Card variant="default" class="overflow-hidden">
<HealthMonitorHeader
v-model:lookback-hours="lookbackHours"
:title="title"
description="基于真实请求统计模型可用率、平均耗时、平均TTFB 与平均速度"
:loading="loading"
@refresh="refreshData"
/>
<div class="p-6">
<div
@@ -60,106 +23,72 @@
>
<Bot class="w-12 h-12 mb-3 opacity-30" />
<p>暂无模型健康监控数据</p>
<p class="text-xs mt-1">
模型尚未产生请求记录
</p>
<p class="text-xs mt-1">模型尚未产生请求记录</p>
</div>
<div
v-else
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
>
<div v-else class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
<div
v-for="monitor in monitors"
:key="monitor.model"
class="relative overflow-hidden rounded-xl border border-border/60 bg-card/60 p-4 transition-colors hover:border-primary/50"
>
<div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
<div
class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent"
/>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-center gap-3">
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
<div
class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50"
>
<Bot class="h-5 w-5 text-muted-foreground" />
</div>
<h4 class="min-w-0 truncate text-sm font-semibold">
{{ monitor.display_name || monitor.model }}
</h4>
</div>
<Badge
:variant="getHealthBadgeVariant(monitor)"
class="shrink-0"
>
<Badge :variant="getHealthBadgeVariant(monitor)" class="shrink-0">
{{ getHealthLabel(monitor) }}
</Badge>
</div>
<div class="mt-4 grid grid-cols-3 gap-2">
<div class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2">
<div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">
<Gauge class="h-3.5 w-3.5" />
延迟
</div>
<div class="mt-1 text-sm font-semibold tabular-nums">
{{ formatMs(monitor.avg_latency_ms) }}
</div>
</div>
<div class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2">
<div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">
<Radio class="h-3.5 w-3.5" />
Ping
</div>
<div class="mt-1 text-sm font-semibold tabular-nums">
{{ formatMs(monitor.avg_first_byte_ms) }}
</div>
</div>
<div class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2">
<div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">
<Activity class="h-3.5 w-3.5" />
可用率
</div>
<div
class="mt-1 text-sm font-semibold tabular-nums"
:class="getSuccessRateClass(monitor.success_rate)"
>
{{ formatPercent(monitor.success_rate) }}
</div>
</div>
</div>
<HealthMetricGrid
class="mt-4"
:avg-latency-ms="monitor.avg_latency_ms"
:avg-first-byte-ms="monitor.avg_first_byte_ms"
:avg-tps="monitor.avg_tps"
:total-attempts="monitor.total_attempts"
:success-rate="monitor.success_rate"
/>
<div class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground">
<div
class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground"
>
<span>History (60pts)</span>
<span class="truncate normal-case tracking-normal">
{{ getModelMetaText(monitor) }}
</span>
</div>
<TooltipProvider :delay-duration="100">
<div class="mt-2 flex h-7 w-full items-center gap-px">
<Tooltip
v-for="(segment, index) in timelineSegments(monitor)"
:key="`${monitor.model}-${index}`"
>
<TooltipTrigger as-child>
<div
class="h-full flex-1 rounded-[2px] transition-all duration-150 hover:scale-y-110 hover:brightness-110"
:class="getTimelineColor(segment)"
/>
</TooltipTrigger>
<TooltipContent
side="top"
:side-offset="8"
class="max-w-xs"
>
<div class="text-xs whitespace-pre-line">
{{ buildTimelineTooltip(monitor, segment, index) }}
</div>
</TooltipContent>
</Tooltip>
</div>
</TooltipProvider>
<HealthStatusTimeline
class="mt-2"
:timeline="monitor.timeline"
:timeline-details="monitor.timeline_details"
:time-range-start="monitor.time_range_start"
:time-range-end="monitor.time_range_end"
:generated-at="generatedAt"
:lookback-hours="parseInt(lookbackHours)"
entity-label="模型"
:entity-name="monitor.model"
/>
<div class="mt-2 flex items-center justify-between text-[10px] text-muted-foreground">
<span>{{ formatTimestamp(monitor.time_range_start) }}</span>
<span>{{ formatTimestamp(monitor.time_range_end || generatedAt) }}</span>
<div class="mt-4 flex justify-end">
<Button
variant="outline"
size="sm"
@click="openDetails(monitor)"
>
查看详情
</Button>
</div>
</div>
</div>
@@ -168,182 +97,136 @@
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Activity, Bot, Gauge, Loader2, Radio } from 'lucide-vue-next'
import Card from '@/components/ui/card.vue'
import Badge from '@/components/ui/badge.vue'
import Label from '@/components/ui/label.vue'
import Select from '@/components/ui/select.vue'
import SelectTrigger from '@/components/ui/select-trigger.vue'
import SelectValue from '@/components/ui/select-value.vue'
import SelectContent from '@/components/ui/select-content.vue'
import SelectItem from '@/components/ui/select-item.vue'
import RefreshButton from '@/components/ui/refresh-button.vue'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { getModelStatusMonitor, getPublicModelStatusMonitor } from '@/api/endpoints/health'
import type { ModelStatusMonitor } from '@/api/endpoints/types'
import { useToast } from '@/composables/useToast'
import { parseApiError } from '@/utils/errorParser'
import { ref, onMounted, watch } from "vue";
import { Bot, Loader2 } from "lucide-vue-next";
import Card from "@/components/ui/card.vue";
import Badge from "@/components/ui/badge.vue";
import Button from "@/components/ui/button.vue";
import HealthMetricGrid from "./HealthMetricGrid.vue";
import HealthMonitorHeader from "./HealthMonitorHeader.vue";
import HealthStatusTimeline from "./HealthStatusTimeline.vue";
import {
getModelStatusMonitor,
getPublicModelStatusMonitor,
} from "@/api/endpoints/health";
import type { ModelStatusMonitor } from "@/api/endpoints/types";
import { useToast } from "@/composables/useToast";
import { parseApiError } from "@/utils/errorParser";
import type {
HealthMonitorDetailTarget,
HealthMonitorSectionSummary,
} from "./health-monitor-utils";
import {
formatCompactNumber,
getHealthBadgeVariant,
getHealthLabel,
summarizeHealthMonitorItems,
} from "./health-monitor-utils";
const props = withDefaults(defineProps<{
title?: string
isAdmin?: boolean
showProviderInfo?: boolean
}>(), {
title: '模型健康监控',
isAdmin: false,
showProviderInfo: false
})
const props = withDefaults(
defineProps<{
title?: string;
isAdmin?: boolean;
showProviderInfo?: boolean;
}>(),
{
title: "模型健康监控",
isAdmin: false,
showProviderInfo: false,
},
);
const { error: showError } = useToast()
const emit = defineEmits<{
viewDetails: [target: HealthMonitorDetailTarget];
summaryUpdated: [summary: HealthMonitorSectionSummary];
}>();
const loading = ref(false)
const loadingMonitors = ref(false)
const monitors = ref<ModelStatusMonitor[]>([])
const generatedAt = ref<string | null>(null)
const lookbackHours = ref('6')
const { error: showError } = useToast();
const loading = ref(false);
const loadingMonitors = ref(false);
const monitors = ref<ModelStatusMonitor[]>([]);
const generatedAt = ref<string | null>(null);
const lookbackHours = ref("6");
async function loadMonitors() {
loadingMonitors.value = true
loadingMonitors.value = true;
try {
const params = {
lookback_hours: parseInt(lookbackHours.value),
model_limit: 12,
per_model_limit: 100
}
per_model_limit: 100,
};
const data = props.isAdmin
? await getModelStatusMonitor(params)
: await getPublicModelStatusMonitor(params)
monitors.value = data.models || []
generatedAt.value = data.generated_at || null
: await getPublicModelStatusMonitor(params);
monitors.value = data.models || [];
generatedAt.value = data.generated_at || null;
emitSummary();
} catch (err: unknown) {
showError(parseApiError(err, '加载模型健康监控数据失败'), '错误')
showError(parseApiError(err, "加载模型健康监控数据失败"), "错误");
} finally {
loadingMonitors.value = false
loadingMonitors.value = false;
}
}
async function refreshData() {
loading.value = true
loading.value = true;
try {
await loadMonitors()
await loadMonitors();
} finally {
loading.value = false
loading.value = false;
}
}
function getHealthLabel(monitor: ModelStatusMonitor) {
if (monitor.total_attempts <= 0) return '未知'
if (monitor.success_rate >= 0.95) return '正常'
if (monitor.success_rate >= 0.8) return '波动'
return '异常'
}
function getHealthBadgeVariant(monitor: ModelStatusMonitor): 'default' | 'secondary' | 'destructive' | 'outline' | 'success' | 'warning' | 'dark' {
if (monitor.total_attempts <= 0) return 'outline'
if (monitor.success_rate >= 0.95) return 'success'
if (monitor.success_rate >= 0.8) return 'warning'
return 'destructive'
}
function getSuccessRateClass(rate: number) {
if (rate >= 0.95) return 'text-green-600 dark:text-green-400'
if (rate >= 0.8) return 'text-amber-600 dark:text-amber-400'
return 'text-red-600 dark:text-red-400'
}
function getModelMetaText(monitor: ModelStatusMonitor) {
const attempts = `${formatCompactNumber(monitor.total_attempts)} 次请求`
if (props.showProviderInfo && typeof monitor.provider_count === 'number') {
return `${monitor.provider_count} 个提供商 / ${attempts}`
const attempts = `${formatCompactNumber(monitor.total_attempts)} 次请求`;
if (props.showProviderInfo && typeof monitor.provider_count === "number") {
return `${monitor.provider_count} 个提供商 / ${attempts}`;
}
return attempts
return attempts;
}
function formatMs(value?: number | null) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
const absValue = Math.abs(value)
if (absValue < 1000) return `${Math.round(value)} ms`
if (absValue < 60_000) return `${formatDurationNumber(value / 1000)} s`
return `${formatDurationNumber(value / 60_000)} min`
function openDetails(monitor: ModelStatusMonitor) {
emit("viewDetails", {
lookbackHours: parseInt(lookbackHours.value),
source: {
kind: "model",
value: monitor.model,
title: monitor.display_name || monitor.model,
metaText: getModelDetailMetaText(monitor),
totalAttempts: monitor.total_attempts,
successCount: monitor.success_count,
failedCount: monitor.failed_count,
successRate: monitor.success_rate,
avgLatencyMs: monitor.avg_latency_ms,
avgFirstByteMs: monitor.avg_first_byte_ms,
avgTps: monitor.avg_tps,
timeline: monitor.timeline || null,
timelineDetails: monitor.timeline_details || null,
timeRangeStart: monitor.time_range_start || null,
timeRangeEnd: monitor.time_range_end || null,
},
});
}
function formatDurationNumber(value: number) {
return new Intl.NumberFormat('zh-CN', {
maximumFractionDigits: Math.abs(value) < 10 ? 2 : 1
}).format(value)
}
function formatPercent(value: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
return `${(value * 100).toFixed(2)}%`
}
function formatCompactNumber(value: number) {
return new Intl.NumberFormat('zh-CN', { notation: 'compact', maximumFractionDigits: 1 }).format(value)
}
function timelineSegments(monitor: ModelStatusMonitor) {
const timeline = Array.isArray(monitor.timeline) ? monitor.timeline : []
if (timeline.length > 0) return timeline
return Array.from({ length: 60 }, () => 'unknown')
}
function getTimelineColor(status: string) {
switch (status) {
case 'healthy':
return 'bg-green-500/85 dark:bg-green-400/90'
case 'warning':
return 'bg-amber-400/85 dark:bg-amber-300/85'
case 'unhealthy':
return 'bg-red-500/85 dark:bg-red-400/90'
default:
return 'bg-gray-300 dark:bg-gray-600'
function getModelDetailMetaText(monitor: ModelStatusMonitor) {
if (props.showProviderInfo && typeof monitor.provider_count === "number") {
return `${monitor.provider_count} 个提供商`;
}
return null;
}
function getTimelineLabel(status: string) {
switch (status) {
case 'healthy':
return '健康'
case 'warning':
return '波动'
case 'unhealthy':
return '异常'
default:
return '无请求'
}
}
function buildTimelineTooltip(monitor: ModelStatusMonitor, status: string, index: number) {
const segmentCount = timelineSegments(monitor).length
const startMs = monitor.time_range_start ? new Date(monitor.time_range_start).getTime() : Date.now() - parseInt(lookbackHours.value) * 60 * 60 * 1000
const endMs = monitor.time_range_end ? new Date(monitor.time_range_end).getTime() : Date.now()
const interval = Math.max(endMs - startMs, 1) / segmentCount
const cellStart = new Date(startMs + index * interval).toISOString()
const cellEnd = new Date(startMs + (index + 1) * interval).toISOString()
return `${formatTimestamp(cellStart)} - ${formatTimestamp(cellEnd)}\n模型:${monitor.model}\n状态:${getTimelineLabel(status)}`
}
function formatTimestamp(timestamp?: string | null) {
if (!timestamp) return '未知时间'
const date = new Date(timestamp)
if (Number.isNaN(date.getTime())) return '未知时间'
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
function emitSummary() {
emit("summaryUpdated", summarizeHealthMonitorItems(monitors.value));
}
watch(lookbackHours, () => {
loadMonitors()
})
loadMonitors();
});
onMounted(() => {
refreshData()
})
refreshData();
});
</script>
@@ -681,10 +681,10 @@
<span>成功 {{ importTask.success }} · 失败 {{ importTask.failed }}</span>
</div>
<p
v-if="importTask.message"
v-if="importTaskMessageText"
class="text-[11px] text-muted-foreground"
>
{{ importTask.message }}
{{ importTaskMessageText }}
</p>
<div
v-if="importTask.error_samples.length > 0"
@@ -926,6 +926,7 @@ const importInputResetKey = ref(0)
const importTask = ref<OAuthBatchImportTaskStatusResponse | null>(null)
let importPollTimer: ReturnType<typeof setTimeout> | null = null
const importPolling = ref(false)
const redundantImportTaskMessagePattern = /^处理中(?:\s+\d+\s*\/\s*\d+)?$/
const windsurfImportMethod = ref<WindsurfImportMethod>('email_password')
const windsurfEmail = ref('')
const windsurfPassword = ref('')
@@ -1036,6 +1037,13 @@ const importButtonText = computed(() => {
return isWindsurfEmailPasswordImport.value ? '登录并导入' : importButtonLabel.value
})
const importTaskMessageText = computed(() => {
const message = importTask.value?.message?.trim()
if (!message) return ''
// message x/y x/y
return redundantImportTaskMessagePattern.test(message) ? '' : message
})
function stopImportPolling() {
if (importPollTimer) {
clearTimeout(importPollTimer)
@@ -3,47 +3,13 @@
variant="default"
class="overflow-hidden"
>
<div class="px-6 py-3.5 border-b border-border/60">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 class="text-base font-semibold">
{{ title }}
</h3>
<p class="mt-1 text-xs text-muted-foreground">
仅展示活跃提供商展开后查看该提供商下的模型健康明细
</p>
</div>
<div class="flex items-center gap-3">
<Label class="text-xs text-muted-foreground">回溯时间</Label>
<Select v-model="lookbackHours">
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">
1 小时
</SelectItem>
<SelectItem value="6">
6 小时
</SelectItem>
<SelectItem value="12">
12 小时
</SelectItem>
<SelectItem value="24">
24 小时
</SelectItem>
<SelectItem value="48">
48 小时
</SelectItem>
</SelectContent>
</Select>
<RefreshButton
:loading="loading"
@click="refreshData"
/>
</div>
</div>
</div>
<HealthMonitorHeader
v-model:lookback-hours="lookbackHours"
:title="title"
description="仅展示活跃提供商,点击详情查看该提供商关联的端点与模型健康"
:loading="loading"
@refresh="refreshData"
/>
<div class="p-6">
<div
@@ -55,209 +21,108 @@
</div>
<div
v-else-if="providers.length === 0"
v-else-if="visibleProviders.length === 0"
class="flex flex-col items-center justify-center py-12 text-muted-foreground"
>
<Server class="w-12 h-12 mb-3 opacity-30" />
<p>暂无活跃提供商健康数据</p>
<p>暂无提供商健康数据</p>
<p class="text-xs mt-1">
当前没有活跃提供商或尚未产生请求记录
当前没有提供商产生请求记录
</p>
</div>
<div
v-else
class="space-y-3"
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
>
<Collapsible
v-for="provider in providers"
<div
v-for="provider in visibleProviders"
:key="provider.provider_id"
v-model:open="expandedProviders[provider.provider_id]"
class="overflow-hidden rounded-xl border border-border/60 bg-card/60"
class="relative overflow-hidden rounded-xl border border-border/60 bg-card/60 p-4 transition-colors hover:border-primary/50"
>
<CollapsibleTrigger as-child>
<button
type="button"
class="flex w-full flex-col gap-4 p-4 text-left transition-colors hover:bg-muted/30 lg:flex-row lg:items-center lg:justify-between"
>
<div class="flex min-w-0 items-start gap-3">
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
<Server class="h-5 w-5 text-muted-foreground" />
</div>
<div class="min-w-0">
<div class="flex min-w-0 flex-wrap items-center gap-2">
<ChevronRight
class="h-4 w-4 text-muted-foreground transition-transform"
:class="{ 'rotate-90': expandedProviders[provider.provider_id] }"
/>
<h4 class="truncate text-sm font-semibold">
{{ provider.provider_name }}
</h4>
<Badge
variant="outline"
class="font-mono text-[11px]"
>
{{ provider.provider_type || 'custom' }}
</Badge>
<Badge :variant="getHealthBadgeVariant(provider)">
{{ getHealthLabel(provider) }}
</Badge>
</div>
<p class="mt-1 text-xs text-muted-foreground">
{{ getProviderMetaText(provider) }}
</p>
</div>
<div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-center gap-3">
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
<Server class="h-5 w-5 text-muted-foreground" />
</div>
<div class="grid w-full grid-cols-3 gap-2 lg:max-w-xl">
<MetricBox
label="延迟"
:value="formatMs(provider.avg_latency_ms)"
/>
<MetricBox
label="Ping"
:value="formatMs(provider.avg_first_byte_ms)"
/>
<MetricBox
label="可用率"
:value="formatPercent(provider.success_rate)"
:value-class="getSuccessRateClass(provider.success_rate)"
/>
</div>
</button>
</CollapsibleTrigger>
<CollapsibleContent class="border-t border-border/50 px-4 pb-4 pt-4">
<div
v-if="provider.models.length === 0"
class="rounded-lg border border-dashed border-border/60 py-8 text-center text-sm text-muted-foreground"
>
该提供商在当前时间范围内暂无模型请求
</div>
<div
v-else
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
>
<div
v-for="model in provider.models"
:key="`${provider.provider_id}-${model.model}`"
class="relative overflow-hidden rounded-xl border border-border/60 bg-card/80 p-4 transition-colors hover:border-primary/50"
>
<div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-center gap-3">
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
<Bot class="h-5 w-5 text-muted-foreground" />
</div>
<h4 class="min-w-0 truncate text-sm font-semibold">
{{ model.display_name || model.model }}
</h4>
</div>
<Badge
:variant="getHealthBadgeVariant(model)"
class="shrink-0"
>
{{ getHealthLabel(model) }}
</Badge>
</div>
<div class="mt-4 grid grid-cols-3 gap-2">
<MetricBox
label="延迟"
:value="formatMs(model.avg_latency_ms)"
/>
<MetricBox
label="Ping"
:value="formatMs(model.avg_first_byte_ms)"
/>
<MetricBox
label="可用率"
:value="formatPercent(model.success_rate)"
:value-class="getSuccessRateClass(model.success_rate)"
/>
</div>
<div class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground">
<span>History (60pts)</span>
<span class="truncate normal-case tracking-normal">
{{ formatCompactNumber(model.total_attempts) }} 次请求
</span>
</div>
<TooltipProvider :delay-duration="100">
<div class="mt-2 flex h-7 w-full items-center gap-px">
<Tooltip
v-for="(segment, index) in timelineSegments(model)"
:key="`${provider.provider_id}-${model.model}-${index}`"
>
<TooltipTrigger as-child>
<div
class="h-full flex-1 rounded-[2px] transition-all duration-150 hover:scale-y-110 hover:brightness-110"
:class="getTimelineColor(segment)"
/>
</TooltipTrigger>
<TooltipContent
side="top"
:side-offset="8"
class="max-w-xs"
>
<div class="text-xs whitespace-pre-line">
{{ buildTimelineTooltip(model, segment, index) }}
</div>
</TooltipContent>
</Tooltip>
</div>
</TooltipProvider>
<div class="mt-2 flex items-center justify-between text-[10px] text-muted-foreground">
<span>{{ formatTimestamp(model.time_range_start) }}</span>
<span>{{ formatTimestamp(model.time_range_end || generatedAt) }}</span>
</div>
<div class="min-w-0">
<h4 class="truncate text-sm font-semibold">
{{ provider.provider_name }}
</h4>
</div>
</div>
</CollapsibleContent>
</Collapsible>
<Badge
:variant="getHealthBadgeVariant(provider)"
class="shrink-0"
>
{{ getHealthLabel(provider) }}
</Badge>
</div>
<HealthMetricGrid
class="mt-4"
:avg-latency-ms="provider.avg_latency_ms"
:avg-first-byte-ms="provider.avg_first_byte_ms"
:avg-tps="provider.avg_tps"
:total-attempts="provider.total_attempts"
:success-rate="provider.success_rate"
/>
<div class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground">
<span>History (60pts)</span>
<span class="truncate normal-case tracking-normal">
{{ getProviderMetaText(provider) }}
</span>
</div>
<HealthStatusTimeline
class="mt-2"
:timeline="provider.timeline"
:timeline-details="provider.timeline_details"
:time-range-start="provider.time_range_start"
:time-range-end="provider.time_range_end"
:generated-at="generatedAt"
:lookback-hours="parseInt(lookbackHours)"
entity-label="提供商"
:entity-name="provider.provider_name"
/>
<div class="mt-4 flex justify-end">
<Button
variant="outline"
size="sm"
@click="openDetails(provider)"
>
查看详情
</Button>
</div>
</div>
</div>
</div>
</Card>
</template>
<script setup lang="ts">
import { defineComponent, h, ref, onMounted, watch } from 'vue'
import { Bot, ChevronRight, Loader2, Server } from 'lucide-vue-next'
import { computed, ref, onMounted, watch } from 'vue'
import { Loader2, Server } from 'lucide-vue-next'
import Card from '@/components/ui/card.vue'
import Badge from '@/components/ui/badge.vue'
import Label from '@/components/ui/label.vue'
import Select from '@/components/ui/select.vue'
import SelectTrigger from '@/components/ui/select-trigger.vue'
import SelectValue from '@/components/ui/select-value.vue'
import SelectContent from '@/components/ui/select-content.vue'
import SelectItem from '@/components/ui/select-item.vue'
import RefreshButton from '@/components/ui/refresh-button.vue'
import Collapsible from '@/components/ui/collapsible.vue'
import CollapsibleTrigger from '@/components/ui/collapsible-trigger.vue'
import CollapsibleContent from '@/components/ui/collapsible-content.vue'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import Button from '@/components/ui/button.vue'
import HealthMetricGrid from './HealthMetricGrid.vue'
import HealthMonitorHeader from './HealthMonitorHeader.vue'
import HealthStatusTimeline from './HealthStatusTimeline.vue'
import { getProviderStatusMonitor } from '@/api/endpoints/health'
import type { ModelStatusMonitor, ProviderStatusMonitor } from '@/api/endpoints/types'
import type { ProviderStatusMonitor } from '@/api/endpoints/types'
import type { HealthMonitorDetailTarget, HealthMonitorSectionSummary } from './health-monitor-utils'
import { useToast } from '@/composables/useToast'
import { parseApiError } from '@/utils/errorParser'
type HealthMonitorItem = Pick<ProviderStatusMonitor | ModelStatusMonitor, 'total_attempts' | 'success_rate'>
const MetricBox = defineComponent({
props: {
label: { type: String, required: true },
value: { type: String, required: true },
valueClass: { type: String, default: '' }
},
setup(props) {
return () => h('div', { class: 'rounded-lg border border-border/40 bg-muted/20 px-3 py-2' }, [
h('div', { class: 'text-[11px] text-muted-foreground' }, props.label),
h('div', { class: ['mt-1 text-sm font-semibold tabular-nums', props.valueClass] }, props.value)
])
}
})
import {
formatCompactNumber,
getHealthBadgeVariant,
getHealthLabel,
summarizeHealthMonitorItems
} from './health-monitor-utils'
const props = withDefaults(defineProps<{
title?: string
@@ -265,6 +130,11 @@ const props = withDefaults(defineProps<{
title: '提供商健康监控'
})
const emit = defineEmits<{
viewDetails: [target: HealthMonitorDetailTarget]
summaryUpdated: [summary: HealthMonitorSectionSummary]
}>()
const { error: showError } = useToast()
const loading = ref(false)
@@ -272,7 +142,7 @@ const loadingMonitors = ref(false)
const providers = ref<ProviderStatusMonitor[]>([])
const generatedAt = ref<string | null>(null)
const lookbackHours = ref('6')
const expandedProviders = ref<Record<string, boolean>>({})
const visibleProviders = computed(() => providers.value.filter(provider => provider.total_attempts > 0))
async function loadMonitors() {
loadingMonitors.value = true
@@ -285,7 +155,7 @@ async function loadMonitors() {
})
providers.value = data.providers || []
generatedAt.value = data.generated_at || null
ensureExpandedProviderState()
emitSummary()
} catch (err: unknown) {
showError(parseApiError(err, '加载提供商健康监控数据失败'), '错误')
} finally {
@@ -302,119 +172,38 @@ async function refreshData() {
}
}
function ensureExpandedProviderState() {
const next = { ...expandedProviders.value }
for (const provider of providers.value) {
if (!(provider.provider_id in next)) {
next[provider.provider_id] = false
}
}
expandedProviders.value = next
}
function getHealthLabel(item: HealthMonitorItem) {
if (item.total_attempts <= 0) return '暂无请求'
if (item.success_rate >= 0.95) return '正常'
if (item.success_rate >= 0.8) return '波动'
return '异常'
}
function getHealthBadgeVariant(item: HealthMonitorItem): 'default' | 'secondary' | 'destructive' | 'outline' | 'success' | 'warning' | 'dark' {
if (item.total_attempts <= 0) return 'outline'
if (item.success_rate >= 0.95) return 'success'
if (item.success_rate >= 0.8) return 'warning'
return 'destructive'
}
function getSuccessRateClass(rate: number) {
if (rate >= 0.95) return 'text-green-600 dark:text-green-400'
if (rate >= 0.8) return 'text-amber-600 dark:text-amber-400'
return 'text-red-600 dark:text-red-400'
}
function getProviderMetaText(provider: ProviderStatusMonitor) {
const attempts = `${formatCompactNumber(provider.total_attempts)} 次请求`
return `${provider.model_count} 个模型 / ${attempts}`
}
function formatMs(value?: number | null) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
const absValue = Math.abs(value)
if (absValue < 1000) return `${Math.round(value)} ms`
if (absValue < 60_000) return `${formatDurationNumber(value / 1000)} s`
return `${formatDurationNumber(value / 60_000)} min`
}
function formatDurationNumber(value: number) {
return new Intl.NumberFormat('zh-CN', {
maximumFractionDigits: Math.abs(value) < 10 ? 2 : 1
}).format(value)
}
function formatPercent(value: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
return `${(value * 100).toFixed(2)}%`
}
function formatCompactNumber(value: number) {
return new Intl.NumberFormat('zh-CN', { notation: 'compact', maximumFractionDigits: 1 }).format(value)
}
function timelineSegments(item: ModelStatusMonitor | ProviderStatusMonitor) {
const timeline = Array.isArray(item.timeline) ? item.timeline : []
if (timeline.length > 0) return timeline
return Array.from({ length: 60 }, () => 'unknown')
}
function getTimelineColor(status: string) {
switch (status) {
case 'healthy':
return 'bg-green-500/85 dark:bg-green-400/90'
case 'warning':
return 'bg-amber-400/85 dark:bg-amber-300/85'
case 'unhealthy':
return 'bg-red-500/85 dark:bg-red-400/90'
default:
return 'bg-gray-300 dark:bg-gray-600'
}
}
function getTimelineLabel(status: string) {
switch (status) {
case 'healthy':
return '健康'
case 'warning':
return '波动'
case 'unhealthy':
return '异常'
default:
return '无请求'
}
}
function buildTimelineTooltip(model: ModelStatusMonitor, status: string, index: number) {
const segmentCount = timelineSegments(model).length
const startMs = model.time_range_start ? new Date(model.time_range_start).getTime() : Date.now() - parseInt(lookbackHours.value) * 60 * 60 * 1000
const endMs = model.time_range_end ? new Date(model.time_range_end).getTime() : Date.now()
const interval = Math.max(endMs - startMs, 1) / segmentCount
const cellStart = new Date(startMs + index * interval).toISOString()
const cellEnd = new Date(startMs + (index + 1) * interval).toISOString()
return `${formatTimestamp(cellStart)} - ${formatTimestamp(cellEnd)}\n模型:${model.model}\n状态:${getTimelineLabel(status)}`
}
function formatTimestamp(timestamp?: string | null) {
if (!timestamp) return '未知时间'
const date = new Date(timestamp)
if (Number.isNaN(date.getTime())) return '未知时间'
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
function openDetails(provider: ProviderStatusMonitor) {
emit('viewDetails', {
lookbackHours: parseInt(lookbackHours.value),
source: {
kind: 'provider',
value: provider.provider_name,
title: provider.provider_name,
metaText: null,
totalAttempts: provider.total_attempts,
successCount: provider.success_count,
failedCount: provider.failed_count,
successRate: provider.success_rate,
avgLatencyMs: provider.avg_latency_ms,
avgFirstByteMs: provider.avg_first_byte_ms,
avgTps: provider.avg_tps,
timeline: provider.timeline || null,
timelineDetails: provider.timeline_details || null,
timeRangeStart: provider.time_range_start || null,
timeRangeEnd: provider.time_range_end || null
}
})
}
function emitSummary() {
emit('summaryUpdated', summarizeHealthMonitorItems(visibleProviders.value))
}
watch(lookbackHours, () => {
loadMonitors()
})
@@ -0,0 +1,259 @@
export type HealthBadgeVariant =
| 'default'
| 'secondary'
| 'destructive'
| 'outline'
| 'success'
| 'warning'
| 'dark'
export type HealthMonitorSourceKind = 'endpoint' | 'model' | 'provider'
export interface HealthMonitorDetailSource {
kind: HealthMonitorSourceKind
value: string
title: string
metaText?: string | null
totalAttempts: number
successCount: number
failedCount: number
successRate: number
avgLatencyMs?: number | null
avgFirstByteMs?: number | null
avgTps?: number | null
timeline?: string[] | null
timelineDetails?: HealthTimelineTooltipMetrics[] | null
timeRangeStart?: string | null
timeRangeEnd?: string | null
}
export interface HealthMonitorDetailTarget {
source: HealthMonitorDetailSource
lookbackHours: number
}
export interface HealthMonitorAvailability {
total_attempts: number
success_rate: number
}
export interface HealthTimelineTooltipMetrics {
time_range_start?: string | null
time_range_end?: string | null
total_attempts?: number | null
success_count?: number | null
failed_count?: number | null
success_rate?: number | null
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
}
export interface HealthMonitorSectionSummary {
total: number
healthy: number
warning: number
unhealthy: number
empty: number
attempts: number
}
export function summarizeHealthMonitorItems(
items: HealthMonitorAvailability[]
): HealthMonitorSectionSummary {
return items.reduce<HealthMonitorSectionSummary>((summary, item) => {
summary.total += 1
summary.attempts += item.total_attempts
if (item.total_attempts <= 0) {
summary.empty += 1
} else if (item.success_rate >= 0.95) {
summary.healthy += 1
} else if (item.success_rate >= 0.8) {
summary.warning += 1
} else {
summary.unhealthy += 1
}
return summary
}, createEmptyHealthMonitorSectionSummary())
}
export function createEmptyHealthMonitorSectionSummary(): HealthMonitorSectionSummary {
return {
total: 0,
healthy: 0,
warning: 0,
unhealthy: 0,
empty: 0,
attempts: 0
}
}
export function getHealthLabel(
item: HealthMonitorAvailability,
emptyLabel = '暂无请求'
) {
if (item.total_attempts <= 0) return emptyLabel
if (item.success_rate >= 0.95) return '正常'
if (item.success_rate >= 0.8) return '波动'
return '异常'
}
export function getHealthBadgeVariant(
item: HealthMonitorAvailability
): HealthBadgeVariant {
if (item.total_attempts <= 0) return 'outline'
if (item.success_rate >= 0.95) return 'success'
if (item.success_rate >= 0.8) return 'warning'
return 'destructive'
}
export function getSuccessRateClass(rate: number) {
if (rate >= 0.95) return 'text-green-600 dark:text-green-400'
if (rate >= 0.8) return 'text-amber-600 dark:text-amber-400'
return 'text-red-600 dark:text-red-400'
}
export function getAvailabilityClass(item: HealthMonitorAvailability) {
if (item.total_attempts <= 0) return ''
return getSuccessRateClass(item.success_rate)
}
export function formatMs(value?: number | null) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
const absValue = Math.abs(value)
if (absValue < 1000) return `${Math.round(value)} ms`
if (absValue < 60_000) return `${formatDurationNumber(value / 1000)} s`
return `${formatDurationNumber(value / 60_000)} min`
}
function formatDurationNumber(value: number) {
return new Intl.NumberFormat('zh-CN', {
maximumFractionDigits: Math.abs(value) < 10 ? 2 : 1
}).format(value)
}
export function formatPercent(value: number) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
return `${(value * 100).toFixed(2)}%`
}
export function formatAvailability(item: HealthMonitorAvailability) {
if (item.total_attempts <= 0) return '-'
return formatPercent(item.success_rate)
}
export function formatTps(value?: number | null) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
return `${new Intl.NumberFormat('zh-CN', {
maximumFractionDigits: value < 10 ? 2 : value < 100 ? 1 : 0
}).format(value)} tps`
}
export function formatFullTimestamp(timestamp?: string | null) {
if (!timestamp) return '未知时间'
const date = new Date(timestamp)
if (Number.isNaN(date.getTime())) return '未知时间'
const pad = (value: number) => value.toString().padStart(2, '0')
return [
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`,
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
].join(' ')
}
export function formatTimelineTooltip(input: {
status: string
timeRangeStart: string
timeRangeEnd: string
metrics?: HealthTimelineTooltipMetrics | null
entityLabel?: string
entityName?: string | null
}) {
const metrics = input.metrics
const lines = [
`总请求/成功/失败/可用率/状态:${formatTimelineRequestBreakdown(metrics, input.status)}`,
`平均耗时/TTFB/速度:${formatTimelineAverageMetrics(metrics)}`,
`时间范围:${formatFullTimestamp(input.timeRangeStart)} - ${formatFullTimestamp(input.timeRangeEnd)}`
]
if (input.entityLabel && input.entityName) {
lines.push(`${input.entityLabel}${input.entityName}`)
}
return lines.join('\n')
}
function formatTimelineAverageMetrics(metrics?: HealthTimelineTooltipMetrics | null) {
return [
formatMs(metrics?.avg_latency_ms),
formatMs(metrics?.avg_first_byte_ms),
formatTps(metrics?.avg_tps)
].join('/')
}
function formatTimelineRequestBreakdown(
metrics: HealthTimelineTooltipMetrics | null | undefined,
status: string
) {
if (!metrics) return '-'
const total = formatTimelineCount(metrics.total_attempts)
const success = formatTimelineCount(metrics.success_count)
const failed = formatTimelineCount(metrics.failed_count)
const availability = formatTimelineMetricAvailability(metrics)
return `${total}/${success}/${failed}/${availability}/${getTimelineLabel(status)}`
}
function formatTimelineCount(value?: number | null) {
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
return `${new Intl.NumberFormat('zh-CN').format(value)}`
}
function formatTimelineMetricAvailability(metrics?: HealthTimelineTooltipMetrics | null) {
if (!metrics) return '-'
if (typeof metrics.total_attempts === 'number' && metrics.total_attempts <= 0) return '-'
if (typeof metrics.success_rate !== 'number' || Number.isNaN(metrics.success_rate)) return '-'
return formatPercent(metrics.success_rate)
}
export function formatCompactNumber(value: number) {
return new Intl.NumberFormat('zh-CN', {
notation: 'compact',
maximumFractionDigits: 1
}).format(value)
}
export function formatTimestamp(timestamp?: string | null) {
if (!timestamp) return '未知时间'
const date = new Date(timestamp)
if (Number.isNaN(date.getTime())) return '未知时间'
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
export function getTimelineColor(status: string) {
switch (status) {
case 'healthy':
return 'bg-green-500/80 dark:bg-green-400/90'
case 'warning':
return 'bg-amber-400/80 dark:bg-amber-300/80'
case 'unhealthy':
return 'bg-red-500/80 dark:bg-red-400/90'
default:
return 'bg-gray-300 dark:bg-gray-600'
}
}
export function getTimelineLabel(status: string) {
switch (status) {
case 'healthy':
return '健康'
case 'warning':
return '波动'
case 'unhealthy':
return '异常'
default:
return '无请求'
}
}
@@ -338,7 +338,22 @@
</template>
</div>
<!-- 第三行性能指标 -->
<!-- 第三行用户 + 提供商 -->
<div
v-if="isAdmin"
class="mt-1 flex min-w-0 items-center gap-1.5 text-[10px] leading-3.5 text-muted-foreground"
>
<span
class="min-w-0 truncate"
:title="formatRecordUserProviderLine(record)"
>
{{ formatRecordUserSegment(record) }}
</span>
<span class="shrink-0 text-muted-foreground/40">·</span>
<span class="min-w-0 truncate">{{ formatRecordProviderSegment(record) }}</span>
</div>
<!-- 第四行性能指标 -->
<div class="mt-1.5 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-[10px] leading-3.5 text-muted-foreground">
<span
class="min-w-0 truncate whitespace-nowrap tabular-nums text-foreground"
@@ -1389,6 +1404,22 @@ function formatRecordTime(dateStr: string): string {
return `${hours}:${minutes}:${seconds}`
}
function getRecordUserName(record: UsageRecord): string {
return record.username || record.user_email || (record.user_id ? `User ${record.user_id}` : '已删除用户')
}
function formatRecordUserProviderLine(record: UsageRecord): string {
return `${formatRecordUserSegment(record)} · ${formatRecordProviderSegment(record)}`
}
function formatRecordUserSegment(record: UsageRecord): string {
return `${getRecordUserName(record)} / ${record.api_key?.name || '-'}`
}
function formatRecordProviderSegment(record: UsageRecord): string {
return `${record.provider || '-'} / ${record.provider_key_name || '-'}`
}
watch(() => props.filterSearch, (value) => {
if (value !== localSearch.value) {
localSearch.value = value
+268 -11
View File
@@ -153,6 +153,77 @@ function generateHealthTimeline(
})
}
function generateHealthTimelineDetails(
timeline: string[],
avgLatencyMs: number | null,
avgFirstByteMs: number | null,
avgTps: number | null,
rangeStart = Date.now() - 6 * 60 * 60 * 1000,
rangeEnd = Date.now()
) {
const safeRange = Math.max(rangeEnd - rangeStart, 1)
const interval = safeRange / Math.max(timeline.length, 1)
return timeline.map((status, index) => {
const totalAttempts = status === 'unknown' ? 0 : 3 + (index % 6)
const successRate = status === 'healthy'
? 0.98
: status === 'warning'
? 0.84
: status === 'unhealthy'
? 0.42
: null
const successCount = successRate == null ? 0 : Math.round(totalAttempts * successRate)
const failedCount = successRate == null ? 0 : Math.max(totalAttempts - successCount, 0)
const latencyFactor = status === 'warning' ? 1.25 : status === 'unhealthy' ? 1.7 : 1
return {
segment_index: index,
status,
time_range_start: new Date(rangeStart + index * interval).toISOString(),
time_range_end: new Date(rangeStart + (index + 1) * interval).toISOString(),
total_attempts: totalAttempts,
success_count: successCount,
failed_count: failedCount,
success_rate: successRate,
avg_latency_ms: avgLatencyMs == null || totalAttempts === 0
? null
: Math.round(avgLatencyMs * latencyFactor),
avg_first_byte_ms: avgFirstByteMs == null || totalAttempts === 0
? null
: Math.round(avgFirstByteMs * latencyFactor),
avg_tps: avgTps == null || totalAttempts === 0
? null
: Number((avgTps / latencyFactor).toFixed(1))
}
})
}
function withHealthTimelineDetails<T extends {
timeline?: string[]
time_range_start?: string
time_range_end?: string
avg_latency_ms?: number | null
avg_first_byte_ms?: number | null
avg_tps?: number | null
}>(item: T) {
const rangeStart = item.time_range_start
? new Date(item.time_range_start).getTime()
: Date.now() - 6 * 60 * 60 * 1000
const rangeEnd = item.time_range_end
? new Date(item.time_range_end).getTime()
: Date.now()
return {
...item,
timeline_details: generateHealthTimelineDetails(
item.timeline || [],
item.avg_latency_ms ?? null,
item.avg_first_byte_ms ?? null,
item.avg_tps ?? null,
rangeStart,
rangeEnd
)
}
}
// Mock 端点健康数据
// 注意:success_rate 使用 0-1 之间的小数,前端会乘以 100 显示为百分比
// 事件的成功/失败/跳过比例必须与 success_rate 保持一致
@@ -168,11 +239,17 @@ const MOCK_ENDPOINT_STATUS = {
failed_count: 30,
skipped_count: 10,
success_rate: 0.984,
avg_latency_ms: 920,
avg_first_byte_ms: 148,
avg_tps: 92.4,
provider_count: 2,
key_count: 4,
last_event_at: new Date().toISOString(),
// 98.4% 成功率:successRate=0.984, failRate=0.012, skipRate=0.004
events: generateHealthEvents(80, 0.984, 0.012, 0.004, 900, 500)
events: generateHealthEvents(80, 0.984, 0.012, 0.004, 900, 500),
timeline: generateHealthTimeline(0.9, 0.06, 60),
time_range_start: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
time_range_end: new Date().toISOString()
},
{
api_format: 'claude:messages',
@@ -182,11 +259,17 @@ const MOCK_ENDPOINT_STATUS = {
failed_count: 85,
skipped_count: 25,
success_rate: 0.942,
avg_latency_ms: 1280,
avg_first_byte_ms: 232,
avg_tps: 71.5,
provider_count: 5,
key_count: 9,
last_event_at: new Date().toISOString(),
// 94.2% 成功率:successRate=0.942, failRate=0.045, skipRate=0.013
events: generateHealthEvents(120, 0.942, 0.045, 0.013, 1200, 800)
events: generateHealthEvents(120, 0.942, 0.045, 0.013, 1200, 800),
timeline: generateHealthTimeline(0.78, 0.14, 60),
time_range_start: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
time_range_end: new Date().toISOString()
},
{
api_format: 'gemini:generate_content',
@@ -196,11 +279,17 @@ const MOCK_ENDPOINT_STATUS = {
failed_count: 0,
skipped_count: 0,
success_rate: 1.0,
avg_latency_ms: 410,
avg_first_byte_ms: 92,
avg_tps: 118.2,
provider_count: 3,
key_count: 3,
last_event_at: new Date().toISOString(),
// 100% 成功率:全部成功
events: generateHealthEvents(45, 1.0, 0, 0, 400, 200)
events: generateHealthEvents(45, 1.0, 0, 0, 400, 200),
timeline: generateHealthTimeline(0.96, 0.02, 60),
time_range_start: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
time_range_end: new Date().toISOString()
},
{
api_format: 'gemini:generate_content',
@@ -210,11 +299,17 @@ const MOCK_ENDPOINT_STATUS = {
failed_count: 4,
skipped_count: 2,
success_rate: 0.987,
avg_latency_ms: 520,
avg_first_byte_ms: 110,
avg_tps: 102.7,
provider_count: 3,
key_count: 3,
last_event_at: new Date().toISOString(),
// 98.7% 成功率:successRate=0.987, failRate=0.009, skipRate=0.004
events: generateHealthEvents(25, 0.987, 0.009, 0.004, 500, 300)
events: generateHealthEvents(25, 0.987, 0.009, 0.004, 500, 300),
timeline: generateHealthTimeline(0.9, 0.06, 60),
time_range_start: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
time_range_end: new Date().toISOString()
},
{
api_format: 'openai:chat',
@@ -224,11 +319,17 @@ const MOCK_ENDPOINT_STATUS = {
failed_count: 35,
skipped_count: 5,
success_rate: 0.974,
avg_latency_ms: 760,
avg_first_byte_ms: 138,
avg_tps: 88.9,
provider_count: 1,
key_count: 2,
last_event_at: new Date().toISOString(),
// 97.4% 成功率:successRate=0.974, failRate=0.022, skipRate=0.004
events: generateHealthEvents(60, 0.974, 0.022, 0.004, 700, 400)
events: generateHealthEvents(60, 0.974, 0.022, 0.004, 700, 400),
timeline: generateHealthTimeline(0.86, 0.09, 60),
time_range_start: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
time_range_end: new Date().toISOString()
},
{
api_format: 'openai:responses',
@@ -238,11 +339,17 @@ const MOCK_ENDPOINT_STATUS = {
failed_count: 100,
skipped_count: 40,
success_rate: 0.940,
avg_latency_ms: 980,
avg_first_byte_ms: 185,
avg_tps: 64.3,
provider_count: 4,
key_count: 5,
last_event_at: new Date().toISOString(),
// 94.0% 成功率:successRate=0.940, failRate=0.043, skipRate=0.017
events: generateHealthEvents(100, 0.940, 0.043, 0.017, 800, 600)
events: generateHealthEvents(100, 0.940, 0.043, 0.017, 800, 600),
timeline: generateHealthTimeline(0.76, 0.14, 60),
time_range_start: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
time_range_end: new Date().toISOString()
},
{
api_format: 'openai:embedding',
@@ -252,10 +359,16 @@ const MOCK_ENDPOINT_STATUS = {
failed_count: 6,
skipped_count: 2,
success_rate: 0.987,
avg_latency_ms: 330,
avg_first_byte_ms: 72,
avg_tps: 0,
provider_count: 1,
key_count: 1,
last_event_at: new Date().toISOString(),
events: generateHealthEvents(40, 0.987, 0.01, 0.003, 320, 140)
events: generateHealthEvents(40, 0.987, 0.01, 0.003, 320, 140),
timeline: generateHealthTimeline(0.92, 0.05, 60),
time_range_start: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
time_range_end: new Date().toISOString()
}
]
}
@@ -272,6 +385,7 @@ const MOCK_MODEL_STATUS = {
success_rate: 0.9896,
avg_latency_ms: 1736,
avg_first_byte_ms: 176,
avg_tps: 84.6,
provider_count: 3,
last_event_at: new Date().toISOString(),
events: generateHealthEvents(60, 0.989, 0.008, 0.003, 1600, 460),
@@ -288,6 +402,7 @@ const MOCK_MODEL_STATUS = {
success_rate: 0.9751,
avg_latency_ms: 1280,
avg_first_byte_ms: 221,
avg_tps: 76.2,
provider_count: 2,
last_event_at: new Date().toISOString(),
events: generateHealthEvents(60, 0.975, 0.02, 0.005, 1200, 520),
@@ -304,6 +419,7 @@ const MOCK_MODEL_STATUS = {
success_rate: 0.9517,
avg_latency_ms: 940,
avg_first_byte_ms: 184,
avg_tps: 101.8,
provider_count: 2,
last_event_at: new Date().toISOString(),
events: generateHealthEvents(55, 0.952, 0.04, 0.008, 860, 300),
@@ -320,6 +436,7 @@ const MOCK_MODEL_STATUS = {
success_rate: 0.835,
avg_latency_ms: 2310,
avg_first_byte_ms: 420,
avg_tps: 38.4,
provider_count: 1,
last_event_at: new Date().toISOString(),
events: generateHealthEvents(45, 0.835, 0.145, 0.02, 2200, 780),
@@ -344,6 +461,7 @@ const MOCK_PROVIDER_HEALTH_STATUS = {
success_rate: 0.9896,
avg_latency_ms: 1736,
avg_first_byte_ms: 176,
avg_tps: 84.6,
model_count: 2,
last_event_at: new Date().toISOString(),
timeline: generateHealthTimeline(0.9, 0.05),
@@ -362,6 +480,7 @@ const MOCK_PROVIDER_HEALTH_STATUS = {
success_rate: 0.9751,
avg_latency_ms: 1280,
avg_first_byte_ms: 221,
avg_tps: 76.2,
model_count: 1,
last_event_at: new Date().toISOString(),
timeline: generateHealthTimeline(0.84, 0.09),
@@ -380,6 +499,7 @@ const MOCK_PROVIDER_HEALTH_STATUS = {
success_rate: 0.9517,
avg_latency_ms: 940,
avg_first_byte_ms: 184,
avg_tps: 101.8,
model_count: 1,
last_event_at: new Date().toISOString(),
timeline: generateHealthTimeline(0.78, 0.14),
@@ -398,6 +518,7 @@ const MOCK_PROVIDER_HEALTH_STATUS = {
success_rate: 1,
avg_latency_ms: null,
avg_first_byte_ms: null,
avg_tps: null,
model_count: 0,
last_event_at: null,
timeline: Array.from({ length: 60 }, () => 'unknown'),
@@ -408,6 +529,110 @@ const MOCK_PROVIDER_HEALTH_STATUS = {
]
}
function mockApiFormatDisplayName(apiFormat: string) {
const labels: Record<string, string> = {
'claude:messages': 'Claude Messages',
'gemini:generate_content': 'Gemini Generate Content',
'openai:chat': 'OpenAI Chat',
'openai:embedding': 'OpenAI Embedding'
}
return labels[apiFormat] || apiFormat
}
function relatedEndpointMonitor(format: typeof MOCK_ENDPOINT_STATUS.formats[number]) {
const detailed = withHealthTimelineDetails(format)
return {
kind: 'endpoint',
key: format.api_format,
display_name: mockApiFormatDisplayName(format.api_format),
meta_text: format.api_path,
total_attempts: format.total_attempts,
success_count: format.success_count,
failed_count: format.failed_count,
success_rate: format.success_rate,
avg_latency_ms: format.avg_latency_ms,
avg_first_byte_ms: format.avg_first_byte_ms,
avg_tps: format.avg_tps,
last_event_at: format.last_event_at,
timeline: format.timeline,
timeline_details: detailed.timeline_details,
time_range_start: format.time_range_start,
time_range_end: format.time_range_end
}
}
function relatedModelMonitor(model: typeof MOCK_MODEL_STATUS.models[number]) {
const detailed = withHealthTimelineDetails(model)
return {
kind: 'model',
key: model.model,
display_name: model.display_name || model.model,
meta_text: model.provider_count ? `${model.provider_count} 个提供商` : null,
total_attempts: model.total_attempts,
success_count: model.success_count,
failed_count: model.failed_count,
success_rate: model.success_rate,
avg_latency_ms: model.avg_latency_ms,
avg_first_byte_ms: model.avg_first_byte_ms,
avg_tps: model.avg_tps,
last_event_at: model.last_event_at,
timeline: model.timeline,
timeline_details: detailed.timeline_details,
time_range_start: model.time_range_start,
time_range_end: model.time_range_end
}
}
function relatedProviderMonitor(provider: typeof MOCK_PROVIDER_HEALTH_STATUS.providers[number]) {
const detailed = withHealthTimelineDetails(provider)
return {
kind: 'provider',
key: provider.provider_name,
display_name: provider.provider_name,
meta_text: provider.provider_type || 'custom',
total_attempts: provider.total_attempts,
success_count: provider.success_count,
failed_count: provider.failed_count,
success_rate: provider.success_rate,
avg_latency_ms: provider.avg_latency_ms,
avg_first_byte_ms: provider.avg_first_byte_ms,
avg_tps: provider.avg_tps,
last_event_at: provider.last_event_at,
timeline: provider.timeline,
timeline_details: detailed.timeline_details,
time_range_start: provider.time_range_start,
time_range_end: provider.time_range_end
}
}
function uniqueMockEndpointFormats() {
const seen = new Set<string>()
return MOCK_ENDPOINT_STATUS.formats.filter(format => {
if (seen.has(format.api_format)) return false
seen.add(format.api_format)
return true
})
}
function buildMockRelatedHealthResponse(config: AxiosRequestConfig, includeProviders: boolean) {
const dimension = String(config.params?.dimension || 'endpoint')
const value = String(config.params?.value || '')
const endpoints = uniqueMockEndpointFormats().slice(0, 3).map(relatedEndpointMonitor)
const models = MOCK_MODEL_STATUS.models.slice(0, 3).map(relatedModelMonitor)
const providers = includeProviders
? MOCK_PROVIDER_HEALTH_STATUS.providers.slice(0, 3).map(relatedProviderMonitor)
: []
return {
generated_at: new Date().toISOString(),
dimension,
value,
related_endpoints: dimension === 'endpoint' ? [] : endpoints,
related_models: dimension === 'model' ? [] : models,
related_providers: dimension === 'provider' ? [] : providers
}
}
// 生成活跃热力图数据(最近365天)
function generateActivityHeatmap() {
const days: Array<{
@@ -1193,19 +1418,37 @@ const mockHandlers: Record<string, (config: AxiosRequestConfig) => Promise<Axios
'GET /api/admin/endpoints/health/api-formats': async () => {
await delay()
requireAdmin()
return createMockResponse(MOCK_ENDPOINT_STATUS)
return createMockResponse({
...MOCK_ENDPOINT_STATUS,
formats: MOCK_ENDPOINT_STATUS.formats.map(withHealthTimelineDetails)
})
},
'GET /api/admin/endpoints/health/models': async () => {
await delay()
requireAdmin()
return createMockResponse(MOCK_MODEL_STATUS)
return createMockResponse({
...MOCK_MODEL_STATUS,
models: MOCK_MODEL_STATUS.models.map(withHealthTimelineDetails)
})
},
'GET /api/admin/endpoints/health/providers': async () => {
await delay()
requireAdmin()
return createMockResponse(MOCK_PROVIDER_HEALTH_STATUS)
return createMockResponse({
...MOCK_PROVIDER_HEALTH_STATUS,
providers: MOCK_PROVIDER_HEALTH_STATUS.providers.map(provider => ({
...withHealthTimelineDetails(provider),
models: provider.models.map(withHealthTimelineDetails)
}))
})
},
'GET /api/admin/endpoints/health/related': async (config) => {
await delay()
requireAdmin()
return createMockResponse(buildMockRelatedHealthResponse(config, true))
},
'GET /api/admin/endpoints/keys': async () => {
@@ -1565,8 +1808,15 @@ const mockHandlers: Record<string, (config: AxiosRequestConfig) => Promise<Axios
failed_count: f.failed_count,
skipped_count: f.skipped_count,
success_rate: f.success_rate,
avg_latency_ms: f.avg_latency_ms,
avg_first_byte_ms: f.avg_first_byte_ms,
avg_tps: f.avg_tps,
last_event_at: f.last_event_at,
events: f.events.slice(0, 10)
events: f.events.slice(0, 10),
timeline: f.timeline,
timeline_details: withHealthTimelineDetails(f).timeline_details,
time_range_start: f.time_range_start,
time_range_end: f.time_range_end
}))
})
},
@@ -1584,13 +1834,20 @@ const mockHandlers: Record<string, (config: AxiosRequestConfig) => Promise<Axios
success_rate: model.success_rate,
avg_latency_ms: model.avg_latency_ms,
avg_first_byte_ms: model.avg_first_byte_ms,
avg_tps: model.avg_tps,
last_event_at: model.last_event_at,
events: model.events.slice(0, 10),
timeline: model.timeline,
timeline_details: withHealthTimelineDetails(model).timeline_details,
time_range_start: model.time_range_start,
time_range_end: model.time_range_end
}))
})
},
'GET /api/public/health/related': async (config) => {
await delay()
return createMockResponse(buildMockRelatedHealthResponse(config, false))
}
}
File diff suppressed because it is too large Load Diff
+335 -62
View File
@@ -1,82 +1,355 @@
<template>
<div class="space-y-6 pb-8">
<Tabs v-model="activeTab">
<TabsList
class="tabs-button-list grid w-full"
:class="isAdminPage ? 'max-w-2xl grid-cols-3' : 'max-w-md grid-cols-2'"
>
<TabsTrigger value="endpoint">
端点健康监控
</TabsTrigger>
<TabsTrigger value="model">
模型健康监控
</TabsTrigger>
<TabsTrigger
v-if="isAdminPage"
value="provider"
>
提供商健康监控
</TabsTrigger>
</TabsList>
<Card
variant="default"
class="overflow-hidden"
>
<div class="relative overflow-hidden border-b border-border/60 px-6 py-5">
<div class="absolute inset-0 bg-gradient-to-br from-primary/10 via-transparent to-muted/30" />
<div class="relative flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div class="max-w-3xl">
<p class="text-xs font-medium uppercase tracking-[0.22em] text-primary/80">
Health Dashboard
</p>
<h2 class="mt-2 text-2xl font-semibold tracking-tight">
健康监控
</h2>
<p class="mt-2 text-sm leading-6 text-muted-foreground">
统一查看端点模型{{ isAdminPage ? '、提供商' : '' }}健康状态先从概览判断风险再进入具体视角排查关联健康
</p>
</div>
</div>
</div>
<TabsContent
value="endpoint"
class="mt-4"
>
<HealthMonitorCard
v-if="visitedTabs.endpoint"
title="端点健康监控"
:is-admin="isAdminPage"
:show-provider-info="isAdminPage"
/>
</TabsContent>
<div class="space-y-5 p-6">
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
<div
v-for="card in overviewCards"
:key="card.label"
class="rounded-xl border border-border/60 bg-card/70 p-4"
>
<div class="flex items-start justify-between gap-3">
<div>
<p class="text-xs text-muted-foreground">
{{ card.label }}
</p>
<div
class="mt-2 text-2xl font-semibold tabular-nums"
:class="card.valueClass"
>
{{ card.value }}
</div>
</div>
<div class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/40">
<component
:is="card.icon"
class="h-5 w-5 text-muted-foreground"
/>
</div>
</div>
<p class="mt-3 text-xs text-muted-foreground">
{{ card.description }}
</p>
</div>
</div>
<TabsContent
value="model"
class="mt-4"
>
<ModelHealthMonitorCard
v-if="visitedTabs.model"
title="模型健康监控"
:is-admin="isAdminPage"
:show-provider-info="isAdminPage"
/>
</TabsContent>
<div>
<div class="mb-3 flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
<div>
<h3 class="text-sm font-semibold">
综合概览
</h3>
<p class="text-xs text-muted-foreground">
点击视角卡片快速跳转到对应健康列表
</p>
</div>
</div>
<TabsContent
v-if="isAdminPage"
value="provider"
class="mt-4"
>
<ProviderHealthMonitorCard
v-if="visitedTabs.provider"
title="提供商健康监控"
/>
</TabsContent>
</Tabs>
<div
class="grid grid-cols-1 gap-3"
:class="isAdminPage ? 'lg:grid-cols-3' : 'lg:grid-cols-2'"
>
<button
v-for="section in sectionCards"
:key="section.key"
type="button"
class="group rounded-xl border border-border/60 bg-muted/20 p-4 text-left transition-colors hover:border-primary/50 hover:bg-primary/5"
@click="scrollToSection(section.id)"
>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-center gap-3">
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-card/70 transition-colors group-hover:border-primary/40">
<component
:is="section.icon"
class="h-5 w-5 text-muted-foreground"
/>
</div>
<div class="min-w-0">
<h4 class="truncate text-sm font-semibold">
{{ section.title }}
</h4>
<p class="mt-1 text-xs text-muted-foreground">
{{ section.description }}
</p>
</div>
</div>
<Badge
:variant="section.badgeVariant"
class="shrink-0"
>
{{ section.badgeLabel }}
</Badge>
</div>
<div class="mt-4 grid grid-cols-3 gap-2 text-xs">
<div class="rounded-lg border border-border/40 bg-card/50 px-3 py-2">
<p class="text-muted-foreground">总数</p>
<p class="mt-1 font-semibold tabular-nums">{{ section.summary.total }}</p>
</div>
<div class="rounded-lg border border-border/40 bg-card/50 px-3 py-2">
<p class="text-muted-foreground">异常</p>
<p class="mt-1 font-semibold tabular-nums text-red-600 dark:text-red-400">{{ section.summary.unhealthy }}</p>
</div>
<div class="rounded-lg border border-border/40 bg-card/50 px-3 py-2">
<p class="text-muted-foreground">波动</p>
<p class="mt-1 font-semibold tabular-nums text-amber-600 dark:text-amber-400">{{ section.summary.warning }}</p>
</div>
</div>
</button>
</div>
</div>
</div>
</Card>
<section
id="health-endpoints"
class="scroll-mt-6"
>
<HealthMonitorCard
title="端点健康监控"
:is-admin="isAdminPage"
:show-provider-info="isAdminPage"
@view-details="openHealthDetails"
@summary-updated="updateSummary('endpoint', $event)"
/>
</section>
<section
id="health-models"
class="scroll-mt-6"
>
<ModelHealthMonitorCard
title="模型健康监控"
:is-admin="isAdminPage"
:show-provider-info="isAdminPage"
@view-details="openHealthDetails"
@summary-updated="updateSummary('model', $event)"
/>
</section>
<section
v-if="isAdminPage"
id="health-providers"
class="scroll-mt-6"
>
<ProviderHealthMonitorCard
title="提供商健康监控"
@view-details="openHealthDetails"
@summary-updated="updateSummary('provider', $event)"
/>
</section>
<HealthMonitorDetailDrawer
v-model:open="detailOpen"
:target="detailTarget"
:is-admin="isAdminPage"
@view-details="openHealthDetails"
/>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { computed, ref, type Component } from 'vue'
import { useRoute } from 'vue-router'
import Tabs from '@/components/ui/tabs.vue'
import TabsContent from '@/components/ui/tabs-content.vue'
import TabsList from '@/components/ui/tabs-list.vue'
import TabsTrigger from '@/components/ui/tabs-trigger.vue'
import { Activity, Bot, Gauge, Server, Zap } from 'lucide-vue-next'
import Card from '@/components/ui/card.vue'
import Badge from '@/components/ui/badge.vue'
import HealthMonitorCard from '@/features/providers/components/HealthMonitorCard.vue'
import ModelHealthMonitorCard from '@/features/providers/components/ModelHealthMonitorCard.vue'
import ProviderHealthMonitorCard from '@/features/providers/components/ProviderHealthMonitorCard.vue'
import HealthMonitorDetailDrawer from '@/features/providers/components/HealthMonitorDetailDrawer.vue'
import {
createEmptyHealthMonitorSectionSummary,
formatCompactNumber,
type HealthBadgeVariant,
type HealthMonitorDetailTarget,
type HealthMonitorSectionSummary,
type HealthMonitorSourceKind
} from '@/features/providers/components/health-monitor-utils'
const route = useRoute()
const isAdminPage = computed(() => route.path.startsWith('/admin'))
const activeTab = ref('endpoint')
const visitedTabs = ref<Record<string, boolean>>({ endpoint: true })
const detailOpen = ref(false)
const detailTarget = ref<HealthMonitorDetailTarget | null>(null)
const sectionSummaries = ref<Partial<Record<HealthMonitorSourceKind, HealthMonitorSectionSummary>>>({})
watch(activeTab, value => {
visitedTabs.value = {
...visitedTabs.value,
[value]: true
const expectedSectionKeys = computed<HealthMonitorSourceKind[]>(() => (
isAdminPage.value ? ['endpoint', 'model', 'provider'] : ['endpoint', 'model']
))
const loadedSectionCount = computed(() => (
expectedSectionKeys.value.filter(key => sectionSummaries.value[key]).length
))
const allSectionsLoaded = computed(() => loadedSectionCount.value >= expectedSectionKeys.value.length)
const combinedSummary = computed(() => {
const summary = createEmptyHealthMonitorSectionSummary()
for (const key of expectedSectionKeys.value) {
const section = getSummary(key)
summary.total += section.total
summary.healthy += section.healthy
summary.warning += section.warning
summary.unhealthy += section.unhealthy
summary.empty += section.empty
summary.attempts += section.attempts
}
return summary
})
const overallLabel = computed(() => getStatusLabel(combinedSummary.value, allSectionsLoaded.value))
const overallBadgeVariant = computed(() => getStatusBadgeVariant(combinedSummary.value, allSectionsLoaded.value))
const overviewCards = computed(() => {
const endpointSummary = getSummary('endpoint')
const modelSummary = getSummary('model')
const providerSummary = getSummary('provider')
const cards = [
{
label: '总体状态',
value: overallLabel.value,
description: allSectionsLoaded.value
? `${combinedSummary.value.total} 项健康对象 / ${formatCompactNumber(combinedSummary.value.attempts)} 次请求`
: `${loadedSectionCount.value}/${expectedSectionKeys.value.length} 个视角已加载`,
icon: Gauge,
valueClass: getStatusValueClass(combinedSummary.value, allSectionsLoaded.value)
},
{
label: '异常端点',
value: endpointSummary.unhealthy,
description: `${endpointSummary.warning} 个波动 / ${formatCompactNumber(endpointSummary.attempts)} 次请求`,
icon: Activity,
valueClass: endpointSummary.unhealthy > 0 ? 'text-red-600 dark:text-red-400' : ''
},
{
label: '异常模型',
value: modelSummary.unhealthy,
description: `${modelSummary.warning} 个波动 / ${formatCompactNumber(modelSummary.attempts)} 次请求`,
icon: Bot,
valueClass: modelSummary.unhealthy > 0 ? 'text-red-600 dark:text-red-400' : ''
}
]
if (isAdminPage.value) {
cards.push({
label: '异常提供商',
value: providerSummary.unhealthy,
description: `${providerSummary.warning} 个波动 / ${providerSummary.empty} 个暂无请求`,
icon: Server,
valueClass: providerSummary.unhealthy > 0 ? 'text-red-600 dark:text-red-400' : ''
})
} else {
cards.push({
label: '请求总量',
value: formatCompactNumber(combinedSummary.value.attempts),
description: '当前回溯窗口内参与健康统计的请求',
icon: Zap,
valueClass: ''
})
}
return cards
})
const sectionCards = computed(() => {
const sections = [
buildSectionCard('endpoint', 'health-endpoints', '端点视角', '按 API 入口定位入口层健康', Activity),
buildSectionCard('model', 'health-models', '模型视角', '按模型聚合查看跨提供商健康', Bot)
]
if (isAdminPage.value) {
sections.push(buildSectionCard('provider', 'health-providers', '提供商视角', '按提供商定位供应商侧波动', Server))
}
return sections
})
function openHealthDetails(target: HealthMonitorDetailTarget) {
detailTarget.value = target
detailOpen.value = true
}
function updateSummary(kind: HealthMonitorSourceKind, summary: HealthMonitorSectionSummary) {
sectionSummaries.value = {
...sectionSummaries.value,
[kind]: summary
}
}
function getSummary(kind: HealthMonitorSourceKind) {
return sectionSummaries.value[kind] || createEmptyHealthMonitorSectionSummary()
}
function buildSectionCard(
key: HealthMonitorSourceKind,
id: string,
title: string,
description: string,
icon: Component
) {
const summary = getSummary(key)
const loaded = Boolean(sectionSummaries.value[key])
return {
key,
id,
title,
description,
icon,
summary,
badgeLabel: getStatusLabel(summary, loaded),
badgeVariant: getStatusBadgeVariant(summary, loaded)
}
}
function getStatusLabel(summary: HealthMonitorSectionSummary, loaded: boolean) {
if (!loaded) return '加载中'
if (summary.total === 0) return '暂无数据'
if (summary.unhealthy > 0) return '异常'
if (summary.warning > 0) return '波动'
if (summary.empty > 0) return '部分暂无请求'
return '正常'
}
function getStatusBadgeVariant(
summary: HealthMonitorSectionSummary,
loaded: boolean
): HealthBadgeVariant {
if (!loaded || summary.total === 0) return 'outline'
if (summary.unhealthy > 0) return 'destructive'
if (summary.warning > 0 || summary.empty > 0) return 'warning'
return 'success'
}
function getStatusValueClass(summary: HealthMonitorSectionSummary, loaded: boolean) {
if (!loaded || summary.total === 0) return ''
if (summary.unhealthy > 0) return 'text-red-600 dark:text-red-400'
if (summary.warning > 0 || summary.empty > 0) return 'text-amber-600 dark:text-amber-400'
return 'text-green-600 dark:text-green-400'
}
function scrollToSection(id: string) {
document.getElementById(id)?.scrollIntoView({
behavior: 'smooth',
block: 'start'
})
}
</script>
@@ -101,6 +101,7 @@ vi.mock('lucide-vue-next', async () => {
Clock: Icon,
Database: Icon,
Shuffle: Icon,
RefreshCw: Icon,
}
})