Skip to content

World's first open-source enterprise world model.

Failures get somewhere to be seen (#76)

WaylandYangc9b352c2cdfd
diff --git a/Cargo.lock b/Cargo.lock
index 20024adf..400792f0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4770,6 +4770,8 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
+ "thiserror 2.0.20",
+ "tokio",
"tracing",
]
diff --git a/crates/utopia-llm/Cargo.toml b/crates/utopia-llm/Cargo.toml
index 8dcbf269..9b0b0eb9 100644
--- a/crates/utopia-llm/Cargo.toml
+++ b/crates/utopia-llm/Cargo.toml
@@ -12,3 +12,7 @@ anyhow.workspace = true
futures-util.workspace = true
async-stream.workspace = true
tracing.workspace = true
+thiserror.workspace = true
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt"] }
diff --git a/crates/utopia-llm/src/lib.rs b/crates/utopia-llm/src/lib.rs
index a3045d06..09e0ce41 100644
--- a/crates/utopia-llm/src/lib.rs
+++ b/crates/utopia-llm/src/lib.rs
@@ -60,6 +60,28 @@ pub enum ToolStreamItem {
Turn(AssistantTurn),
}
+/// **没能从端点拿到一个能解析的回答。** 两种:连不上(DNS、连接、TLS、超时),
+/// 或者连上了但回来的根本不是这个 API(响应体解不成 JSON)。
+///
+/// 合成一类是有意的:从用户那边看这两种是同一件事——"你配的这个地址不是模型 API",
+/// 该做的也是同一件事:去看 URL、看代理。第一版只收传输层失败,结果最常见的那种
+/// 故障(URL 配错、代理挡在中间回了 HTML)一条告警都不产生,
+/// 正是"失败无声"本身。
+///
+/// **不含**端点干干净净地回了 4xx/5xx:那说明它就是模型 API,只是密钥、
+/// 配额或模型名不对——另一类问题,该找的人也不同。
+///
+/// 有类型而不是匹配错误文本:调用链上任何一层加一句 context 都会改文本,
+/// 而 `anyhow` 的 source 链让 `downcast_ref` 一路都认得出来。
+#[derive(Debug, thiserror::Error)]
+#[error("LLM endpoint gave no usable answer: {0}")]
+pub struct Unreachable(#[from] pub reqwest::Error);
+
+/// anyhow 错误链里有没有 [`Unreachable`]。
+pub fn is_unreachable(err: &anyhow::Error) -> bool {
+ err.chain().any(|e| e.is::<Unreachable>())
+}
+
#[derive(Clone)]
pub struct LlmClient {
http: reqwest::Client,
@@ -92,9 +114,10 @@ impl LlmClient {
.request("/chat/completions")
.json(&json!({ "model": self.model, "messages": messages, "stream": false }))
.send()
- .await?;
+ .await
+ .map_err(Unreachable)?;
let status = resp.status();
- let body: serde_json::Value = resp.json().await?;
+ let body: serde_json::Value = resp.json().await.map_err(Unreachable)?;
if !status.is_success() {
anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body));
}
@@ -121,9 +144,10 @@ impl LlmClient {
"stream": false,
}))
.send()
- .await?;
+ .await
+ .map_err(Unreachable)?;
let status = resp.status();
- let body: serde_json::Value = resp.json().await?;
+ let body: serde_json::Value = resp.json().await.map_err(Unreachable)?;
if !status.is_success() {
anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body));
}
@@ -175,7 +199,8 @@ impl LlmClient {
"stream": true,
}))
.send()
- .await?;
+ .await
+ .map_err(Unreachable)?;
if !resp.status().is_success() {
let status = resp.status();
let body: serde_json::Value = resp.json().await.unwrap_or_default();
@@ -266,7 +291,8 @@ impl LlmClient {
.request("/chat/completions")
.json(&json!({ "model": self.model, "messages": messages, "stream": true }))
.send()
- .await?;
+ .await
+ .map_err(Unreachable)?;
if !resp.status().is_success() {
let status = resp.status();
let body: serde_json::Value = resp.json().await.unwrap_or_default();
@@ -310,9 +336,10 @@ impl LlmClient {
.request("/embeddings")
.json(&json!({ "model": self.model, "input": texts }))
.send()
- .await?;
+ .await
+ .map_err(Unreachable)?;
let status = resp.status();
- let body: serde_json::Value = resp.json().await?;
+ let body: serde_json::Value = resp.json().await.map_err(Unreachable)?;
if !status.is_success() {
anyhow::bail!("Embedding request failed ({status}): {}", err_detail(&body));
}
@@ -364,3 +391,52 @@ fn err_detail(body: &serde_json::Value) -> String {
.unwrap_or("unknown error")
.to_string()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// 真发一次注定失败的请求,拿一个货真价实的 `reqwest::Error`。
+ /// 端口 1 上不会有东西监听,而 127.0.0.1 不走代理。
+ async fn a_real_transport_error() -> reqwest::Error {
+ reqwest::Client::builder()
+ .no_proxy()
+ .build()
+ .unwrap()
+ .get("http://127.0.0.1:1/")
+ .send()
+ .await
+ .expect_err("端口 1 不该连得上")
+ }
+
+ /// **判定必须穿透 context 层。**
+ ///
+ /// 这是整条链上最容易悄悄坏掉的一环:调用方每加一句 `.context("抽取失败")`
+ /// 就换掉一次错误文本,靠文本匹配的判定当天就废——而症状是告警再也不出现,
+ /// 没有任何测试会红,用户也不会来报"我没收到告警"。
+ #[tokio::test]
+ async fn unreachable_survives_context_layers() {
+ let raw = a_real_transport_error().await;
+ let err = anyhow::Error::new(Unreachable(raw))
+ .context("embedding 失败")
+ .context("process_document 失败");
+ assert!(is_unreachable(&err));
+ // 顺带钉住"文本会变"这件事本身:最外层已经不含端点的任何字样
+ assert!(!err.to_string().contains("endpoint"));
+ }
+
+ /// 反面:普通错误不该被认成端点问题,否则告警会对任何失败都亮。
+ #[tokio::test]
+ async fn an_ordinary_failure_is_not_the_endpoint() {
+ let e = anyhow::anyhow!("Embedding 响应缺少向量").context("抽取失败");
+ assert!(!is_unreachable(&e));
+ }
+
+ /// 端点干干净净地回了 4xx 不算——那说明它就是模型 API,
+ /// 只是密钥或模型名不对,该找的人和该做的事都不一样。
+ #[tokio::test]
+ async fn a_clean_api_error_is_a_different_problem() {
+ let e = anyhow::anyhow!("LLM request failed (401 Unauthorized): bad key");
+ assert!(!is_unreachable(&e));
+ }
+}
diff --git a/crates/utopia-server/src/alerting.rs b/crates/utopia-server/src/alerting.rs
new file mode 100644
index 00000000..5277a979
--- /dev/null
+++ b/crates/utopia-server/src/alerting.rs
@@ -0,0 +1,73 @@
+//! 告警的产生侧(0005)。存取在 `utopia_store::alerts`,这里只管**什么时候报**。
+//!
+//! 没有"什么时候消"——一次故障一行,写完不再改。见那个模块的文档。
+
+use utopia_core::models::Role;
+use utopia_store::alerts;
+
+use crate::state::AppState;
+
+/// 告警保留多少天。**纯原子的代价就在这里**:一个坏掉的来源按小时同步,
+/// 一天写 24 行,不清理这张表会长成第二个日志文件。
+///
+/// 30 天够回答"上个月那次是怎么回事",而更久远的事该去翻 `audit_events` 与日志。
+const RETAIN_DAYS: i32 = 30;
+
+/// 任务失败时看一眼是不是模型端点不可用。
+///
+/// **只在任务最终放弃时报**(`attempts >= max_attempts`)。中间那几次重试报了
+/// 就是同一件事发三遍——重试本来就是为了不惊动人,报出去等于把它的意义抵消掉。
+/// 一个任务至多一条告警,不需要任何去重状态。
+///
+/// 判据是错误链里有没有 [`utopia_llm::Unreachable`],**不匹配错误文本**——
+/// 调用链上任何一层加一句 context 都会改文本。
+pub async fn observe_job_failure(
+ state: &AppState,
+ job: &utopia_store::jobs::Job,
+ err: &anyhow::Error,
+) {
+ if job.attempts < job.max_attempts {
+ return;
+ }
+ if !utopia_llm::is_unreachable(err) {
+ return;
+ }
+ // 系统级:哪个库的任务撞上的不重要,端点是整个部署共用的
+ if let Err(e) = alerts::raise(
+ &state.pool,
+ alerts::NewAlert {
+ kb_id: None,
+ severity: "error",
+ kind: alerts::kind::LLM_UNREACHABLE,
+ min_role: Role::Admin,
+ subject_type: Some("system"),
+ subject_id: None,
+ detail: serde_json::json!({ "job": job.kind, "error": err.to_string() }),
+ },
+ )
+ .await
+ {
+ tracing::warn!(error = %e, "上报 llm.unreachable 失败");
+ return;
+ }
+ state.emit_alert();
+}
+
+/// 每天清一次过期告警。
+pub fn spawn_retention_sweep(state: AppState) {
+ tokio::spawn(async move {
+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(24 * 60 * 60));
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ tick.tick().await;
+ match alerts::purge_older_than(&state.pool, RETAIN_DAYS).await {
+ Ok(n) if n > 0 => {
+ tracing::info!(count = n, days = RETAIN_DAYS, "清理过期告警");
+ state.emit_alert();
+ }
+ Ok(_) => {}
+ Err(e) => tracing::warn!(error = %e, "清理过期告警失败"),
+ }
+ }
+ });
+}
diff --git a/crates/utopia-server/src/api/alerts_routes.rs b/crates/utopia-server/src/api/alerts_routes.rs
new file mode 100644
index 00000000..07c1acd3
--- /dev/null
+++ b/crates/utopia-server/src/api/alerts_routes.rs
@@ -0,0 +1,156 @@
+//! 告警中心(0005)。**跨库**:一个顶栏面板,不挂在某个 KB 下面。
+//!
+//! 可见性不在这里判——它在 `utopia_store::alerts` 的那几条 SQL 里判且只判一次。
+//! 路由层只负责取当前用户。
+
+use axum::extract::{Query, State};
+use axum::response::sse::{Event, KeepAlive, Sse};
+use axum::Json;
+use chrono::{DateTime, Utc};
+use futures_util::Stream;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use std::convert::Infallible;
+use tokio::sync::broadcast;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+/// 一页几组。弹窗里放得下的量——再多就该翻页,而不是让人滚一屏。
+const PAGE: i64 = 8;
+/// 一页最多能要多少:防的是有人把 limit 写成 100000 让服务端去数全表
+const MAX_PAGE: i64 = 50;
+
+#[derive(Deserialize)]
+pub struct ListQuery {
+ /// 搜库名、对象详情、kind 代号。**搜不到界面上那句标题**——
+ /// 措辞在客户端,服务端没有它(见 store 里 SEARCH 的注释)
+ #[serde(default)]
+ pub q: Option<String>,
+ #[serde(default)]
+ pub limit: Option<i64>,
+ #[serde(default)]
+ pub offset: Option<i64>,
+}
+
+/// 一组连着的同类故障。折叠是**读**出来的,存储那边仍是一次故障一行。
+#[derive(Serialize)]
+pub struct GroupView {
+ pub kb_id: Option<Uuid>,
+ pub kb_name: Option<String>,
+ pub kind: String,
+ pub severity: String,
+ pub count: i64,
+ pub unread: i64,
+ pub latest_at: DateTime<Utc>,
+ /// 跟 `latest_at` 一起圈出这一组,标已读时原样发回来
+ pub earliest_at: DateTime<Utc>,
+ /// 明细,最多几条,新的在前
+ pub lines: Vec<serde_json::Value>,
+}
+
+#[derive(Serialize)]
+pub struct ListResponse {
+ pub items: Vec<GroupView>,
+ /// 总**组**数——翻页控件数的是组,不是行
+ pub total: i64,
+}
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Query(q): Query<ListQuery>,
+) -> ApiResult<Json<ListResponse>> {
+ let limit = q.limit.unwrap_or(PAGE).clamp(1, MAX_PAGE);
+ let offset = q.offset.unwrap_or(0).max(0);
+ let page = utopia_store::alerts::list_groups(&state.pool, &user, q.q.as_deref(), limit, offset)
+ .await?;
+ Ok(Json(ListResponse {
+ items: page
+ .items
+ .into_iter()
+ .map(|g| GroupView {
+ kb_id: g.kb_id,
+ kb_name: g.kb_name,
+ kind: g.kind,
+ severity: g.severity,
+ count: g.count,
+ unread: g.unread,
+ latest_at: g.latest_at,
+ earliest_at: g.earliest_at,
+ lines: g.lines,
+ })
+ .collect(),
+ total: page.total,
+ }))
+}
+
+/// 角标。单独一条路由而不是从列表里数:这个每开一页都要。
+pub async fn unread(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<serde_json::Value>> {
+ let n = utopia_store::alerts::unread_count(&state.pool, &user).await?;
+ Ok(Json(json!({ "unread": n })))
+}
+
+#[derive(Deserialize)]
+pub struct ReadGroupBody {
+ pub kb_id: Option<Uuid>,
+ pub kind: String,
+ /// 组的时间区间,原样来自列表返回的 `earliest_at` / `latest_at`
+ pub from: DateTime<Utc>,
+ pub to: DateTime<Utc>,
+}
+
+/// 把一整组标已读。**逐人**——读过不等于问题没了,别人的未读不受影响。
+///
+/// 按时间区间圈而不是发 id 列表:一组可能有几百条。可见性在 store 里照查,
+/// 所以猜一个 kind 也标不掉自己看不见的东西。
+pub async fn mark_group_read(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(b): Json<ReadGroupBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let n =
+ utopia_store::alerts::mark_group_read(&state.pool, &user, b.kb_id, &b.kind, b.from, b.to)
+ .await?;
+ Ok(Json(json!({ "marked": n })))
+}
+
+/// 全部已读。
+pub async fn mark_all_read(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<serde_json::Value>> {
+ let n = utopia_store::alerts::mark_all_read(&state.pool, &user).await?;
+ Ok(Json(json!({ "marked": n })))
+}
+
+/// 全局事件流。KB 那条是 `/kbs/{id}/events`,按库过滤;角标是跨库的,
+/// 挂不上去。
+///
+/// **这里不做任何权限过滤**:事件不带数据,收到的人一律回头重取列表,
+/// 而列表那条查询会把不该看的挡掉。代价是没权限的人也被叫醒一次,
+/// 换来的是推送这条路上一行权限逻辑都没有——不会出现"推送判得比列表松"。
+pub async fn stream(
+ State(state): State<AppState>,
+ AuthUser(_user): AuthUser,
+) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
+ let mut rx = state.events.subscribe();
+ let stream = async_stream::stream! {
+ loop {
+ match rx.recv().await {
+ Ok(ev) if ev.kind == "alert" => {
+ yield Ok(Event::default().event("alert").data("{}"));
+ }
+ Ok(_) => continue,
+ Err(broadcast::error::RecvError::Lagged(_)) => continue,
+ Err(broadcast::error::RecvError::Closed) => return,
+ }
+ }
+ };
+ Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
+}
diff --git a/crates/utopia-server/src/api/events_routes.rs b/crates/utopia-server/src/api/events_routes.rs
index 8763afcc..e7e36280 100644
--- a/crates/utopia-server/src/api/events_routes.rs
+++ b/crates/utopia-server/src/api/events_routes.rs
@@ -24,7 +24,7 @@ pub async fn kb_events(
let stream = async_stream::stream! {
loop {
match rx.recv().await {
- Ok(ev) if ev.kb_id == kb_id => {
+ Ok(ev) if ev.kb_id == Some(kb_id) => {
yield Ok(Event::default()
.event(ev.kind)
.data(serde_json::to_string(&ev).unwrap_or_else(|_| "{}".into())));
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 77a7cc85..6692de99 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -1,4 +1,5 @@
mod admin_routes;
+mod alerts_routes;
mod auth_routes;
mod chat;
mod datasource_routes;
@@ -34,6 +35,12 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.route("/auth/register", post(auth_routes::register))
.route("/auth/login", post(auth_routes::login))
.route("/auth/logout", post(auth_routes::logout))
+ // 告警中心:跨库,不挂在 /kbs/{id} 下面
+ .route("/alerts", get(alerts_routes::list))
+ .route("/alerts/unread", get(alerts_routes::unread))
+ .route("/alerts/read-all", post(alerts_routes::mark_all_read))
+ .route("/alerts/read-group", post(alerts_routes::mark_group_read))
+ .route("/alerts/events", get(alerts_routes::stream))
.route(
"/auth/me",
get(auth_routes::me).patch(auth_routes::update_me),
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index 00167f15..bcb2a1fa 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -1,4 +1,5 @@
mod adjudication;
+mod alerting;
mod api;
mod auth;
mod blob;
@@ -101,77 +102,19 @@ async fn main() -> anyhow::Result<()> {
move |job| {
let st = worker_state.clone();
async move {
- match job.kind.as_str() {
- "noop" => {
- tracing::info!(job_id = job.id, "noop 任务执行成功");
- Ok(())
- }
- "process_document" => {
- let id = payload_document_id(&job.payload)?;
- pipeline::process_document(&st, id).await
- }
- "memory_ingest" => {
- let id = payload_document_id(&job.payload)?;
- pipeline::memory_ingest(&st, id).await
- }
- "explore_mappings" => {
- let kb_id: Uuid = job
- .payload
- .get("kb_id")
- .and_then(|v| v.as_str())
- .and_then(|s| s.parse().ok())
- .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
- mappings::explore_mappings(&st, kb_id).await
- }
- "extract_document" => {
- let id = payload_document_id(&job.payload)?;
- extraction::extract_document(&st, id).await
- }
- "bootstrap_ontology" => {
- let kb_id: Uuid = job
- .payload
- .get("kb_id")
- .and_then(|v| v.as_str())
- .and_then(|s| s.parse().ok())
- .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
- bootstrap_ontology::bootstrap_ontology(&st, kb_id).await
- }
- // 本体向量索引:**后台建,不卡请求**。
- // 一份 965 类的本体首次要嵌 2600 行,六到八分钟;放在
- // 交互请求里就是导入完之后第一个用到检索的人干等
- "embed_ontology" => {
- let kb_id: Uuid = job
- .payload
- .get("kb_id")
- .and_then(|v| v.as_str())
- .and_then(|s| s.parse().ok())
- .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
- ontology_index::refresh(&st, kb_id).await.map(|_| ())
- }
- "adjudicate_entities" => {
- let kb_id: Uuid = job
- .payload
- .get("kb_id")
- .and_then(|v| v.as_str())
- .and_then(|s| s.parse().ok())
- .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
- adjudication::adjudicate_entities(&st, kb_id).await
- }
- "sync_source" => {
- let source_id: Uuid = job
- .payload
- .get("source_id")
- .and_then(|v| v.as_str())
- .and_then(|s| s.parse().ok())
- .ok_or_else(|| anyhow::anyhow!("payload 缺少 source_id"))?;
- ingest_sources::sync_source(&st, source_id).await
- }
- other => anyhow::bail!("未知任务类型: {other}"),
+ // 任务失败时看一眼是不是模型端点连不上——那是系统级故障,
+ // 而现在它只会留在 jobs.last_error 里,没有任何界面看得到
+ let result = dispatch(&st, &job).await;
+ if let Err(e) = &result {
+ alerting::observe_job_failure(&st, &job, e).await;
}
+ result
}
},
));
+ alerting::spawn_retention_sweep(state.clone());
+
// 定时摄入调度器:每分钟扫一次到期来源,入队同步任务
let sched_state = state.clone();
tokio::spawn(async move {
@@ -233,3 +176,77 @@ async fn main() -> anyhow::Result<()> {
axum::serve(listener, svc).await?;
Ok(())
}
+
+/// 任务分发:新任务类型在这里注册。
+///
+/// 单拎成函数而不是内联在闭包里,是为了让失败**有一个统一的出口**——
+/// 上面那层要在每次失败时看一眼错误链,内联的话每个分支都得自己记得。
+async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow::Result<()> {
+ match job.kind.as_str() {
+ "noop" => {
+ tracing::info!(job_id = job.id, "noop 任务执行成功");
+ Ok(())
+ }
+ "process_document" => {
+ let id = payload_document_id(&job.payload)?;
+ pipeline::process_document(st, id).await
+ }
+ "memory_ingest" => {
+ let id = payload_document_id(&job.payload)?;
+ pipeline::memory_ingest(st, id).await
+ }
+ "explore_mappings" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ mappings::explore_mappings(st, kb_id).await
+ }
+ "extract_document" => {
+ let id = payload_document_id(&job.payload)?;
+ extraction::extract_document(st, id).await
+ }
+ "bootstrap_ontology" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ bootstrap_ontology::bootstrap_ontology(st, kb_id).await
+ }
+ // 本体向量索引:**后台建,不卡请求**。
+ // 一份 965 类的本体首次要嵌 2600 行,六到八分钟;放在
+ // 交互请求里就是导入完之后第一个用到检索的人干等
+ "embed_ontology" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ ontology_index::refresh(st, kb_id).await.map(|_| ())
+ }
+ "adjudicate_entities" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ adjudication::adjudicate_entities(st, kb_id).await
+ }
+ "sync_source" => {
+ let source_id: Uuid = job
+ .payload
+ .get("source_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 source_id"))?;
+ ingest_sources::sync_source(st, source_id).await
+ }
+ other => anyhow::bail!("未知任务类型: {other}"),
+ }
+}
diff --git a/crates/utopia-server/src/state.rs b/crates/utopia-server/src/state.rs
index 94fde742..5908c6f0 100644
--- a/crates/utopia-server/src/state.rs
+++ b/crates/utopia-server/src/state.rs
@@ -9,8 +9,10 @@ use uuid::Uuid;
/// 服务内事件(SSE 推送给前端做局部刷新)。
#[derive(Clone, Debug, serde::Serialize)]
pub struct AppEvent {
- pub kb_id: Uuid,
- /// document = 文档摄入/抽取状态变化;review = 审核队列变化
+ /// None = 不属于任何库。告警的角标是跨库的,而系统级告警根本没有库
+ pub kb_id: Option<Uuid>,
+ /// document = 文档摄入/抽取状态变化;review = 审核队列变化;
+ /// alert = 告警中心有变动
pub kind: &'static str,
pub document_id: Option<Uuid>,
}
@@ -63,7 +65,7 @@ impl AppState {
/// 无订阅者时 send 返回 Err——正常情况,静默忽略。
pub fn emit_document(&self, kb_id: Uuid, document_id: Uuid) {
let _ = self.events.send(AppEvent {
- kb_id,
+ kb_id: Some(kb_id),
kind: "document",
document_id: Some(document_id),
});
@@ -71,7 +73,7 @@ impl AppState {
pub fn emit_review(&self, kb_id: Uuid) {
let _ = self.events.send(AppEvent {
- kb_id,
+ kb_id: Some(kb_id),
kind: "review",
document_id: None,
});
@@ -79,9 +81,22 @@ impl AppState {
pub fn emit_source(&self, kb_id: Uuid) {
let _ = self.events.send(AppEvent {
- kb_id,
+ kb_id: Some(kb_id),
kind: "source",
document_id: None,
});
}
+
+ /// 告警有变动。**不带任何数据,也不判权限**——收到的人一律重取列表,
+ /// 而"谁能看见什么"在列表查询里判且只判一次。
+ ///
+ /// 代价是没权限的人也会被叫醒重取一次,拿到的仍是空。换来的是推送这条路上
+ /// 一行权限逻辑都没有,不存在"推送和列表判得不一样"这种漏。
+ pub fn emit_alert(&self) {
+ let _ = self.events.send(AppEvent {
+ kb_id: None,
+ kind: "alert",
+ document_id: None,
+ });
+ }
}
diff --git a/crates/utopia-store/src/access.rs b/crates/utopia-store/src/access.rs
index 8215844b..f047f702 100644
--- a/crates/utopia-store/src/access.rs
+++ b/crates/utopia-store/src/access.rs
@@ -36,6 +36,49 @@ pub async fn kb_role(pool: &PgPool, user: &User, kb: &KnowledgeBase) -> AppResul
Ok(None)
}
+/// `kb_role` 的集合版:这个人**在所有工作区里**能看见的每个 KB → 有效角色。
+///
+/// **改上面那个函数就必须改这个**。之所以不用循环调 `kb_role` 拼出来:
+/// 告警列表是跨库的,逐条一次查询就是 N+1,而告警数会随部署规模长。
+/// 三条分支与 `kb_role` 一一对应,顺序也一致:
+/// 1. is_admin → 全部 KB,Owner
+/// 2. kb_members 有记录 → 矩阵角色
+/// 3. open 库 + 该工作区的 membership → Viewer
+///
+/// 第 3 条这里显式查了 `memberships`,而 `kbs::list_visible` 没查——
+/// 那个函数已被工作区路由限定过范围,这个没有。
+pub async fn visible_kb_roles(pool: &PgPool, user: &User) -> AppResult<Vec<(Uuid, Role)>> {
+ if user.is_admin {
+ let ids: Vec<(Uuid,)> = sqlx::query_as("SELECT id FROM knowledge_bases")
+ .fetch_all(pool)
+ .await?;
+ return Ok(ids.into_iter().map(|(id,)| (id, Role::Owner)).collect());
+ }
+ let rows: Vec<(Uuid, Option<String>, bool)> = sqlx::query_as(
+ "SELECT k.id,
+ m.role,
+ (k.visibility = 'open'
+ AND EXISTS (SELECT 1 FROM memberships ws
+ WHERE ws.workspace_id = k.workspace_id AND ws.user_id = $1))
+ FROM knowledge_bases k
+ LEFT JOIN kb_members m ON m.kb_id = k.id AND m.user_id = $1",
+ )
+ .bind(user.id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .filter_map(|(id, matrix, open_member)| {
+ // 矩阵优先于 open——跟 kb_role 一样,矩阵有记录就不再看 visibility
+ match matrix {
+ Some(r) => Role::parse(&r).map(|r| (id, r)),
+ None if open_member => Some((id, Role::Viewer)),
+ None => None,
+ }
+ })
+ .collect())
+}
+
/// 要求对 KB 至少具备 `min` 角色,返回 KB。
pub async fn require_kb(
pool: &PgPool,
diff --git a/crates/utopia-store/src/alerts.rs b/crates/utopia-store/src/alerts.rs
new file mode 100644
index 00000000..2d156289
--- /dev/null
+++ b/crates/utopia-store/src/alerts.rs
@@ -0,0 +1,312 @@
+//! 告警中心(0005)。**Review 管知识的对错,告警管系统的死活。**
+//!
+//! **一次故障一行,写完不再改。** 这张表刻意没有状态机:没有"已解决",
+//! 没有自愈,没有把多次故障并成一行。
+//!
+//! 曾经有过,代价是每种新告警都得自己实现一遍"怎么算修好了"——
+//! `source.sync_failed` 有天然的成功信号(同步成功了),`llm.unreachable` 没有,
+//! 就得为它单独造一个后台探针;第三种告警要造第三套,而漏写清除编译期看不出来,
+//! 症状是告警永远亮着。更根本的是**那不是告警中心该回答的问题**:现在还坏不坏,
+//! 来源页面上写着、文档状态里写着。告警的职责是让人去看一眼,不是当实时看板。
+//!
+//! 去重也不做。「同一个源连续 24 小时每小时失败」是 24 条不是 1 条——
+//! 要写成 1 条就得判断"这是复发还是一直没好",而那**在数据上无法区分**,
+//! 除非引入时钟或者成功信号。漏报比行数贵得多,所以宁可多写行,
+//! 靠 [`purge_older_than`] 收尾。
+
+use sqlx::PgPool;
+use utopia_core::models::{Role, User};
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+/// 告警 kind。**字符串写死在这里而不是散在调用点**:界面按它查措辞,
+/// 拼错一个字母就会退回显示代号,而这种错编译期看不出来。
+pub mod kind {
+ /// 库级:某个来源同步失败。`min_role = editor`
+ pub const SOURCE_SYNC_FAILED: &str = "source.sync_failed";
+ /// 系统级:模型端点没给出可用的回答——连不上,或者连上了但回来的不是这个 API。
+ /// 端点干净地回 4xx 不算:那说明它就是模型 API,只是密钥或配额不对
+ pub const LLM_UNREACHABLE: &str = "llm.unreachable";
+}
+
+/// 一次故障。打包成结构体不只是为了参数个数——调用点写 `severity: "error"`
+/// 比"第三个位置参数是 error"好读得多,而告警源只会越来越多。
+pub struct NewAlert<'a> {
+ /// None = 系统级
+ pub kb_id: Option<Uuid>,
+ pub severity: &'a str,
+ /// 用 [`kind`] 里的常量,别写字面量
+ pub kind: &'a str,
+ pub min_role: Role,
+ /// document / source / system
+ pub subject_type: Option<&'a str>,
+ pub subject_id: Option<Uuid>,
+ /// 给人看的那份:名字、报错原文。**名字要在这里存一份**——
+ /// 对象被删之后 `subject_id` 就解析不出名字了,而告警该留得住
+ pub detail: serde_json::Value,
+}
+
+/// 记一次故障。就是一条 INSERT,没有冲突处理,没有回读。
+pub async fn raise(pool: &PgPool, a: NewAlert<'_>) -> AppResult<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO alerts
+ (id, kb_id, severity, kind, min_role, subject_type, subject_id, detail)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(id)
+ .bind(a.kb_id)
+ .bind(a.severity)
+ .bind(a.kind)
+ .bind(a.min_role.as_str())
+ .bind(a.subject_type)
+ .bind(a.subject_id)
+ .bind(a.detail)
+ .fetch_optional(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 保留期清理。**纯原子的代价就在这里**:一个坏掉的来源按小时同步,
+/// 一天写 24 行;不清理这张表会长成第二个日志文件。
+///
+/// 一并删掉已读记录(外键 CASCADE)。
+pub async fn purge_older_than(pool: &PgPool, days: i32) -> AppResult<u64> {
+ let n = sqlx::query("DELETE FROM alerts WHERE created_at < now() - make_interval(days => $1)")
+ .bind(days)
+ .execute(pool)
+ .await?;
+ Ok(n.rows_affected())
+}
+
+/// 可见性谓词,**只写这一份**。列表、未读数、全部已读各查各的,
+/// 但"谁能看见什么"是同一条规则;抄三遍迟早会漂。
+///
+/// `$1` = user_id、`$2` = is_admin、`$3` = 可见 kb 数组、`$4` = 对应角色的秩。
+const VISIBLE: &str = "
+ CASE
+ WHEN a.kb_id IS NULL THEN $2::bool
+ ELSE EXISTS (
+ SELECT 1 FROM unnest($3::uuid[], $4::int[]) AS v(kb, rank)
+ WHERE v.kb = a.kb_id
+ AND v.rank >= CASE a.min_role
+ WHEN 'viewer' THEN 0
+ WHEN 'editor' THEN 1
+ WHEN 'admin' THEN 2
+ ELSE 3 END)
+ END";
+
+/// 搜索匹配的是**库名、对象详情、kind 代号**,不是界面上那句标题。
+///
+/// 标题的措辞在客户端(0004:服务端不产出展示文案),所以服务端搜不到它。
+/// 这不是将就:人会去搜的是来源名、库名、报错原文——那些语言中立、
+/// 而且就在 detail 里。按类别找东西该用筛选,不是搜索框。
+const SEARCH: &str = "
+ ($5::text IS NULL
+ OR a.kind ILIKE '%' || $5 || '%'
+ OR COALESCE(k.name, '') ILIKE '%' || $5 || '%'
+ OR a.detail::text ILIKE '%' || $5 || '%')";
+
+/// 一组:**连着的**、同 `(kb, kind)` 的几次故障。
+///
+/// 存储是原子的(一次故障一行),折叠只影响读。分组在服务端做而不是前端,
+/// 是因为**分页得按组分**:前端折叠的话一页只能取固定行数,一段连续故障
+/// 跨了页边界就会断成两组,点一下也只标到边界为止。
+#[derive(sqlx::FromRow)]
+pub struct AlertGroup {
+ pub kb_id: Option<Uuid>,
+ pub kb_name: Option<String>,
+ pub kind: String,
+ /// 组里最重的那一档
+ pub severity: String,
+ /// 这一组几次
+ pub count: i64,
+ /// 其中我没读过的几次
+ pub unread: i64,
+ /// 组里最新与最早的时刻。**标已读按这个区间圈**,不用把 id 列表发给前端——
+ /// 一组可能有几百条
+ pub latest_at: chrono::DateTime<chrono::Utc>,
+ pub earliest_at: chrono::DateTime<chrono::Utc>,
+ /// 明细,最多 [`GROUP_LINES`] 条,新的在前
+ pub lines: Vec<serde_json::Value>,
+}
+
+/// 一组里最多带回几条明细。面板里列不下更多,而一组可能有几百条——
+/// 全发过来只是让首屏更慢
+const GROUP_LINES: i64 = 5;
+
+/// 一页分组,外加总组数。
+pub struct GroupPage {
+ pub items: Vec<AlertGroup>,
+ pub total: i64,
+}
+
+/// 相邻同类折叠:两个 `row_number()` 相减(gaps and islands)。
+///
+/// 全局序号减去"同 (kb, kind) 内的序号",连着的同类会得到同一个差值,
+/// 中间插进别的故障就会让差值变化——于是差值就是组号。
+/// `PARTITION BY kb_id` 把 NULL 当作相等,所以系统级告警自然归成一组。
+const ISLANDS: &str = "
+ SELECT v.*,
+ row_number() OVER (ORDER BY v.created_at DESC, v.id DESC)
+ - row_number() OVER (PARTITION BY v.kb_id, v.kind
+ ORDER BY v.created_at DESC, v.id DESC) AS grp
+ FROM v";
+
+/// 这个人能看见的告警,**按组分页**,时间倒序。
+pub async fn list_groups(
+ pool: &PgPool,
+ user: &User,
+ q: Option<&str>,
+ limit: i64,
+ offset: i64,
+) -> AppResult<GroupPage> {
+ let (kb_ids, kb_roles) = visible(pool, user).await?;
+ // 空串当没搜:前端清空搜索框时不该变成"搜一个空字符串"
+ let q = q.map(str::trim).filter(|s| !s.is_empty());
+ let base = format!(
+ "WITH v AS (
+ SELECT a.id, a.kb_id, k.name AS kb_name, a.severity, a.kind,
+ a.detail, a.created_at, (r.user_id IS NOT NULL) AS read
+ FROM alerts a
+ LEFT JOIN knowledge_bases k ON k.id = a.kb_id
+ LEFT JOIN alert_reads r ON r.alert_id = a.id AND r.user_id = $1
+ WHERE ({VISIBLE}) AND ({SEARCH})
+ ),
+ isl AS ({ISLANDS})"
+ );
+ let sql = format!(
+ "{base}
+ SELECT kb_id, max(kb_name) AS kb_name, kind,
+ -- severity 按轻重取最大,不能按字典序:那样 warning 会压过 error
+ CASE max(CASE severity WHEN 'error' THEN 3 WHEN 'warning' THEN 2 ELSE 1 END)
+ WHEN 3 THEN 'error' WHEN 2 THEN 'warning' ELSE 'info' END AS severity,
+ count(*) AS count,
+ count(*) FILTER (WHERE NOT read) AS unread,
+ max(created_at) AS latest_at,
+ min(created_at) AS earliest_at,
+ (array_agg(detail ORDER BY created_at DESC))[1:{GROUP_LINES}] AS lines
+ FROM isl
+ GROUP BY kb_id, kind, grp
+ ORDER BY max(created_at) DESC
+ LIMIT $6 OFFSET $7"
+ );
+ let items: Vec<AlertGroup> = sqlx::query_as(&sql)
+ .bind(user.id)
+ .bind(user.is_admin)
+ .bind(&kb_ids)
+ .bind(&kb_roles)
+ .bind(q)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(pool)
+ .await?;
+ // 总**组**数,不是总行数——翻页控件数的是组
+ let count_sql =
+ format!("{base} SELECT count(*) FROM (SELECT 1 FROM isl GROUP BY kb_id, kind, grp) g");
+ let (total,): (i64,) = sqlx::query_as(&count_sql)
+ .bind(user.id)
+ .bind(user.is_admin)
+ .bind(&kb_ids)
+ .bind(&kb_roles)
+ .bind(q)
+ .fetch_one(pool)
+ .await?;
+ Ok(GroupPage { items, total })
+}
+
+/// 把一整组标已读。**按时间区间圈**,不按 id 列表——一组可能有几百条,
+/// 把 id 全发给前端再发回来只是白跑一趟。
+///
+/// 可见性照查:不能让人靠猜 kind 把看不见的告警标掉。
+pub async fn mark_group_read(
+ pool: &PgPool,
+ user: &User,
+ kb_id: Option<Uuid>,
+ kind: &str,
+ from: chrono::DateTime<chrono::Utc>,
+ to: chrono::DateTime<chrono::Utc>,
+) -> AppResult<u64> {
+ let (kb_ids, kb_roles) = visible(pool, user).await?;
+ let sql = format!(
+ "INSERT INTO alert_reads (alert_id, user_id)
+ SELECT a.id, $1 FROM alerts a
+ WHERE ({VISIBLE})
+ AND a.kind = $5
+ -- IS NOT DISTINCT FROM:系统级告警的 kb_id 是 NULL,= 比不出来
+ AND a.kb_id IS NOT DISTINCT FROM $6
+ AND a.created_at BETWEEN $7 AND $8
+ ON CONFLICT DO NOTHING"
+ );
+ let n = sqlx::query(&sql)
+ .bind(user.id)
+ .bind(user.is_admin)
+ .bind(&kb_ids)
+ .bind(&kb_roles)
+ .bind(kind)
+ .bind(kb_id)
+ .bind(from)
+ .bind(to)
+ .execute(pool)
+ .await?;
+ Ok(n.rows_affected())
+}
+
+/// 我的未读数。
+pub async fn unread_count(pool: &PgPool, user: &User) -> AppResult<i64> {
+ let (kb_ids, kb_roles) = visible(pool, user).await?;
+ let sql = format!(
+ "SELECT count(*) FROM alerts a
+ LEFT JOIN alert_reads r ON r.alert_id = a.id AND r.user_id = $1
+ WHERE ({VISIBLE}) AND r.user_id IS NULL"
+ );
+ let (n,): (i64,) = sqlx::query_as(&sql)
+ .bind(user.id)
+ .bind(user.is_admin)
+ .bind(&kb_ids)
+ .bind(&kb_roles)
+ .fetch_one(pool)
+ .await?;
+ Ok(n)
+}
+
+/// 把我能看见的全标已读。
+///
+/// 一条 SQL 而不是逐条 insert:逐条要先把列表取回来,而"能看见什么"
+/// 已经在 [`VISIBLE`] 里写过一遍了,取回来再遍历等于把同一条规则用两次。
+pub async fn mark_all_read(pool: &PgPool, user: &User) -> AppResult<u64> {
+ let (kb_ids, kb_roles) = visible(pool, user).await?;
+ let sql = format!(
+ "INSERT INTO alert_reads (alert_id, user_id)
+ SELECT a.id, $1 FROM alerts a
+ WHERE ({VISIBLE})
+ ON CONFLICT DO NOTHING"
+ );
+ let n = sqlx::query(&sql)
+ .bind(user.id)
+ .bind(user.is_admin)
+ .bind(&kb_ids)
+ .bind(&kb_roles)
+ .execute(pool)
+ .await?;
+ Ok(n.rows_affected())
+}
+
+/// 可见 KB 拆成两个平行数组:Postgres 没有元组数组的方便写法,
+/// `unnest(a, b)` 两列并排展开是标准做法。
+async fn visible(pool: &PgPool, user: &User) -> AppResult<(Vec<Uuid>, Vec<i32>)> {
+ let roles = crate::access::visible_kb_roles(pool, user).await?;
+ Ok(roles.into_iter().map(|(id, r)| (id, rank(r))).unzip())
+}
+
+/// 角色的序,用来跟 `alerts.min_role` 比大小。
+/// 跟 [`Role`] 的 `PartialOrd` 同序,也跟 [`VISIBLE`] 里那个 CASE 同序——
+/// 三处必须一致
+fn rank(r: Role) -> i32 {
+ match r {
+ Role::Viewer => 0,
+ Role::Editor => 1,
+ Role::Admin => 2,
+ Role::Owner => 3,
+ }
+}
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index a2f8c969..0bef16ba 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -3,6 +3,7 @@
pub mod access;
pub mod accounts;
+pub mod alerts;
pub mod audit;
pub mod conversations;
pub mod datasources;
diff --git a/crates/utopia-store/src/settings.rs b/crates/utopia-store/src/settings.rs
index d7881c3a..07f9df81 100644
--- a/crates/utopia-store/src/settings.rs
+++ b/crates/utopia-store/src/settings.rs
@@ -11,6 +11,19 @@ pub async fn get(pool: &PgPool, workspace_id: Uuid) -> AppResult<Option<LlmSetti
Ok(row)
}
+/// 任取一个配了对话模型的工作区设置。给端点探针用:端点地址是部署共用的,
+/// 从哪个工作区的配置读到的都是同一个地方,而探针没有"当前工作区"这个上下文。
+pub async fn any_with_chat(pool: &PgPool) -> AppResult<Option<LlmSettings>> {
+ let row = sqlx::query_as(
+ "SELECT * FROM llm_settings
+ WHERE chat_base_url IS NOT NULL AND chat_model IS NOT NULL
+ ORDER BY workspace_id LIMIT 1",
+ )
+ .fetch_optional(pool)
+ .await?;
+ Ok(row)
+}
+
/// upsert;api_key 传 None 表示保留旧值(前端不回传密钥)。
#[allow(clippy::too_many_arguments)]
pub async fn upsert(
diff --git a/crates/utopia-store/src/sources.rs b/crates/utopia-store/src/sources.rs
index 37b914d6..9152c456 100644
--- a/crates/utopia-store/src/sources.rs
+++ b/crates/utopia-store/src/sources.rs
@@ -2,7 +2,7 @@
use chrono::{DateTime, Utc};
use sqlx::PgPool;
-use utopia_core::models::{Source, SourceView, SyncRun};
+use utopia_core::models::{Role, Source, SourceView, SyncRun};
use utopia_core::{AppError, AppResult};
use uuid::Uuid;
@@ -232,24 +232,51 @@ pub async fn mark_running(pool: &PgPool, id: Uuid) -> AppResult<()> {
Ok(())
}
+/// 一次同步收尾。失败时记一条告警,成功时什么都不做——
+/// **"现在好了没有"不是告警中心该回答的问题**,来源页面上就写着。
+///
+/// 返回值是"记了没有",调用方据此决定要不要推事件。
pub async fn finish_sync(
pool: &PgPool,
id: Uuid,
error: Option<&str>,
added: i32,
-) -> AppResult<()> {
- sqlx::query(
+) -> AppResult<bool> {
+ let row: Option<(Uuid, String)> = sqlx::query_as(
"UPDATE sources SET last_sync_status = $2, last_sync_error = $3,
last_sync_added = $4, last_sync_at = now()
- WHERE id = $1",
+ WHERE id = $1
+ RETURNING kb_id, name",
)
.bind(id)
.bind(if error.is_some() { "failed" } else { "ok" })
.bind(error)
.bind(added)
- .execute(pool)
+ .fetch_optional(pool)
.await?;
- Ok(())
+ let Some((kb_id, name)) = row else {
+ return Ok(false);
+ };
+ let Some(msg) = error else {
+ return Ok(false);
+ };
+ crate::alerts::raise(
+ pool,
+ crate::alerts::NewAlert {
+ kb_id: Some(kb_id),
+ severity: "error",
+ kind: crate::alerts::kind::SOURCE_SYNC_FAILED,
+ // 内容类给 editor,不只给 admin:管理员需要知道该修连接了,
+ // 但**配这个源的人**更需要知道你的东西没进来
+ min_role: Role::Editor,
+ subject_type: Some("source"),
+ subject_id: Some(id),
+ // 名字存一份:源被删之后 subject_id 解析不出名字,而告警该留得住
+ detail: serde_json::json!({ "name": name, "error": msg }),
+ },
+ )
+ .await?;
+ Ok(true)
}
/// 文档打标签(整组替换)。
diff --git a/docs/decisions/0005-alert-center.md b/docs/decisions/0005-alert-center.md
index e3efa5fb..d48a5242 100644
--- a/docs/decisions/0005-alert-center.md
+++ b/docs/decisions/0005-alert-center.md
@@ -1,6 +1,7 @@
# 0005 · 告警中心
-- **状态**:规划中 · 未动工
+- **状态**:第一刀已建成(`source.sync_failed` + `llm.unreachable`)。
+ 三个决定里第 1、2 条在实现过程中被推翻,就地留痕见下
- **成文**:2026-08-29
- **相关**:与 Review 队列(0001 P4)职责相邻,本文划边界
@@ -46,19 +47,59 @@
## 三个决定
-### 1. 聚合:同一类未解决的只有一条
+### 1. 聚合属于视图,不属于表
-拖 100 份 PDF、12 份是扫描件,产生的是**一条**「12 份文档没有文本层」,点开看列表 —— 不是 12 条。同理「Notion 源连续 3 次同步失败」是一条,`last_seen` 往前推。
+> **修订记录**:这一条原本写的是"同一类未解决的只有一条",让 `(kb_id, kind)`
+> 在表里唯一,多次故障并成一行、往 `subject_ids` 数组里追加。
+> **前半句是对的,后半句是错的**,而且它是第 2 条那套状态机的根源。
-没有聚合的告警中心,两周后就没人看了。这不是优化,是能不能用的前提。
+拖 100 份 PDF、12 份是扫描件,界面上该读到**一条**「12 份文档没有文本层」,不是 12 条。
+没有聚合的告警中心两周后就没人看了 —— 这不是优化,是能不能用的前提。这句仍然成立。
-### 2. 自愈优先于人工关闭
+**但聚合必须是读出来的,不能存下来。** 存在表里的聚合是**活的**,活的东西要维护:
+东西好了得从数组里摘掉,不摘就撒谎。而"什么时候算好了"正是下面第 2 条那个坑。
+实现时先按存储聚合写了一版,三个 bug 全出自同一个根源 —— 那一行在自愈过程中被
+一路掏空,于是它既说不出自己曾经是什么事(`subject_ids` 与 `detail` 都空了),
+又会写出"0 个来源同步失败"这种标题。
-`resolved_at` 由**产生方**清空:配好 OCR 端点、那 12 份重新处理成功,告警自己消失。人工"标记已解决"只是兜底。
+现在的做法:**存储一次故障一行,读的时候把连着的同 `(kb, kind)` 折成一组。**
+折叠在 SQL 里做(两个 `row_number()` 相减,gaps and islands),因为分页得按组分 ——
+放前端折的话一段连续故障跨了页边界就会断成两组,点一下也只标到边界为止。
+计数是算出来的,永远不会过期。
-做不到自愈的告警,用户很快学会无视它 —— 一旦养成无视的习惯,这个功能就废了,而且是不可逆的。
+只折**相邻**的:中间隔了别的故障就说明那是另一段时间的事,不该并进来。
-### 3. 读是各人的,解决是共享的
+### 2. 「修好了没有」不是告警中心该回答的问题
+
+> **修订记录**:这一条原本是"自愈优先于人工关闭",理由是"做不到自愈的告警,
+> 用户很快学会无视它"。**那个担心是真的,但这个解法是错的**,而且错得很贵 ——
+> 整节推翻,留在这里是因为这个主意足够诱人,不留痕就会被再提一次。
+
+原方案:`resolved_at` 由产生方清空,配好 OCR 端点、那 12 份重新处理成功,告警自己消失。
+
+**它要求每一种新告警都自己实现一遍"怎么算修好了"。** 第一刀两种告警就要了两套机制:
+`source.sync_failed` 有天然的成功信号(`finish_sync` 成功失败走同一个出口,白捡的);
+`llm.unreachable` 没有,只好为它单独造一个后台探针 —— 每分钟敲一次端点,
+而且得先判断"这条告警还亮着吗"才敢发请求,否则健康的部署也在空转。
+第三种告警要造第三套。**而漏写清除是编译期看不出来的**,症状是告警永远亮着 ——
+恰好就是这个功能最怕的那件事。
+
+更根本的一层:**那不是告警中心的职责。** 现在还坏不坏,来源页面上写着、文档状态里写着。
+告警的职责是让人去看一眼,不是当实时看板。
+
+那"用户学会无视"怎么办?靠**每次故障发一条新的**:修好了就不再有新故障,
+读过的那些沉下去、角标自己灭;两个月后再坏,那是一条新的告警,角标重新亮。
+不需要成功信号,不需要探针,不需要任何时间常数。
+
+代价只有一个,也确实要付:**行数**。一个坏掉的来源按小时同步,一天写 24 行。
+所以有保留期(30 天,`alerting::RETAIN_DAYS`)—— 不清理这张表会长成第二个日志文件。
+
+> 也考虑过按 `(kb, kind, subject)` 去重、重复发生只推时间戳:行数有界、不用保留期。
+> **否掉了**,因为那样"复发"和"一直没好"在数据上无法区分,除非引入时钟或者成功信号;
+> 于是只能二选一 —— 读过就永久已读(两个月后复发静默,**漏报**),
+> 或者时间戳一动就重新变未读(已知故障每小时点亮,**噪音**)。漏报比行数贵得多。
+
+### 3. 读是各人的(这一条完好无损)
**这条推翻了一个更省事的方案,理由值得记下来。**
@@ -70,14 +111,16 @@
这是共享已读的经典失效:**所有人都以为别人在处理**,而且发生之后没有任何痕迹能让人发现漏了。
-根子在于把两件事合并了:**「已读」是我看没看过,「已解决」是事情完没完**。一个人读过不代表事情解决;而事情解决了,才是所有人都该从列表里移除它的时刻。
+根子在于把两件事合并了:**「已读」是我看没看过,「已解决」是事情完没完**。一个人读过不代表事情解决。
-所以:
+> **修订记录**:原文接着写"而事情解决了,才是所有人都该从列表里移除它的时刻",
+> 并把"告警消失 = `resolved_at` 落下,对所有人同时消失"列成与已读并列的一半。
+> **那半边随第 2 条一起没了** —— 没有"已解决",告警也不会消失,
+> 它只是随时间沉下去、到期被清理。这一条真正立得住的部分是**已读逐人**,
+> 而那部分一个字没改。
-- **未读角标** = 我可见的、未解决的告警中我没读过的条数 —— 每人独立
-- **告警消失** = `resolved_at` 落下,对所有人同时消失 —— 全局共享
-
-代价只有一张两列小表。换来的是**没有人能替别人把一件事读掉**。GitHub 通知、Slack 未读都这么做,不是巧合。
+所以:**未读 = 我可见的告警里我没点过的** —— 每人独立,一张两列小表。
+换来的是**没有人能替别人把一件事读掉**。GitHub 通知、Slack 未读都这么做,不是巧合。
---
@@ -104,39 +147,31 @@ kb_id 有值 知识库级:解析失败、抽取失败、源同步失败
---
-## 数据模型草案
-
-```sql
-CREATE TABLE alerts (
- id UUID PRIMARY KEY,
- kb_id UUID REFERENCES knowledge_bases(id) ON DELETE CASCADE, -- NULL = 系统级
- severity TEXT NOT NULL CHECK (severity IN ('info','warning','error')),
- kind TEXT NOT NULL, -- 'source.sync_failed' / 'llm.unreachable' / ...
- min_role TEXT NOT NULL, -- 见「可见性」
- subject_type TEXT, -- document / source / system
- subject_ids UUID[], -- 聚合:同一 kind 下的所有对象
- detail JSONB NOT NULL DEFAULT '{}',
- first_seen TIMESTAMPTZ NOT NULL DEFAULT now(),
- last_seen TIMESTAMPTZ NOT NULL DEFAULT now(),
- resolved_at TIMESTAMPTZ
-);
-
--- 聚合的实现关键:同类未解决的告警在库里只能有一条。
--- 新实例往 subject_ids 追加、更新 last_seen,而不是插新行。
-CREATE UNIQUE INDEX alerts_open_kind_idx ON alerts (kb_id, kind)
- WHERE resolved_at IS NULL;
-
-CREATE TABLE alert_reads (
- alert_id UUID NOT NULL REFERENCES alerts(id) ON DELETE CASCADE,
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- read_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- PRIMARY KEY (alert_id, user_id)
-);
-```
+## 数据模型
-`kb_id IS NULL` 时那个部分唯一索引不生效(NULL 不参与唯一性判定),系统级告警的去重需要单独处理 —— 实现时用 `COALESCE(kb_id, '00000000-...')` 或一个独立的部分索引。**这是个已知的坑,先记在这里。**
+> **修订记录**:这一节原本是一份草案,含 `subject_ids UUID[]`、`resolved_at`、
+> 以及一个 `WHERE resolved_at IS NULL` 的部分唯一索引。随上面前两条决定一起作废。
+> **不在这里重抄一份 schema** —— 一份和迁移不一致的草案比没有草案更坏。
-**推送**复用现有的 `AppEvent` broadcast(当前只有 `document` / `review` 两种 kind,加一个 `alert`),SSE 通道是现成的。
+真实定义见 [`migrations/0039_alerts.sql`](../../migrations/0039_alerts.sql)。形状是:
+
+- `alerts` 一次故障一行,写完不再改。`subject_id` 是**单列**不是数组 ——
+ 一行只讲一个对象,`detail` 里存一份当时的名字,所以对象被删了这条告警仍然显示得出来。
+- `alert_reads` 两列,逐人。
+- 没有唯一索引,没有 `resolved_at`,没有状态机。
+
+有一个坑草案里记对了,值得留着:**`kb_id IS NULL` 的那些行**。当初打算用
+`WHERE resolved_at IS NULL` 的部分唯一索引做聚合,而 NULL 不参与唯一性判定,
+系统级告警会每次上报插新行 —— 聚合对最需要它的那一类静默失效。
+现在没有唯一索引了所以这个坑不存在,但**同类问题还在别处**:
+`mark_group_read` 里比 `kb_id` 用的是 `IS NOT DISTINCT FROM` 而不是 `=`,
+就是同一件事。
+
+**推送**复用现有的 `AppEvent` broadcast(加了一个 `alert` kind)。
+但 SSE 路由是**按库**的(`/kbs/{id}/events`),而角标跨库、系统级告警根本没有库,
+所以另开了一条全局流 `/alerts/events`。那条流**不带数据也不判权限**:
+收到的人一律回头重取,谁能看见什么由列表查询判且只判一次 ——
+代价是没权限的人也被叫醒一次,换来的是推送这条路上一行权限逻辑都没有。
---
@@ -148,27 +183,55 @@ CREATE TABLE alert_reads (
更要紧的是:**聚合、自愈、per-user 已读这三件最容易设计错的事,只有真有数据经过才验得出来。** 空框架把它们全留到了以后。
+> **这一段被验证了,方式跟预期的不一样**:真有数据经过之后,三件里有两件被证明是错的
+> ——而且都是先照原设计写出来、跑起来才看出来的。要是先建了空框架、
+> 等到有第二第三种告警才接真实数据,这两个设计早就随迁移发出去了。
+
所以第一刀接**两条真实告警源**,各验一条权限路径,且都不需要新的检测逻辑:
-| kind | 级别 | 验证什么 |
-|---|---|---|
-| `source.sync_failed` | KB 级 | 聚合(同源连续失败仍是一条)、自愈(下次成功即消失)、`min_role=editor` |
-| `llm.unreachable` | 系统级 | `kb_id IS NULL` 那条去重路径、`is_admin` 可见性 |
+| kind | 级别 | 验证什么 | 结果 |
+|---|---|---|---|
+| `source.sync_failed` | KB 级 | 聚合、自愈、`min_role=editor` | 聚合改到视图层;自愈作废;权限如设计 |
+| `llm.unreachable` | 系统级 | `kb_id IS NULL` 那条路径、`is_admin` 可见性 | 它没有成功信号,就是这一条逼出了第 2 节的推翻 |
-两条加起来把 schema 的每个字段都跑过一遍真实数据。**如果设计有错,这一刀就会暴露**,而此时改迁移零成本。
+**如果设计有错,这一刀就会暴露** —— 确实暴露了,见上面两条修订记录。
-UI 第一版可以粗:顶栏角标 + 一个列表页,能点进出问题的对象即可。
+`llm.unreachable` 的判据在实现中也放宽过一次:起初只认传输层失败(连不上),
+结果最常见的那种故障——URL 配错、代理挡在中间回了 HTML——**一条告警都不产生**,
+正是"失败无声"本身。现在它的含义是"没能从端点拿到一个能解析的回答":
+连不上,或者连上了但回来的不是这个 API。端点干干净净地回 4xx 不算 ——
+那说明它就是模型 API,只是密钥或配额不对,该找的人不同。
+
+UI:顶栏铃铛 + **弹出面板**,不是页面 —— 告警是顺手瞄一眼的东西,
+做成页面会逼人离开手头的事,而离开的代价就是没人去看。
+未读是一个红点不是数字("有事没看"是二元的,而数字会随重试一路往上跳),
+**点击才算读过,不是划过**(鼠标经过一列告警不代表看过它们,而已读落下就不会自己回来)。
### 留到第二批
-**`document.no_text_layer`(扫描件)** —— 它需要先写检测逻辑(判断解析结果为空),而且真正有用是在有了 OCR 端点之后:那时提示语才完整 ——「12 份文档没有文本层,配置 OCR 端点后可重新处理」,同时是错误说明和功能引导。
+**`document.no_text_layer`(扫描件)** —— 它需要先写检测逻辑(判断解析结果为空),
+而且真正有用是在有了 OCR 端点之后:那时提示语才完整 ——「文档没有文本层,
+配置 OCR 端点后可重新处理」,同时是错误说明和功能引导。
+
+接它的时候**不要再想"什么时候算修好了"**(见第 2 条):一份扫描件解析为空就记一条,
+12 份就是 12 行,面板把连着的折成一行并显示计数。重新处理成功之后不用去清任何东西 ——
+不再有新故障,那些行自己沉下去,到期被保留期清理。
---
## 被否决的方案
-**复用 `audit_events`。** 那张表是"谁做了什么"的台账,性质是不可变记录;告警是"出了什么事",需要状态流转(未读 → 已读 → 已解决)和聚合。塞进同一张表会让台账不再是台账。
+**复用 `audit_events`。** 那张表是"谁做了什么"的台账,性质是不可变记录;告警是"出了什么事",需要 per-user 已读与折叠展示。塞进同一张表会让台账不再是台账。
-**不建表,把六处失败状态 union 起来查询展示。** 零迁移、零新概念,但存不下 per-user 已读,也表达不了自愈语义 —— 而那两件正是这个功能的核心价值。
+> **修订记录**:原文这一条的理由是"告警需要状态流转(未读 → 已读 → 已解决)"。
+> 状态流转那部分随第 2 条作废了 —— 告警行现在也是不可变记录。
+> **但结论不变**,只是理由换了一条:台账记的是人做的事,告警记的是系统出的事,
+> 两者的保留期、可见性规则、读者都不同(告警 30 天到期清理,台账不能清)。
+
+**不建表,把六处失败状态 union 起来查询展示。** 零迁移、零新概念,但存不下 per-user 已读,
+也留不住历史 —— 来源修好之后 `last_sync_status` 就变了,"上周三那次为什么没进来"再也查不到。
**共享已读**。见上文「三个决定」第 3 条。
+
+**存储层聚合**、**自愈 + 探针**、**按 `(kb, kind, subject)` 去重**。
+见第 1、2 条的修订记录 —— 前两个是先建成再拆的,第三个在纸面上就否掉了。
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 4b08034a..441282a2 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -26,7 +26,7 @@
| 0002 | [推理机](0002-reasoning-engine.md) | 规划中 · 取代 0001 P5 的排期 |
| 0003 | [本体从语料里长出来,人站在哪一环](0003-ontology-growth-loop.md) | 已建成 · 含三次判断变化的留痕 |
| 0004 | [语言:哪些字跟着看的人走,哪些跟着语料走](0004-language-and-localization.md) | 已建成 · L0–L3 全部落地 |
-| 0005 | [告警中心](0005-alert-center.md) | 规划中 · 未动工 |
+| 0005 | [告警中心](0005-alert-center.md) | 第一刀已建成 · 三个决定推翻两个(就地留痕) |
## 不放这里的东西
diff --git a/migrations/0041_alerts.sql b/migrations/0041_alerts.sql
new file mode 100644
index 00000000..e55eec9e
--- /dev/null
+++ b/migrations/0041_alerts.sql
@@ -0,0 +1,53 @@
+-- 告警中心(0005)。失败状态此前散在六处:jobs.last_error、documents.status、
+-- documents.graph_status、sources.last_sync_status、source_sync_runs.status、日志。
+-- 每来一类新的失败就往对应的表上加一列——推演层、执行层、OCR、湖仓连接都还没进来。
+--
+-- 真正伤人的不是失败,是**失败无声**:拖 100 份 PDF、12 份是扫描件,
+-- 界面上 100 份全绿。
+
+-- **一次故障一条,写完就不再变。**
+--
+-- 这张表刻意没有状态机:没有"已解决",没有自愈,没有把多次故障并成一行。
+-- 曾经有过,代价是每种新告警都得自己实现一遍"怎么算修好了"——
+-- source.sync_failed 有天然的成功信号,llm.unreachable 没有,就得为它单独造
+-- 一个后台探针;第三种告警要造第三套,而漏写清除编译期看不出来。
+--
+-- 更根本的是**那不是告警中心该回答的问题**:现在还坏不坏,来源页面上写着,
+-- 文档状态里写着。告警的职责是让人去看一眼,不是当实时看板。
+CREATE TABLE alerts (
+ id UUID PRIMARY KEY,
+ -- NULL = 系统级(端点不可达、连接池打满),仅 is_admin 可见
+ kb_id UUID REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ severity TEXT NOT NULL CHECK (severity IN ('info', 'warning', 'error')),
+ -- 'source.sync_failed' / 'llm.unreachable' / ...
+ kind TEXT NOT NULL,
+ -- 存在行上而不是按 kind 硬编码:同一类告警在不同场景下该找的人不同。
+ -- 配置类(端点、配额)找 admin;内容类(解析、抽取、同步)要给到 editor——
+ -- 传那 12 份扫描件的人比管理员更需要知道"你传的东西没进去"
+ min_role TEXT NOT NULL CHECK (min_role IN ('viewer', 'editor', 'admin', 'owner')),
+ -- 出问题的那个对象:document / source / system。系统级的两列都为空
+ subject_type TEXT,
+ subject_id UUID,
+ -- 给人看的那份:名字、报错原文
+ detail JSONB NOT NULL DEFAULT '{}',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- 列表按时间倒序,这是唯一的排序方式
+CREATE INDEX alerts_recent_idx ON alerts (created_at DESC);
+CREATE INDEX alerts_kb_idx ON alerts (kb_id);
+
+-- 已读是各人的。
+--
+-- 被否决的方案是共享已读(任何管理员点开就对所有人标记已读)。失效方式:
+-- 三个管理员,A 早上顺手点开看了一眼没处理,这条从 B、C 的未读里**永远消失**——
+-- 他们不知道发生过这件事,而 A 想着等会儿再说。所有人都以为别人在处理,
+-- 且事后没有任何痕迹能发现漏了。
+--
+-- 告警行写完不再变,所以已读也是一次性的:读过就是读过。
+CREATE TABLE alert_reads (
+ alert_id UUID NOT NULL REFERENCES alerts(id) ON DELETE CASCADE,
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ read_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (alert_id, user_id)
+);
diff --git a/web/src/api.ts b/web/src/api.ts
index bad9fbcb..c0d480d2 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -557,12 +557,56 @@ export interface ConversationMessage {
created_at: string;
}
+/** 告警中心的一组(0005):**连着的、同类的几次故障**。
+ *
+ * 存储那边仍是一次故障一行,折叠在服务端读的时候做——这样翻页数的是组,
+ * 一段连续故障不会被页边界切断。 */
+export type AlertGroup = {
+ kb_id: string | null;
+ /** 系统级告警没有库名 */
+ kb_name: string | null;
+ /** `source.sync_failed` / `llm.unreachable` —— 措辞在 i18n 里按这个查 */
+ kind: string;
+ severity: "info" | "warning" | "error";
+ /** 这一组几次 */
+ count: number;
+ /** 其中我没读过的几次 */
+ unread: number;
+ latest_at: string;
+ /** 跟 latest_at 一起圈出这一组,标已读时原样发回去 */
+ earliest_at: string;
+ /** 明细,最多几条,新的在前 */
+ lines: { name?: string; error?: string; job?: string }[];
+};
+
export const api = {
health: () =>
request<{ status: string; name: string; version: string }>(
"/api/v1/health",
),
me: () => request<User>("/api/v1/auth/me"),
+ alerts: (o: { q?: string; limit?: number; offset?: number }) => {
+ const p = new URLSearchParams();
+ if (o.q?.trim()) p.set("q", o.q.trim());
+ if (o.limit != null) p.set("limit", String(o.limit));
+ if (o.offset) p.set("offset", String(o.offset));
+ return request<{ items: AlertGroup[]; total: number }>(
+ `/api/v1/alerts?${p}`,
+ );
+ },
+ alertsUnread: () => request<{ unread: number }>("/api/v1/alerts/unread"),
+ alertReadGroup: (g: {
+ kb_id: string | null;
+ kind: string;
+ from: string;
+ to: string;
+ }) =>
+ request<{ marked: number }>("/api/v1/alerts/read-group", {
+ method: "POST",
+ body: JSON.stringify(g),
+ }),
+ alertsReadAll: () =>
+ request<{ ok: boolean }>("/api/v1/alerts/read-all", { method: "POST" }),
login: (email: string, password: string) =>
request<{ user: User }>("/api/v1/auth/login", {
method: "POST",
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 29ee0324..9cffc59d 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -121,6 +121,38 @@ export const en = {
searchPlaceholder: "Search the docs…",
noResults: "No matches.",
},
+ // 告警的措辞在客户端,按 kind 查——服务端只发 kind 与 detail,
+ // 不产出展示文案(docs/decisions/0004)
+ alerts: {
+ title: "Alerts",
+ badgeLabel: "Alerts",
+ empty: "Nothing needs attention",
+ emptyHint:
+ "Ingestion, sync and model failures show up here instead of only in the logs.",
+ markAllRead: "Mark all read",
+ close: "Close",
+ // 说清搜的是什么:标题的措辞在客户端,服务端搜不到它,
+ // 所以别让人以为输入 "sync failed" 会有结果
+ searchPlaceholder: "Search sources, knowledge bases, errors",
+ noMatch: "Nothing matches",
+ andMore: (n: number) => `and ${n} more`,
+ system: "System",
+ // kind → 一句说清出了什么事。第二句说该做什么——这才是告警比日志多出来的东西。
+ // **一条告警就是一次故障**,所以标题里没有数量
+ kinds: {
+ "source.sync_failed": {
+ title: "A source failed to sync",
+ hint: "Nothing new came in from it. Check the source's settings.",
+ },
+ "llm.unreachable": {
+ title: "The model endpoint gave no usable answer",
+ hint: "Extraction and embedding are stopped. Check the endpoint URL in system settings.",
+ },
+ } as Record<string, { title: string; hint: string } | undefined>,
+ // 没见过的 kind 也要能显示:新告警源上线时前端可能还没更新
+ unknownKind: (kind: string) => kind,
+ },
+
nav: {
workspaceLabel: "Workspace",
kbLabel: "Knowledge base",
@@ -481,8 +513,10 @@ export const en = {
searchEntity: "Search entities…",
searchInSubgraph: "Search in subgraph…",
backToOverview: "← Full graph",
+ // 顺序不是随便排的:模型没配好之前,上传的文档只会排队等着,
+ // 一个实体也抽不出来。先配模型,再传文档
emptyBody:
- "The graph is empty. Upload documents and configure a chat model in Settings — entities and relations are extracted automatically.",
+ "The graph is empty. Configure a chat model in Settings first, then upload documents in the Library — entities and relations are extracted automatically.",
facts: "facts",
noFacts: "No facts for this entity yet",
confidence: "confidence",
diff --git a/web/src/i18n/index.ts b/web/src/i18n/index.ts
index 7efdb0a5..becdcac5 100644
--- a/web/src/i18n/index.ts
+++ b/web/src/i18n/index.ts
@@ -22,11 +22,13 @@ function detect(): Lang {
const saved = localStorage.getItem(KEY);
if (saved && (LANGS as readonly string[]).includes(saved))
return saved as Lang;
- // 只在首次访问猜一次;人一旦选过就以人选的为准
- if (navigator.language?.toLowerCase().startsWith("zh")) return "zh";
} catch {
// 隐私模式下 localStorage 会抛——回落到英文,别让首屏挂掉
}
+ // **不跟随浏览器语言**。中文包还在跟着英文包后面追,猜错语言的代价是
+ // 一个中文用户看到半成品,而不是看到完整的英文。等 zh 追平了再把
+ // navigator.language 那一句加回来——那是一行代码的事。
+ // 人自己选过的仍然作数(上面那段),切换器照常在用户菜单里
return "en";
}
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 03385be6..a883afe7 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -111,6 +111,30 @@ export const zh: Strings = {
searchPlaceholder: "搜索文档…",
noResults: "没有匹配。",
},
+ alerts: {
+ title: "告警",
+ badgeLabel: "告警",
+ empty: "没有需要处理的",
+ emptyHint: "摄入、同步、模型端点出问题时会出现在这里,而不是只留在日志里。",
+ markAllRead: "全部标为已读",
+ close: "关闭",
+ searchPlaceholder: "搜索来源、知识库、报错",
+ noMatch: "没有匹配的",
+ andMore: (n: number) => `还有 ${n} 条`,
+ system: "系统",
+ kinds: {
+ "source.sync_failed": {
+ title: "来源同步失败",
+ hint: "它没有带进新内容。去来源设置里看一下。",
+ },
+ "llm.unreachable": {
+ title: "模型端点没有给出可用的回答",
+ hint: "抽取与向量化已停摆。去系统设置里检查端点地址。",
+ },
+ } as Record<string, { title: string; hint: string } | undefined>,
+ unknownKind: (kind: string) => kind,
+ },
+
nav: {
workspaceLabel: "工作区",
kbLabel: "知识库",
@@ -458,7 +482,7 @@ export const zh: Strings = {
searchInSubgraph: "在子图中搜索…",
backToOverview: "← 全图",
emptyBody:
- "图谱是空的。上传文档并在「设置」里配置对话模型——实体与关系会被自动抽取。",
+ "图谱是空的。请先在「设置」里配置对话模型,然后在「文库」中上传文档——实体与关系会被自动抽取。",
facts: "条事实",
noFacts: "这个实体还没有事实",
confidence: "置信度",
diff --git a/web/src/pages/AlertBell.tsx b/web/src/pages/AlertBell.tsx
new file mode 100644
index 00000000..a8428551
--- /dev/null
+++ b/web/src/pages/AlertBell.tsx
@@ -0,0 +1,276 @@
+// 顶栏告警(0005):铃铛 + 未读角标 + 弹出面板。
+//
+// **弹窗不是页面**:告警是"顺手瞄一眼"的东西,不是一个要专门去逛的地方。
+// 做成页面会逼人离开手头的事,而离开的代价就是没人去看。
+//
+// 一条告警 = 一次故障,写完不再变,没有"已解决"。
+// 「已读」逐人——一个人读过不代表别人也该从未读里消失。
+import { type Ref, useEffect, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Bell, Search, X } from "lucide-react";
+
+import { api, type AlertGroup } from "../api";
+import { S } from "../i18n";
+import { Chip, Pager, cn } from "../ui";
+import { usePopoverFlip } from "../ui/popoverFlip";
+
+const PAGE = 8;
+
+/** 明细里给人看的那一行:对象名 — 报错原文 */
+function line(d: AlertGroup["lines"][number]): string | null {
+ const parts = [d.name ?? d.job, d.error].filter(Boolean);
+ return parts.length ? parts.join(" — ") : null;
+}
+
+function AlertRow({
+ g,
+ onRead,
+}: {
+ g: AlertGroup;
+ onRead: (g: AlertGroup) => void;
+}) {
+ // 没见过的 kind 也得显示得出来:新告警源上线时前端可能还没跟上,
+ // 而"有条告警但我不认识它"远好过"什么都不显示"
+ const worded = S.alerts.kinds[g.kind];
+ const lines = g.lines.map(line).filter((l): l is string => !!l);
+ // count 数的是整组,lines 只带回前几条——差额是"还有 N 条"
+ const rest = g.count - lines.length;
+ return (
+ <button
+ type="button"
+ // **点击才算读过**,不是划过。鼠标经过一列告警不代表看过它们,
+ // 而已读一旦落下就再也不会自己回来。点一下把这一组整个标掉
+ onClick={() => {
+ if (g.unread > 0) onRead(g);
+ }}
+ className="w-full text-left flex gap-2.5 px-3.5 py-3 border-b border-white/[0.06] last:border-b-0 hover:bg-white/[0.03] transition-colors"
+ >
+ {/* 未读就是一个红点。整行描边或底色会让面板在告警多时变成一片红,
+ 而红点只占它该占的那一点地方,读过就没了 */}
+ <span
+ className={cn(
+ "mt-[7px] h-1.5 w-1.5 rounded-full shrink-0",
+ g.unread > 0 ? "bg-rose-500" : "bg-transparent",
+ )}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <span
+ className={cn(
+ "text-[13px]",
+ g.unread > 0 ? "font-medium text-white" : "text-neutral-400",
+ )}
+ >
+ {worded?.title ?? S.alerts.unknownKind(g.kind)}
+ </span>
+ {g.count > 1 && <Chip tone="neutral">{g.count}</Chip>}
+ <Chip tone={g.kb_name ? "neutral" : "violet"}>
+ {g.kb_name ?? S.alerts.system}
+ </Chip>
+ </div>
+ {worded && (
+ <p className="mt-0.5 text-[11.5px] text-neutral-500">{worded.hint}</p>
+ )}
+ {lines.length > 0 && (
+ <ul className="mt-1 space-y-0.5">
+ {lines.map((l, i) => (
+ <li key={i} className="text-[11px] text-neutral-400 break-words">
+ {l}
+ </li>
+ ))}
+ {rest > 0 && (
+ <li className="text-[11px] text-neutral-600">
+ {S.alerts.andMore(rest)}
+ </li>
+ )}
+ </ul>
+ )}
+ {/* 时间取组里最新的那一次 */}
+ <p className="u-num mt-1.5 text-[10.5px] text-neutral-600">
+ {new Date(g.latest_at).toLocaleString()}
+ </p>
+ </div>
+ </button>
+ );
+}
+
+function Panel({ panelRef }: { panelRef: Ref<HTMLDivElement> }) {
+ const [q, setQ] = useState("");
+ const [page, setPage] = useState(0);
+ const qc = useQueryClient();
+
+ // 搜索后回第一页:停在第 4 页看一个只有 2 页的结果,
+ // 面板会显示空白,而人会读成"没有告警"
+ useEffect(() => {
+ setPage(0);
+ }, [q]);
+
+ const list = useQuery({
+ queryKey: ["alerts", "list", q, page],
+ queryFn: () => api.alerts({ q, limit: PAGE, offset: page * PAGE }),
+ // 翻页时留着上一页,免得面板高度塌一下再弹回来
+ placeholderData: (prev) => prev,
+ });
+
+ const read = useMutation({
+ mutationFn: (g: AlertGroup) =>
+ api.alertReadGroup({
+ kb_id: g.kb_id,
+ kind: g.kind,
+ from: g.earliest_at,
+ to: g.latest_at,
+ }),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["alerts"] }),
+ });
+ const readAll = useMutation({
+ mutationFn: () => api.alertsReadAll(),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["alerts"] }),
+ });
+
+ const groups = list.data?.items ?? [];
+ const total = list.data?.total ?? 0;
+
+ return (
+ // top-0 而不是 top-9:面板要从铃铛**原位**长出来,右上角对齐
+ <div
+ ref={panelRef}
+ className="u-menu-glass absolute right-0 top-0 w-[420px] rounded-xl shadow-2xl z-50 overflow-hidden"
+ >
+ <div className="flex items-center gap-2 pl-3.5 pr-10 py-2.5 border-b border-white/10">
+ <span className="text-[13px] font-medium text-neutral-100">
+ {S.alerts.title}
+ </span>
+ </div>
+
+ {/* 跟文库的过滤框同一套:input-dark + 左侧图标 + 有值时右侧清除、Esc 清空 */}
+ <div className="px-3.5 py-2.5 border-b border-white/[0.06]">
+ <div className="relative">
+ <Search
+ size={13}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none"
+ />
+ <input
+ className="input-dark w-full pl-8 pr-7 py-1.5 text-[13px]"
+ placeholder={S.alerts.searchPlaceholder}
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ onKeyDown={(e) => e.key === "Escape" && setQ("")}
+ />
+ {q && (
+ <button
+ onClick={() => setQ("")}
+ className="absolute right-2 top-1/2 -translate-y-1/2 text-neutral-500 hover:text-neutral-200"
+ >
+ <X size={12} />
+ </button>
+ )}
+ </div>
+ </div>
+
+ <div className="max-h-[420px] overflow-y-auto">
+ {groups.length === 0 ? (
+ <div className="px-3.5 py-8 text-center">
+ <p className="text-[13px] text-neutral-300">
+ {q ? S.alerts.noMatch : S.alerts.empty}
+ </p>
+ {!q && (
+ <p className="mt-1 text-[11.5px] text-neutral-500">
+ {S.alerts.emptyHint}
+ </p>
+ )}
+ </div>
+ ) : (
+ groups.map((g) => (
+ <AlertRow
+ key={`${g.kb_id ?? "system"}|${g.kind}|${g.latest_at}`}
+ g={g}
+ onRead={(x) => read.mutate(x)}
+ />
+ ))
+ )}
+ </div>
+
+ {/* 底栏:整张列表级的动作跟翻页放一起,离光标最远 */}
+ {groups.length > 0 && (
+ <div className="flex items-center gap-3 px-3.5 py-2 border-t border-white/[0.06]">
+ {groups.some((g) => g.unread > 0) && (
+ <button
+ className="text-[11.5px] text-neutral-500 hover:text-neutral-200 transition-colors"
+ onClick={() => readAll.mutate()}
+ >
+ {S.alerts.markAllRead}
+ </button>
+ )}
+ <Pager
+ className="ml-auto"
+ total={total}
+ pageSize={PAGE}
+ page={page}
+ onPage={setPage}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function AlertBell() {
+ // 跟用户菜单同一份原地变形:两个面板紧挨着,动画差一点点来回点两下就看得出来
+ const { open, setOpen, close, rootRef, anchorRef, panelRef } =
+ usePopoverFlip<HTMLButtonElement, HTMLDivElement>();
+ const unread = useQuery({
+ queryKey: ["alerts", "unread"],
+ queryFn: () => api.alertsUnread(),
+ // 推送是主路,这个只是断流时的兜底
+ refetchInterval: 120_000,
+ });
+ const n = unread.data?.unread ?? 0;
+
+ return (
+ <div ref={rootRef} className="relative">
+ <button
+ ref={anchorRef}
+ onClick={() => (open ? close() : setOpen(true))}
+ title={S.alerts.badgeLabel}
+ aria-label={S.alerts.badgeLabel}
+ aria-expanded={open}
+ // h-7 w-7 正方形:只装一个图标的按钮不该是长方形。
+ // 关闭按钮用同一组尺寸绝对定位在面板的 right-0 top-0,两者严丝合缝
+ className={cn(
+ "relative grid h-7 w-7 place-items-center rounded-lg transition-colors",
+ open
+ ? "text-neutral-200 bg-white/[0.06]"
+ : "text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05]",
+ )}
+ >
+ <Bell size={15} />
+ {/* 角标也是个点,不是数字。"有事没看"是二元的,具体几条打开就知道;
+ 数字还会随重试一路往上跳,跳到三位数就把铃铛撑变形了 */}
+ {n > 0 && (
+ <span className="absolute top-1 right-1 h-1.5 w-1.5 rounded-full bg-rose-500" />
+ )}
+ </button>
+ {open && (
+ <>
+ <Panel panelRef={panelRef} />
+ {/* 关闭按钮是面板的**兄弟**,不是它的孩子:放里面的话 `right-0 top-0`
+ 相对的是面板的内边距盒,而 u-menu-glass 有一条 0.667px 的发丝边框
+ (DPR 1.5 上的一个物理像素),永远差那么一点。放在这里,定位祖先
+ 就是裹着铃铛的这个 div,跟铃铛同一个盒子——重合是构造出来的。
+
+ 光标点开面板之后正停在这个位置,所以这儿必须是"再点一下关掉"。
+ 放"全部标为已读"等于把误触做成默认动作,而它一下清掉的是
+ 所有库的所有告警 */}
+ <button
+ onClick={close}
+ title={S.alerts.close}
+ aria-label={S.alerts.close}
+ className="absolute right-0 top-0 z-[60] grid h-7 w-7 place-items-center rounded-lg text-neutral-500 hover:text-neutral-200 transition-colors"
+ >
+ <X size={15} />
+ </button>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index c8559bf7..ae7a9539 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -883,10 +883,9 @@ export function Graph() {
{empty && (
<div className="absolute inset-0 grid place-items-center pointer-events-none">
+ {/* 不放标题方块:页面本身就是图谱页,tab 条上也写着,
+ 第三遍写"图谱"两个字不带任何信息。空状态该说的是下一步做什么 */}
<div className="text-center text-sm text-neutral-500 max-w-xs">
- <div className="glass mx-auto mb-3 h-14 w-14 rounded-2xl grid place-items-center text-lg font-bold text-neutral-300">
- {S.nav.graph}
- </div>
{S.graph.emptyBody}
</div>
</div>
diff --git a/web/src/pages/Shell.tsx b/web/src/pages/Shell.tsx
index 7e3513c0..51bb07a3 100644
--- a/web/src/pages/Shell.tsx
+++ b/web/src/pages/Shell.tsx
@@ -14,8 +14,10 @@ import { api, ApiError } from "../api";
import { S } from "../i18n";
import { useKb } from "../kb";
import { Dropdown, GithubMark, Wordmark } from "../ui";
+import { AlertBell } from "./AlertBell";
import { UserMenu } from "./UserMenu";
import { ServerDown } from "./ServerDown";
+import { useAlertEvents } from "../useAlertEvents";
import { useKbEvents } from "../useKbEvents";
import { usePageTitle } from "../useTitle";
@@ -45,6 +47,8 @@ export function Shell() {
usePageTitle(S.app.name, tabLabel);
// 全局唯一的 KB 事件流连接:文档/审核状态实时刷新(替轮询)
useKbEvents(kb?.id);
+ // 告警流是全局的:角标跨库,而系统级告警根本没有库
+ useAlertEvents();
if (me.isPending) {
return (
@@ -83,31 +87,39 @@ export function Shell() {
onChange={setKb}
options={kbs.map((k) => ({ value: k.id, label: k.name }))}
/>
- <div className="ml-auto flex items-center gap-1.5">
+ {/* 三组:项目入口 / 告警 / 身份。**组间 gap-3,组内 gap-1.5**——
+ 间距由结构表达,而不是给某一个元素补一次性的 ml。
+ 此前用户菜单挂着一个 ml-1.5(当初它紧挨 GitHub 胶囊时调的),
+ 铃铛插进两者之间以后就成了左 6px 右 12px */}
+ <div className="ml-auto flex items-center gap-3">
{/* 项目入口:Docs + [GitHub·版本] 胶囊(版本取自后端 health,与部署一致)。
- 版本并入 GitHub 胶囊:两个等高元素,视觉平衡 */}
- <Link
- to="/docs"
- className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
- >
- {S.nav.docs}
- </Link>
- <a
- href={S.login.githubUrl}
- target="_blank"
- rel="noreferrer"
- title="GitHub"
- className="flex items-center gap-1.5 rounded-full border border-white/10 px-2.5 py-1 text-neutral-500 hover:text-neutral-200 hover:border-white/25 transition-colors"
- >
- <GithubMark size={13} />
- {health.data && (
- <span className="u-num text-[11px]">v{health.data.version}</span>
- )}
- </a>
- {/* 用户菜单:个人信息 / 系统管理(仅管理员)/ 登出 */}
- <div className="ml-1.5">
- <UserMenu user={me.data} />
+ 版本并入 GitHub 胶囊:两个等高元素,视觉平衡。
+ 这两个是一对,所以彼此贴得比组间近 */}
+ <div className="flex items-center gap-1.5">
+ <Link
+ to="/docs"
+ className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
+ >
+ {S.nav.docs}
+ </Link>
+ <a
+ href={S.login.githubUrl}
+ target="_blank"
+ rel="noreferrer"
+ title="GitHub"
+ className="flex items-center gap-1.5 rounded-full border border-white/10 px-2.5 py-1 text-neutral-500 hover:text-neutral-200 hover:border-white/25 transition-colors"
+ >
+ <GithubMark size={13} />
+ {health.data && (
+ <span className="u-num text-[11px]">v{health.data.version}</span>
+ )}
+ </a>
</div>
+ {/* 告警角标:跨库的未读数。失败此前只留在日志与 jobs.last_error 里,
+ 界面上一份文档也不会变颜色(0005) */}
+ <AlertBell />
+ {/* 用户菜单:个人信息 / 系统管理(仅管理员)/ 登出 */}
+ <UserMenu user={me.data} />
</div>
</header>
diff --git a/web/src/pages/UserMenu.tsx b/web/src/pages/UserMenu.tsx
index c0fd1d5c..36fda419 100644
--- a/web/src/pages/UserMenu.tsx
+++ b/web/src/pages/UserMenu.tsx
@@ -1,6 +1,5 @@
/* 用户菜单:顶栏右侧的头像胶囊 + 弹出面板(个人信息 / 系统管理 / 登出)。
Shell(KB 工作区)与 AccountShell(账户层)共用。 */
-import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import {
@@ -12,6 +11,7 @@ import {
UserRound,
} from "lucide-react";
import { api, type User } from "../api";
+import { usePopoverFlip } from "../ui/popoverFlip";
import { LANGS, LANG_NAMES, S, lang, setLang } from "../i18n";
/** 首字母头像:中性灰底(chrome 零色偏),拉丁取词首两枚,CJK 取前两字。 */
@@ -33,86 +33,13 @@ export function Avatar({ name, size = 24 }: { name: string; size?: number }) {
}
export function UserMenu({ user }: { user: User }) {
- const [open, setOpen] = useState(false);
- const rootRef = useRef<HTMLDivElement>(null);
- const chipRef = useRef<HTMLButtonElement>(null);
- const panelRef = useRef<HTMLDivElement>(null);
+ // 原地变形(FLIP):胶囊"长成"面板。实现共用,见 ui/popoverFlip——
+ // 告警铃铛就在旁边,两处各写一遍迟早会差出一点点
+ const { open, setOpen, close, rootRef, anchorRef, panelRef } =
+ usePopoverFlip<HTMLButtonElement, HTMLDivElement>();
const navigate = useNavigate();
const queryClient = useQueryClient();
- // 原地变形(FLIP):面板盖在胶囊原位,首帧压到胶囊的真实边界
- //(右上角对齐,圆角 999px),下一帧过渡到面板全形——胶囊"长成"面板
- useLayoutEffect(() => {
- if (!open) return;
- const panel = panelRef.current;
- const chip = chipRef.current;
- if (!panel || !chip) return;
- if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
- const c = chip.getBoundingClientRect();
- const p = panel.getBoundingClientRect();
- if (p.width < 1 || p.height < 1) return;
- panel.style.transformOrigin = "top right";
- panel.style.transform = `scale(${c.width / p.width}, ${c.height / p.height})`;
- panel.style.borderRadius = "999px";
- panel.style.opacity = "0.35";
- const raf = requestAnimationFrame(() =>
- requestAnimationFrame(() => {
- panel.style.transition =
- "transform 0.26s cubic-bezier(0.16,1,0.3,1), border-radius 0.26s cubic-bezier(0.16,1,0.3,1), opacity 0.18s ease";
- panel.style.transform = "scale(1, 1)";
- panel.style.borderRadius = "12px";
- panel.style.opacity = "1";
- }),
- );
- return () => cancelAnimationFrame(raf);
- }, [open]);
-
- // 反向变形收回:面板缩回胶囊边界后再卸载(导航等即时场景直接关)
- const closingRef = useRef(false);
- const close = () => {
- const panel = panelRef.current;
- const chip = chipRef.current;
- if (closingRef.current) return;
- if (
- !panel ||
- !chip ||
- window.matchMedia("(prefers-reduced-motion: reduce)").matches
- ) {
- setOpen(false);
- return;
- }
- closingRef.current = true;
- const c = chip.getBoundingClientRect();
- // offsetWidth/Height:布局尺寸,不受当前 transform 影响
- panel.style.transition =
- "transform 0.2s cubic-bezier(0.5,0,0.9,0.4), border-radius 0.2s cubic-bezier(0.5,0,0.9,0.4), opacity 0.16s ease";
- panel.style.transform = `scale(${c.width / panel.offsetWidth}, ${c.height / panel.offsetHeight})`;
- panel.style.borderRadius = "999px";
- panel.style.opacity = "0.3";
- window.setTimeout(() => {
- closingRef.current = false;
- setOpen(false);
- }, 190);
- };
-
- useEffect(() => {
- if (!open) return;
- const onDown = (e: MouseEvent) => {
- if (rootRef.current && !rootRef.current.contains(e.target as Node))
- close();
- };
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") close();
- };
- document.addEventListener("mousedown", onDown);
- document.addEventListener("keydown", onKey);
- return () => {
- document.removeEventListener("mousedown", onDown);
- document.removeEventListener("keydown", onKey);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [open]);
-
const go = (to: string) => {
setOpen(false);
navigate({ to });
@@ -131,7 +58,7 @@ export function UserMenu({ user }: { user: User }) {
return (
<div ref={rootRef} className="relative">
<button
- ref={chipRef}
+ ref={anchorRef}
onClick={() => setOpen((v) => !v)}
className={`flex items-center gap-2 rounded-full py-1 pl-1 pr-3 transition-[background-color,opacity] duration-150 ${
open ? "opacity-0" : "hover:bg-white/[0.06]"
diff --git a/web/src/ui/index.tsx b/web/src/ui/index.tsx
index bf5f06bb..6d340c42 100644
--- a/web/src/ui/index.tsx
+++ b/web/src/ui/index.tsx
@@ -634,17 +634,21 @@ export function Pager({
pageSize,
page,
onPage,
+ /** 覆盖默认的上边距。默认 `mt-3` 适合跟在列表后面;
+ 放进一个已经有内边距的底栏时传 `""` 去掉它 */
+ className = "mt-3",
}: {
total: number;
pageSize: number;
page: number;
onPage: (p: number) => void;
+ className?: string;
}) {
const pageCount = Math.max(1, Math.ceil(total / pageSize));
const safe = Math.min(page, pageCount - 1);
if (total <= pageSize) return null;
return (
- <div className="mt-3 flex items-center justify-end gap-2 text-xs text-neutral-500">
+ <div className={cn("flex items-center justify-end gap-2 text-xs text-neutral-500", className)}>
<span className="u-num">
{S.library.pageOf(
safe * pageSize + 1,
diff --git a/web/src/ui/popoverFlip.ts b/web/src/ui/popoverFlip.ts
new file mode 100644
index 00000000..95d9f1fa
--- /dev/null
+++ b/web/src/ui/popoverFlip.ts
@@ -0,0 +1,107 @@
+// 顶栏弹出面板的"原地变形"(FLIP):面板盖在触发按钮原位,首帧压到按钮的
+// 真实边界(圆角 999px),下一帧过渡到面板全形——按钮"长成"面板;关闭时反向缩回。
+//
+// **抽成一份共用**,而不是让用户菜单和告警各写一遍:这两个面板紧挨着,
+// 时长或缓动差一点点,来回点两下就看得出来。
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+
+const OPEN_MS = 260;
+const CLOSE_MS = 190;
+
+function reduced(): boolean {
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+}
+
+/**
+ * 返回 `{ open, setOpen, close, anchorRef, panelRef }`。
+ *
+ * `close()` 会先播收回动画再卸载;要立刻关(比如导航走了)直接 `setOpen(false)`。
+ * 面板外点击与 Esc 已经接好,挂在 `rootRef` 上。
+ */
+export function usePopoverFlip<A extends HTMLElement, P extends HTMLElement>() {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const anchorRef = useRef<A>(null);
+ const panelRef = useRef<P>(null);
+ const closingRef = useRef(false);
+
+ useLayoutEffect(() => {
+ if (!open) return;
+ const panel = panelRef.current;
+ const anchor = anchorRef.current;
+ if (!panel || !anchor || reduced()) return;
+ const a = anchor.getBoundingClientRect();
+ const p = panel.getBoundingClientRect();
+ if (p.width < 1 || p.height < 1) return;
+ panel.style.transformOrigin = "top right";
+ panel.style.transform = `scale(${a.width / p.width}, ${a.height / p.height})`;
+ panel.style.borderRadius = "999px";
+ panel.style.opacity = "0.35";
+ let done: number | undefined;
+ const raf = requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ panel.style.transition = `transform ${OPEN_MS}ms cubic-bezier(0.16,1,0.3,1), border-radius ${OPEN_MS}ms cubic-bezier(0.16,1,0.3,1), opacity 0.18s ease`;
+ panel.style.transform = "scale(1, 1)";
+ panel.style.borderRadius = "12px";
+ panel.style.opacity = "1";
+ // 动画完把行内样式**清干净**,别留一个 `scale(1,1)`。
+ // 恒等变换看着无害,但它照样生成合成层,于是面板里绝对定位的子元素
+ // 会按设备像素吸附一次——在 DPR 1.5 上就是 0.67px 的偏移,
+ // 而关闭按钮要跟触发它的那个按钮**原位重合**,差一个物理像素也看得出来
+ done = window.setTimeout(() => {
+ panel.style.transition = "";
+ panel.style.transform = "";
+ panel.style.borderRadius = "";
+ panel.style.opacity = "";
+ panel.style.transformOrigin = "";
+ }, OPEN_MS + 20);
+ }),
+ );
+ return () => {
+ cancelAnimationFrame(raf);
+ if (done !== undefined) window.clearTimeout(done);
+ };
+ }, [open]);
+
+ const close = () => {
+ const panel = panelRef.current;
+ const anchor = anchorRef.current;
+ if (closingRef.current) return;
+ if (!panel || !anchor || reduced()) {
+ setOpen(false);
+ return;
+ }
+ closingRef.current = true;
+ const a = anchor.getBoundingClientRect();
+ // offsetWidth/Height 是布局尺寸,不受当前 transform 影响——
+ // 用 getBoundingClientRect 会拿到已经缩过的值,越缩越小
+ panel.style.transition = `transform ${CLOSE_MS}ms cubic-bezier(0.5,0,0.9,0.4), border-radius ${CLOSE_MS}ms cubic-bezier(0.5,0,0.9,0.4), opacity 0.16s ease`;
+ panel.style.transform = `scale(${a.width / panel.offsetWidth}, ${a.height / panel.offsetHeight})`;
+ panel.style.borderRadius = "999px";
+ panel.style.opacity = "0.3";
+ window.setTimeout(() => {
+ closingRef.current = false;
+ setOpen(false);
+ }, CLOSE_MS);
+ };
+
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => {
+ if (rootRef.current && !rootRef.current.contains(e.target as Node))
+ close();
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") close();
+ };
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ return { open, setOpen, close, rootRef, anchorRef, panelRef };
+}
diff --git a/web/src/useAlertEvents.ts b/web/src/useAlertEvents.ts
new file mode 100644
index 00000000..a9222806
--- /dev/null
+++ b/web/src/useAlertEvents.ts
@@ -0,0 +1,17 @@
+// 告警事件订阅。**全局,不按库**——顶栏角标是跨库的,而系统级告警根本没有库。
+//
+// 服务端推的那条不带任何数据也不判权限(见 alerts_routes::stream):收到就重取,
+// 谁能看见什么由列表查询说了算。所以这里也不需要知道当前是哪个库。
+import { useEffect } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+
+export function useAlertEvents() {
+ const queryClient = useQueryClient();
+ useEffect(() => {
+ const es = new EventSource("/api/v1/alerts/events");
+ es.addEventListener("alert", () => {
+ queryClient.invalidateQueries({ queryKey: ["alerts"] });
+ });
+ return () => es.close();
+ }, [queryClient]);
+}