Skip to content

World's first open-source enterprise world model.

The interface speaks Chinese, and the ontology speaks whatever your documents speak (#56)

WaylandYangbb7f74740da3
diff --git a/crates/utopia-core/src/error.rs b/crates/utopia-core/src/error.rs
index 759d640f..4d897bbd 100644
--- a/crates/utopia-core/src/error.rs
+++ b/crates/utopia-core/src/error.rs
@@ -10,10 +10,43 @@ pub enum AppError {
Conflict(String),
#[error("{0}")]
Validation(String),
+ /// 带稳定 code 的校验错误。**message 仍是英文原句**——它是给不做本地化的
+ /// 客户端(MCP、CLI)与日志用的;界面拿 code 去 i18n 里查措辞。
+ ///
+ /// 界面语言在客户端之后,后端不再拥有 locale(见 docs/decisions/0004),
+ /// 所以留在这里的字符串是永久英文。用户能撞到的都该带上 code。
+ #[error("{message}")]
+ Invalid {
+ code: &'static str,
+ message: String,
+ /// 机器给的补充(cron 解析器的报错之类)。措辞归界面,细节归这里
+ detail: Option<String>,
+ },
#[error(transparent)]
Db(#[from] sqlx::Error),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
+impl AppError {
+ pub fn invalid(code: &'static str, message: impl Into<String>) -> Self {
+ AppError::Invalid {
+ code,
+ message: message.into(),
+ detail: None,
+ }
+ }
+ pub fn invalid_detail(
+ code: &'static str,
+ message: impl Into<String>,
+ detail: impl Into<String>,
+ ) -> Self {
+ AppError::Invalid {
+ code,
+ message: message.into(),
+ detail: Some(detail.into()),
+ }
+ }
+}
+
pub type AppResult<T> = Result<T, AppError>;
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 24b2086b..75a1f744 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -628,6 +628,10 @@ pub struct KnowledgeBase {
/// 缺省开——新库的十个默认关系不是任何人选的,等人手工补齐之前图基本没法用。
/// 关掉不影响"留意":未匹配统计照常累积、照常可见,只是变成你点一下的提案。
pub auto_extend_ontology: bool,
+ /// 内置本体按哪种语言播种,以及新的类/关系描述写成哪种语言(`en` | `zh`)。
+ /// **跟语料走,不跟界面走**——description 的读者是正在读这些文档的模型。
+ /// 见 docs/decisions/0004。
+ pub ontology_lang: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs
index 999a0564..f3296307 100644
--- a/crates/utopia-extract/src/lib.rs
+++ b/crates/utopia-extract/src/lib.rs
@@ -50,8 +50,16 @@ pub fn build_messages(
attributes: &[String],
doc_time: Option<&str>,
filename: &str,
+ // 本文档前面几块已经认下的 (类型 key, 实体名),按首次出现排序。
+ // 第一块为空——那时还没有"前面"
+ known: &[(String, String)],
chunk_text: &str,
) -> Vec<ChatMessage> {
+ // **有描述时不送 label**。label 是给人看的显示名,而且它跟界面无关、
+ // 跟这个库的语料语言走——中文库里 person 的 label 是"人物"。
+ // `- person (人物): 有名有姓的具体的人…` 里那个"人物"相对 key 近乎零信息量,
+ // 却让提示词在语料语言与标识符之间来回跳。描述为空时才拿它兜底:
+ // 光一个 key 太单薄。见 docs/decisions/0004
let fmt_list = |items: &[(String, String, String)]| {
items
.iter()
@@ -60,7 +68,7 @@ pub fn build_messages(
if d.is_empty() {
format!("- {k} ({l})")
} else {
- format!("- {k} ({l}): {d}")
+ format!("- {k}: {d}")
}
})
.collect::<Vec<_>>()
@@ -115,7 +123,10 @@ pub fn build_messages(
\n\
Rules:\n\
1. Use the canonical full name as written in the text, in the text's original language; \
- list each entity once.\n\
+ list each entity once. Text introduces a full name and then shortens it — \
+ \"星云科技上海研究院\" becomes \"上海研究院\", \"Nebula Technologies Inc.\" becomes \
+ \"Nebula\" — and both forms mean one entity, listed once under the fuller form. \
+ Two names are two entities only when the text is talking about two things.\n\
2. Every fact's subject/object must appear in entities.\n\
3. Dates must be \"YYYY\", \"YYYY-MM\", \"YYYY-MM-DD\", or null. If a relation is still \
ongoing, valid_to is null. If the text states no date, use null — never invent dates.\n\
@@ -133,7 +144,11 @@ pub fn build_messages(
{attr_rules}"
);
- let user = format!("Source file: \"{filename}\"\n\nText:\n{chunk_text}");
+ // 已知实体紧挨着正文:服从性靠位置,理由见 known_block 的注释
+ let user = format!(
+ "Source file: \"{filename}\"\n{}\nText:\n{chunk_text}",
+ known_block(known)
+ );
vec![
ChatMessage {
@@ -147,6 +162,60 @@ pub fn build_messages(
]
}
+/// 已在本文档中出现过的实体,放进提示词的字符预算。
+///
+/// 超出就截断(保留先出现的)。中文商业文本先出全称、主角先出场,所以
+/// **首次出现顺序天然偏向那些后面会被简称的名字**。
+const KNOWN_BUDGET_CHARS: usize = 1200;
+
+/// 把「本文档已经认下的实体」排版成提示词里的一段。空则返回空串。
+///
+/// **为什么在正文之前、指令贴着清单**:抽象规则打不过挨着它的具体块——本体建议
+/// 那次,语言要求就输给了紧随其后的英文 JSON 骨架,挪到骨架之后并点名它才生效。
+/// 服从性靠位置,所以指令挨着它管的数据放,两者一起挨着正文。
+///
+/// **顺带一条与放哪条消息无关的规矩:逐块变化的内容一律放最后。** 前缀缓存匹配的是
+/// token 前缀,而消息按 system→user 拼接,所以「system 末尾」与「user 开头」几乎等价;
+/// 真正会打碎缓存的是把它塞在**中间**(本体之后、规则之前),那会把规则挤出前缀。
+/// 缓存本身不归我们管——供应商开不开、报不报都由它,本部署实测 `cached=0`——
+/// 我们只负责别把它弄碎。自部署 vLLM 默认开着自动前缀缓存,那省的是算力不是钱。
+fn known_block(known: &[(String, String)]) -> String {
+ if known.is_empty() {
+ return String::new();
+ }
+ // 按类型分组:更紧凑,而且顺带压住跨块类型漂移
+ //(同一个"沧海"在一块里是 product、另一块里是 project)
+ let mut by_type: Vec<(&str, Vec<&str>)> = Vec::new();
+ let mut used = 0usize;
+ for (type_key, name) in known {
+ used += name.chars().count() + 2;
+ if used > KNOWN_BUDGET_CHARS {
+ break;
+ }
+ match by_type.iter_mut().find(|(k, _)| *k == type_key.as_str()) {
+ Some((_, names)) => names.push(name),
+ None => by_type.push((type_key, vec![name])),
+ }
+ }
+ if by_type.is_empty() {
+ return String::new();
+ }
+ let lines = by_type
+ .iter()
+ .map(|(k, names)| format!(" {k}: {}", names.join(", ")))
+ .collect::<Vec<_>>()
+ .join("\n");
+ format!(
+ "\nAlready recorded from earlier parts of this same document:\n{lines}\n\
+ \n\
+ If something in the text below refers to one of these, write that exact string as \
+ the name, and give it that same type — documents abbreviate after first mention \
+ (\"星云科技上海研究院\" later becomes \"上海研究院\"), and the shortened form must \
+ not become a second entity. If it is a different thing, name it as the text does; \
+ do not force it onto this list.\n"
+ )
+}
+
/// 从 LLM 回复中稳健地取出 JSON 块(容忍代码围栏与前后废话)。
pub fn json_block(raw: &str) -> anyhow::Result<String> {
let text = raw.trim();
@@ -211,6 +280,14 @@ pub fn build_adjudication_messages(pairs: &[AdjudicationPair]) -> Vec<ChatMessag
Contradictory affiliations in overlapping time periods indicate different entities \
(but people do change jobs — non-overlapping periods can belong to one person).\n\
\n\
+ One name containing the other is a different case, and the rule above does not apply \
+ to it: \"星云科技上海研究院\" against \"上海研究院\", \"Nebula Technologies Inc.\" \
+ against \"Nebula\". Documents drop the qualifier after first mention, so the shorter \
+ form is usually the longer one abbreviated — treat the containment as evidence FOR \
+ sameness and let the facts settle it. Shared people, parent or location confirm one \
+ entity; a different parent or conflicting leadership means the shorter name belongs \
+ to something else.\n\
+ \n\
Output exactly one JSON object and nothing else:\n\
{\"verdicts\":[{\"i\":0,\"verdict\":\"same|different|unsure\",\"confidence\":0.9}]}\n\
\n\
@@ -326,6 +403,67 @@ pub fn parse_time(s: &str) -> Option<(DateTime<Utc>, &'static str)> {
None
}
+#[cfg(test)]
+mod prompt_shape_tests {
+ use super::*;
+
+ /// 已知实体必须落在 **user** 消息里、紧挨着正文。
+ ///
+ /// 理由是服从性不是缓存:抽象规则打不过挨着它的具体块。清单放进 system 的
+ /// 规则区,就会隔着输出格式、十条规则、文件名,离它要管的正文最远。
+ #[test]
+ fn known_entities_stay_out_of_the_system_message() {
+ // 用一个规则 1 的例子里没有的名字:规则 1 也提"星云科技上海研究院",
+ // 拿它断言等于测不出清单到底在哪条消息里
+ let known = vec![(
+ "organization".to_string(),
+ "华瑞集团智能制造研究院".to_string(),
+ )];
+ let msgs = build_messages(&[], &[], &[], None, "a.txt", &known, "text");
+ assert_eq!(msgs[0].role, "system");
+ assert!(!msgs[0].content.contains("Already recorded"));
+ assert!(!msgs[0].content.contains("华瑞集团智能制造研究院"));
+ assert!(msgs[1]
+ .content
+ .contains("organization: 华瑞集团智能制造研究院"));
+ }
+
+ /// 第一块没有"前面",那一段应当完全不出现——成本为零,而不是一段空标题
+ #[test]
+ fn the_first_chunk_carries_no_block() {
+ let msgs = build_messages(&[], &[], &[], None, "a.txt", &[], "text");
+ assert!(!msgs[1].content.contains("Already recorded"));
+ }
+
+ /// 反向护栏必须在:给了参照物就会有人硬套(`concept` 那次的教训)
+ #[test]
+ fn the_block_tells_the_model_not_to_force_a_match() {
+ let known = vec![("person".to_string(), "陈立".to_string())];
+ let msgs = build_messages(&[], &[], &[], None, "a.txt", &known, "text");
+ assert!(msgs[1].content.contains("do not force it onto this list"));
+ }
+
+ /// 有描述就不送 label——中文库的 label 是中文,混进提示词只会让
+ /// 标识符与语料语言来回跳,而它相对 key 近乎零信息量。
+ #[test]
+ fn described_types_drop_the_label() {
+ let types = vec![
+ (
+ "person".into(),
+ "人物".into(),
+ "有名有姓的具体的人。".into(),
+ ),
+ ("event".into(), "事件".into(), String::new()),
+ ];
+ let msgs = build_messages(&types, &[], &[], None, "a.txt", &[], "text");
+ let prompt = format!("{:?}", msgs);
+ assert!(prompt.contains("- person: 有名有姓的具体的人。"));
+ assert!(!prompt.contains("person (人物)"));
+ // 描述为空时 label 仍是唯一的额外线索,留着
+ assert!(prompt.contains("- event (事件)"));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/utopia-llm/src/lib.rs b/crates/utopia-llm/src/lib.rs
index 3d3670c8..a3045d06 100644
--- a/crates/utopia-llm/src/lib.rs
+++ b/crates/utopia-llm/src/lib.rs
@@ -98,6 +98,7 @@ impl LlmClient {
if !status.is_success() {
anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body));
}
+ log_usage(&self.model, &body);
body["choices"][0]["message"]["content"]
.as_str()
.map(String::from)
@@ -332,6 +333,30 @@ impl LlmClient {
}
}
+/// 记一次调用的 token 开销。**缓存命中数是这里最重要的一列**:抽取靠
+/// "system 消息在一篇文档内逐块完全相同" 吃供应商的前缀缓存,
+/// 往 system 里塞逐块变化的内容会让它悄悄归零——只有这个数看得见。
+///
+/// 字段名各家不一:OpenAI 用 prompt_tokens_details.cached_tokens,
+/// DeepSeek 用 prompt_cache_hit_tokens。两个都读,谁在读谁。
+fn log_usage(model: &str, body: &serde_json::Value) {
+ let u = &body["usage"];
+ if u.is_null() {
+ return;
+ }
+ let n = |k: &str| u[k].as_u64();
+ let cached = u["prompt_tokens_details"]["cached_tokens"]
+ .as_u64()
+ .or_else(|| n("prompt_cache_hit_tokens"));
+ tracing::info!(
+ model,
+ prompt = n("prompt_tokens"),
+ completion = n("completion_tokens"),
+ cached,
+ "llm usage"
+ );
+}
+
fn err_detail(body: &serde_json::Value) -> String {
body["error"]["message"]
.as_str()
diff --git a/crates/utopia-server/src/adjudication.rs b/crates/utopia-server/src/adjudication.rs
index 685a1b07..9da41b81 100644
--- a/crates/utopia-server/src/adjudication.rs
+++ b/crates/utopia-server/src/adjudication.rs
@@ -45,12 +45,8 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul
let items =
utopia_store::resolution::pending_adjudications(&state.pool, kb_id, 500).await?;
for item in items {
- utopia_store::resolution::escalate_review(
- &state.pool,
- item.id,
- "chat model not configured — needs human review",
- )
- .await?;
+ utopia_store::resolution::escalate_review(&state.pool, item.id, "escalate_no_model")
+ .await?;
}
state.emit_review(kb_id);
return Ok(());
@@ -130,7 +126,7 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul
utopia_store::resolution::escalate_review(
&state.pool,
item.id,
- "adjudicator returned no verdict — needs human review",
+ "escalate_no_verdict",
)
.await?;
}
@@ -155,7 +151,7 @@ async fn apply_verdict(
let (target, source) =
utopia_store::resolution::merge_direction(&state.pool, item.left.id, item.right.id)
.await?;
- let reason = format!("auto-merge: {via} same (confidence {conf:.2})");
+ let reason = format!("auto_merged|{via} {conf:.2}");
match utopia_store::resolution::merge_entities(
&state.pool,
kb_id,
@@ -194,7 +190,7 @@ async fn apply_verdict(
utopia_store::resolution::escalate_review(
&state.pool,
item.id,
- "entity changed during adjudication — needs human review",
+ "escalate_entity_changed",
)
.await?;
}
@@ -206,7 +202,7 @@ async fn apply_verdict(
&state.pool,
item.id,
"kept",
- &format!("{via} different (confidence {conf:.2})"),
+ &format!("kept_apart|{via} {conf:.2}"),
)
.await?;
let _ = utopia_store::audit::record_opt(
@@ -227,7 +223,7 @@ async fn apply_verdict(
utopia_store::resolution::escalate_review(
&state.pool,
item.id,
- &format!("{via} unsure (confidence {conf:.2}) — needs human review"),
+ &format!("escalate_unsure|{via} {conf:.2}"),
)
.await?;
}
diff --git a/crates/utopia-server/src/api/admin_routes.rs b/crates/utopia-server/src/api/admin_routes.rs
index 7ef007a3..5979e312 100644
--- a/crates/utopia-server/src/api/admin_routes.rs
+++ b/crates/utopia-server/src/api/admin_routes.rs
@@ -26,11 +26,13 @@ pub async fn get_deployment(
require_admin(&user)?;
let open = utopia_store::access::open_registration(&state.pool).await?;
let workers = utopia_store::access::worker_concurrency(&state.pool).await?;
+ let onto_lang = utopia_store::access::default_ontology_lang(&state.pool).await?;
let (limits, dflt) = utopia_store::model_limits::list(&state.pool).await?;
let in_use = utopia_store::model_limits::models_in_use(&state.pool).await?;
Ok(Json(json!({
"open_registration": open,
"worker_concurrency": workers,
+ "default_ontology_lang": onto_lang,
"model_limits": limits,
"default_model_concurrency": dflt,
"models_in_use": in_use.into_iter().map(|(b, m, k)| json!({"base_url": b, "model": m, "kind": k})).collect::<Vec<_>>(),
@@ -50,6 +52,9 @@ pub struct DeploymentReq {
/// 单个模型的并发;`max_concurrent` 为 null 表示删掉专属配置、回落到缺省
#[serde(default)]
pub model_limit: Option<ModelLimitReq>,
+ /// 新建知识库时本体用哪种语言播种。**不是界面语言**——那个在客户端
+ #[serde(default)]
+ pub default_ontology_lang: Option<String>,
}
#[derive(Deserialize)]
@@ -74,6 +79,9 @@ pub async fn put_deployment(
.store(n as usize, std::sync::atomic::Ordering::Relaxed);
}
// 按模型的限额即时生效:闸门每次调用前读库,发现限额变了就换一把新信号量
+ if let Some(l) = &req.default_ontology_lang {
+ utopia_store::access::set_default_ontology_lang(&state.pool, l).await?;
+ }
if let Some(n) = req.default_model_concurrency {
utopia_store::model_limits::set_default(&state.pool, n).await?;
}
@@ -102,13 +110,19 @@ pub async fn create_user(
) -> ApiResult<Json<serde_json::Value>> {
require_admin(&user)?;
if !req.email.contains('@') || req.email.len() > 254 {
- return Err(AppError::Validation("Invalid email address".into()).into());
+ return Err(AppError::invalid("bad_email", "Invalid email address").into());
}
if req.password.chars().count() < 8 {
- return Err(AppError::Validation("Password must be at least 8 characters".into()).into());
+ return Err(AppError::invalid(
+ "password_too_short",
+ "Password must be at least 8 characters",
+ )
+ .into());
}
if req.display_name.trim().is_empty() || req.display_name.chars().count() > 64 {
- return Err(AppError::Validation("Display name must be 1-64 characters".into()).into());
+ return Err(
+ AppError::invalid("bad_display_name", "Display name must be 1-64 characters").into(),
+ );
}
let role = match req.role.as_deref().unwrap_or("editor") {
"admin" => Role::Admin,
diff --git a/crates/utopia-server/src/api/auth_routes.rs b/crates/utopia-server/src/api/auth_routes.rs
index 2abf933c..57b76952 100644
--- a/crates/utopia-server/src/api/auth_routes.rs
+++ b/crates/utopia-server/src/api/auth_routes.rs
@@ -27,16 +27,18 @@ pub struct LoginReq {
fn validate_register(req: &RegisterReq) -> Result<(), AppError> {
if !req.email.contains('@') || req.email.len() > 254 {
- return Err(AppError::Validation("Invalid email address".into()));
+ return Err(AppError::invalid("bad_email", "Invalid email address"));
}
if req.password.chars().count() < 8 {
- return Err(AppError::Validation(
- "Password must be at least 8 characters".into(),
+ return Err(AppError::invalid(
+ "password_too_short",
+ "Password must be at least 8 characters",
));
}
if req.display_name.trim().is_empty() || req.display_name.chars().count() > 64 {
- return Err(AppError::Validation(
- "Display name must be 1-64 characters".into(),
+ return Err(AppError::invalid(
+ "bad_display_name",
+ "Display name must be 1-64 characters",
));
}
Ok(())
@@ -181,7 +183,9 @@ pub async fn update_me(
) -> ApiResult<Json<User>> {
let name = req.display_name.trim();
if name.is_empty() || name.chars().count() > 64 {
- return Err(AppError::Validation("Display name must be 1-64 characters".into()).into());
+ return Err(
+ AppError::invalid("bad_display_name", "Display name must be 1-64 characters").into(),
+ );
}
let updated = utopia_store::accounts::update_display_name(&state.pool, user.id, name).await?;
Ok(Json(updated))
@@ -200,10 +204,14 @@ pub async fn change_password(
Json(req): Json<ChangePasswordReq>,
) -> ApiResult<Json<serde_json::Value>> {
if !auth::verify_password(&req.current_password, &user.password_hash) {
- return Err(AppError::Validation("Current password is incorrect".into()).into());
+ return Err(AppError::invalid("wrong_password", "Current password is incorrect").into());
}
if req.new_password.chars().count() < 8 {
- return Err(AppError::Validation("Password must be at least 8 characters".into()).into());
+ return Err(AppError::invalid(
+ "password_too_short",
+ "Password must be at least 8 characters",
+ )
+ .into());
}
let hash = auth::hash_password(&req.new_password)?;
utopia_store::accounts::update_password(&state.pool, user.id, &hash).await?;
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 83132b6e..fc6129b2 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -237,9 +237,9 @@ pub async fn chat(
const NO_MODEL: &str = "Chat model not configured. Go to Settings → Models.";
let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
.await?
- .ok_or_else(|| AppError::Validation(NO_MODEL.into()))?;
- let client =
- llm_util::chat_client(&settings).ok_or_else(|| AppError::Validation(NO_MODEL.into()))?;
+ .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?;
+ let client = llm_util::chat_client(&settings)
+ .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?;
let query = req.message.trim().to_string();
if query.is_empty() {
diff --git a/crates/utopia-server/src/api/datasource_routes.rs b/crates/utopia-server/src/api/datasource_routes.rs
index f1d77a4e..b44134b7 100644
--- a/crates/utopia-server/src/api/datasource_routes.rs
+++ b/crates/utopia-server/src/api/datasource_routes.rs
@@ -161,7 +161,7 @@ pub async fn explore(
.await?
.is_empty()
{
- return Err(AppError::Validation("No data sources mounted".into()).into());
+ return Err(AppError::invalid("no_data_sources", "No data sources mounted").into());
}
utopia_store::jobs::enqueue(&state.pool, "explore_mappings", json!({ "kb_id": kb_id })).await?;
Ok(Json(json!({ "ok": true })))
diff --git a/crates/utopia-server/src/api/documents_routes.rs b/crates/utopia-server/src/api/documents_routes.rs
index 6c04ef23..f3eaa282 100644
--- a/crates/utopia-server/src/api/documents_routes.rs
+++ b/crates/utopia-server/src/api/documents_routes.rs
@@ -31,8 +31,9 @@ pub async fn upload(
Some(sid) => {
let src = utopia_store::sources::get(&state.pool, sid).await?;
if src.kb_id != kb_id || src.kind != "folder" {
- return Err(AppError::Validation(
- "Uploads can only target a folder source in this knowledge base".into(),
+ return Err(AppError::invalid(
+ "upload_needs_folder",
+ "Uploads can only target a folder source in this knowledge base",
)
.into());
}
@@ -47,7 +48,7 @@ pub async fn upload(
while let Some(field) = multipart
.next_field()
.await
- .map_err(|e| AppError::Validation(format!("Malformed upload: {e}")))?
+ .map_err(|e| AppError::invalid_detail("bad_upload", "Malformed upload", e.to_string()))?
{
let Some(filename) = field.file_name().map(String::from) else {
continue;
@@ -56,10 +57,9 @@ pub async fn upload(
.content_type()
.unwrap_or("application/octet-stream")
.to_string();
- let bytes = field
- .bytes()
- .await
- .map_err(|e| AppError::Validation(format!("Failed to read upload: {e}")))?;
+ let bytes = field.bytes().await.map_err(|e| {
+ AppError::invalid_detail("upload_read_failed", "Failed to read upload", e.to_string())
+ })?;
if bytes.is_empty() {
skipped.push(json!({ "filename": filename, "reason": "empty file" }));
continue;
@@ -102,7 +102,7 @@ pub async fn upload(
}
if created.is_empty() && skipped.is_empty() {
- return Err(AppError::Validation("No files received".into()).into());
+ return Err(AppError::invalid("no_files", "No files received").into());
}
Ok(Json(json!({ "created": created, "skipped": skipped })))
}
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
index 1950e958..ab67dd4f 100644
--- a/crates/utopia-server/src/api/graph_routes.rs
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -122,7 +122,7 @@ pub async fn update_entity(
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Editor).await?;
if req.type_id.is_none() && req.canonical_name.is_none() {
- return Err(AppError::Validation("Nothing to update".into()).into());
+ return Err(AppError::invalid("nothing_to_update", "Nothing to update").into());
}
let (before, after) = utopia_store::graph::update_entity(
&state.pool,
diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs
index e9ffab9b..d953eb74 100644
--- a/crates/utopia-server/src/api/kbs.rs
+++ b/crates/utopia-server/src/api/kbs.rs
@@ -29,6 +29,9 @@ pub struct UpdateKbReq {
/// 自动扩本体开关(缺省开;关掉不影响"留意",只是变成你点一下的提案)
#[serde(default)]
pub auto_extend_ontology: Option<bool>,
+ /// 本体语言(`en` | `zh`):跟语料走,不跟界面走。见 docs/decisions/0004
+ #[serde(default)]
+ pub ontology_lang: Option<String>,
}
/// 用户可见的 KB 列表(restricted 库仅矩阵成员与系统管理员可见)。
@@ -53,7 +56,7 @@ pub async fn create(
) -> ApiResult<Json<KnowledgeBase>> {
let name = req.name.trim();
if name.is_empty() || name.chars().count() > 64 {
- return Err(AppError::Validation("Name must be 1-64 characters".into()).into());
+ return Err(AppError::invalid("bad_name", "Name must be 1-64 characters").into());
}
let kind = req.kind.as_deref().unwrap_or("knowledge");
if !matches!(kind, "knowledge" | "memory") {
@@ -76,7 +79,7 @@ pub async fn create(
)
.await?;
if let Some(v) = req.visibility.as_deref() {
- utopia_store::kbs::update(&state.pool, kb.id, None, None, Some(v), None).await?;
+ utopia_store::kbs::update(&state.pool, kb.id, None, None, Some(v), None, None).await?;
}
utopia_store::access::set_kb_member(&state.pool, kb.id, user.id, "admin", Some(user.id))
.await?;
@@ -150,6 +153,7 @@ pub async fn update(
req.description.as_deref(),
req.visibility.as_deref(),
req.auto_extend_ontology,
+ req.ontology_lang.as_deref(),
)
.await?;
// 审计只记不阻断
diff --git a/crates/utopia-server/src/api/members_routes.rs b/crates/utopia-server/src/api/members_routes.rs
index 0c1e45b7..ecbeff32 100644
--- a/crates/utopia-server/src/api/members_routes.rs
+++ b/crates/utopia-server/src/api/members_routes.rs
@@ -67,7 +67,7 @@ pub async fn set_role(
&& new_role != Role::Owner
&& utopia_store::members::owner_count(&state.pool, workspace_id).await? <= 1
{
- return Err(AppError::Validation("Cannot demote the last owner".into()).into());
+ return Err(AppError::invalid("last_owner_demote", "Cannot demote the last owner").into());
}
utopia_store::members::set_role(&state.pool, workspace_id, target_id, new_role).await?;
@@ -91,7 +91,9 @@ pub async fn remove(
return Err(AppError::Forbidden.into());
}
if utopia_store::members::owner_count(&state.pool, workspace_id).await? <= 1 {
- return Err(AppError::Validation("Cannot remove the last owner".into()).into());
+ return Err(
+ AppError::invalid("last_owner_remove", "Cannot remove the last owner").into(),
+ );
}
}
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 98b99966..5ca6b2cc 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -30,7 +30,8 @@ pub async fn get(
Path(kb_id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
- utopia_store::graph::ensure_default_ontology(&state.pool, kb_id).await?;
+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
+ utopia_store::graph::ensure_default_ontology(&state.pool, kb_id, &kb.ontology_lang).await?;
let entity_types = utopia_store::ontology::entity_type_views(&state.pool, kb_id).await?;
let relation_types = utopia_store::ontology::relation_type_views(&state.pool, kb_id).await?;
let misses = utopia_store::ontology::list_misses(&state.pool, kb_id).await?;
@@ -97,7 +98,7 @@ pub async fn create_entity_type(
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
- .ok_or_else(|| AppError::Validation("key is required".into()))?;
+ .ok_or_else(|| AppError::invalid("key_required", "key is required"))?;
let id = utopia_store::ontology::create_entity_type(
&state.pool,
kb_id,
@@ -216,7 +217,7 @@ pub async fn create_relation_type(
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
- .ok_or_else(|| AppError::Validation("key is required".into()))?;
+ .ok_or_else(|| AppError::invalid("key_required", "key is required"))?;
let kind = req.kind.as_deref().unwrap_or("relation");
let id = utopia_store::ontology::create_relation_type(
&state.pool,
@@ -319,24 +320,41 @@ pub async fn dismiss_miss(
}
/// LLM 本体扩展建议:现有本体 + 未匹配统计 → 提案(人审后经 create 端点合入)。
+/// `locale` 是**调用方**说的,不是后端的设置。reason 只给人看,而人就在这次请求的
+/// 另一端;界面语言在客户端(docs/decisions/0004),所以它只能这样传进来。
+#[derive(Deserialize, Default)]
+pub struct SuggestReq {
+ #[serde(default)]
+ pub locale: Option<String>,
+}
+
pub async fn suggest(
State(state): State<AppState>,
AuthUser(user): AuthUser,
Path(kb_id): Path<Uuid>,
+ body: Option<Json<SuggestReq>>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Editor).await?;
- Ok(Json(build_proposals(&state, kb_id).await?))
+ let locale = body
+ .and_then(|Json(b)| b.locale)
+ .filter(|l| matches!(l.as_str(), "en" | "zh"))
+ .unwrap_or_else(|| "en".into());
+ Ok(Json(build_proposals(&state, kb_id, &locale).await?))
}
/// 生成本体扩展提案。人工点 Suggest 与冷启动自动扩本体走同一条路——
/// 自动那条不该是另一套判断,只是少了点头那一步。
-pub async fn build_proposals(state: &AppState, kb_id: Uuid) -> Result<serde_json::Value, AppError> {
+pub async fn build_proposals(
+ state: &AppState,
+ kb_id: Uuid,
+ reason_lang: &str,
+) -> Result<serde_json::Value, AppError> {
let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
.await?
- .ok_or_else(|| AppError::Validation("Chat model not configured".into()))?;
+ .ok_or_else(|| AppError::invalid("no_chat_model", "Chat model not configured"))?;
let client = llm_util::chat_client(&settings)
- .ok_or_else(|| AppError::Validation("Chat model not configured".into()))?;
+ .ok_or_else(|| AppError::invalid("no_chat_model", "Chat model not configured"))?;
let entity_types = utopia_store::ontology::entity_type_views(&state.pool, kb_id).await?;
let relation_types = utopia_store::ontology::relation_type_views(&state.pool, kb_id).await?;
@@ -404,11 +422,19 @@ pub async fn build_proposals(state: &AppState, kb_id: Uuid) -> Result<serde_json
\n\
Output exactly one JSON object:\n\
{{\"entity_types\":[{{\"key\":\"snake_case\",\"label\":\"Display Name\",\"description\":\"what belongs here, and what does not\",\"reason\":\"why add it\"}}],\n\
- \"relation_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"temporal\":\"state|event|eternal\",\"functional\":false,\"forms\":[\"surface spellings this covers\"],\"description\":\"what this relation asserts, and what it does not\",\"reason\":\"why add it\"}}]}}",
+ \"relation_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"temporal\":\"state|event|eternal\",\"functional\":false,\"forms\":[\"surface spellings this covers\"],\"description\":\"what this relation asserts, and what it does not\",\"reason\":\"why add it\"}}]}}\n\
+ \n\
+ Language, and it overrides the skeleton above — that skeleton is written in English \
+ only because these instructions are. Write every \"label\" and \"description\" in {}: \
+ they become this knowledge base's own ontology, and the description is read by the \
+ extraction model while it reads documents in that language. Write every \"reason\" \
+ in {}: a person reads it. \"key\" and \"forms\" stay lowercase ASCII either way.",
current_et.join(", "),
current_rt.join(", "),
miss_lines.join("\n"),
- form_lines.join("\n")
+ form_lines.join("\n"),
+ lang_name(&kb.ontology_lang),
+ lang_name(reason_lang)
);
let reply = client
@@ -456,7 +482,7 @@ pub async fn adopt_predicate(
require_kb(&state, &user, kb_id, Role::Editor).await?;
let key = req.key.trim();
if req.forms.is_empty() {
- return Err(AppError::Validation("forms cannot be empty".into()).into());
+ return Err(AppError::invalid("forms_required", "forms cannot be empty").into());
}
let predicate_id = utopia_store::ontology::create_relation_type(
&state.pool,
@@ -662,27 +688,37 @@ const MAX_ONTOLOGY_BYTES: usize = 8 * 1024 * 1024;
async fn read_upload(
mut multipart: axum::extract::Multipart,
) -> Result<(String, Vec<u8>), AppError> {
- while let Some(field) = multipart
- .next_field()
- .await
- .map_err(|e| AppError::Validation(format!("Could not read the upload: {e}")))?
- {
+ while let Some(field) = multipart.next_field().await.map_err(|e| {
+ AppError::invalid_detail("bad_upload", "Could not read the upload", e.to_string())
+ })? {
let Some(filename) = field.file_name().map(String::from) else {
continue;
};
- let bytes = field
- .bytes()
- .await
- .map_err(|e| AppError::Validation(format!("Could not read the uploaded file: {e}")))?;
+ let bytes = field.bytes().await.map_err(|e| {
+ AppError::invalid_detail(
+ "upload_read_failed",
+ "Could not read the uploaded file",
+ e.to_string(),
+ )
+ })?;
if bytes.len() > MAX_ONTOLOGY_BYTES {
- return Err(AppError::Validation(
- "Ontology file is too large (max 8 MB)".into(),
+ return Err(AppError::invalid(
+ "file_too_large",
+ "Ontology file is too large (max 8 MB)",
));
}
if bytes.is_empty() {
- return Err(AppError::Validation("Ontology file is empty".into()));
+ return Err(AppError::invalid("empty_file", "Ontology file is empty"));
}
return Ok((filename, bytes.to_vec()));
}
- Err(AppError::Validation("No file in the upload".into()))
+ Err(AppError::invalid("no_files", "No file in the upload"))
+}
+
+/// 语言代码 → 提示词里写给模型看的名字。模型认得懂 "Chinese",未必认得懂 "zh"。
+fn lang_name(code: &str) -> &'static str {
+ match code {
+ "zh" => "Chinese",
+ _ => "English",
+ }
}
diff --git a/crates/utopia-server/src/api/search_routes.rs b/crates/utopia-server/src/api/search_routes.rs
index 84854524..2f3fc77a 100644
--- a/crates/utopia-server/src/api/search_routes.rs
+++ b/crates/utopia-server/src/api/search_routes.rs
@@ -26,7 +26,7 @@ pub async fn search(
) -> ApiResult<Json<serde_json::Value>> {
let q = req.q.trim();
if q.is_empty() {
- return Err(AppError::Validation("Search query cannot be empty".into()).into());
+ return Err(AppError::invalid("empty_query", "Search query cannot be empty").into());
}
let kb = utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
diff --git a/crates/utopia-server/src/api/sources_routes.rs b/crates/utopia-server/src/api/sources_routes.rs
index e267fbef..2c35a66b 100644
--- a/crates/utopia-server/src/api/sources_routes.rs
+++ b/crates/utopia-server/src/api/sources_routes.rs
@@ -231,9 +231,11 @@ pub async fn delete(
// Memory 来源常驻:记忆空间不因来源整理而蒸发(记忆文档本身可在 Library 删除)
let source = utopia_store::sources::get(&state.pool, source_id).await?;
if source.kind == utopia_store::memory::MEMORY_SOURCE_KIND {
- return Err(
- utopia_core::AppError::Validation("The Memory source is permanent.".into()).into(),
- );
+ return Err(utopia_core::AppError::invalid(
+ "memory_source_permanent",
+ "The Memory source is permanent.",
+ )
+ .into());
}
utopia_store::sources::delete(&state.pool, source_id).await?;
state.emit_source(kb_id);
diff --git a/crates/utopia-server/src/api/workspaces.rs b/crates/utopia-server/src/api/workspaces.rs
index e9ab62da..d092c4f1 100644
--- a/crates/utopia-server/src/api/workspaces.rs
+++ b/crates/utopia-server/src/api/workspaces.rs
@@ -18,7 +18,10 @@ pub struct NameReq {
fn validate_name(name: &str) -> Result<&str, AppError> {
let name = name.trim();
if name.is_empty() || name.chars().count() > 64 {
- return Err(AppError::Validation("Name must be 1-64 characters".into()));
+ return Err(AppError::invalid(
+ "bad_name",
+ "Name must be 1-64 characters",
+ ));
}
Ok(name)
}
diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rs
index ad1e97c2..684535f8 100644
--- a/crates/utopia-server/src/bootstrap_ontology.rs
+++ b/crates/utopia-server/src/bootstrap_ontology.rs
@@ -54,7 +54,9 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
return Ok(());
}
- let proposals = ontology_routes::build_proposals(state, kb_id).await?;
+ // 自动那条路没有人类调用者,reason 也不会被展示(lastAutoExtension 不回它),
+ // 所以 reason 的语言无所谓——description 的语言才要紧,那个跟库走
+ let proposals = ontology_routes::build_proposals(state, kb_id, "en").await?;
let relations = proposals
.get("relation_types")
.and_then(|v| v.as_array())
diff --git a/crates/utopia-server/src/error.rs b/crates/utopia-server/src/error.rs
index f9e426fb..5224c2be 100644
--- a/crates/utopia-server/src/error.rs
+++ b/crates/utopia-server/src/error.rs
@@ -17,7 +17,19 @@ pub type ApiResult<T> = Result<T, ApiErr>;
impl IntoResponse for ApiErr {
fn into_response(self) -> Response {
+ // code 与 detail 只有 Invalid 才有;其余保持原样,转换可以一条条推进
+ let mut code: Option<&'static str> = None;
+ let mut detail: Option<String> = None;
let (status, message) = match &self.0 {
+ AppError::Invalid {
+ code: c,
+ message,
+ detail: d,
+ } => {
+ code = Some(c);
+ detail.clone_from(d);
+ (StatusCode::UNPROCESSABLE_ENTITY, message.clone())
+ }
AppError::NotFound => (StatusCode::NOT_FOUND, self.0.to_string()),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, self.0.to_string()),
AppError::Forbidden => (StatusCode::FORBIDDEN, self.0.to_string()),
@@ -38,6 +50,13 @@ impl IntoResponse for ApiErr {
)
}
};
- (status, Json(json!({ "error": message }))).into_response()
+ let mut body = json!({ "error": message });
+ if let Some(c) = code {
+ body["code"] = json!(c);
+ }
+ if let Some(d) = detail {
+ body["detail"] = json!(d);
+ }
+ (status, Json(body)).into_response()
}
}
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 1f4d16ef..b693a438 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -100,7 +100,10 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
let my_epoch = utopia_store::documents::extract_epoch(&state.pool, document_id).await?;
utopia_store::documents::set_graph_status(&state.pool, document_id, "extracting").await?;
state.emit_document(doc.kb_id, document_id);
- utopia_store::graph::ensure_default_ontology(&state.pool, doc.kb_id).await?;
+ let kb_lang = utopia_store::kbs::get(&state.pool, doc.kb_id)
+ .await?
+ .ontology_lang;
+ utopia_store::graph::ensure_default_ontology(&state.pool, doc.kb_id, &kb_lang).await?;
let etypes = utopia_store::graph::entity_types(&state.pool, doc.kb_id).await?;
let rtypes = utopia_store::graph::relation_types(&state.pool, doc.kb_id).await?;
@@ -185,6 +188,12 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
let chunks = utopia_store::documents::chunks_for_extraction(&state.pool, document_id).await?;
let mut doc_cache: HashMap<(Uuid, String), Uuid> = HashMap::new();
+ // 本文档已经认下的实体,按首次出现排序,送进后续分块的提示词。
+ //
+ // **按 entity_id 去重,不按名字**:第 3 块写"上海研究院"若消解到了第 1 块的
+ // "星云科技上海研究院",那它不该以第二个名字进清单——清单里每个实体只有
+ // 一个展示形态,就是这篇文档第一次用的那个。中文里全称先出现,所以这也是较全的那个。
+ let mut doc_entities: Vec<(Uuid, String, String)> = Vec::new();
let mut needs_adjudication = false;
let mut conflicts_found = false;
let mut fact_count = 0usize;
@@ -198,12 +207,17 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
return Ok(());
}
let ctx: Option<&[f32]> = chunk.embedding.as_ref().map(|v| v.as_slice());
+ let known: Vec<(String, String)> = doc_entities
+ .iter()
+ .map(|(_, k, n)| (k.clone(), n.clone()))
+ .collect();
let messages = utopia_extract::build_messages(
&type_pairs,
&rel_pairs,
&attr_lines,
doc_time.as_deref(),
&doc.filename,
+ &known,
&chunk.text,
);
// 按模型限流:许可持有到调用结束,超出限额的分块在这里排队而不是打爆供应商
@@ -265,6 +279,12 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
if let Some(p) = proposed {
let _ = utopia_store::resolution::set_proposed_type(&state.pool, id, p).await;
}
+ // 只记模型自己声明过类型的:主宾兜底那条路一律按 concept 消解,
+ // 把一个猜出来的类型放进清单等于让后续分块照着猜的抄
+ if !doc_entities.iter().any(|(eid, _, _)| *eid == id) {
+ let tk = type_key_by_id.get(&type_id).copied().unwrap_or("concept");
+ doc_entities.push((id, tk.to_string(), name.to_string()));
+ }
entity_ids.insert(name.to_string(), id);
entity_type_of.insert(name.to_string(), type_id);
}
diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rs
index c87d1825..45841471 100644
--- a/crates/utopia-server/src/owl_import.rs
+++ b/crates/utopia-server/src/owl_import.rs
@@ -67,7 +67,11 @@ pub async fn plan(
) -> AppResult<(ImportPlan, OwlProjection, RdfFormat)> {
let format = RdfFormat::detect(filename, bytes);
let proj = ontology_rdf::project(bytes, format).map_err(|e| {
- utopia_core::AppError::Validation(format!("Could not parse this ontology file: {e}"))
+ utopia_core::AppError::invalid_detail(
+ "bad_ontology_file",
+ "Could not parse this ontology file",
+ e.to_string(),
+ )
})?;
// 现有本体:按 IRI 与按 key 各建一份索引,两种冲突分别判
diff --git a/crates/utopia-store/src/access.rs b/crates/utopia-store/src/access.rs
index e6d62b00..8215844b 100644
--- a/crates/utopia-store/src/access.rs
+++ b/crates/utopia-store/src/access.rs
@@ -151,6 +151,29 @@ pub async fn set_open_registration(pool: &PgPool, value: bool) -> AppResult<()>
Ok(())
}
+/// 新建知识库时 `ontology_lang` 的默认值。
+///
+/// **刻意不叫"系统语言"**:叫那个名字的话,迟早有人试图把界面语言挂上来,
+/// 然后发现挂不上(界面语言在客户端)。名字本身就该把误用挡住。见 docs/decisions/0004。
+pub async fn default_ontology_lang(pool: &PgPool) -> AppResult<String> {
+ let row: Option<(String,)> =
+ sqlx::query_as("SELECT default_ontology_lang FROM deployment_settings LIMIT 1")
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(v,)| v).unwrap_or_else(|| "en".into()))
+}
+
+pub async fn set_default_ontology_lang(pool: &PgPool, value: &str) -> AppResult<()> {
+ if !matches!(value, "en" | "zh") {
+ return Err(AppError::invalid("bad_lang", "language must be en or zh"));
+ }
+ sqlx::query("UPDATE deployment_settings SET default_ontology_lang = $1")
+ .bind(value)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
/// 任务 worker 并发数(系统设置可改,改动即时生效——见 jobs::run_worker)。
pub async fn worker_concurrency(pool: &PgPool) -> AppResult<i32> {
let row: Option<(i32,)> =
@@ -162,8 +185,9 @@ pub async fn worker_concurrency(pool: &PgPool) -> AppResult<i32> {
pub async fn set_worker_concurrency(pool: &PgPool, value: i32) -> AppResult<()> {
if !(1..=256).contains(&value) {
- return Err(AppError::Validation(
- "worker_concurrency must be between 1 and 256".into(),
+ return Err(AppError::invalid(
+ "concurrency_range",
+ "worker_concurrency must be between 1 and 256",
));
}
sqlx::query("UPDATE deployment_settings SET worker_concurrency = $1")
diff --git a/crates/utopia-store/src/accounts.rs b/crates/utopia-store/src/accounts.rs
index f3502c96..0eb1bafb 100644
--- a/crates/utopia-store/src/accounts.rs
+++ b/crates/utopia-store/src/accounts.rs
@@ -50,9 +50,9 @@ pub async fn register(
}
Some((org_id,)) => {
if !open_registration {
- return Err(AppError::Validation(
- "Registration is closed for this deployment. Contact your administrator."
- .into(),
+ return Err(AppError::invalid(
+ "registration_closed",
+ "Registration is closed for this deployment. Contact your administrator.",
));
}
let user =
diff --git a/crates/utopia-store/src/datasources.rs b/crates/utopia-store/src/datasources.rs
index 533fd538..57dfe84f 100644
--- a/crates/utopia-store/src/datasources.rs
+++ b/crates/utopia-store/src/datasources.rs
@@ -66,16 +66,21 @@ pub async fn create(
created_by: Uuid,
) -> AppResult<Uuid> {
if name.trim().is_empty() {
- return Err(AppError::Validation("Data source name is required".into()));
+ return Err(AppError::invalid(
+ "ds_name_required",
+ "Data source name is required",
+ ));
}
if engine != "postgres" {
- return Err(AppError::Validation(
- "Only the postgres engine is supported for now".into(),
+ return Err(AppError::invalid(
+ "only_postgres",
+ "Only the postgres engine is supported for now",
));
}
if !conn_string.starts_with("postgres://") && !conn_string.starts_with("postgresql://") {
- return Err(AppError::Validation(
- "Connection string must start with postgres://".into(),
+ return Err(AppError::invalid(
+ "bad_conn_string",
+ "Connection string must start with postgres://",
));
}
let id = Uuid::now_v7();
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 8eaeb7e8..44c26842 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -215,10 +215,132 @@ const DEFAULT_RELATION_TYPES: &[(&str, &str, &str, bool, bool, &str)] = &[
),
];
+/// 内置本体的中文措辞:`key → (label, description)`。
+///
+/// **只覆盖 label 与 description**。颜色、形状、时态、函数性与语言无关,
+/// 在上面那两张表里只有一份——复制一遍迟早会漂移。
+///
+/// 两条写法上的规矩,都不是文风问题:
+///
+/// 1. **描述里提到其它类型时用 key,不用 label。** 中文库的 label 是「人物」,
+/// 但模型必须输出 `person`。描述逐字进提示词,写「那些属于人物」等于教模型
+/// 输出一个不存在的类型。
+/// 2. **负面例子是干活的那半。** 模型的错误集中在相邻类的边界上,不在类的中心;
+/// "什么不算" 比 "什么算" 更能改变结果(`product` 加上 GPU 那句反例后,
+/// 真实语料上误标从 37.2% 降到 8.6%)。所以这不是翻译,是用中文重写一遍。
+const ENTITY_TEXT_ZH: &[(&str, &str, &str)] = &[
+ (
+ "person",
+ "人物",
+ "有名有姓的具体的人。**不是**职务、头衔或团队——那些属于 concept 或 organization。",
+ ),
+ (
+ "organization",
+ "组织",
+ "作为一个整体行动的人的集合:公司、机构、政府部门、团队。包括事业部与有名字的小组。\
+ **不包括它做出来的产品**。",
+ ),
+ (
+ "project",
+ "项目",
+ "有起点也有终点的、有名字的计划、工程或一批工作。**不是**已经发布的产品,\
+ 也不是承担它的那个 organization。",
+ ),
+ (
+ "metric",
+ "指标",
+ "可度量、可聚合的量——营收、时延、人数。指**被数的那个东西本身**,\
+ 不是某一次量出来的具体数值。",
+ ),
+ (
+ "dimension",
+ "维度",
+ "指标可以被拆开看的那个轴——地区、渠道、产品线。指**轴本身**,不是轴上的某个取值。",
+ ),
+ (
+ "product",
+ "产品",
+ "可以购买、下载、游玩或订阅的**具体**产物:一台设备、一个模型、一项服务、\
+ 一个应用或一部作品。**泛指的能力、品类或技术是 concept,不是 product**——\
+ 「GeForce RTX 5090」是 product,「GPU」是 concept。",
+ ),
+ (
+ "event",
+ "事件",
+ "在某个时间点发生或将要发生的事——发布、收购、大会、故障。\
+ **不是**这件事发生在谁身上的那个「谁」。",
+ ),
+ (
+ "concept",
+ "概念",
+ "一个想法、能力、品类、标准、技术或领域——泛指而非特指。\
+ 用于「推理」「GPU」「零信任」这类。**不要拿它当兜底**:\
+ 原文若点名了具体的产品、组织或人,就用那个类型;\
+ 若点的是本体里没有对应类型的东西,直说没有,别往这里塞(见类型规则)。",
+ ),
+ (
+ "location",
+ "地点",
+ "一个地方——国家、地区、城市、园区、场所。**不是**总部设在那里的那个 organization。",
+ ),
+];
+
+/// 关系的中文措辞。label 是**动词短语**,读起来要能接上主宾:
+/// 「张三 —任职于→ 星云科技」。
+const RELATION_TEXT_ZH: &[(&str, &str, &str)] = &[
+ ("works_at", "任职于", "一个人受雇于某个组织,或隶属于它。"),
+ ("leads", "领导", "一个人领导一个组织、项目或团队。"),
+ ("reports_to", "汇报给", "组织架构里一个人的直属上级。"),
+ (
+ "part_of",
+ "属于",
+ "主语是宾语的组成部分或成员——系统的一个模块、公司内部的一个团队。\
+ **不是「可以在……上用」**:一款游戏能在某个服务上玩,不等于它属于那个服务。\
+ 也不是泛泛的「有关联」。",
+ ),
+ ("participates_in", "参与", "主语参与某个事件、计划或行动。"),
+ ("located_in", "位于", "主语在物理上处在某个地方。"),
+ ("produces", "出品", "一个组织或项目制造、发布或推出了宾语。"),
+ (
+ "alias_of",
+ "别名",
+ "同一个东西的两个名字——缩写、代号或曾用名。",
+ ),
+ (
+ "related_to",
+ "相关",
+ "代码层面的兜底,给本体表达不了的谓词用。**刻意不出现在抽取提示词里**:\
+ 给了兜底选项,模型就会去拿它,而不去说原文究竟说了什么。",
+ ),
+ (
+ "mapped_to",
+ "映射到",
+ "一个业务概念映射到一份具体的数据资产——语义层里「这个东西怎么算」的定义。",
+ ),
+];
+
+/// 取某个 key 在给定语言下的 (label, description);没有该语言的措辞就回落到英文。
+///
+/// 回落是必须的:中文表漏了一条不该让建库失败,只该让那一条是英文。
+fn localized(
+ table: &'static [(&'static str, &'static str, &'static str)],
+ key: &str,
+ lang: &str,
+ fallback: (&'static str, &'static str),
+) -> (&'static str, &'static str) {
+ if lang == "zh" {
+ if let Some((_, label, description)) = table.iter().find(|(k, _, _)| *k == key) {
+ return (label, description);
+ }
+ }
+ fallback
+}
+
/// 建库时铺内置本体。**已存在的行只补空描述,不覆盖人写过的**——种子里的描述是
/// 缺省值不是权威,用户按自己的语料调过之后不该被下一次调用抹掉。
-pub async fn ensure_default_ontology(pool: &PgPool, kb_id: Uuid) -> AppResult<()> {
- for (key, label, color, shape, description) in DEFAULT_ENTITY_TYPES {
+pub async fn ensure_default_ontology(pool: &PgPool, kb_id: Uuid, lang: &str) -> AppResult<()> {
+ for (key, en_label, color, shape, en_description) in DEFAULT_ENTITY_TYPES {
+ let (label, description) = localized(ENTITY_TEXT_ZH, key, lang, (en_label, en_description));
sqlx::query(
"INSERT INTO entity_types (id, kb_id, key, label, color, shape, builtin, description)
VALUES ($1, $2, $3, $4, $5, $6, TRUE, $7)
@@ -236,9 +358,11 @@ pub async fn ensure_default_ontology(pool: &PgPool, kb_id: Uuid) -> AppResult<()
.execute(pool)
.await?;
}
- for (key, label, temporal, functional, inverse_functional, description) in
+ for (key, en_label, temporal, functional, inverse_functional, en_description) in
DEFAULT_RELATION_TYPES
{
+ let (label, description) =
+ localized(RELATION_TEXT_ZH, key, lang, (en_label, en_description));
sqlx::query(
"INSERT INTO relation_types
(id, kb_id, key, label, temporal, functional, inverse_functional, builtin,
@@ -713,11 +837,17 @@ pub async fn update_entity(
Some(raw) => {
let n = raw.trim();
if n.is_empty() {
- return Err(AppError::Validation("Name cannot be empty".into()));
+ return Err(AppError::invalid(
+ "entity_name_required",
+ "Name cannot be empty",
+ ));
}
// 与抽取侧同一上限:越过这条线的多半是整句被当成了名字
if n.chars().count() > 100 {
- return Err(AppError::Validation("Name is too long (max 100)".into()));
+ return Err(AppError::invalid(
+ "entity_name_too_long",
+ "Name is too long (max 100)",
+ ));
}
Some(n)
}
@@ -732,8 +862,9 @@ pub async fn update_entity(
.fetch_optional(pool)
.await?;
if exists.is_none() {
- return Err(AppError::Validation(
- "No such entity type in this KB".into(),
+ return Err(AppError::invalid(
+ "unknown_entity_type",
+ "No such entity type in this KB",
));
}
}
diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rs
index d59de982..98eafb1f 100644
--- a/crates/utopia-store/src/kbs.rs
+++ b/crates/utopia-store/src/kbs.rs
@@ -44,10 +44,15 @@ pub async fn create(
description: Option<&str>,
) -> AppResult<KnowledgeBase> {
// 部署的第一个库自动成为默认库:公共空间,永远 open、不可删(API 强制 + DB CHECK)
+ //
+ // ontology_lang 取部署默认值:中文部署不该每建一个库就手动选一次。
+ // 之后按库可改——同一个部署里完全可能一个库读中文合同、另一个读英文论文
let kb = sqlx::query_as(
- "INSERT INTO knowledge_bases (id, workspace_id, name, kind, description, is_default)
+ "INSERT INTO knowledge_bases
+ (id, workspace_id, name, kind, description, is_default, ontology_lang)
VALUES ($1, $2, $3, $4, $5,
- NOT EXISTS (SELECT 1 FROM knowledge_bases WHERE workspace_id = $2))
+ NOT EXISTS (SELECT 1 FROM knowledge_bases WHERE workspace_id = $2),
+ COALESCE((SELECT default_ontology_lang FROM deployment_settings LIMIT 1), 'en'))
RETURNING *",
)
.bind(Uuid::now_v7())
@@ -75,7 +80,15 @@ pub async fn update(
description: Option<&str>,
visibility: Option<&str>,
auto_extend_ontology: Option<bool>,
+ ontology_lang: Option<&str>,
) -> AppResult<KnowledgeBase> {
+ // 改语言不回头重写已有的类——它们已经是这个库的数据,可能有人手工调过。
+ // 这一列往后管的是**新**描述(自动扩本体、AI 建议)写成什么语言
+ if let Some(l) = ontology_lang {
+ if !matches!(l, "en" | "zh") {
+ return Err(AppError::invalid("bad_lang", "language must be en or zh"));
+ }
+ }
if let Some(v) = visibility {
if !matches!(v, "open" | "restricted") {
return Err(AppError::Validation(
@@ -86,8 +99,9 @@ pub async fn update(
if v == "restricted" {
let current = get(pool, id).await?;
if current.is_default {
- return Err(AppError::Validation(
- "The default knowledge base stays open to everyone.".into(),
+ return Err(AppError::invalid(
+ "default_kb_open",
+ "The default knowledge base stays open to everyone.",
));
}
}
@@ -98,6 +112,7 @@ pub async fn update(
description = COALESCE($3, description),
visibility = COALESCE($4, visibility),
auto_extend_ontology = COALESCE($5, auto_extend_ontology),
+ ontology_lang = COALESCE($6, ontology_lang),
updated_at = now()
WHERE id = $1 RETURNING *",
)
@@ -106,6 +121,7 @@ pub async fn update(
.bind(description)
.bind(visibility)
.bind(auto_extend_ontology)
+ .bind(ontology_lang)
.fetch_optional(pool)
.await?
.ok_or(AppError::NotFound)
@@ -114,8 +130,9 @@ pub async fn update(
pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
let current = get(pool, id).await?;
if current.is_default {
- return Err(AppError::Validation(
- "The default knowledge base cannot be deleted.".into(),
+ return Err(AppError::invalid(
+ "default_kb_undeletable",
+ "The default knowledge base cannot be deleted.",
));
}
let res = sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
diff --git a/crates/utopia-store/src/model_limits.rs b/crates/utopia-store/src/model_limits.rs
index 0b697d31..2f30b1df 100644
--- a/crates/utopia-store/src/model_limits.rs
+++ b/crates/utopia-store/src/model_limits.rs
@@ -58,8 +58,9 @@ pub async fn set(
match max_concurrent {
Some(n) => {
if !(1..=256).contains(&n) {
- return Err(utopia_core::AppError::Validation(
- "max_concurrent must be between 1 and 256".into(),
+ return Err(utopia_core::AppError::invalid(
+ "concurrency_range",
+ "max_concurrent must be between 1 and 256",
));
}
sqlx::query(
@@ -88,8 +89,9 @@ pub async fn set(
/// 部署缺省并发(未单独配置的模型都走它)。
pub async fn set_default(pool: &PgPool, value: i32) -> AppResult<()> {
if !(1..=256).contains(&value) {
- return Err(utopia_core::AppError::Validation(
- "default_model_concurrency must be between 1 and 256".into(),
+ return Err(utopia_core::AppError::invalid(
+ "concurrency_range",
+ "default_model_concurrency must be between 1 and 256",
));
}
sqlx::query("UPDATE deployment_settings SET default_model_concurrency = $1")
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index dc29c94f..b23ffe60 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -83,8 +83,9 @@ fn validate_key(key: &str) -> AppResult<()> {
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
if !ok {
- return Err(AppError::Validation(
- "Key must be lowercase snake_case (a-z, 0-9, _), max 40 chars".into(),
+ return Err(AppError::invalid(
+ "bad_key",
+ "Key must be lowercase snake_case (a-z, 0-9, _), max 40 chars",
));
}
Ok(())
@@ -139,8 +140,9 @@ pub async fn update_entity_type(
description: &str,
) -> AppResult<()> {
if parent_id == Some(id) {
- return Err(AppError::Validation(
- "A class cannot be its own parent".into(),
+ return Err(AppError::invalid(
+ "self_parent",
+ "A class cannot be its own parent",
));
}
validate_shape(shape)?;
@@ -197,8 +199,9 @@ fn validate_attribute_fields(
"relation" => Ok(()),
"attribute" => {
if domain_type_id.is_none() {
- return Err(AppError::Validation(
- "An attribute needs a class (domain)".into(),
+ return Err(AppError::invalid(
+ "attr_needs_class",
+ "An attribute needs a class (domain)",
));
}
if !matches!(datatype, Some("text" | "number" | "date" | "bool")) {
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 04ea47bf..f177b0ae 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -273,16 +273,19 @@ pub async fn resolve_mention(
// 走到这里:所有候选都有画像且最高分 < ATTACH → 新建实体(同名不同人)
let id = create_entity(pool, kb_id, type_id, &name, context).await?;
refresh_disambiguators(pool, kb_id, &name).await?;
- let reviews = best_scored
+ let mut reviews = best_scored
.filter(|(_, sim)| *sim >= SIM_NEW)
.map(|(c, sim)| {
vec![ReviewRequest {
other_id: c.id,
score: sim,
- reason: format!("ambiguous name match (context similarity {sim:.2})"),
+ reason: format!("ambiguous_name|{sim:.2}"),
}]
})
.unwrap_or_default();
+ // 名字互相包含的既有实体:等值召回看不见它们(前缀枚举不完),
+ // 于是简称会静默变成第二个实体。只入队,不合并
+ reviews.extend(containment_reviews(pool, kb_id, type_id, &name, id, context).await?);
Ok(Resolution {
entity_id: id,
created: true,
@@ -290,6 +293,87 @@ pub async fn resolve_mention(
})
}
+/// 包含关系候选的最短边:两个名字里**较短的那个**至少这么长才算数。
+/// 低于它的多是「研究院」「中心」这类通名,配对没有信息量,只会刷爆队列。
+const MIN_CONTAIN_CHARS: i32 = 4;
+
+/// 单次最多产出的包含关系审阅对。与 `MAX_DRIFT_REVIEWS` 同理:
+/// 一个通名可能包含在几十个实体里,全放进去就把队列淹了。
+const MAX_CONTAIN_REVIEWS: i64 = 4;
+
+/// 新建实体之后,找出**名字互相包含**的既有实体,作为审阅候选。
+///
+/// 中文商业文本在一篇之内就会全称转简称(「星云科技上海研究院」→「上海研究院」),
+/// 而 [`recall_keys`] 是等值查:它靠枚举泛用后缀命中反向,可前缀是任意组织名,
+/// **枚举不完**。于是这三类全部漏网,静默变成第二个实体:
+///
+/// ```text
+/// 上海研究院 ⊂ 星云科技上海研究院 后缀被限定
+/// 启明 X7 加速卡 ~ 启明 X7 推理加速卡 中间插词(靠 LIKE 覆盖不到,见下)
+/// 沧海 ⊂ 沧海分布式推理平台 2.0 前缀被扩展
+/// ```
+///
+/// **只出候选,永不自动合并。** 同名候选那条路在相似度 ≥ [`SIM_ATTACH`] 时直接归并,
+/// 包含关系绝不能走它:`华瑞集团技术中心` 与 `星云科技技术中心` 都含「技术中心」,
+/// 同一篇文档里上下文相似度很容易过线,而它们是两个部门。宁分勿合。
+///
+/// **已知不覆盖**:中间插词(`启明 X7 加速卡` 与 `启明 X7 推理加速卡` 谁也不含谁)。
+/// 那要三元组相似度,而 `CREATE EXTENSION pg_trgm` 需要超级权限——本仓库刚改成
+/// 受限角色连库(迁移 0031),装扩展会在部署上失败。留给需要时再说。
+///
+/// **性能**:反向那半(新名字包含旧名字)用不上任何索引,所以这里靠
+/// `kb_id + type_id` 收窄行集并设上限,且只在**新建实体时**跑一次,不是每条 mention。
+/// 大库上如果不够,正解是建一张「后缀键」表走等值查,而不是加模糊索引。
+async fn containment_reviews(
+ pool: &PgPool,
+ kb_id: Uuid,
+ type_id: Uuid,
+ name: &str,
+ new_id: Uuid,
+ ctx: Option<&[f32]>,
+) -> AppResult<Vec<ReviewRequest>> {
+ let lower = name.to_lowercase();
+ if lower.chars().count() < MIN_CONTAIN_CHARS as usize {
+ return Ok(Vec::new());
+ }
+ let rows: Vec<(Uuid, String, Option<Vector>)> = sqlx::query_as(
+ "SELECT e.id, e.canonical_name, e.profile_embedding
+ FROM entities e
+ WHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL
+ AND e.id <> $3
+ AND lower(e.canonical_name) <> $4
+ AND char_length(e.canonical_name) >= $5
+ AND (lower(e.canonical_name) LIKE '%' || $4 || '%'
+ OR $4 LIKE '%' || lower(e.canonical_name) || '%')
+ ORDER BY char_length(e.canonical_name)
+ LIMIT $6",
+ )
+ .bind(kb_id)
+ .bind(type_id)
+ .bind(new_id)
+ .bind(&lower)
+ .bind(MIN_CONTAIN_CHARS)
+ .bind(MAX_CONTAIN_REVIEWS)
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|(id, other_name, emb)| {
+ // 分数只是给队列排序用的参考,**不参与是否合并的判断**——
+ // 那个判断本来就不在这条路上
+ let score = ctx
+ .and_then(|x| emb.as_ref().and_then(|p| cosine(p.as_slice(), x)))
+ .unwrap_or(0.0);
+ ReviewRequest {
+ other_id: id,
+ score,
+ reason: format!("contains|{other_name}"),
+ }
+ })
+ .collect())
+}
+
#[derive(Debug, sqlx::FromRow)]
struct CrossCandidate {
id: Uuid,
@@ -299,12 +383,12 @@ struct CrossCandidate {
profile_n: i32,
}
+/// `reason` 存 code,措辞归界面(docs/decisions/0004)——这一列不该一半 code
+/// 一半英文句子,那样中文界面上就是一半能翻一半不能。
fn drift_reason(mention_key: &str, other_key: &str, sim: Option<f32>) -> String {
match sim {
- Some(s) => format!("type drift: {mention_key} vs {other_key} (context similarity {s:.2})"),
- None => {
- format!("type drift: {mention_key} vs {other_key} (same name, no context to compare)")
- }
+ Some(s) => format!("type_drift|{mention_key} vs {other_key} {s:.2}"),
+ None => format!("type_drift|{mention_key} vs {other_key}"),
}
}
@@ -431,6 +515,8 @@ async fn resolve_type_drift(
}
}
reviews.truncate(MAX_DRIFT_REVIEWS);
+ // 漂移这条路一样会新建实体,包含关系照查
+ reviews.extend(containment_reviews(pool, kb_id, type_id, name, id, context).await?);
Ok(Resolution {
entity_id: id,
created: true,
@@ -747,6 +833,10 @@ pub async fn pending_adjudications(
}
/// LLM 不确定 / 未配模型 → 转人工。
+/// `reason` 存的是 **code**,可选地跟 `|detail`——不是给人看的句子。
+///
+/// 界面语言在客户端(见 docs/decisions/0004),服务端没有 locale 可用来措辞;
+/// 写进这一列的英文散文会永久留在中文界面上。措辞归 i18n,这里只留稳定的 code。
pub async fn escalate_review(pool: &PgPool, review_id: Uuid, reason: &str) -> AppResult<()> {
sqlx::query(
"UPDATE resolution_reviews SET stage = 'human', reason = $2
@@ -891,8 +981,9 @@ pub async fn merge_entities(
reason: &str,
) -> AppResult<Uuid> {
if source_id == target_id {
- return Err(AppError::Validation(
- "Cannot merge an entity into itself".into(),
+ return Err(AppError::invalid(
+ "self_merge",
+ "Cannot merge an entity into itself",
));
}
let source = entity_full(pool, kb_id, source_id).await?;
diff --git a/crates/utopia-store/src/sources.rs b/crates/utopia-store/src/sources.rs
index 8c88d4b2..37b914d6 100644
--- a/crates/utopia-store/src/sources.rs
+++ b/crates/utopia-store/src/sources.rs
@@ -17,13 +17,16 @@ pub fn validate_cron(expr: &str) -> AppResult<String> {
let normalized = expr.split_whitespace().collect::<Vec<_>>().join(" ");
let fields = normalized.split(' ').count();
if fields != 5 {
- return Err(AppError::Validation(format!(
- "Cron expression must have 5 fields (minute hour day month weekday), got {fields}"
- )));
+ return Err(AppError::invalid_detail(
+ "bad_cron_fields",
+ "Cron expression must have 5 fields (minute hour day month weekday)",
+ format!("got {fields}"),
+ ));
}
use std::str::FromStr;
- cron::Schedule::from_str(&format!("0 {normalized}"))
- .map_err(|e| AppError::Validation(format!("Invalid cron expression: {e}")))?;
+ cron::Schedule::from_str(&format!("0 {normalized}")).map_err(|e| {
+ AppError::invalid_detail("bad_cron", "Invalid cron expression", e.to_string())
+ })?;
Ok(normalized)
}
@@ -81,7 +84,10 @@ pub async fn create(
)));
}
if name.trim().is_empty() {
- return Err(AppError::Validation("Source name is required".into()));
+ return Err(AppError::invalid(
+ "source_name_required",
+ "Source name is required",
+ ));
}
// 互斥:cron 优先(UI 只会传其一)
let cron_norm = sync_cron.map(validate_cron).transpose()?;
diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rs
index f0367486..36d339b3 100644
--- a/crates/utopia-store/src/temporal.rs
+++ b/crates/utopia-store/src/temporal.rs
@@ -358,8 +358,9 @@ pub async fn resolve_conflict(
let stored = match resolution {
"close" => {
let at = close_at.or(new_from).ok_or_else(|| {
- utopia_core::AppError::Validation(
- "close_at is required when the new fact has no start time".into(),
+ utopia_core::AppError::invalid(
+ "close_at_required",
+ "close_at is required when the new fact has no start time",
)
})?;
close_superseded(pool, old_fact_id, at).await?;
diff --git a/docs/decisions/0004-language-and-localization.md b/docs/decisions/0004-language-and-localization.md
new file mode 100644
index 00000000..5d8fdb3c
--- /dev/null
+++ b/docs/decisions/0004-language-and-localization.md
@@ -0,0 +1,126 @@
+# 0004 · 语言:哪些字跟着看的人走,哪些跟着语料走
+
+- **状态**:规划中
+- **成文**:2026-08-29
+- **相关**:[0001](0001-ontology-import-and-governance.md) 论证过 `description` 是承重字段——本文把「它该用什么语言」补上;[0003](0003-ontology-growth-loop.md) 的 `reason` 与 `description` 之分是本文分界线的起点
+
+> 触发:产品要面向中文企业出中文版。但「加个语言开关」这句话底下藏着**五种性质不同的文本**,它们的正确语言互不相同,用一个开关管必然有一半是错的。
+
+---
+
+## 五种文本
+
+平时都叫「文案」,但读者和来源完全不同:
+
+| | 例子 | 读者 | 来源 |
+|---|---|---|---|
+| **界面词汇** | "Import an ontology" | 人 | 我们写死在 `i18n.ts` |
+| **服务端错误** | "Password must be at least 8 characters" | 人 | 我们写死在 Rust 里 |
+| **本体的 label / description** | `person` / "A named individual human being…" | **description 的读者是模型** | 内置播种 + 用户撰写 + OWL 导入 |
+| **LLM 当场生成给人看的** | 建议的 `reason` | 人 | 模型,按需生成 |
+| **抽出来的数据** | 实体名 `张三`、`surface_predicate` "runs on" | 人与模型 | **原文,逐字** |
+
+最后一行不是文案。**它是引文。**
+
+---
+
+## 分界线
+
+### 界面词汇 → 客户端,每个人自己设
+
+和暗色模式同类:这是**看的人**的偏好,不是部署的属性。中国企业里的外籍同事不该为了看英文界面去找管理员。
+
+`localStorage` + [wsStore.ts:22](../../web/src/wsStore.ts) 已有的 `makeStore` 模式,多一行 `makeStore("utopia.lang")`。首次访问按 `navigator.language` 猜一次,之后以人选的为准。
+
+> **修订记录**:本文初稿把界面语言放在**部署级管理员设置**里,理由是"和并发上限一样,DB 存、即时生效"。那个类比是错的——并发上限是**部署的属性**(供应商速率限制),界面语言是**读者的属性**。判断一个设置该放哪,问的不是"改起来方不方便",是"它描述的是谁"。
+
+中文包写成 `const zh: typeof S = { … }`。**不用 `Partial` + 逐键回退**:那样漏译不报错,只是某一行悄悄变回英文,而这种缺口只有用户会发现。`typeof S` 让漏一条就编译不过——512 条字符串 + 44 个函数,靠人眼对不齐。
+
+### 服务端错误 → 改成 key,措辞归前端
+
+界面语言在客户端之后,**后端不再拥有任何 locale**。所以留在 Rust 里的字符串是**永久不可翻译**的,不是"以后再补"。
+
+`AppError::Validation` 目前 75 处。分两类处理:
+
+- **用户正常操作能撞到的**(密码规则、邮箱格式、空文件、日期格式等)→ 改成 key,前端查表。这样全部措辞收进 `i18n.ts` 一个文件,而不是前端一半后端一半。
+- **API 契约守卫**(`role must be admin, editor or viewer`——只有调错接口才会碰到)→ 留英文。它的读者是开发者,永久英文正是它该有的样子。
+
+关键是**逐条判断并认下来**,而不是含糊地"以后再说"。
+
+> 这让本仓库一条既有原则从好品味变成硬约束:**服务端不产出展示形态**。此前违反它只是不优雅(OWL 导入把 `(手工建的)` 塞进 `conflict_with`,直接漏进英文界面);现在违反它等于制造一个永远翻不了的字符串。
+
+### 本体的 description → 跟语料,不跟界面
+
+`description` 逐字进抽取提示词([0001](0001-ontology-import-and-governance.md) 已论证它是承重字段),**读者是模型,而模型正在读你的文档**。
+
+所以正确语言是**语料的语言**,不是界面的语言。中国企业读英文技术文档是常见组合:界面要中文,而类描述**应该是英文**——描述与被判断的文本同语言时,模型判断"这段文字里的东西算不算 `product`"更稳。
+
+这是一个**知识库级**的属性(一个库就是一份语料),不是部署级,更不是客户端。
+
+### 本体的 label → 是数据,不跟任何开关
+
+`label` 存在库里,跟不了客户端的开关。**而这是对的**:它是那个团队写下的本体。一个中国团队建的库里类叫 `人物`,用英文界面的同事看到的也该是 `人物`——那是他同事定义的概念,不是界面元素。翻译它反而错。
+
+内置的 9 个类只在**播种那一刻**是应用词汇,落库之后就是这个库的数据,可编辑。
+
+**`key` 永不翻译**:它是标识符(`[a-z0-9_]`,最长 40),是模型读写的令牌,也是 `type_ids` 的查找键。
+
+**一个连带修改**:提示词现在排成 `- {key} ({label}): {description}`([lib.rs:61](../../crates/utopia-extract/src/lib.rs))。界面语言与语料语言不一致时,这一行会中英混排。`Person` 相对 `person` 本来就近乎零信息量,所以**提示词只送 `key` + `description`,`label` 仅在 description 为空时兜底**。
+
+### LLM 当场生成给人看的 → 调用方在请求里说
+
+`reason` 是人点 "Suggest with AI" 当场生成、当场显示、接受或忽略后就没了——`suggest` **即时返回不存库**([ontology_routes.rs:328](../../crates/utopia-server/src/api/ontology_routes.rs))。调用者就在现场,那就让请求自己说要什么语言,而不是让后端记一个设置。
+
+冷启动自动扩本体走同一条路但没有人类调用者。它生成的 `reason` 本来就被丢掉(`lastAutoExtension` 只回 relations / classes / facts_remapped / batches),所以那条路不需要 locale。
+
+**今天真正的毛病不是语言错,是语言没定**:[bootstrap_ontology.rs](../../crates/utopia-server/src/bootstrap_ontology.rs) 的提示词压根没说输出用什么语言,模型看心情。
+
+### 抽出来的数据 → 逐字跟文档,连开关都不给
+
+实体名之所以是 `张三`,因为文档第 3 段就是这么写的——证据链指着那个位置。翻译成 `Zhang San` 同时坏掉三件事:证据对不上原文、同一个人在中英文档里裂成两个实体、`surface_predicate` 那一整套「原文用的什么词」的记录失去意义。
+
+**不是语言偏好问题,是出处问题。**
+
+---
+
+## 于是后端只剩一个语言概念
+
+| 层 | 管什么 | 存哪 |
+|---|---|---|
+| 客户端 | 界面词汇(512 条 + 44 个函数) | `localStorage` |
+| 单次请求 | LLM 当场生成给人看的文本 | 请求参数 |
+| **知识库** | `description`、播种哪套内置本体 | `knowledge_bases` 一列 |
+| 部署 | 上一行的默认值 | 管理员设置 |
+
+最后一行是「系统语言」唯一剩下的东西。它值得留——中文部署不该每次建库都手动选——但**必须换个名字**。叫「系统语言」的话,三个月后一定有人试图把界面语言挂上去,然后发现挂不上。叫**「新建知识库的默认本体语言」**,名字本身就把误用挡住了。
+
+---
+
+## 一条架构约束
+
+locale 必须**在一个函数里解析出来**,其余全部消费它,不各自去读来源。
+
+这样将来要不要做「每用户语言」「跟随浏览器」「按知识库切界面」,改的是那一个函数,而不是翻遍 512 个调用点。**设置放哪会变,解析在一处不会变。**
+
+---
+
+## 分步
+
+| | 内容 | 依赖 |
+|---|---|---|
+| **L0** | 前端 i18n 骨架:locale store + 语言切换 + `zh.ts`(`typeof S` 全量) | 无 |
+| **L1** | 服务端错误文案分类,能撞到的改 key | L0 |
+| **L2** | 知识库本体语言列 + 中文内置本体 + 部署级默认值 | 无(可与 L0 并行) |
+| **L3** | 提示词去掉 `label`;`suggest` 带 locale;提示词钉死输出语言 | L0(locale 来源) |
+
+**L2 独立于界面语言,且今天就有收益**:中文语料配中文类描述,抽取质量直接受益,不必等中文界面。
+
+**L2 里最实的一块不是加列,是重写内置本体的描述**——9 个类 + 14 个关系。它们当初是斟酌着写的(负面例子那部分尤其:「不是角色、职位或团队,那些归 concept 或 organization」——错误聚集在边界上,负面例子才是干活的那半)。**翻译不能敷衍,得按同样的思路用中文重写一遍。**
+
+---
+
+## 已知会疼的地方
+
+- **中文包与英文包漂移**。`typeof S` 挡住"漏一条",挡不住"英文改了措辞、中文还是旧的"——两边都合法。目前没有好办法,只能靠改文案时同时改两处。
+- **一个库里中英文档混放**时,`description` 该用哪种语言没有正确答案。本文选了「知识库单语」,因为混放本身就会让抽取质量下降(不只是描述的问题)。真遇到了再说,别提前设计。
+- **中文分词与检索**。Tantivy 那边已经用了 `tantivy-jieba`,不在本文范围,但中文版上线后会被更认真地检验。
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index e2467164..7122d4b6 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -22,9 +22,10 @@
| | 文档 | 状态 |
|---|---|---|
-| 0001 | [本体导入与治理路线](0001-ontology-import-and-governance.md) | 进行中 · P0/P1 已建成,P2–P5 未开工 |
+| 0001 | [本体导入与治理路线](0001-ontology-import-and-governance.md) | 进行中 · P0/P1/P2 已建成,P2c 与 P3–P5 未开工 |
| 0002 | [推理机](0002-reasoning-engine.md) | 规划中 · 取代 0001 P5 的排期 |
| 0003 | [本体从语料里长出来,人站在哪一环](0003-ontology-growth-loop.md) | 已建成 · 含三次判断变化的留痕 |
+| 0004 | [语言:哪些字跟着看的人走,哪些跟着语料走](0004-language-and-localization.md) | 规划中 · L0–L3 |
## 不放这里的东西
diff --git a/migrations/0034_ontology_language.sql b/migrations/0034_ontology_language.sql
new file mode 100644
index 00000000..6e0a88c9
--- /dev/null
+++ b/migrations/0034_ontology_language.sql
@@ -0,0 +1,19 @@
+-- 内置本体用哪种语言播种,以及新库的默认值。
+--
+-- **这不是"系统语言"**(见 docs/decisions/0004)。界面语言在客户端,后端没有 locale。
+-- 这一列管的是**语料的语言**:类的 description 逐字进抽取提示词,读者是正在读你文档
+-- 的模型——描述与被判断的文本同语言,判断更稳。所以中国团队读英文技术文档时,
+-- 界面要中文而这一列该是 'en',一个开关按不下去这两件事。
+--
+-- 语言只在**播种那一刻**决定内置类的措辞。此后 label/description 是这个库的数据,
+-- 可编辑;改这一列不会回头重写它们。它继续管的是新描述(自动扩本体、AI 建议)写成什么语言。
+ALTER TABLE knowledge_bases ADD COLUMN ontology_lang TEXT NOT NULL DEFAULT 'en';
+ALTER TABLE deployment_settings ADD COLUMN default_ontology_lang TEXT NOT NULL DEFAULT 'en';
+
+-- 取值收在 CHECK 里而不是应用层:这一列会被用来挑一张编译期常量表,
+-- 写进一个没有对应表的值只会静默回落到英文,不报错——那种错最难查
+ALTER TABLE knowledge_bases
+ ADD CONSTRAINT knowledge_bases_ontology_lang_chk CHECK (ontology_lang IN ('en', 'zh'));
+ALTER TABLE deployment_settings
+ ADD CONSTRAINT deployment_default_ontology_lang_chk
+ CHECK (default_ontology_lang IN ('en', 'zh'));
diff --git a/web/src/api.ts b/web/src/api.ts
index d237c88b..0c357de7 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1,8 +1,13 @@
+import { S, lang } from "./i18n";
+
export class ApiError extends Error {
status: number;
- constructor(status: number, message: string) {
+ /** 服务端给的稳定错误码(没有则是尚未转换的契约守卫,message 已是英文原句) */
+ code?: string;
+ constructor(status: number, message: string, code?: string) {
super(message);
this.status = status;
+ this.code = code;
}
}
@@ -16,14 +21,29 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
...init,
});
if (!res.ok) {
+ // 措辞在这一个收口点定:22 个文件里的 toast.error(e.message) 一处都不用改。
+ // 有 code 就查 i18n,没有(或这一条还没进表)就退回服务端的英文原句——
+ // 服务端永远说英文,因为界面语言在客户端(docs/decisions/0004)
let message = res.statusText;
+ let code: string | undefined;
try {
- const body = (await res.json()) as { error?: string };
+ const body = (await res.json()) as {
+ error?: string;
+ code?: string;
+ detail?: string;
+ };
if (body.error) message = body.error;
+ code = body.code;
+ // code 来自网络,不是字面量——这一处 cast 换来 err 表本身的全量类型检查
+ const worded = code
+ ? (S.err as Record<string, string | undefined>)[code]
+ : undefined;
+ if (worded) message = worded;
+ if (body.detail) message = S.errDetail(message, body.detail);
} catch {
// 非 JSON 响应体,保留 statusText
}
- throw new ApiError(res.status, message);
+ throw new ApiError(res.status, message, code);
}
return res.json() as Promise<T>;
}
@@ -56,6 +76,9 @@ export interface Kb {
/** 抽取遇到本体外的说法时,是否允许系统自动补进本体并改写等它的事实。
关掉不影响"留意":未匹配统计照常累积可见,只是变成你点一下的提案 */
auto_extend_ontology: boolean;
+ /** 内置本体按哪种语言播种、新描述写哪种语言。**跟语料走,不跟界面走**
+ (界面语言在客户端,见 docs/decisions/0004) */
+ ontology_lang: "en" | "zh";
/** 调用者在本库的角色(仅详情接口返回):前端据此门控破坏性入口 */
my_role?: "viewer" | "editor" | "admin" | "owner" | null;
}
@@ -572,6 +595,8 @@ export const api = {
/** 外层兜底,防任务无限堆积;真正的节流是按模型的限额 */
worker_concurrency: number;
default_model_concurrency: number;
+ /** 新建知识库的本体语言默认值。**不是界面语言**——那个在客户端 */
+ default_ontology_lang: "en" | "zh";
model_limits: {
base_url: string;
model: string;
@@ -588,6 +613,7 @@ export const api = {
model: string;
max_concurrent: number | null;
},
+ defaultOntologyLang?: "en" | "zh",
) =>
request<{ ok: boolean }>("/api/v1/admin/deployment", {
method: "PUT",
@@ -600,6 +626,9 @@ export const api = {
? { default_model_concurrency: defaultModelConcurrency }
: {}),
...(modelLimit ? { model_limit: modelLimit } : {}),
+ ...(defaultOntologyLang
+ ? { default_ontology_lang: defaultOntologyLang }
+ : {}),
}),
}),
adminCreateUser: (body: {
@@ -812,9 +841,12 @@ export const api = {
method: "POST",
body: JSON.stringify({ kind, key }),
}),
+ /** reason 只给人看,而人就在这次请求的另一端——所以语言由调用方说,
+ 不是后端的设置(docs/decisions/0004)。description 的语言跟知识库走,服务端自己知道 */
suggestOntology: (kbId: string) =>
request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, {
method: "POST",
+ body: JSON.stringify({ locale: lang }),
}),
/** 上传本体文件只算出计划,一个字节都不写库 */
diff --git a/web/src/i18n.ts b/web/src/i18n/en.ts
similarity index 86%
rename from web/src/i18n.ts
rename to web/src/i18n/en.ts
index fd772ad8..136d2d54 100644
--- a/web/src/i18n.ts
+++ b/web/src/i18n/en.ts
@@ -1,12 +1,66 @@
-// i18n shell: all UI strings live here, English-only for now.
-// Later: swap this module for a real i18n runtime (i18next) without touching components.
-export const S = {
+// 英文语言包。这一份是**结构的权威**:`Strings = typeof en`,其余语言包按它定型,
+// 漏一条就编译不过(见 docs/decisions/0004)。
+//
+// 加新文案时先加在这里,再补其余语言包——顺序反了会得到一个类型错误,那正是本意。
+export const en = {
app: {
name: "Utopia",
tagline: "The living memory of your organization",
siteUrl: "https://utopia.bi",
docsUrl: "https://utopia.bi/docs",
},
+ /** 服务端校验错误的措辞。key = 服务端给的 code;缺一条就退回英文原句,不会崩。
+ 契约守卫(调错接口才碰得到)刻意不在这里——它们的读者是开发者 */
+ err: {
+ bad_email: "That doesn't look like an email address.",
+ password_too_short: "Password must be at least 8 characters.",
+ bad_display_name: "Display name must be 1-64 characters.",
+ wrong_password: "Current password is incorrect.",
+ registration_closed:
+ "Sign-up is closed on this deployment — ask an administrator for an account.",
+ no_chat_model:
+ "No chat model configured yet. Set one under Settings → Models.",
+ bad_upload: "That upload could not be read.",
+ upload_read_failed: "The file could not be read to the end.",
+ no_files: "No file was attached.",
+ upload_needs_folder: "Files can only be uploaded into a folder source.",
+ empty_file: "That file is empty.",
+ file_too_large: "That file is too large — the limit is 8 MB.",
+ bad_ontology_file: "That is not a readable OWL or RDFS file.",
+ bad_name: "Name must be 1-64 characters.",
+ default_kb_open:
+ "The default knowledge base stays open to everyone — create a separate one for private work.",
+ default_kb_undeletable: "The default knowledge base cannot be deleted.",
+ last_owner_demote: "This is the last owner — promote someone else first.",
+ last_owner_remove: "This is the last owner — hand ownership over first.",
+ key_required: "A key is required.",
+ forms_required: "Pick at least one phrase this relation covers.",
+ bad_key:
+ "Keys are lowercase, letters digits and underscores only, up to 40 characters.",
+ self_parent: "A class cannot be its own parent.",
+ attr_needs_class: "An attribute has to belong to a class.",
+ entity_name_required: "Name cannot be empty.",
+ entity_name_too_long: "Name is too long — 100 characters at most.",
+ unknown_entity_type: "That class is not in this ontology.",
+ nothing_to_update: "Nothing to change.",
+ self_merge: "An entity cannot be merged into itself.",
+ close_at_required:
+ "Pick the date this fact ended — the new one does not say when it started.",
+ empty_query: "Type something to search for.",
+ no_data_sources: "No databases are mounted on this knowledge base.",
+ memory_source_permanent:
+ "The Memory source is part of the knowledge base and stays.",
+ source_name_required: "Give this source a name.",
+ bad_cron: "That cron expression could not be parsed.",
+ bad_cron_fields:
+ "A cron expression has five fields: minute hour day month weekday.",
+ ds_name_required: "Give this data source a name.",
+ only_postgres: "Only PostgreSQL is supported for now.",
+ bad_conn_string: "A connection string starts with postgres://",
+ concurrency_range: "Pick a number between 1 and 256.",
+ },
+ /** 机器给的补充(cron 解析器的原话之类)缀在措辞后面 */
+ errDetail: (msg: string, detail: string) => `${msg} (${detail})`,
toast: {
saved: "Saved",
created: "Created",
@@ -32,6 +86,7 @@ export const S = {
changePassword: "Update password",
passwordChanged: "Password updated",
avatarHint: "Avatars are generated from your name for now.",
+ language: "Language",
kbsNav: "Knowledge bases",
kbsTitle: "Knowledge bases",
kbOpen: "Open",
@@ -426,8 +481,12 @@ export const S = {
evidence: "evidence",
noEvidence: "No evidence recorded",
noQuote: "(no quote)",
- /* 原文说的谓词。词表外的词会被降级成 related to,原意只在这里活着 */
- proposedPredicate: (p: string) => `the text said “${p}”`,
+ /* 抽取器从原文读出来的谓词,规范成了标识符。词表外的说法会被降级成
+ related to,原意只在这里活着。
+ **措辞不能宣称这是引文**:关系 key 只能是 [a-z0-9_],所以中文语料里
+ 「采购了」出来是 purchases——说"原文说的是 purchases"是假的。
+ 逐字原句就在旁边的证据引文里,没丢。 */
+ proposedPredicate: (p: string) => `read from the text as “${p}”`,
sectionRef: (filename: string, seq: number) =>
`${filename} · section ${seq} →`,
fromVersion: (v: number) => `v${v}`,
@@ -523,6 +582,13 @@ export const S = {
"provider and is per model — a local Ollama may manage two, a hosted API fifty. " +
"Background work (extraction, resolution, indexing) waits for a slot; chat and search " +
"never do. Takes effect immediately.",
+ /* 部署级默认值:新建库时用。名字刻意不叫"系统语言" */
+ ontologyLang: "Default ontology language",
+ ontologyLangHint:
+ "The language new knowledge bases start their ontology in — class descriptions go " +
+ "into the extraction prompt, so this follows the documents you expect, not the " +
+ "interface. Each knowledge base can change its own afterwards. " +
+ "Interface language is a per-reader choice in the account menu.",
modelDefault: "Default",
modelReset: "Reset",
modelResetHint:
@@ -762,6 +828,19 @@ export const S = {
"merge.revert": "Reverted merge",
"merge.manual": "Merged manually",
} as Record<string, string>,
+ /** 升格给人裁决的原因。服务端存 code(可选 |detail),措辞在这里 */
+ escalated: {
+ escalate_no_model: "No chat model — the adjudicator could not run",
+ escalate_no_verdict: "The adjudicator returned no verdict",
+ escalate_entity_changed: "The entity changed while being adjudicated",
+ escalate_unsure: "The adjudicator was not confident enough",
+ /* 名字互相包含:等值召回看不见,简称会静默变成第二个实体 */
+ contains: "One name contains the other",
+ ambiguous_name: "Same name, context did not settle it",
+ type_drift: "Same name arrived under a different type",
+ auto_merged: "Merged by the AI adjudicator",
+ kept_apart: "The AI adjudicator judged these different",
+ } as Record<string, string>,
duplicates: "Possible duplicates",
duplicatesHint:
"Same name, different context. The AI adjudicates clear cases in the background; the rest wait for you. Merging is always reversible.",
@@ -825,6 +904,13 @@ export const S = {
"facts that were waiting for it. Every change is listed and can be undone. Turning this " +
"off does not stop Utopia from noticing — the phrases still collect under Unmatched, they " +
"just wait for you to approve them.",
+ /* 语料语言。措辞要把"这不是界面语言"讲清楚,否则一定有人当成界面开关 */
+ ontologyLang: "Language of this ontology",
+ ontologyLangNote:
+ "Which language class and relation descriptions are written in. Those go straight " +
+ "into the extraction prompt, so the reader is the model while it reads your documents — " +
+ "match your documents, not your interface. Changing this does not rewrite what is " +
+ "already here; it decides the language of descriptions written from now on.",
defaultOpenLabel: "Open to everyone",
defaultOpenNote:
"This is the deployment's default knowledge base, so visibility is locked: every member " +
@@ -903,4 +989,7 @@ export const S = {
viewer: "Viewer",
},
},
-} as const;
+};
+
+/** 语言包的结构契约。其余语言包写成 `const zh: Strings = {…}`,漏一条即编译失败 */
+export type Strings = typeof en;
diff --git a/web/src/i18n/index.ts b/web/src/i18n/index.ts
new file mode 100644
index 00000000..7efdb0a5
--- /dev/null
+++ b/web/src/i18n/index.ts
@@ -0,0 +1,53 @@
+// 界面语言:**看的人自己定**,不经过后端(见 docs/decisions/0004)。
+// 和暗色模式同类——并发上限那种设置描述的是部署,界面语言描述的是读者。
+//
+// locale 只在这一个文件里解析。其余 600 多处只消费 `S`,谁都不去读来源。
+// 将来要不要跟随浏览器、要不要每用户覆盖,改的是这里,不是那 600 处。
+import { en, type Strings } from "./en";
+import { zh } from "./zh";
+
+export type { Strings };
+
+export const LANGS = ["en", "zh"] as const;
+export type Lang = (typeof LANGS)[number];
+
+/** 语言自己的名字,永远不翻译——在切换器里,"中文"对看不懂英文的人才是路标 */
+export const LANG_NAMES: Record<Lang, string> = { en: "English", zh: "中文" };
+
+const BUNDLES: Record<Lang, Strings> = { en, zh };
+const KEY = "utopia.lang";
+
+function detect(): Lang {
+ try {
+ 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 会抛——回落到英文,别让首屏挂掉
+ }
+ return "en";
+}
+
+export const lang: Lang = detect();
+
+/** 当前语言包。模块加载时定一次——所以模块级常量(`const X = S.a.b`)也是对的 */
+export const S: Strings = BUNDLES[lang];
+
+/**
+ * 切语言走整页重载,不是重挂载。
+ *
+ * 635 处引用里已经有一处在模块顶层求值(`Members.tsx` 的 ROLE_OPTIONS),
+ * 而这种写法今后还会有人写。重挂载会让它们停在旧语言且**不报错**;
+ * 重载让整个模块图重新求值,代价只是一次刷新——切语言一年也没几次。
+ */
+export function setLang(next: Lang) {
+ if (next === lang) return;
+ try {
+ localStorage.setItem(KEY, next);
+ } catch {
+ // 存不下就只对本次会话生效,好过什么都不发生
+ }
+ location.reload();
+}
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
new file mode 100644
index 00000000..1e70a4c6
--- /dev/null
+++ b/web/src/i18n/zh.ts
@@ -0,0 +1,906 @@
+// 中文语言包。结构由 en.ts 定死(`Strings = typeof en`)——漏一条、多一条、
+// 函数签名对不上,都是编译错误。这是唯一靠得住的同步办法:512 条字符串靠人眼对不齐。
+//
+// 术语约定:知识库 / 工作区 / 本体 / 类 / 实体 / 关系 / 属性 / 事实 / 证据 /
+// 抽取 / 摄入 / 来源 / 文本块 / 图谱 / 审阅 / 冲突 / 合并 / 置信度 / 时态 /
+// 函数性 / 提示词 / 三元组。
+//
+// **不译的东西**:品牌字标(Utopia / Persona / Charter)、标识符(key、IRI)、
+// 产品名(DeepSeek、Ollama…)、URL。字标不译是因为它们是标记不是词。
+import type { Strings } from "./en";
+
+export const zh: Strings = {
+ app: {
+ name: "Utopia",
+ tagline: "你的组织,活着的记忆",
+ siteUrl: "https://utopia.bi",
+ docsUrl: "https://utopia.bi/docs",
+ },
+ err: {
+ bad_email: "这看起来不像一个邮箱地址。",
+ password_too_short: "密码至少 8 位。",
+ bad_display_name: "显示名需要 1–64 个字符。",
+ wrong_password: "当前密码不对。",
+ registration_closed: "本部署已关闭自助注册——请找管理员开通账户。",
+ no_chat_model: "还没有配置对话模型。到「设置 → 模型」里配一个。",
+ bad_upload: "这次上传读不出来。",
+ upload_read_failed: "文件没能读完。",
+ no_files: "没有附带文件。",
+ upload_needs_folder: "文件只能上传到「文件夹」类型的来源里。",
+ empty_file: "这个文件是空的。",
+ file_too_large: "文件太大了——上限是 8 MB。",
+ bad_ontology_file: "这不是一个能读的 OWL 或 RDFS 文件。",
+ bad_name: "名称需要 1–64 个字符。",
+ default_kb_open: "默认知识库对所有人开放——需要私密空间就另建一个。",
+ default_kb_undeletable: "默认知识库不能删除。",
+ last_owner_demote: "这是最后一位所有者——先把另一个人提上来。",
+ last_owner_remove: "这是最后一位所有者——先把所有权交出去。",
+ key_required: "需要填 key。",
+ forms_required: "至少选一个这个关系涵盖的说法。",
+ bad_key: "key 只能用小写字母、数字和下划线,最长 40 个字符。",
+ self_parent: "一个类不能是自己的父类。",
+ attr_needs_class: "属性必须挂在某个类上。",
+ entity_name_required: "名称不能为空。",
+ entity_name_too_long: "名称太长了——最多 100 个字符。",
+ unknown_entity_type: "这个类不在当前本体里。",
+ nothing_to_update: "没有要改的内容。",
+ self_merge: "实体不能合并到自己身上。",
+ close_at_required: "选一个这条事实结束的日期——新的那条没说自己何时开始。",
+ empty_query: "输入点什么再检索。",
+ no_data_sources: "这个知识库没有挂载任何数据库。",
+ memory_source_permanent: "「记忆」是知识库自带的来源,会一直在。",
+ source_name_required: "给这个来源起个名字。",
+ bad_cron: "这个 cron 表达式解析不了。",
+ bad_cron_fields: "cron 表达式有五段:分 时 日 月 周。",
+ ds_name_required: "给这个数据源起个名字。",
+ only_postgres: "目前只支持 PostgreSQL。",
+ bad_conn_string: "连接串要以 postgres:// 开头",
+ concurrency_range: "填一个 1 到 256 之间的数。",
+ },
+ errDetail: (msg: string, detail: string) => `${msg}(${detail})`,
+ toast: {
+ saved: "已保存",
+ created: "已创建",
+ deleted: "已删除",
+ added: "已加入本体",
+ },
+ account: {
+ brand: "Utopia Persona",
+ titleTag: "Persona",
+ profile: "个人资料",
+ administration: "管理",
+ adminChip: "管理员",
+ backToApp: "← 返回",
+ profileTitle: "个人资料",
+ displayName: "显示名",
+ email: "邮箱",
+ save: "保存",
+ passwordTitle: "修改密码",
+ currentPassword: "当前密码",
+ newPassword: "新密码(至少 8 位)",
+ changePassword: "更新密码",
+ passwordChanged: "密码已更新",
+ avatarHint: "头像目前由你的名字生成。",
+ language: "语言",
+ kbsNav: "知识库",
+ kbsTitle: "知识库",
+ kbOpen: "公开",
+ kbRestricted: "受限",
+ kbStats: (docs: number, members: number) =>
+ `${docs} 篇文档 · ${members} 名成员`,
+ addedBy: (name: string, date: string) => `由 ${name} 加入 · ${date}`,
+ joinedOn: (date: string) => `${date} 加入`,
+ openToEveryone: "对所有人开放",
+ deploymentAdmin: "部署管理员",
+ openKb: "打开",
+ kbSettingsBtn: "设置",
+ roleNames: {
+ owner: "所有者",
+ admin: "管理员",
+ editor: "编辑者",
+ viewer: "只读",
+ },
+ },
+ docs: {
+ brand: "Utopia Charter",
+ backTitle: "返回 Utopia",
+ searchPlaceholder: "搜索文档…",
+ noResults: "没有匹配。",
+ },
+ nav: {
+ workspaceLabel: "工作区",
+ kbLabel: "知识库",
+ ask: "对话",
+ askHint: "与你的知识库对话——它会记住",
+ search: "检索",
+ searchHint: "混合检索",
+ graph: "图谱",
+ graphHint: "实体与时间线",
+ library: "文库",
+ libraryHint: "文档与摄入",
+ settings: "设置",
+ settingsHint: "模型与成员",
+ signOut: "退出登录",
+ docs: "文档",
+ loading: "加载中…",
+ serverUnreachable: "罚则 500:Utopia 沉默了——它没有回应。",
+ notFound: "罚则 404:你在 Utopia 里迷了路。",
+ returnHome: "回到首页",
+ reportIssue: "反馈问题",
+ refresh: "刷新",
+ },
+ login: {
+ signIn: "登录",
+ signUp: "注册",
+ displayName: "显示名",
+ email: "邮箱",
+ password: "密码(至少 8 位)",
+ submitting: "稍候…",
+ createAccount: "创建账户",
+ networkError: "网络异常,请重试",
+ agreePrefix: "继续即表示你同意",
+ agreeAnd: ",并已知悉",
+ agreeSuffix: "。",
+ githubUrl: "https://github.com/deeplethe/utopia",
+ },
+ legal: {
+ privacyTitle: "隐私政策",
+ termsTitle: "使用条款",
+ backToSignIn: "← 返回登录",
+ privacy: {
+ title: "隐私政策",
+ note: "Utopia 自带的默认文本。运营本部署的组织可以替换成自己的政策。",
+ sections: [
+ {
+ h: "一个自部署的平台",
+ body: [
+ "Utopia 完全运行在部署方(运营者)自行选择的基础设施上。Utopia 项目本身接触不到这个部署:软件不向任何人发送遥测、分析或崩溃报告。",
+ ],
+ },
+ {
+ h: "本实例存了什么",
+ body: ["以下全部存放在运营者自己的服务器上:"],
+ bullets: [
+ "账户信息——你的邮箱、显示名,以及密码的哈希值。",
+ "内容——上传的文档、从中抽取的文本、检索索引与向量,以及据此构建的知识图谱(实体、关系及其出处)。",
+ "活动记录——你与助手的对话、审阅决定与摄入日志,保留它们是为了让依赖它们的功能能够工作。",
+ ],
+ },
+ {
+ h: "数据在什么情况下会离开这台服务器",
+ body: [
+ "若运营者为对话或向量化配置了外部模型服务商,文档片段与你的消息会被发送给该服务商,用于回答问题与索引内容。用哪家服务商——或是否使用完全本地的模型——是一项部署设置。除此之外不向任何地方发送任何内容。",
+ ],
+ },
+ {
+ h: "谁能看到什么",
+ body: [
+ "访问权限按知识库角色划分:只读成员能看到被授权的知识库,编辑者可以修改内容,管理员管理成员与设置。部署管理员可以创建账户并查看用户列表。",
+ ],
+ },
+ {
+ h: "留存与删除",
+ body: [
+ "删除一篇文档会移除它的存储内容与索引条目。已经抽取进知识图谱的事实连同其出处仍会保留,直到在「审阅」中被移除。删除一个知识库会永久移除它的文档、图谱与来源。",
+ ],
+ },
+ {
+ h: "有疑问",
+ body: [
+ "本部署由你所在的组织运营。关于数据在此如何被处理的问题,请联系该组织的管理员。",
+ ],
+ },
+ ],
+ },
+ terms: {
+ title: "使用条款",
+ note: "Utopia 自带的默认文本。运营本部署的组织可以替换成自己的条款。",
+ sections: [
+ {
+ h: "关于这份条款",
+ body: [
+ "这个 Utopia 实例由部署它的组织运营,而非 Utopia 项目。你对它的使用受该组织自身政策约束;在运营者替换之前,这份默认条款覆盖基本事项。",
+ ],
+ },
+ {
+ h: "你的账户",
+ body: [
+ "请勿将凭据交给他人。管理员可依据运营者的政策创建、停用或移除账户。",
+ ],
+ },
+ {
+ h: "可接受的使用",
+ body: [],
+ bullets: [
+ "只上传你有权在组织内存储与共享的内容。",
+ "尊重访问级别:不要试图查看或修改超出你所获角色的知识库。",
+ "不得利用本平台存储或传播违法内容。",
+ ],
+ },
+ {
+ h: "AI 生成的回答",
+ body: [
+ "助手的回答由语言模型基于你所在组织的文档生成,并附引用。它们可能出错或不完整——在依赖之前,请对照被引用的原文核实。",
+ ],
+ },
+ {
+ h: "关于本软件",
+ body: [
+ "Utopia 是开源软件,按「原样」提供,不附带任何形式的担保。运营本部署的责任——包括备份、可用性与合规——由运营者承担。",
+ ],
+ },
+ ],
+ },
+ },
+ library: {
+ title: "文库",
+ upload: "上传文件",
+ uploading: "上传中…",
+ uploadFailed: "上传失败",
+ dropHint: "把文件拖到这里,或点击「上传文件」",
+ formats: "PDF · Word · Excel · PowerPoint · Markdown · HTML · TXT · CSV 等",
+ emptyPull: "还没有文档——这个来源同步时它们会出现。",
+ filterPlaceholder: "按名称筛选",
+ filterNoMatch: "没有文档匹配当前筛选。",
+ colFile: "文件",
+ colStatus: "状态",
+ colGraph: "图谱",
+ colChunks: "文本块",
+ colSize: "大小",
+ colSource: "来源",
+ delete: "删除",
+ extract: "抽取",
+ reExtract: "重新抽取",
+ reprocess: "重新处理",
+ extractProgress: (done: number, total: number) =>
+ `抽取中 · ${done} / ${total}`,
+ errorTitle: "失败详情",
+ errorParse: "摄入管道",
+ errorGraph: "图谱抽取",
+ copyError: "复制",
+ errorCopied: "错误信息已复制",
+ dropsChip: (n: number) => `丢弃 ${n} 条`,
+ dropsTitle: "没能落地的事实",
+ dropsNote:
+ "这些是从文档里抽出来的,但在写入途中被挡下了。每行说明原因与条数。",
+ dropsExample: "例如",
+ dropReason: {
+ attr_domain_mismatch: "属性挂在了错误的类上",
+ subject_not_declared: "主语类型未知",
+ attr_no_value: "属性没有取值",
+ attr_datatype: "取值与数据类型不符",
+ low_confidence: "低于置信度阈值",
+ object_missing: "关系缺少宾语",
+ fallback_relation_missing: "本体里没有兜底关系",
+ },
+ reExtractSource: "重新抽取",
+ reExtractTitle: "重新抽取这个来源?",
+ reExtractHint: (n: number, name: string) =>
+ `「${name}」中全部 ${n} 篇已就绪的文档会再走一遍抽取模型。` +
+ `已有的合并、审阅决定与已确认的事实都会保留。`,
+ reExtractConfirm: "重新抽取",
+ queuedDocs: (n: number) => `已排队 ${n} 篇文档`,
+ rebuild: "重建图谱",
+ rebuildTitle: "重建知识图谱?",
+ rebuildHint: (docs: number, name: string) =>
+ `输入「${name}」确认。本知识库中的每一个实体、事实、合并与待审阅项都会被永久移除,` +
+ `随后全部 ${docs} 篇文档从头重新抽取。` +
+ `文档、检索索引与本体不受影响;决策台账保留。`,
+ rebuildConfirm: "永久重建",
+ rebuildDone: (e: number, f: number, q: number) =>
+ `已清除 ${e} 个实体与 ${f} 条事实 · ${q} 篇文档已排队`,
+ status: {
+ pending: "排队中",
+ parsing: "解析中",
+ indexing: "索引中",
+ embedding: "向量化",
+ ready: "就绪",
+ failed: "失败",
+ },
+ graphStatus: {
+ none: "—",
+ queued: "排队中",
+ extracting: "抽取中",
+ done: "完成",
+ failed: "失败",
+ },
+ sources: "来源",
+ allDocs: "全部文档",
+ uploads: "上传",
+ addSource: "新增来源",
+ sourceKinds: {
+ folder: "文件夹",
+ url: "网页",
+ rss: "RSS 订阅",
+ api: "API",
+ custom: "自定义",
+ },
+ sourceKindHints: {
+ folder:
+ "一个普通文件夹。选中它,把文件直接上传(或拖)进去——不监听、不同步。",
+ url: "抓取所列的网页;内容变化时更新同一篇文档。",
+ rss: "订阅一个源;每条目成为一篇文档,日期取其发布时间。",
+ api: "外部系统把 JSON 文档推送到这里,用这个来源自己的令牌认证。",
+ custom:
+ "按计划轮询一个你控制的 URL——你的服务返回 JSON 条目,Utopia 保持同步。",
+ memory:
+ "从「对话」中记下的片段。只追加:被推翻的记忆是闭合有效区间,而不是删除——" +
+ "时间线保留完整的来龙去脉。",
+ },
+ ingestGuide: "阅读摄入接口指南 →",
+ ingestGuideTitle: "摄入接口指南",
+ endpointField: "接口地址",
+ endpointCopied: "接口地址已复制",
+ copyEndpoint: "点击复制完整地址",
+ pushStatus: {
+ never: "尚未推送",
+ queued: "—",
+ running: "—",
+ ok: "已收到推送",
+ failed: "推送失败",
+ },
+ tokenTitle: "来源令牌",
+ tokenWarning:
+ "持有这个令牌的任何人都能往这个来源推送文档。一旦泄露就轮换——旧令牌立即失效。",
+ tokenUsage: "每次推送时这样带上:",
+ tokenCopied: "令牌已复制",
+ viewToken: "令牌",
+ rotateToken: "轮换",
+ noToken: "这个来源还没有令牌——生成一个即可开始推送。",
+ generateToken: "生成令牌",
+ close: "关闭",
+ authHeaderField: "Authorization 头(可选,不再显示)",
+ syncNow: "立即同步",
+ syncStatus: {
+ never: "从未同步",
+ queued: "排队中",
+ running: "同步中…",
+ ok: "已同步",
+ failed: "同步失败",
+ },
+ lastSyncAdded: (n: number) => `上次同步 +${n}`,
+ sourceName: "名称",
+ urlsField: "网页地址(每行一个)",
+ feedUrl: "订阅地址",
+ interval: "同步计划",
+ intervalManual: "仅手动",
+ intervalEvery: (m: number) =>
+ m < 60 ? `每 ${m} 分钟` : `每 ${m / 60} 小时`,
+ schedule: {
+ manual: "手动",
+ interval: "间隔",
+ daily: "每天",
+ weekly: "每周",
+ advanced: "高级",
+ every: "每",
+ minutes: "分钟",
+ hours: "小时",
+ at: "于",
+ cronPlaceholder: "输入 cron 表达式",
+ whatIsCron: "什么是 cron?",
+ cronDocsUrl: "https://crontab.guru",
+ daysShort: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
+ dailyAt: (t: string) => `每天 ${t}`,
+ },
+ createSource: "创建",
+ cancel: "取消",
+ deleteSource: "删除来源",
+ deleteSourceHint: "文档会保留,并移入「上传」。",
+ newSourceTitle: "新建来源",
+ iconLabel: "图标",
+ pageOf: (from: number, to: number, total: number) =>
+ `${from}–${to} / 共 ${total}`,
+ syncHistory: "历史",
+ runNew: (n: number) => `新增 ${n}`,
+ runUpdated: (n: number) => `更新 ${n}`,
+ runNothing: "无变化",
+ noRuns: "还没有同步记录。",
+ sourceSettings: "来源设置",
+ editSourceTitle: "来源设置",
+ saveChanges: "保存修改",
+ authHeaderEditField: "Authorization 头",
+ authKeepHint: "留空则保持当前值。",
+ editKeepNote:
+ "改变这个来源抓取什么,绝不会删除已有文档。新配置不再返回的条目会在下次同步后" +
+ "标记为「已不在来源中」。要整个换成另一个服务?那就新建一个来源。",
+ notInSource: "已不在来源中",
+ cleanupMissing: (n: number) => `清理 ${n} 篇缺失`,
+ cleanupTitle: "删除缺失的文档",
+ cleanupHint: (n: number, name: string) =>
+ `「${name}」中有 ${n} 篇文档已不在来源里。` +
+ "删除会永久移除它们的内容与检索条目。" +
+ "已经抽取进图谱的事实连同出处仍会保留。",
+ cleanupConfirm: "删除它们",
+ deleteSourceTitle: "删除这个来源",
+ deleteSourceBody: (name: string) =>
+ `输入「${name}」确认。文档会保留并移入「上传」;定时同步停止。`,
+ dangerZone: "危险操作",
+ },
+ search: {
+ placeholder: "检索知识库…(关键词 + 语义)",
+ button: "检索",
+ searching: "检索中…",
+ noResults: "没有结果",
+ chunkOf: (filename: string, seq: number) => `${filename} · 第 ${seq} 段`,
+ },
+ ask: {
+ greeting: "问问 Utopia 记得什么",
+ emptyTitle: "对话",
+ emptyBody:
+ "与你的知识库对话——带引用的回答、关于时间的提问,而且它会记住。\n请先在「文库」上传文档,并在「设置」里配置模型。",
+ placeholder: "问点什么…",
+ composerHint: "回车发送 · Shift+回车 换行",
+ scopeLabel: "知识库",
+ send: "发送",
+ stop: "停止",
+ thinking: "思考中…",
+ newChat: "新对话",
+ untitled: "未命名",
+ noConversations: "还没有对话。",
+ deleteConversation: "删除对话",
+ deleteTitle: "删除这个对话?",
+ deleteHint: (name: string) => `「${name}」及其消息将被永久移除。`,
+ deleteBtn: "删除",
+ cancel: "取消",
+ },
+ graph: {
+ zoomIn: "放大",
+ zoomOut: "缩小",
+ fitView: "适应视图",
+ layoutForce: "力导布局",
+ layoutCircular: "环形布局",
+ layoutPack: "按类型聚簇",
+ searchEntity: "搜索实体…",
+ searchInSubgraph: "在子图中搜索…",
+ backToOverview: "← 全图",
+ emptyBody:
+ "图谱是空的。上传文档并在「设置」里配置对话模型——实体与关系会被自动抽取。",
+ facts: "条事实",
+ noFacts: "这个实体还没有事实",
+ confidence: "置信度",
+ evidence: "证据",
+ noEvidence: "没有记录证据",
+ noQuote: "(无引文)",
+ proposedPredicate: (p: string) => `从原文读作「${p}」`,
+ sectionRef: (filename: string, seq: number) =>
+ `${filename} · 第 ${seq} 段 →`,
+ fromVersion: (v: number) => `v${v}`,
+ staleEvidenceHint:
+ "这条证据来自文档的较早版本。文档此后已更新;事实本身不受影响。",
+ staleFactChip: "未确认",
+ staleFactHint:
+ "这条事实的全部证据都来自来源文档的较早版本——现行内容不再这么说。" +
+ "它可能仍然成立;请到「审阅」里核对。",
+ edit: "编辑",
+ editName: "名称",
+ editType: "类型",
+ editSave: "保存",
+ editCancel: "取消",
+ editSaved: "实体已更新",
+ editEmptyName: "名称不能为空",
+ sameNameNote: (n: number) => `另有 ${n} 个实体同名。`,
+ sameNameHint: "如果它们是同一个东西,去「审阅」里合并。",
+ viewRelations: "关系",
+ viewTimeline: "时间线",
+ viewHistory: "记录历史",
+ historyHint: "这个实体的记录如何变化——以及是谁改的。",
+ historyEmpty: "这个实体还没有记录。",
+ historyKind: {
+ asserted: "记入",
+ corrected: "区间被修正",
+ rejected: "已撤回",
+ merged: "并入了已有事实",
+ },
+ historyEngine: "引擎",
+ historyClosedAt: (t: string) => `闭合于 ${t}`,
+ historyFrom: (t: string) => `自 ${t} 起`,
+ historyOngoing: "未闭合",
+ historicalNote: (n: number) => `另有 ${n} 条历史事实未显示——见时间线 →`,
+ undated: "无日期",
+ timelineEmpty: "还没有带日期的事实。",
+ lastConfirmed: (d: string) => `${d} 确认`,
+ correctedHint:
+ "这个区间是被调和过程闭合的(自动接续或一次审阅决定),并非文档里逐字这么写。" +
+ "被取代的那条断言仍留在台账里。",
+ ongoing: "至今",
+ stats: (n: number, e: number, active: number) =>
+ `${n} 个实体 · ${e} 条事实 · ${active} 条现行`,
+ stabilizing: "布局收敛中",
+ allTime: "全部时间",
+ nowBtn: "现在",
+ play: "播放时间线",
+ pause: "暂停",
+ },
+ doc: {
+ backToLibrary: "← 返回文库",
+ sections: "段",
+ section: "第",
+ citedHere: "← 此处被引用",
+ loading: "加载中…",
+ extracted: "已抽取",
+ ongoing: "至今",
+ },
+ settings: {
+ title: "系统设置",
+ tabModels: "模型",
+ tabMembers: "用户",
+ tabKbs: "知识库",
+ tabDeployment: "部署",
+ newUser: "创建用户",
+ initialPassword: "初始密码(至少 8 位)",
+ createUserBtn: "创建",
+ searchUsers: "按名称或邮箱筛选…",
+ deployment: {
+ openReg: "允许自助注册",
+ openRegHint: "关闭后注册表单不再开放,只有管理员能在此创建账户。",
+ workers: "后台工作线程",
+ workersHint:
+ "同时运行的任务数的外层上限(1–256),作用是防止工作无限堆积。" +
+ "真正的节流是下面的按模型上限,所以这个数留得比它们之和宽裕些。即时生效。",
+ workersApply: "应用",
+ modelConcurrency: "模型并发",
+ modelConcurrencyHint:
+ "一个模型同时接多少个调用。真正起作用的上限属于服务商,而且是按模型算的——" +
+ "本地 Ollama 也许只扛得住两个,托管 API 能到五十。" +
+ "后台工作(抽取、消解、索引)会等空位;对话与检索永远不等。即时生效。",
+ ontologyLang: "默认本体语言",
+ ontologyLangHint:
+ "新建知识库时本体从哪种语言开始——类描述会进抽取提示词," +
+ "所以它跟你预期的文档走,不跟界面走。每个知识库之后可以自己改。" +
+ "界面语言是每个人自己的选择,在账户菜单里。",
+ modelDefault: "默认",
+ modelReset: "重置",
+ modelResetHint: "去掉这个模型自己的上限,回落到默认值。",
+ },
+ datasources: {
+ tab: "数据源",
+ title: "数据源",
+ hint:
+ "只读的数据库连接,用于在「对话」里就你的数据提问。" +
+ "在这里登记连接;每个知识库各自挂载允许查询的那些。",
+ name: "名称",
+ connString: "连接串(postgres://user:pass@host:5432/db)",
+ add: "添加数据源",
+ test: "测试",
+ testOk: "已连接",
+ testFail: "失败",
+ neverTested: "未测试",
+ remove: "移除",
+ },
+ kbs: {
+ hint:
+ "本部署中的全部知识库。公开的对所有成员可读;受限的仅限受邀者。" +
+ "创建知识库是管理员动作——成员在顶栏切换。",
+ defaultChip: "默认",
+ newKb: "新建知识库",
+ name: "名称",
+ description: "描述",
+ visibility: "可见性",
+ visOpen: "公开——本部署内所有人",
+ visRestricted: "仅受邀者",
+ create: "创建",
+ openSettings: "设置",
+ docs: (n: number) => `${n} 篇文档`,
+ },
+ modelsIntro:
+ "OpenAI 兼容协议——DeepSeek、Qwen、GLM、Ollama、vLLM 都可用。完全内网友好。",
+ chatModel: "对话模型",
+ embedModel: "向量模型(可选,启用语义检索)",
+ baseUrl: "接口地址",
+ model: "模型",
+ apiKey: "API 密钥",
+ keyConfigured: "(已配置——留空即保持不变)",
+ save: "保存",
+ saving: "保存中…",
+ saved: "已保存",
+ test: "测试连接",
+ testing: "测试中…",
+ chatLabel: "对话",
+ embedLabel: "向量",
+ ok: (reply: string) => `已连接(${reply})`,
+ okDim: (dim: number) => `已连接(维度 ${dim})`,
+ },
+ ontology: {
+ title: "本体",
+ hint: "类与属性",
+ tabClasses: "类",
+ tabProperties: "属性",
+ newClass: "新建类",
+ newSubClass: "+ 子类",
+ newProperty: "新建属性",
+ filter: "筛选…",
+ missesShort: "未匹配",
+ instances: "实例",
+ instanceFacts: (n: number) => `${n} 条事实`,
+ description: "描述",
+ descriptionHint:
+ "指导抽取器:什么属于这里,配上几个例子。它会被原样送进抽取提示词。",
+ overviewHint: "抽取器遵循的模式。在左侧选一个类或属性来编辑,或用 + 新建。",
+ overviewStats: (c: number, p: number) => `${c} 个类 · ${p} 个属性`,
+ attributes: "属性",
+ attributesHint:
+ "这个类的字面值字段(一个人的薪资、一份合同的金额)。和任何事实一样带证据与历史。",
+ newAttribute: "新建属性",
+ attrDatatype: "值类型",
+ attrUnit: "单位",
+ attrUnitHint: "可选——如 CNY、%",
+ attrSingle: "单值——新值会闭合上一个",
+ datatypeNames: {
+ text: "文本",
+ number: "数字",
+ date: "日期",
+ bool: "是 / 否",
+ },
+ cancel: "取消",
+ key: "Key",
+ label: "标签",
+ color: "颜色",
+ shapeColor: "形状与颜色",
+ parent: "父类",
+ noParent: "(顶层)",
+ temporal: "时态语义",
+ temporalState: "状态(有区间)",
+ temporalEvent: "事件(时间点)",
+ temporalEternal: "恒常(无时间)",
+ functional: "函数性(同一时刻只有一个值)",
+ inverseFunctional: "反函数性(同一时刻一个宾语只对一个主语)",
+ usage: (n: number) => `${n} 处在用`,
+ builtin: "内置",
+ save: "保存",
+ delete: "删除",
+ deleteBlocked: "在用中——无法删除",
+ importShort: "导入",
+ importTitle: "导入本体",
+ importHint:
+ "载入一个 OWL 或 RDFS 文件(.owl、.rdf、.ttl)。类与属性按 IRI 匹配,所以重新导入同一份词汇表的新版本,是更新它已建出来的东西,而不是再建一份。",
+ importPick: "选择文件",
+ importChange: "换一个",
+ importReading: "读取中…",
+ importApplying: "导入中…",
+ importApply: "导入",
+ importCancel: "取消",
+ importParsed: (fmt: string, triples: number) =>
+ `${fmt === "rdfxml" ? "RDF/XML" : "Turtle"} · ${triples.toLocaleString()} 个三元组`,
+ importNothing: "没有可导入的内容——这个文件里没有找到类或属性。",
+ importWillCreate: (n: number) => `新建 ${n}`,
+ importWillUpdate: (n: number) => `更新 ${n}`,
+ importKeyTaken: (n: number) => `跳过 ${n}`,
+ importClasses: "类",
+ importRelations: "关系",
+ importAttributes: "属性",
+ importAttributesLater:
+ "已解析,但尚未建立——属性需要挂在某个类上,那一步在下一版落地。",
+ warnFunctional: (n: number) => `${n} 个关系自称是函数性的`,
+ warnFunctionalBody:
+ "函数性关系同一时刻只能有一个值,所以一条新事实会自动闭合上一条。当词汇表声称的唯一性你的数据并不遵守时,结果就是一队冲突。导入后请去核对它们。",
+ warnNoDescription: (n: number) => `${n} 个类没有描述`,
+ warnNoDescriptionBody:
+ "类的描述会被原样送进抽取提示词——它是唯一告诉模型「什么算这个类」的东西。给它们补上,否则它们会悄悄少抽。",
+ warnKeyTaken: (n: number) => `${n} 个 key 已被占用`,
+ warnKeyTakenBody:
+ "已经有另一个身份占着这个 key。它们被原样留下——如果你想要导入的那一份,先把现有的改名。",
+ importTakenBy: (iri: string | null) =>
+ iri ? `被 ${iri} 占用` : "被这个知识库里已有的条目占用",
+ importUnprojected: "暂未投影",
+ importUnprojectedBody:
+ "这个文件用到、而 Utopia 目前还不消费的公理。什么都没丢:原文按上传时的样子存着,将来的版本可以投影它们。",
+ importDone: (created: number, updated: number) =>
+ `导入完成——新建 ${created} 个类,更新 ${updated} 个。`,
+ importHistory: "历次导入",
+ importNoHistory: "还没有导入过。",
+ importBy: (who: string, when: string) => `${who} · ${when}`,
+ importSize: (bytes: number) =>
+ bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(0)} KB`,
+ misses: "抽取中未匹配的",
+ missesHint:
+ "抽取器产出了这些,但它们不在你的本体里(于是降级成了 concept / related to)。它们是扩展本体的信号。",
+ dismiss: "忽略",
+ suggest: "用 AI 建议",
+ suggesting: "分析中…",
+ noMisses: "没有未匹配的类型——本体覆盖了你的语料。",
+ approve: "加入",
+ willRemap: (n: number) => `将重新归类 ${n} 条事实`,
+ adopted: (n: number) => `已加入——${n} 条事实已重新归类`,
+ undoAdopt: (key: string, n: number) =>
+ `已加入 ${key},${n} 条事实已重新归类`,
+ undoAdoptBtn: "撤销",
+ reverted: (n: number) => `已撤销——${n} 条事实已复原`,
+ undoKeepsRelation: "关系保留;只有事实被移回去。",
+ undoTitle: "撤销这次本体变更?",
+ undoHint: (n: number) =>
+ `${n} 条事实会回到「related to」。关系本身保留——` +
+ `什么都不会被删除,之后仍可再次采纳。`,
+ undoConfirm: "撤销",
+ undoCancel: "保持",
+ autoRanTitle: "Utopia 依据你的文档扩展了这个本体",
+ autoRanBody: (rels: string[], facts: number) =>
+ `新增 ${rels.join("、")} · ${facts} 条事实已重新归类`,
+ autoRanOff: "可在知识库设置里关掉它。",
+ addAll: (n: number) => `全部加入(${n})`,
+ addingAll: "加入中…",
+ addAllLabel: "批量",
+ addAllPartial: (keys: string[]) =>
+ `有几个没能加入:${keys.join("、")}——其余的已经成功。`,
+ proposals: "AI 提案",
+ keyHint: "小写下划线命名",
+ },
+ review: {
+ title: "审阅",
+ hint: "重复项与低置信度事实",
+ tabQueue: "队列",
+ tabHistory: "历史",
+ empty: "没有待审阅的——图谱是干净的。",
+ historyEmpty: "还没有合并记录。",
+ railDuplicates: "重复项",
+ railConflicts: "冲突",
+ railUnconfirmed: "未确认",
+ railLowConfidence: "低置信度",
+ railDecisions: "决定",
+ railMerges: "合并",
+ categoryEmpty: "这个队列是空的。",
+ decisionsTitle: "决定",
+ decisionsHint:
+ "每一次审阅决定、由谁在何时做出——快照在决定当时留存,即使底下的事实已经不在了也保留。",
+ decisionsEmpty: "还没有决定记录。",
+ aiActor: "AI 裁决",
+ decisionActions: {
+ "review.merge": "已合并",
+ "review.keep": "保持分开",
+ "fact.confirm": "已确认",
+ "fact.reject": "已驳回",
+ "fact.close": "已闭合",
+ "conflict.close_old": "闭合旧的",
+ "conflict.keep_both": "两条都留",
+ "conflict.reject_new": "驳回新的",
+ "merge.revert": "撤销合并",
+ "merge.manual": "手动合并",
+ },
+ escalated: {
+ escalate_no_model: "没有对话模型——裁决跑不起来",
+ escalate_no_verdict: "裁决没有给出结论",
+ escalate_entity_changed: "裁决过程中实体发生了变化",
+ escalate_unsure: "裁决的把握不够",
+ contains: "一个名字包含另一个",
+ ambiguous_name: "同名,但上下文没能定夺",
+ type_drift: "同名,但类型不同",
+ auto_merged: "AI 裁决已自动合并",
+ kept_apart: "AI 裁决认为不是同一个",
+ } as Record<string, string>,
+ duplicates: "可能重复",
+ duplicatesHint:
+ "同名,但上下文不同。AI 在后台裁决明确的情形;其余等你。合并永远可撤销。",
+ stageAdjudicating: "AI 裁决中",
+ stageHuman: "需要你来定",
+ similarity: (pct: number) => `上下文相似度 ${pct}%`,
+ factsCount: (n: number) => `${n} 条事实`,
+ noFacts: "没有记录的事实",
+ merge: "合并",
+ keep: "保持分开",
+ lowConfidence: "低置信度事实",
+ lowConfidenceHint:
+ "抽取时置信度低于 75%。确认表示采信,驳回表示从图谱移除(台账仍留有记录)。",
+ confirm: "确认",
+ reject: "驳回",
+ confidence: (pct: number) => `${pct}%`,
+ mergeHistory: "合并历史",
+ mergedBy: (name: string) => `由 ${name}`,
+ mergedByAi: "由 AI 裁决",
+ revert: "撤销",
+ reverted: "已撤销",
+ ongoing: "至今",
+ conflicts: "时态冲突",
+ conflictsHint:
+ "两条事实主张同一个单值关系。明确的接续会自动闭合;" +
+ "这些需要人来定。闭合可通过台账撤销。",
+ conflictReason: {
+ no_time: "新事实没有日期",
+ simultaneous: "起始日期相同",
+ low_confidence: "置信度低",
+ },
+ conflictVs: "对",
+ conflictSince: (d: string) => `自 ${d} 起`,
+ closeOld: "闭合旧的",
+ closeOldAt: (d: string) => `在 ${d} 闭合旧的`,
+ keepBoth: "两条都留",
+ rejectNew: "驳回新的",
+ closeAtPlaceholder: "YYYY-MM-DD",
+ unconfirmed: "已不再被陈述",
+ unconfirmedHint:
+ "曾经陈述这些事实的每一个来源,此后都更新过且不再包含它们。" +
+ "系统不会自动删除任何东西——没提到不等于否定。抽取错误就驳回," +
+ "真正结束了的就闭合(选它结束的日期)。",
+ closeFact: "闭合",
+ closeFactAt: (d: string) => `在 ${d} 闭合`,
+ },
+ ui: {
+ noMatches: "没有匹配",
+ keepTyping: (n: number) => `还有 ${n} 项——继续输入以缩小范围`,
+ },
+ kbset: {
+ title: "知识库设置",
+ general: "常规",
+ members: "成员",
+ autoExtend: "自动扩展本体",
+ autoExtendNote:
+ "当抽取遇到这个本体里没有的关系时,把它加进来,并把一直等着它的那些事实重新归类。" +
+ "每一次变更都会列出,并且可以撤销。关掉它并不会让 Utopia 不再留意——" +
+ "那些说法仍然会汇集到「未匹配」下,只是要等你点头。",
+ ontologyLang: "本体的语言",
+ ontologyLangNote:
+ "类与关系的描述用哪种语言写。它们会被原样送进抽取提示词," +
+ "所以读者是正在读你文档的模型——跟你的文档一致,而不是跟界面一致。" +
+ "改这一项不会重写已经写好的;它决定的是此后新写的描述用什么语言。",
+ defaultOpenLabel: "对所有人开放",
+ defaultOpenNote:
+ "这是本部署的默认知识库,所以可见性被锁定:每位成员在这里至少有只读权限," +
+ "这保证了没有人登录后面对一片空白。出于同样的原因它也不能被删除。" +
+ "要给某人超出只读的权限,在「成员」里授予角色;需要私密空间的话," +
+ "另建一个知识库并设为受限。",
+ data: "数据",
+ dataHint:
+ "已挂载的只读数据库,本知识库可以在「对话」里查询它们。" +
+ "挂载会摄入数据库模式,好让助手知道有哪些表。",
+ dataMount: "挂载",
+ dataUnmount: "卸载",
+ dataSyncSchema: "刷新模式",
+ dataSchemaSynced: (n: number) => `模式已摄入(${n} 张表)`,
+ dataExplore: "探查映射",
+ dataExploreHint:
+ "一个智能体读取这些模式并提出指标/维度定义——在「对话」用上它们之前,先到「审阅」里过一遍。",
+ dataExploreQueued: "探查已排队——提案稍后会出现在「审阅」中。",
+ dataNone: "没有挂载任何数据源。",
+ dataNoneAvailable: "还没有登记数据源——请部署管理员登记一个。",
+ dataNewConn: "登记新连接",
+ activity: "活动",
+ activityHint: "谁在这个知识库里改了什么。纯审计——记录只追加。",
+ activityEmpty: "还没有记录。",
+ deletedUser: "一位已移除的用户",
+ auditActions: {
+ "entity_type.created": "创建了实体类型",
+ "entity_type.updated": "更新了实体类型",
+ "entity_type.deleted": "删除了一个实体类型",
+ "relation_type.created": "创建了关系类型",
+ "relation_type.updated": "更新了关系类型",
+ "relation_type.deleted": "删除了一个关系类型",
+ "kb.updated": "更新了知识库设置",
+ "kb.member_set": "设置了成员角色",
+ "kb.member_removed": "移除了成员",
+ "source.created": "创建了来源",
+ "source.updated": "更新了来源",
+ "source.deleted": "删除了一个来源",
+ "document.deleted": "删除了文档",
+ "ontology.imported": "导入了一份本体",
+ },
+ membersHint:
+ "本部署内的所有人都能读公开知识库;写权限在这里授予" +
+ "(部署管理员始终拥有)。受邀制的知识库只有这里列出的人能看到。",
+ addMember: "添加…",
+ roles: { viewer: "只读", editor: "编辑者", admin: "管理员" },
+ remove: "移除",
+ noMembers: "没有设置任何库内角色。",
+ save: "保存",
+ saved: "已保存",
+ danger: "危险操作",
+ deleteKb: "删除这个知识库",
+ deleteHint: (name: string) =>
+ `输入「${name}」确认。文档、图谱与来源都将被永久移除。`,
+ deleteBtn: "永久删除",
+ deleteRowTitle: "删除这个知识库",
+ deleteRowHint: "文档、图谱与来源都将被永久移除。",
+ deleteRowBtn: "删除",
+ },
+ members: {
+ title: "部署用户",
+ systemAdmin: "系统管理员",
+ remove: "移除",
+ pickUser: "选择要添加的用户…",
+ add: "添加",
+ allAdded: "本部署内的所有人都已是成员。新注册的用户会出现在这里。",
+ roles: {
+ owner: "所有者",
+ admin: "管理员",
+ editor: "编辑者",
+ viewer: "只读",
+ },
+ },
+};
diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsx
index 1f2d9d53..b76ab414 100644
--- a/web/src/pages/KbSettings.tsx
+++ b/web/src/pages/KbSettings.tsx
@@ -15,9 +15,15 @@ import {
Users,
} from "lucide-react";
import { api, type AuditEvent } from "../api";
-import { S } from "../i18n";
+import { LANG_NAMES, S } from "../i18n";
import { useKb } from "../kb";
-import { DangerConfirm, Dropdown, Loading, RAIL_CLS, SearchSelect } from "../ui";
+import {
+ DangerConfirm,
+ Dropdown,
+ Loading,
+ RAIL_CLS,
+ SearchSelect,
+} from "../ui";
const KB_ROLES = [
{ value: "viewer", label: S.kbset.roles.viewer },
@@ -45,6 +51,7 @@ export function KbSettings() {
const [desc, setDesc] = useState("");
const [visibility, setVisibility] = useState<"open" | "restricted">("open");
const [autoExtend, setAutoExtend] = useState(true);
+ const [ontoLang, setOntoLang] = useState<"en" | "zh">("en");
const [confirmingDelete, setConfirmingDelete] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -54,6 +61,7 @@ export function KbSettings() {
setDesc(kb.data.description ?? "");
setVisibility(kb.data.visibility);
setAutoExtend(kb.data.auto_extend_ontology);
+ setOntoLang(kb.data.ontology_lang);
}
}, [kb.data]);
@@ -69,6 +77,7 @@ export function KbSettings() {
description: desc.trim() || null,
visibility,
auto_extend_ontology: autoExtend,
+ ontology_lang: ontoLang,
}),
onSuccess: () => {
setError(null);
@@ -88,14 +97,23 @@ export function KbSettings() {
if (!kbId || kb.isPending) return <Loading>{S.nav.loading}</Loading>;
if (kb.isError)
- return <div className="p-8 text-sm text-rose-400">{(kb.error as Error).message}</div>;
+ return (
+ <div className="p-8 text-sm text-rose-400">
+ {(kb.error as Error).message}
+ </div>
+ );
const lbl = "block text-xs font-medium text-neutral-500 mb-1";
const rail =
"w-full flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-left transition-colors";
const isDefault = kb.data.is_default;
- const sections: { key: Section; label: string; Icon: typeof Settings2; danger?: boolean }[] = [
+ const sections: {
+ key: Section;
+ label: string;
+ Icon: typeof Settings2;
+ danger?: boolean;
+ }[] = [
{ key: "general", label: S.kbset.general, Icon: Settings2 },
{ key: "members", label: S.kbset.members, Icon: Users },
{ key: "data", label: S.kbset.data, Icon: Database },
@@ -103,7 +121,14 @@ export function KbSettings() {
// 默认库不可删除:danger 节整个不出现
...(isDefault
? []
- : [{ key: "danger" as Section, label: S.kbset.danger, Icon: TriangleAlert, danger: true }]),
+ : [
+ {
+ key: "danger" as Section,
+ label: S.kbset.danger,
+ Icon: TriangleAlert,
+ danger: true,
+ },
+ ]),
];
return (
@@ -200,12 +225,39 @@ export function KbSettings() {
onChange={(e) => setAutoExtend(e.target.checked)}
/>
<span className="min-w-0">
- <span className="block text-sm text-neutral-200">{S.kbset.autoExtend}</span>
+ <span className="block text-sm text-neutral-200">
+ {S.kbset.autoExtend}
+ </span>
<span className="block text-xs leading-relaxed text-neutral-500">
{S.kbset.autoExtendNote}
</span>
</span>
</label>
+ {/* 语料语言。**不是界面语言**——类描述逐字进抽取提示词,
+ 读者是正在读这些文档的模型,所以它跟文档走不跟读者走 */}
+ <div className="pt-1">
+ <span className="block text-sm text-neutral-200">
+ {S.kbset.ontologyLang}
+ </span>
+ <span className="mt-0.5 block text-xs leading-relaxed text-neutral-500">
+ {S.kbset.ontologyLangNote}
+ </span>
+ <div className="mt-2 flex gap-1 rounded-lg bg-white/5 p-1 w-fit">
+ {(["en", "zh"] as const).map((l) => (
+ <button
+ key={l}
+ onClick={() => setOntoLang(l)}
+ className={`rounded-md px-3 py-1 text-[12px] font-medium transition-colors ${
+ ontoLang === l
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:text-neutral-300"
+ }`}
+ >
+ {LANG_NAMES[l]}
+ </button>
+ ))}
+ </div>
+ </div>
<div className="flex items-center gap-3">
<button
className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
@@ -215,7 +267,9 @@ export function KbSettings() {
{S.kbset.save}
</button>
{save.isSuccess && (
- <span className="text-xs text-neutral-400">{S.kbset.saved}</span>
+ <span className="text-xs text-neutral-400">
+ {S.kbset.saved}
+ </span>
)}
</div>
</div>
@@ -232,11 +286,16 @@ export function KbSettings() {
<div className="text-sm font-medium text-neutral-200">
{S.kbset.deleteRowTitle}
</div>
- <div className="mt-0.5 text-xs text-neutral-500">{S.kbset.deleteRowHint}</div>
+ <div className="mt-0.5 text-xs text-neutral-500">
+ {S.kbset.deleteRowHint}
+ </div>
</div>
<button
className="u-btn px-3.5 py-1.5 text-xs font-semibold shrink-0"
- style={{ background: "var(--u-danger-solid)", color: "#ffffff" }}
+ style={{
+ background: "var(--u-danger-solid)",
+ color: "#ffffff",
+ }}
onClick={() => setConfirmingDelete(true)}
>
{S.kbset.deleteRowBtn}
@@ -289,7 +348,10 @@ function KbActivity({ kbId }: { kbId: string }) {
) : (
<div className="space-y-0.5">
{events.map((e) => (
- <div key={e.id} className="flex items-baseline gap-3 py-1.5 text-[13px]">
+ <div
+ key={e.id}
+ className="flex items-baseline gap-3 py-1.5 text-[13px]"
+ >
<span className="u-num shrink-0 text-[11px] text-neutral-600">
{e.created_at.slice(0, 16).replace("T", " ")}
</span>
@@ -301,7 +363,10 @@ function KbActivity({ kbId }: { kbId: string }) {
{S.kbset.auditActions[e.action] ?? e.action}
</span>
{auditDetailName(e) && (
- <span className="text-neutral-300"> “{auditDetailName(e)}”</span>
+ <span className="text-neutral-300">
+ {" "}
+ “{auditDetailName(e)}”
+ </span>
)}
</span>
</div>
@@ -328,7 +393,8 @@ function KbDataSources({ kbId }: { kbId: string }) {
});
const [picked, setPicked] = useState("");
const [notice, setNotice] = useState<string | null>(null);
- const invalidate = () => queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });
const mount = useMutation({
mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),
@@ -351,8 +417,12 @@ function KbDataSources({ kbId }: { kbId: string }) {
onSuccess: () => setNotice(S.kbset.dataExploreQueued),
});
- const mountedIds = new Set((mounted.data?.data_sources ?? []).map((d) => d.id));
- const mountable = (available.data?.data_sources ?? []).filter((d) => !mountedIds.has(d.id));
+ const mountedIds = new Set(
+ (mounted.data?.data_sources ?? []).map((d) => d.id),
+ );
+ const mountable = (available.data?.data_sources ?? []).filter(
+ (d) => !mountedIds.has(d.id),
+ );
return (
<div className="space-y-4">
@@ -363,7 +433,9 @@ function KbDataSources({ kbId }: { kbId: string }) {
<div key={d.id} className="px-4 py-3 flex items-center gap-3">
<div className="min-w-0 flex-1">
<div className="text-sm text-neutral-200">{d.name}</div>
- <div className="text-xs text-neutral-500 font-mono truncate">{d.summary}</div>
+ <div className="text-xs text-neutral-500 font-mono truncate">
+ {d.summary}
+ </div>
</div>
<button
className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
@@ -382,7 +454,9 @@ function KbDataSources({ kbId }: { kbId: string }) {
</div>
))}
{mounted.data?.data_sources.length === 0 && (
- <p className="px-4 py-6 text-sm text-neutral-500">{S.kbset.dataNone}</p>
+ <p className="px-4 py-6 text-sm text-neutral-500">
+ {S.kbset.dataNone}
+ </p>
)}
</div>
@@ -391,7 +465,11 @@ function KbDataSources({ kbId }: { kbId: string }) {
<SearchSelect
className="flex-1"
value={picked}
- options={mountable.map((d) => ({ value: d.id, label: d.name, hint: d.summary }))}
+ options={mountable.map((d) => ({
+ value: d.id,
+ label: d.name,
+ hint: d.summary,
+ }))}
onChange={setPicked}
placeholder={S.kbset.dataMount + "…"}
/>
@@ -408,7 +486,9 @@ function KbDataSources({ kbId }: { kbId: string }) {
{me.data?.is_admin ? (
<button
className="flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
- onClick={() => navigate({ to: "/admin", search: { tab: "datasources" } })}
+ onClick={() =>
+ navigate({ to: "/admin", search: { tab: "datasources" } })
+ }
>
<Plus size={12} />
{S.kbset.dataNewConn}
@@ -417,12 +497,16 @@ function KbDataSources({ kbId }: { kbId: string }) {
mountable.length === 0 &&
available.data &&
(mounted.data?.data_sources.length ?? 0) === 0 && (
- <p className="text-xs text-neutral-600">{S.kbset.dataNoneAvailable}</p>
+ <p className="text-xs text-neutral-600">
+ {S.kbset.dataNoneAvailable}
+ </p>
)
)}
{(mounted.data?.data_sources.length ?? 0) > 0 && (
<div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
- <p className="text-xs text-neutral-500 flex-1">{S.kbset.dataExploreHint}</p>
+ <p className="text-xs text-neutral-500 flex-1">
+ {S.kbset.dataExploreHint}
+ </p>
<button
className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
disabled={explore.isPending}
@@ -452,7 +536,8 @@ function KbMembers({ kbId }: { kbId: string }) {
const [addUserId, setAddUserId] = useState("");
const [addRole, setAddRole] = useState("viewer");
- const invalidate = () => queryClient.invalidateQueries({ queryKey: ["kbMembers", kbId] });
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ["kbMembers", kbId] });
const setMember = useMutation({
mutationFn: ({ userId, role }: { userId: string; role: string }) =>
@@ -514,11 +599,18 @@ function KbMembers({ kbId }: { kbId: string }) {
hint: u.email,
}))}
/>
- <Dropdown className="w-24" value={addRole} onChange={setAddRole} options={KB_ROLES} />
+ <Dropdown
+ className="w-24"
+ value={addRole}
+ onChange={setAddRole}
+ options={KB_ROLES}
+ />
<button
className="u-btn u-btn-primary px-3 py-1.5 text-xs"
disabled={!addUserId || setMember.isPending}
- onClick={() => setMember.mutate({ userId: addUserId, role: addRole })}
+ onClick={() =>
+ setMember.mutate({ userId: addUserId, role: addRole })
+ }
>
{S.members.add}
</button>
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 92f76cba..449361fe 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -20,6 +20,14 @@ const CONFLICT_PAGE = 8;
const ym = (iso: string | null) => (iso ? iso.slice(0, 7) : null);
+/** `code` 或 `code|detail`。查不到就原样显示——存量行里还是旧的英文散文 */
+function escalationText(reason: string): string {
+ const [code, detail] = reason.split("|");
+ const worded = S.review.escalated[code];
+ if (!worded) return reason;
+ return detail ? S.errDetail(worded, detail) : worded;
+}
+
function dateRange(from: string | null, to: string | null): string | null {
if (!from && !to) return null;
return `${ym(from) ?? "…"} → ${ym(to) ?? S.review.ongoing}`;
@@ -33,9 +41,13 @@ function SideCard({ side }: { side: ReviewSide }) {
className="h-2.5 w-2.5 rounded-full shrink-0"
style={{ backgroundColor: side.color }}
/>
- <span className="text-sm font-medium text-white truncate">{side.name}</span>
+ <span className="text-sm font-medium text-white truncate">
+ {side.name}
+ </span>
{side.disambiguator && (
- <span className="text-xs text-neutral-500 truncate">· {side.disambiguator}</span>
+ <span className="text-xs text-neutral-500 truncate">
+ · {side.disambiguator}
+ </span>
)}
</div>
<div className="text-xs text-neutral-500 mb-2">
@@ -76,13 +88,17 @@ function DuplicateCard({
<span
className={`u-chip ${item.stage === "human" ? "u-chip-warn" : "u-chip-neutral"}`}
>
- {item.stage === "human" ? S.review.stageHuman : S.review.stageAdjudicating}
+ {item.stage === "human"
+ ? S.review.stageHuman
+ : S.review.stageAdjudicating}
</span>
<span className="text-xs text-neutral-500">
{S.review.similarity(Math.round(item.score * 100))}
</span>
{item.reason && (
- <span className="text-xs text-neutral-600 truncate min-w-0">{item.reason}</span>
+ <span className="text-xs text-neutral-600 truncate min-w-0">
+ {escalationText(item.reason)}
+ </span>
)}
<div className="ml-auto flex gap-2 shrink-0">
<button
@@ -120,16 +136,24 @@ function FactRow({
return (
<div className="glass rounded-xl p-4">
<div className="flex items-center gap-2 flex-wrap">
- <span className="text-sm font-medium text-white">{fact.subject_name}</span>
- <span className="text-xs text-neutral-500">— {fact.predicate_label} →</span>
- <span className="text-sm font-medium text-white">{fact.object_name ?? "?"}</span>
+ <span className="text-sm font-medium text-white">
+ {fact.subject_name}
+ </span>
+ <span className="text-xs text-neutral-500">
+ — {fact.predicate_label} →
+ </span>
+ <span className="text-sm font-medium text-white">
+ {fact.object_name ?? "?"}
+ </span>
{range && <span className="text-xs text-neutral-500">({range})</span>}
<span className="u-chip u-chip-warn ml-auto">
{S.review.confidence(Math.round(fact.confidence * 100))}
</span>
</div>
{fact.quote && (
- <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">“{fact.quote}”</p>
+ <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">
+ “{fact.quote}”
+ </p>
)}
<div className="mt-3 flex gap-2 justify-end">
<button
@@ -159,7 +183,10 @@ function ConflictRow({
}: {
conflict: ConflictItem;
busy: boolean;
- onResolve: (action: "close" | "keep" | "reject_new", closeAt?: string) => void;
+ onResolve: (
+ action: "close" | "keep" | "reject_new",
+ closeAt?: string,
+ ) => void;
}) {
const [closeAt, setCloseAt] = useState("");
const c = conflict;
@@ -173,8 +200,12 @@ function ConflictRow({
<div className="glass rounded-xl p-4">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium text-white">{c.old_subject}</span>
- <span className="text-xs text-neutral-500">— {c.predicate_label} →</span>
- <span className="text-sm font-medium text-white">{c.old_object ?? "?"}</span>
+ <span className="text-xs text-neutral-500">
+ — {c.predicate_label} →
+ </span>
+ <span className="text-sm font-medium text-white">
+ {c.old_object ?? "?"}
+ </span>
{c.old_valid_from && (
<span className="u-num text-xs text-neutral-500">
({S.review.conflictSince(c.old_valid_from.slice(0, 10))})
@@ -182,8 +213,12 @@ function ConflictRow({
)}
<span className="text-xs text-neutral-600">{S.review.conflictVs}</span>
<span className="text-sm font-medium text-white">{c.new_subject}</span>
- <span className="text-xs text-neutral-500">— {c.predicate_label} →</span>
- <span className="text-sm font-medium text-white">{c.new_object ?? "?"}</span>
+ <span className="text-xs text-neutral-500">
+ — {c.predicate_label} →
+ </span>
+ <span className="text-sm font-medium text-white">
+ {c.new_object ?? "?"}
+ </span>
{c.new_valid_from && (
<span className="u-num text-xs text-neutral-500">
({S.review.conflictSince(c.new_valid_from.slice(0, 10))})
@@ -251,13 +286,23 @@ function UnconfirmedRow({
return (
<div className="glass rounded-xl p-4">
<div className="flex items-center gap-2 flex-wrap">
- <span className="text-sm font-medium text-white">{fact.subject_name}</span>
- <span className="text-xs text-neutral-500">— {fact.predicate_label} →</span>
- <span className="text-sm font-medium text-white">{fact.object_name ?? "?"}</span>
- {range && <span className="u-num text-xs text-neutral-500">({range})</span>}
+ <span className="text-sm font-medium text-white">
+ {fact.subject_name}
+ </span>
+ <span className="text-xs text-neutral-500">
+ — {fact.predicate_label} →
+ </span>
+ <span className="text-sm font-medium text-white">
+ {fact.object_name ?? "?"}
+ </span>
+ {range && (
+ <span className="u-num text-xs text-neutral-500">({range})</span>
+ )}
</div>
{fact.quote && (
- <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">“{fact.quote}”</p>
+ <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">
+ “{fact.quote}”
+ </p>
)}
<div className="mt-3 flex items-center gap-2 justify-end">
<button
@@ -278,7 +323,9 @@ function UnconfirmedRow({
disabled={busy || !closeAtIso}
onClick={() => closeAtIso && onClose(closeAtIso)}
>
- {closeAt.trim() ? S.review.closeFactAt(closeAt.trim()) : S.review.closeFact}
+ {closeAt.trim()
+ ? S.review.closeFactAt(closeAt.trim())
+ : S.review.closeFact}
</button>
</div>
</div>
@@ -303,14 +350,18 @@ function MergeRow({
<span className="text-white">{merge.target_name}</span>
</div>
<div className="text-xs text-neutral-500 truncate">
- {merge.merged_by_name ? S.review.mergedBy(merge.merged_by_name) : S.review.mergedByAi}
+ {merge.merged_by_name
+ ? S.review.mergedBy(merge.merged_by_name)
+ : S.review.mergedByAi}
{" · "}
{merge.created_at.slice(0, 10)}
- {merge.reason ? ` · ${merge.reason}` : ""}
+ {merge.reason ? ` · ${escalationText(merge.reason)}` : ""}
</div>
</div>
{merge.reverted_at ? (
- <span className="u-chip u-chip-neutral shrink-0">{S.review.reverted}</span>
+ <span className="u-chip u-chip-neutral shrink-0">
+ {S.review.reverted}
+ </span>
) : (
<button
className="u-btn u-btn-ghost px-3 py-1.5 text-xs shrink-0"
@@ -380,9 +431,20 @@ function DecisionRow({ e }: { e: ReviewHistoryEvent }) {
/* ---------- 页面:左栏分类 + 单类内容区 ---------- */
-type Sel = "duplicates" | "conflicts" | "unconfirmed" | "lowconf" | "decisions" | "merges";
-
-const QUEUE_ORDER: Sel[] = ["duplicates", "conflicts", "unconfirmed", "lowconf"];
+type Sel =
+ | "duplicates"
+ | "conflicts"
+ | "unconfirmed"
+ | "lowconf"
+ | "decisions"
+ | "merges";
+
+const QUEUE_ORDER: Sel[] = [
+ "duplicates",
+ "conflicts",
+ "unconfirmed",
+ "lowconf",
+];
const PAGE_SIZE: Record<Sel, number> = {
duplicates: DUP_PAGE,
conflicts: CONFLICT_PAGE,
@@ -416,7 +478,9 @@ function RailItem({
onClick={onClick}
className={cn(
"w-full flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] transition-colors",
- active ? "u-nav-active" : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",
+ active
+ ? "u-nav-active"
+ : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",
)}
>
<span className="truncate">{label}</span>
@@ -465,8 +529,16 @@ export function Review() {
onSettled: invalidate,
});
const factAction = useMutation({
- mutationFn: ({ id, action }: { id: string; action: "confirm" | "reject" }) =>
- action === "confirm" ? api.confirmFact(kb!.id, id) : api.rejectFact(kb!.id, id),
+ mutationFn: ({
+ id,
+ action,
+ }: {
+ id: string;
+ action: "confirm" | "reject";
+ }) =>
+ action === "confirm"
+ ? api.confirmFact(kb!.id, id)
+ : api.rejectFact(kb!.id, id),
onSettled: invalidate,
});
const revert = useMutation({
@@ -505,7 +577,8 @@ export function Review() {
// 首批数据到达:定位到第一个非空队列(全空落在 duplicates 显示"干净"文案)
useEffect(() => {
- if (sel === null && data) setSel(QUEUE_ORDER.find((k) => counts[k] > 0) ?? "duplicates");
+ if (sel === null && data)
+ setSel(QUEUE_ORDER.find((k) => counts[k] > 0) ?? "duplicates");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data]);
@@ -520,8 +593,14 @@ export function Review() {
const SECTION: Record<Sel, { title: string; hint: string | null }> = {
duplicates: { title: S.review.duplicates, hint: S.review.duplicatesHint },
conflicts: { title: S.review.conflicts, hint: S.review.conflictsHint },
- unconfirmed: { title: S.review.unconfirmed, hint: S.review.unconfirmedHint },
- lowconf: { title: S.review.lowConfidence, hint: S.review.lowConfidenceHint },
+ unconfirmed: {
+ title: S.review.unconfirmed,
+ hint: S.review.unconfirmedHint,
+ },
+ lowconf: {
+ title: S.review.lowConfidence,
+ hint: S.review.lowConfidenceHint,
+ },
decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },
merges: { title: S.review.mergeHistory, hint: null },
};
@@ -577,9 +656,13 @@ export function Review() {
{/* 右侧:一次只显示选中的一类,单一分页 */}
<div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">
<div className="max-w-4xl">
- {review.isPending && <p className="text-sm text-neutral-500">{S.nav.loading}</p>}
+ {review.isPending && (
+ <p className="text-sm text-neutral-500">{S.nav.loading}</p>
+ )}
{review.isError && (
- <p className="text-sm text-rose-400">{(review.error as Error).message}</p>
+ <p className="text-sm text-rose-400">
+ {(review.error as Error).message}
+ </p>
)}
{data && (
@@ -587,7 +670,9 @@ export function Review() {
{/* 页级标题:与 Library/KB Settings 同级(text-lg),不是卡片头 */}
<h2 className="u-title text-lg mb-1">{SECTION[active].title}</h2>
{SECTION[active].hint && (
- <p className="text-xs text-neutral-500 mb-3">{SECTION[active].hint}</p>
+ <p className="text-xs text-neutral-500 mb-3">
+ {SECTION[active].hint}
+ </p>
)}
{/* 空态:整个待办全清 vs 单类清空 */}
@@ -603,8 +688,12 @@ export function Review() {
<DuplicateCard
key={item.id}
item={item}
- busy={decide.isPending && decide.variables?.id === item.id}
- onDecide={(action) => decide.mutate({ id: item.id, action })}
+ busy={
+ decide.isPending && decide.variables?.id === item.id
+ }
+ onDecide={(action) =>
+ decide.mutate({ id: item.id, action })
+ }
/>
))}
</div>
@@ -612,33 +701,46 @@ export function Review() {
{active === "conflicts" && counts.conflicts > 0 && (
<div className="space-y-3">
- {pageSlice(data.conflicts, page, CONFLICT_PAGE).rows.map((c) => (
- <ConflictRow
- key={c.id}
- conflict={c}
- busy={conflictAction.isPending && conflictAction.variables?.id === c.id}
- onResolve={(action, closeAt) =>
- conflictAction.mutate({ id: c.id, action, closeAt })
- }
- />
- ))}
+ {pageSlice(data.conflicts, page, CONFLICT_PAGE).rows.map(
+ (c) => (
+ <ConflictRow
+ key={c.id}
+ conflict={c}
+ busy={
+ conflictAction.isPending &&
+ conflictAction.variables?.id === c.id
+ }
+ onResolve={(action, closeAt) =>
+ conflictAction.mutate({ id: c.id, action, closeAt })
+ }
+ />
+ ),
+ )}
</div>
)}
{active === "unconfirmed" && counts.unconfirmed > 0 && (
<div className="space-y-3">
- {pageSlice(data.unconfirmed, page, FACT_PAGE).rows.map((fact) => (
- <UnconfirmedRow
- key={fact.id}
- fact={fact}
- busy={
- (factAction.isPending && factAction.variables?.id === fact.id) ||
- (closeFactAction.isPending && closeFactAction.variables?.id === fact.id)
- }
- onReject={() => factAction.mutate({ id: fact.id, action: "reject" })}
- onClose={(validTo) => closeFactAction.mutate({ id: fact.id, validTo })}
- />
- ))}
+ {pageSlice(data.unconfirmed, page, FACT_PAGE).rows.map(
+ (fact) => (
+ <UnconfirmedRow
+ key={fact.id}
+ fact={fact}
+ busy={
+ (factAction.isPending &&
+ factAction.variables?.id === fact.id) ||
+ (closeFactAction.isPending &&
+ closeFactAction.variables?.id === fact.id)
+ }
+ onReject={() =>
+ factAction.mutate({ id: fact.id, action: "reject" })
+ }
+ onClose={(validTo) =>
+ closeFactAction.mutate({ id: fact.id, validTo })
+ }
+ />
+ ),
+ )}
</div>
)}
@@ -648,9 +750,16 @@ export function Review() {
<FactRow
key={fact.id}
fact={fact}
- busy={factAction.isPending && factAction.variables?.id === fact.id}
- onConfirm={() => factAction.mutate({ id: fact.id, action: "confirm" })}
- onReject={() => factAction.mutate({ id: fact.id, action: "reject" })}
+ busy={
+ factAction.isPending &&
+ factAction.variables?.id === fact.id
+ }
+ onConfirm={() =>
+ factAction.mutate({ id: fact.id, action: "confirm" })
+ }
+ onReject={() =>
+ factAction.mutate({ id: fact.id, action: "reject" })
+ }
/>
))}
</div>
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index c1f9b8c7..43492cd1 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -3,27 +3,43 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { Lock, Plus, X } from "lucide-react";
import { api } from "../api";
-import { S } from "../i18n";
+import { LANG_NAMES, S } from "../i18n";
import { useKb } from "../kb";
import { Members } from "./Members";
/** 部署级配置:注册开关 + worker 并发。 */
function DeploymentAdmin() {
const queryClient = useQueryClient();
- const dep = useQuery({ queryKey: ["deployment"], queryFn: api.adminDeployment });
+ const dep = useQuery({
+ queryKey: ["deployment"],
+ queryFn: api.adminDeployment,
+ });
const [workers, setWorkers] = useState<number | null>(null);
const shown = workers ?? dep.data?.worker_concurrency ?? 32;
// 按模型的并发:缺省值 + 每个在用模型的覆盖
const [modelDefault, setModelDefault] = useState<number | null>(null);
- const shownDefault = modelDefault ?? dep.data?.default_model_concurrency ?? 10;
+ const shownDefault =
+ modelDefault ?? dep.data?.default_model_concurrency ?? 10;
const [perModel, setPerModel] = useState<Record<string, number>>({});
const save = useMutation({
mutationFn: (v: {
open: boolean;
workers?: number;
defaultModel?: number;
- modelLimit?: { base_url: string; model: string; max_concurrent: number | null };
- }) => api.saveAdminDeployment(v.open, v.workers, v.defaultModel, v.modelLimit),
+ modelLimit?: {
+ base_url: string;
+ model: string;
+ max_concurrent: number | null;
+ };
+ ontologyLang?: "en" | "zh";
+ }) =>
+ api.saveAdminDeployment(
+ v.open,
+ v.workers,
+ v.defaultModel,
+ v.modelLimit,
+ v.ontologyLang,
+ ),
onSuccess: () => {
setPerModel({});
queryClient.invalidateQueries({ queryKey: ["deployment"] });
@@ -42,16 +58,49 @@ function DeploymentAdmin() {
onChange={(e) => save.mutate({ open: e.target.checked })}
/>
<span>
- <span className="block text-sm text-neutral-200">{S.settings.deployment.openReg}</span>
+ <span className="block text-sm text-neutral-200">
+ {S.settings.deployment.openReg}
+ </span>
<span className="block text-xs text-neutral-500 mt-0.5">
{S.settings.deployment.openRegHint}
</span>
</span>
</label>
+ {/* 新建库的本体语言。**不是界面语言**——界面语言是每个人自己在账户菜单里选的,
+ 根本不经过后端(docs/decisions/0004)。说明里必须把这句讲出来 */}
+ <div className="flex items-start justify-between gap-4 border-t border-white/10 pt-4">
+ <div className="min-w-0">
+ <span className="block text-sm text-neutral-200">
+ {S.settings.deployment.ontologyLang}
+ </span>
+ <span className="block text-xs text-neutral-500 mt-0.5">
+ {S.settings.deployment.ontologyLangHint}
+ </span>
+ </div>
+ <div className="flex gap-1 rounded-lg bg-white/5 p-1 h-fit shrink-0">
+ {(["en", "zh"] as const).map((l) => (
+ <button
+ key={l}
+ disabled={dep.isPending || save.isPending}
+ onClick={() => save.mutate({ open, ontologyLang: l })}
+ className={`rounded-md px-3 py-1 text-[12px] font-medium transition-colors ${
+ (dep.data?.default_ontology_lang ?? "en") === l
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:text-neutral-300"
+ }`}
+ >
+ {LANG_NAMES[l]}
+ </button>
+ ))}
+ </div>
+ </div>
+
<div className="flex items-start justify-between gap-4 border-t border-white/10 pt-4">
<div className="min-w-0">
- <span className="block text-sm text-neutral-200">{S.settings.deployment.workers}</span>
+ <span className="block text-sm text-neutral-200">
+ {S.settings.deployment.workers}
+ </span>
<span className="block text-xs text-neutral-500 mt-0.5">
{S.settings.deployment.workersHint}
</span>
@@ -64,11 +113,17 @@ function DeploymentAdmin() {
className="input-dark u-input-plain w-16 px-2 py-1.5 text-sm u-num text-center"
value={shown}
disabled={dep.isPending}
- onChange={(e) => setWorkers(Math.max(1, Math.min(32, Number(e.target.value) || 1)))}
+ onChange={(e) =>
+ setWorkers(Math.max(1, Math.min(32, Number(e.target.value) || 1)))
+ }
/>
<button
className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
- disabled={save.isPending || workers === null || workers === dep.data?.worker_concurrency}
+ disabled={
+ save.isPending ||
+ workers === null ||
+ workers === dep.data?.worker_concurrency
+ }
onClick={() => save.mutate({ open, workers: shown })}
>
{S.settings.deployment.workersApply}
@@ -88,7 +143,9 @@ function DeploymentAdmin() {
</span>
</div>
<div className="flex items-center gap-2 shrink-0">
- <span className="text-xs text-neutral-500">{S.settings.deployment.modelDefault}</span>
+ <span className="text-xs text-neutral-500">
+ {S.settings.deployment.modelDefault}
+ </span>
<input
type="number"
min={1}
@@ -97,7 +154,9 @@ function DeploymentAdmin() {
value={shownDefault}
disabled={dep.isPending}
onChange={(e) =>
- setModelDefault(Math.max(1, Math.min(256, Number(e.target.value) || 1)))
+ setModelDefault(
+ Math.max(1, Math.min(256, Number(e.target.value) || 1)),
+ )
}
/>
<button
@@ -128,8 +187,12 @@ function DeploymentAdmin() {
<span className="u-chip u-chip-neutral !text-[10px] !px-1.5 shrink-0">
{m.kind}
</span>
- <span className="font-mono text-neutral-300 truncate">{m.model}</span>
- <span className="text-neutral-600 truncate hidden sm:inline">{m.base_url}</span>
+ <span className="font-mono text-neutral-300 truncate">
+ {m.model}
+ </span>
+ <span className="text-neutral-600 truncate hidden sm:inline">
+ {m.base_url}
+ </span>
<input
type="number"
min={1}
@@ -139,7 +202,10 @@ function DeploymentAdmin() {
onChange={(e) =>
setPerModel({
...perModel,
- [key]: Math.max(1, Math.min(256, Number(e.target.value) || 1)),
+ [key]: Math.max(
+ 1,
+ Math.min(256, Number(e.target.value) || 1),
+ ),
})
}
/>
@@ -214,7 +280,9 @@ function KbsAdmin() {
<div key={kb.id} className="px-4 py-3 flex items-center gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
- <span className="text-sm text-neutral-200 truncate">{kb.name}</span>
+ <span className="text-sm text-neutral-200 truncate">
+ {kb.name}
+ </span>
{kb.is_default && (
<span className="u-chip u-chip-neutral !text-[10px]">
{S.settings.kbs.defaultChip}
@@ -228,7 +296,9 @@ function KbsAdmin() {
)}
</div>
<div className="mt-0.5 text-xs text-neutral-500">
- <span className="u-num">{S.account.kbStats(doc_count, member_count)}</span>
+ <span className="u-num">
+ {S.account.kbStats(doc_count, member_count)}
+ </span>
</div>
</div>
<button
@@ -260,7 +330,9 @@ function KbsAdmin() {
workspaceId={workspace.id}
onDone={(id) => {
setCreating(false);
- queryClient.invalidateQueries({ queryKey: ["myKbs", workspace.id] });
+ queryClient.invalidateQueries({
+ queryKey: ["myKbs", workspace.id],
+ });
queryClient.invalidateQueries({ queryKey: ["kbs", workspace.id] });
// 建完直达库设置:下一步几乎总是邀人/配置
if (id) {
@@ -306,7 +378,10 @@ function NewKbModal({
<div className="glass-strong w-[24rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl p-5">
<div className="flex items-center justify-between mb-4">
<h2 className="u-title text-[15px]">{S.settings.kbs.newKb}</h2>
- <button onClick={() => onDone()} className="text-neutral-500 hover:text-neutral-200">
+ <button
+ onClick={() => onDone()}
+ className="text-neutral-500 hover:text-neutral-200"
+ >
<X size={15} />
</button>
</div>
@@ -332,10 +407,15 @@ function NewKbModal({
{S.settings.kbs.visRestricted}
</label>
{create.isError && (
- <p className="text-xs text-rose-400 mb-2">{(create.error as Error).message}</p>
+ <p className="text-xs text-rose-400 mb-2">
+ {(create.error as Error).message}
+ </p>
)}
<div className="flex justify-end gap-2">
- <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={() => onDone()}>
+ <button
+ className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs"
+ onClick={() => onDone()}
+ >
{S.library.cancel}
</button>
<button
@@ -354,13 +434,21 @@ function NewKbModal({
/** 系统层数据源注册(问数):凭据只进不出,列表只显示 host:port/db 摘要。 */
function DataSourcesAdmin() {
const queryClient = useQueryClient();
- const list = useQuery({ queryKey: ["dataSources"], queryFn: api.adminDataSources });
+ const list = useQuery({
+ queryKey: ["dataSources"],
+ queryFn: api.adminDataSources,
+ });
const [name, setName] = useState("");
const [conn, setConn] = useState("");
- const invalidate = () => queryClient.invalidateQueries({ queryKey: ["dataSources"] });
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ["dataSources"] });
const create = useMutation({
- mutationFn: () => api.adminCreateDataSource({ name: name.trim(), conn_string: conn.trim() }),
+ mutationFn: () =>
+ api.adminCreateDataSource({
+ name: name.trim(),
+ conn_string: conn.trim(),
+ }),
onSuccess: () => {
setName("");
setConn("");
@@ -385,7 +473,9 @@ function DataSourcesAdmin() {
<div key={d.id} className="px-4 py-3 flex items-center gap-3">
<div className="min-w-0 flex-1">
<div className="text-sm text-neutral-200">{d.name}</div>
- <div className="text-xs text-neutral-500 font-mono truncate">{d.summary}</div>
+ <div className="text-xs text-neutral-500 font-mono truncate">
+ {d.summary}
+ </div>
</div>
<span
className={`u-chip shrink-0 ${
@@ -445,7 +535,9 @@ function DataSourcesAdmin() {
{S.settings.datasources.add}
</button>
{create.isError && (
- <span className="text-xs text-rose-400">{(create.error as Error).message}</span>
+ <span className="text-xs text-rose-400">
+ {(create.error as Error).message}
+ </span>
)}
</div>
</div>
@@ -492,9 +584,9 @@ const PRESETS: Record<
export function Settings() {
const { workspace } = useKb();
const { tab: tabParam } = useSearch({ from: "/account/admin" });
- const [tab, setTab] = useState<"models" | "members" | "kbs" | "datasources" | "deployment">(
- tabParam ?? "models",
- );
+ const [tab, setTab] = useState<
+ "models" | "members" | "kbs" | "datasources" | "deployment"
+ >(tabParam ?? "models");
const queryClient = useQueryClient();
const settings = useQuery({
queryKey: ["settings", workspace?.id],
@@ -525,24 +617,30 @@ export function Settings() {
const save = useMutation({
mutationFn: () => api.saveSettings(workspace!.id, form),
- onSuccess: () => queryClient.invalidateQueries({ queryKey: ["settings", workspace?.id] }),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: ["settings", workspace?.id] }),
});
- const test = useMutation({ mutationFn: () => api.testSettings(workspace!.id) });
+ const test = useMutation({
+ mutationFn: () => api.testSettings(workspace!.id),
+ });
- if (!workspace) return <div className="p-8 text-sm text-neutral-500">{S.nav.loading}</div>;
+ if (!workspace)
+ return <div className="p-8 text-sm text-neutral-500">{S.nav.loading}</div>;
- const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
- setForm({ ...form, [k]: e.target.value });
+ const set =
+ (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
+ setForm({ ...form, [k]: e.target.value });
- const input =
- "input-dark w-full px-3 py-2 text-sm";
+ const input = "input-dark w-full px-3 py-2 text-sm";
const label = "block text-xs font-medium text-neutral-400 mb-1";
return (
<div className="h-full overflow-y-auto p-6">
<div className="max-w-xl">
- <h2 className="text-lg font-bold text-neutral-100 mb-3">{S.settings.title}</h2>
+ <h2 className="text-lg font-bold text-neutral-100 mb-3">
+ {S.settings.title}
+ </h2>
<div className="flex gap-1 mb-5 bg-white/5 rounded-lg p-1 w-fit">
{(
[
@@ -574,7 +672,9 @@ export function Settings() {
{tab === "models" && (
<>
- <p className="text-sm text-neutral-400 mb-4">{S.settings.modelsIntro}</p>
+ <p className="text-sm text-neutral-400 mb-4">
+ {S.settings.modelsIntro}
+ </p>
<div className="mb-5 flex flex-wrap gap-2">
{Object.entries(PRESETS).map(([name, p]) => (
@@ -597,7 +697,9 @@ export function Settings() {
</div>
<div className="glass rounded-xl p-5 space-y-4">
- <h3 className="text-sm font-bold text-neutral-200">{S.settings.chatModel}</h3>
+ <h3 className="text-sm font-bold text-neutral-200">
+ {S.settings.chatModel}
+ </h3>
<div>
<label className={label}>{S.settings.baseUrl}</label>
<input
@@ -621,7 +723,9 @@ export function Settings() {
<label className={label}>
{S.settings.apiKey}{" "}
{settings.data?.has_chat_key && (
- <span className="text-[var(--u-accent)]">{S.settings.keyConfigured}</span>
+ <span className="text-[var(--u-accent)]">
+ {S.settings.keyConfigured}
+ </span>
)}
</label>
<input
@@ -634,7 +738,9 @@ export function Settings() {
</div>
</div>
- <h3 className="text-sm font-bold text-neutral-200 pt-2">{S.settings.embedModel}</h3>
+ <h3 className="text-sm font-bold text-neutral-200 pt-2">
+ {S.settings.embedModel}
+ </h3>
<div>
<label className={label}>{S.settings.baseUrl}</label>
<input
@@ -658,7 +764,9 @@ export function Settings() {
<label className={label}>
{S.settings.apiKey}{" "}
{settings.data?.has_embed_key && (
- <span className="text-[var(--u-accent)]">{S.settings.keyConfigured}</span>
+ <span className="text-[var(--u-accent)]">
+ {S.settings.keyConfigured}
+ </span>
)}
</label>
<input
@@ -687,19 +795,37 @@ export function Settings() {
</button>
</div>
- {save.isSuccess && <p className="text-sm text-[var(--u-accent)]">{S.settings.saved}</p>}
+ {save.isSuccess && (
+ <p className="text-sm text-[var(--u-accent)]">
+ {S.settings.saved}
+ </p>
+ )}
{save.isError && (
- <p className="text-sm text-rose-400">{(save.error as Error).message}</p>
+ <p className="text-sm text-rose-400">
+ {(save.error as Error).message}
+ </p>
)}
{test.data && (
<div className="text-sm space-y-1 pt-1">
- <p className={test.data.chat.ok ? "text-[var(--u-accent)]" : "text-rose-400"}>
+ <p
+ className={
+ test.data.chat.ok
+ ? "text-[var(--u-accent)]"
+ : "text-rose-400"
+ }
+ >
{S.settings.chatLabel}:{" "}
{test.data.chat.ok
? S.settings.ok(test.data.chat.reply ?? "OK")
: test.data.chat.error}
</p>
- <p className={test.data.embed.ok ? "text-[var(--u-accent)]" : "text-neutral-400"}>
+ <p
+ className={
+ test.data.embed.ok
+ ? "text-[var(--u-accent)]"
+ : "text-neutral-400"
+ }
+ >
{S.settings.embedLabel}:{" "}
{test.data.embed.ok
? S.settings.okDim(test.data.embed.dim ?? 0)
diff --git a/web/src/pages/UserMenu.tsx b/web/src/pages/UserMenu.tsx
index 37f0fa99..c0fd1d5c 100644
--- a/web/src/pages/UserMenu.tsx
+++ b/web/src/pages/UserMenu.tsx
@@ -3,9 +3,16 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
-import { BookMarked, LogOut, ShieldCheck, UserRound } from "lucide-react";
+import {
+ BookMarked,
+ Check,
+ Languages,
+ LogOut,
+ ShieldCheck,
+ UserRound,
+} from "lucide-react";
import { api, type User } from "../api";
-import { S } from "../i18n";
+import { LANGS, LANG_NAMES, S, lang, setLang } from "../i18n";
/** 首字母头像:中性灰底(chrome 零色偏),拉丁取词首两枚,CJK 取前两字。 */
export function Avatar({ name, size = 24 }: { name: string; size?: number }) {
@@ -66,7 +73,11 @@ export function UserMenu({ user }: { user: User }) {
const panel = panelRef.current;
const chip = chipRef.current;
if (closingRef.current) return;
- if (!panel || !chip || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ if (
+ !panel ||
+ !chip ||
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ ) {
setOpen(false);
return;
}
@@ -87,7 +98,8 @@ export function UserMenu({ user }: { user: User }) {
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => {
- if (rootRef.current && !rootRef.current.contains(e.target as Node)) close();
+ if (rootRef.current && !rootRef.current.contains(e.target as Node))
+ close();
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") close();
@@ -151,7 +163,9 @@ export function UserMenu({ user }: { user: User }) {
</span>
)}
</div>
- <div className="truncate text-[11px] text-neutral-500">{user.email}</div>
+ <div className="truncate text-[11px] text-neutral-500">
+ {user.email}
+ </div>
</div>
</div>
@@ -173,8 +187,30 @@ export function UserMenu({ user }: { user: User }) {
)}
</div>
+ {/* 界面语言:看的人自己定,不经过后端(docs/decisions/0004)。
+ 每个选项用**它自己的语言**写——看不懂英文的人才认得出"中文" */}
+ <div className="border-t border-white/10">
+ <div className="flex items-center gap-2.5 px-3.5 pt-2.5 pb-1 text-[11px] text-neutral-500">
+ <Languages size={13} className="text-neutral-500" />
+ {S.account.language}
+ </div>
+ {LANGS.map((l) => (
+ <button key={l} onClick={() => setLang(l)} className={item}>
+ <span className="w-[13px] shrink-0">
+ {l === lang && (
+ <Check size={13} className="text-neutral-400" />
+ )}
+ </span>
+ {LANG_NAMES[l]}
+ </button>
+ ))}
+ </div>
+
<div className="border-t border-white/10">
- <button onClick={logout} className={`${item} !text-[var(--u-danger)]`}>
+ <button
+ onClick={logout}
+ className={`${item} !text-[var(--u-danger)]`}
+ >
<LogOut size={13} />
{S.nav.signOut}
</button>