World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Give each chat step fields the interface words in the reader's language, and let a query step carry its SQL, rows and failure (#957)
Maya Kidaad5b067c115
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rsindex 958ea085..6c6bb698 100644--- a/crates/utopia-server/src/api/chat.rs+++ b/crates/utopia-server/src/api/chat.rs@@ -221,15 +221,12 @@ pub(super) fn check_call(name: &str,raw_args: &str,) -> Result<serde_json::Value, (String, serde_json::Value)> {- let refuse = |detail: &str, message: String| {- (- message,- json!({ "kind": "tool", "label": name, "detail": detail }),- )- };+ // 界面按字段说(#942):哪个参数、没给还是给错了;整个解析不出来的没有 `param`+ let step = |detail: &str| super::tools::Step::new("tool", name, detail);+ let refuse = |step: super::tools::Step, message: String| (message, step.json());let Ok(args) = serde_json::from_str::<serde_json::Value>(raw_args) else {return Err(refuse(- "bad arguments",+ step("bad arguments").status("invalid"),format!("The arguments for {name} were not valid JSON, so the call was not run. \They were probably cut off. Call it again with complete arguments."@@ -253,7 +250,7 @@ pub(super) fn check_call(};if missing {return Err(refuse(- &format!("missing {key}"),+ step(&format!("missing {key}")).missing(key),format!("{name} needs `{key}`, and it was missing or empty, so the call was not \run. Call it again with `{key}` set."@@ -271,7 +268,7 @@ pub(super) fn check_call(.is_none_or(|s| s.trim().parse::<Uuid>().is_err()){return Err(refuse(- &format!("invalid {key}"),+ step(&format!("invalid {key}")).invalid(key),format!("{name} needs `{key}` to be a uuid returned by another tool, and it was \not, so the call was not run. Look the id up first, then call it again."@@ -282,7 +279,7 @@ pub(super) fn check_call(function.is_some_and(|f| f["parameters"]["properties"][key]["type"] == "string");if is_string && !args[key].is_string() {return Err(refuse(- &format!("invalid {key}"),+ step(&format!("invalid {key}")).invalid(key),format!("{name} needs `{key}`, which must be a string, so the call was not run. \Call it again with `{key}` set to a string."@@ -903,7 +900,7 @@ pub async fn chat(if tool_result.name != agent::NO_EVIDENCE_TOOL {let mut step = match shared.take_step(&internal_call_id) {Some((step, failed)) => { is_error = Some(failed); step }- None => json!({ "kind": "tool", "label": tool_result.name, "detail": "unknown" }),+ None => super::tools::Step::new("tool", tool_result.name.as_str(), "unknown").status("not_found").json(),};// **这一步发生在正文的哪个位置。**//@@ -1576,6 +1573,30 @@ mod tests {}}+ /// 拒绝的那一步也按字段说(#942):哪个参数、没给还是给错了。参数名是数据,+ /// 界面照写;整个解析不出来的没有 `param`。存下的英文 detail 一个字不改+ #[test]+ fn a_refused_call_names_its_parameter_for_the_interface() {+ let tools = tools_schema(false, &[]);+ let missing = check_call(&tools, "search_chunks", "{}").unwrap_err().1;+ assert_eq!(missing["status"], "invalid", "{missing}");+ assert_eq!(missing["param"], "query", "{missing}");+ assert_eq!(missing["missing"], true, "{missing}");+ assert_eq!(missing["detail"], "missing query");+ let wrong = check_call(&tools, "get_document", "{\"document_id\": \"notes.txt\"}")+ .unwrap_err()+ .1;+ assert_eq!(wrong["status"], "invalid", "{wrong}");+ assert_eq!(wrong["param"], "document_id", "{wrong}");+ assert!(wrong.get("missing").is_none(), "{wrong}");+ let cut = check_call(&tools, "search_chunks", "{\"query\": \"Acme")+ .unwrap_err()+ .1;+ assert_eq!(cut["status"], "invalid", "{cut}");+ assert!(cut.get("param").is_none(), "{cut}");+ assert_eq!(cut["detail"], "bad arguments");+ }+/// **判据取自工具表本身。** 这条守的是「加了必填参数却忘了改校验」——/// query_data 只在挂了数据源时才出现在表里,它的两个必填参数/// 从没在别处被单独写过一遍diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rsindex 46777cc9..b7f285ac 100644--- a/crates/utopia-server/src/api/mcp_tests.rs+++ b/crates/utopia-server/src/api/mcp_tests.rs@@ -202,6 +202,39 @@ fn uuid(value: &Value) -> Uuid {value.as_str().unwrap().parse().unwrap()}+/// 调一个工具,取它交给界面的那一步(#942)。MCP 的回复里没有这一步,所以直接调+async fn step_of(+ f: &Fixture,+ sources: &[utopia_core::models::DataSourceView],+ name: &str,+ args: Value,+) -> Value {+ let ctx = ToolCtx {+ state: &f.state,+ kb_id: f.kb,+ workspace_id: f.ws,+ mounted_sources: sources,+ can_write: false,+ actor: None,+ via_token: None,+ question: None,+ };+ tools::dispatch(&ctx, &mut ToolSink::default(), name, &args)+ .await+ .step+}++/// `want` 里的每一项这一步都有、而且相等;写成 null 的那一项必须没有+fn step_has(step: &Value, want: Value) -> anyhow::Result<()> {+ for (key, value) in want.as_object().expect("the fields to check") {+ anyhow::ensure!(+ step.get(key).unwrap_or(&Value::Null) == value,+ "`{key}` should be {value} in {step}"+ );+ }+ Ok(())+}+#[tokio::test]async fn record_axis_subseconds_survive_authenticated_rdf_export() -> anyhow::Result<()> {use axum::body::{to_bytes, Body};@@ -1864,8 +1897,10 @@ async fn failed_reads_do_not_become_successful_empty_results() -> anyhow::Result"Could not read the graph changes.",),] {- let result =- tool_result(tools::dispatch(&ctx, &mut ToolSink::default(), name, &args).await);+ let called = tools::dispatch(&ctx, &mut ToolSink::default(), name, &args).await;+ // 界面上的那一步也是失败,不是一个「0 个」(#942)+ assert_eq!(called.step["status"], "failed", "{name}: {}", called.step);+ let result = tool_result(called);assert_eq!(result["isError"], true, "{name}: {result}");assert_eq!(result["content"][0]["text"], text, "{name}: {args}");assert!(result.get("structuredContent").is_none());@@ -2594,6 +2629,8 @@ async fn rule_matches_keep_materialized_intervals_and_count_rows() -> anyhow::Re};let card = tools::rule_matches(&ctx, &json!({"rule_id":rule})).await;assert_eq!(card.step["detail"], "2 matches");+ assert_eq!(card.step["status"], "ok");+ assert_eq!(card.step["count"], 2);}let after: Value=sqlx::query_scalar("SELECT coalesce(jsonb_agg(to_jsonb(d) ORDER BY id),'[]') FROM derived_facts d WHERE kb_id=$1").bind(f.kb).fetch_one(&f.state.pool).await?;@@ -2895,6 +2932,27 @@ async fn a_list_cut_at_its_limit_says_so() -> anyhow::Result<()> {.await?;anyhow::ensure!(!text(&few).contains("most recent changes"), "{few}");anyhow::ensure!(few["structuredContent"]["limit_reached"] == false, "{few}");+ // 界面上的那一步同样说「40+」:`more`,窗口的两头按问的那两天(#942)+ step_has(+ &step_of(+ f,+ &[],+ "changes",+ json!({"since":"2025-01","until":"2025-01"}),+ )+ .await,+ json!({"status":"ok","count":40,"more":true,"since":"2025-01-01","until":"2025-01-31"}),+ )?;+ step_has(+ &step_of(+ f,+ &[],+ "changes",+ json!({"since":"2025-03","until":"2025-03"}),+ )+ .await,+ json!({"status":"ok","count":3,"more":null}),+ )?;// find_entities: ten widgets, three gadgetsfor i in 1..=10 {@@ -2912,6 +2970,14 @@ async fn a_list_cut_at_its_limit_says_so() -> anyhow::Result<()> {);let gadgets = f.call("find_entities", json!({"name":"Gadget"})).await?;anyhow::ensure!(!text(&gadgets).contains("were read"), "{gadgets}");+ step_has(+ &step_of(f, &[], "find_entities", json!({"name":"Widget"})).await,+ json!({"status":"ok","count":8,"total":10}),+ )?;+ step_has(+ &step_of(f, &[], "find_entities", json!({"name":"Gadget"})).await,+ json!({"status":"ok","count":3,"total":null}),+ )?;// paths_between: eleven two-hop paths, then twolet (start, end) = (@@ -2944,9 +3010,295 @@ async fn a_list_cut_at_its_limit_says_so() -> anyhow::Result<()> {.await?;anyhow::ensure!(text(&two).starts_with("2 paths between"), "{two}");anyhow::ensure!(!text(&two).contains("are listed"), "{two}");+ step_has(+ &step_of(f, &[], "paths_between", json!({"from":start,"to":end})).await,+ json!({"status":"ok","count":10,"more":true,"hops":2}),+ )?;+ step_has(+ &step_of(f, &[], "paths_between", json!({"from":near,"to":far})).await,+ json!({"status":"ok","count":2,"more":null,"hops":2}),+ )?;Ok(())}let result = check(&f).await;let cleanup = f.clean().await;result.and(cleanup)}++/// 每一步交给界面的是字段,不只是一句英文(#942):界面按读者的语言说,+/// `detail` 留给存下的旧消息和不做本地化的读者,一个字不改+#[tokio::test]+async fn each_step_carries_the_fields_the_interface_words() -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ async fn check(f: &Fixture) -> anyhow::Result<()> {+ let search = step_of(f, &[], "search_chunks", json!({"query":"orchard"})).await;+ step_has(+ &search,+ json!({"kind":"search","label":"orchard","status":"ok"}),+ )?;+ anyhow::ensure!(+ search["detail"] == format!("{} sources", search["count"]),+ "{search}"+ );++ step_has(+ &step_of(f, &[], "get_document", json!({"document_id":f.document})).await,+ json!({"kind":"document","label":"orchard.md","detail":"2 sections",+ "status":"ok","count":2}),+ )?;+ step_has(+ &step_of(f, &[], "get_document", json!({"document_id":"orchard.md"})).await,+ json!({"detail":"invalid id","status":"invalid","param":"document_id",+ "missing":null}),+ )?;+ step_has(+ &step_of(+ f,+ &[],+ "get_document",+ json!({"document_id":Uuid::now_v7()}),+ )+ .await,+ json!({"detail":"not found","status":"not_found"}),+ )?;++ let docs = step_of(f, &[], "search_docs", json!({"query":"entity"})).await;+ step_has(&docs, json!({"kind":"docs","status":"ok"}))?;+ anyhow::ensure!(+ docs["detail"] == format!("{} sections", docs["count"]),+ "{docs}"+ );++ step_has(+ &step_of(f, &[], "find_entities", json!({"name":"Alice"})).await,+ json!({"kind":"entity","label":"Alice","detail":"1 matches","status":"ok",+ "count":1,"total":null}),+ )?;++ // 世界时间一个,记录时间一个:给了 before 就只写 before,那是人问的那一刻+ let facts = step_of(+ f,+ &[],+ "entity_facts",+ json!({"entity_id":f.subject,"at":"2026-02-15","before":CORRECTION}),+ )+ .await;+ step_has(+ &facts,+ json!({"kind":"facts","label":"Alice","status":"ok",+ "valid_at":"2026-02-15T00:00:00Z","before":CORRECTION,"as_of":null,+ "at":null}),+ )?;+ anyhow::ensure!(+ facts["detail"]+ .as_str()+ .is_some_and(|d| d.starts_with(&format!("{} facts at ", facts["count"]))),+ "{facts}"+ );+ step_has(+ &step_of(+ f,+ &[],+ "entity_facts",+ json!({"entity_id":f.subject,"as_of":CORRECTION}),+ )+ .await,+ json!({"status":"ok","as_of":CORRECTION,"before":null,"valid_at":null}),+ )?;+ step_has(+ &step_of(f, &[], "entity_facts", json!({"entity_id":"Nobody"})).await,+ json!({"kind":"facts","status":"not_found"}),+ )?;++ for kind in ["neighbors", "timeline"] {+ let step = step_of(f, &[], kind, json!({"entity":f.subject})).await;+ step_has(&step, json!({"kind":kind,"label":"Alice","status":"ok"}))?;+ let word = if kind == "neighbors" {+ "linked"+ } else {+ "dated"+ };+ anyhow::ensure!(+ step["detail"] == format!("{} of {} {word}", step["count"], step["total"]),+ "{step}"+ );+ step_has(+ &step_of(f, &[], kind, json!({"entity":"Nobody"})).await,+ json!({"kind":kind,"status":"not_found"}),+ )?;+ }++ // 两个方向各算一条(见 opposite_directions_reach_authenticated_path_output):+ // 数不写死,与存下的那句英文对上+ let path = step_of(+ f,+ &[],+ "paths_between",+ json!({"from":f.subject,"to":f.object}),+ )+ .await;+ step_has(+ &path,+ json!({"kind":"path","status":"ok","hops":1,"more":null}),+ )?;+ anyhow::ensure!(+ path["detail"]+ .as_str()+ .is_some_and(|d| d.starts_with(&format!("{} path", path["count"]))),+ "{path}"+ );+ step_has(+ &step_of(+ f,+ &[],+ "paths_between",+ json!({"from":f.subject,"to":Uuid::now_v7()}),+ )+ .await,+ json!({"kind":"path","status":"not_found"}),+ )?;++ // 窗口的两头按问的那两天,没有 until 就不写:label 里那个 "now" 是英文+ let window = step_of(+ f,+ &[],+ "changes",+ json!({"since":"2026-03-01","until":"2026-03-31"}),+ )+ .await;+ step_has(+ &window,+ json!({"kind":"changes","label":"2026-03-01 → 2026-03-31","status":"ok",+ "since":"2026-03-01","until":"2026-03-31","more":null}),+ )?;+ anyhow::ensure!(+ window["detail"] == format!("{} changes", window["count"]),+ "{window}"+ );+ step_has(+ &step_of(f, &[], "changes", json!({"since":"2026-03"})).await,+ json!({"label":"2026-03-01 → now","since":"2026-03-01","until":null}),+ )?;+ step_has(+ &step_of(f, &[], "changes", json!({"since":"sometime"})).await,+ json!({"status":"invalid","param":"since"}),+ )?;++ let rules = step_of(f, &[], "list_rules", json!({})).await;+ step_has(+ &rules,+ json!({"kind":"tool","label":"list_rules","status":"ok"}),+ )?;+ anyhow::ensure!(rules["count"].is_u64(), "{rules}");+ step_has(+ &step_of(f, &[], "rule_matches", json!({"rule_id":"weight"})).await,+ json!({"label":"rule_matches","status":"invalid","param":"rule_id"}),+ )?;+ step_has(+ &step_of(f, &[], "rule_matches", json!({"rule_id":Uuid::now_v7()})).await,+ json!({"label":"rule_matches","status":"ok","count":0}),+ )?;+ step_has(+ &step_of(f, &[], "no_such_tool", json!({})).await,+ json!({"kind":"tool","label":"no_such_tool","status":"not_found"}),+ )?;++ // 只剩 NUL 的一句:什么也没写,这一步说缺的是 text+ let writer = ToolCtx {+ state: &f.state,+ kb_id: f.kb,+ workspace_id: f.ws,+ mounted_sources: &[],+ can_write: true,+ actor: None,+ via_token: None,+ question: None,+ };+ let empty = tools::dispatch(+ &writer,+ &mut ToolSink::default(),+ "remember",+ &json!({"text":"\u{0}"}),+ )+ .await;+ step_has(+ &empty.step,+ json!({"label":"remember","status":"invalid","param":"text","missing":true}),+ )+ }+ let result = check(&f).await;+ let cleanup = f.clean().await;+ result.and(cleanup)+}++/// 问数那一步带着它跑的 SQL、读到几行、成没成(#936):界面可以展开那条 SQL,+/// 出错的查询是失败的一步,不再和「查到了」长得一样+#[tokio::test]+async fn a_query_step_carries_its_sql_rows_and_failure() -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ // 数据源指向测试库本身:只读会话里跑 SELECT,什么也不改+ let user: Uuid = sqlx::query_scalar("SELECT id FROM users WHERE org_id=$1")+ .bind(f.org)+ .fetch_one(&f.state.pool)+ .await?;+ let name = format!("steps-{}", Uuid::now_v7().simple());+ let id = utopia_store::datasources::create(+ &f.state.pool,+ &name,+ "postgres",+ &utopia_store::test_db::url().unwrap(),+ user,+ )+ .await?;+ let sources = [utopia_core::models::DataSourceView {+ id,+ name: name.clone(),+ engine: "postgres".into(),+ summary: String::new(),+ created_at: chrono::Utc::now(),+ last_test_at: None,+ last_test_ok: None,+ }];+ let check = async {+ step_has(+ &step_of(+ &f,+ &sources,+ "query_data",+ json!({"data_source":name,"sql":"SELECT 1 AS x","purpose":"a probe"}),+ )+ .await,+ json!({"kind":"query","label":name,"detail":"a probe","status":"ok",+ "count":1,"more":null,"sql":"SELECT 1 AS x"}),+ )?;+ step_has(+ &step_of(+ &f,+ &sources,+ "query_data",+ json!({"data_source":name,"sql":"SELECT x FROM no_such_table_for_steps"}),+ )+ .await,+ json!({"status":"failed","count":null,+ "sql":"SELECT x FROM no_such_table_for_steps"}),+ )?;+ step_has(+ &step_of(+ &f,+ &sources,+ "query_data",+ json!({"data_source":"elsewhere","sql":"SELECT 1"}),+ )+ .await,+ json!({"label":"elsewhere","status":"not_found","sql":"SELECT 1"}),+ )+ };+ let result = check.await;+ let removed = utopia_store::datasources::delete(&f.state.pool, id).await;+ let cleanup = f.clean().await;+ result.and(removed.map_err(Into::into)).and(cleanup)+}diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rsindex 48f3ed20..c6f21452 100644--- a/crates/utopia-server/src/api/tools.rs+++ b/crates/utopia-server/src/api/tools.rs@@ -82,6 +82,96 @@ pub struct ToolSink {pub resolved: Vec<serde_json::Value>,}+/// 界面上的一步(#942)。+///+/// `kind` 与 `label`(数据:查询、实体名、来源名)照旧;`detail` 是给存量消息和不做+/// 本地化的读者的英文。界面按结构化字段用读者的语言说(0004):`status`、`count` /+/// `total`、时间点,以及个别步骤自己的几样。**成功的一步也写 `status: ok`**——有+/// status 的按字段说,没有的(这之前存下的消息)退回 detail+pub(crate) struct Step(serde_json::Map<String, serde_json::Value>);++impl Step {+ pub(crate) fn new(+ kind: &str,+ label: impl Into<serde_json::Value>,+ detail: impl Into<String>,+ ) -> Self {+ let mut step = serde_json::Map::new();+ step.insert("kind".into(), json!(kind));+ step.insert("label".into(), label.into());+ step.insert("detail".into(), json!(detail.into()));+ step.insert("status".into(), json!("ok"));+ Self(step)+ }++ /// `ok | failed | not_found | invalid`+ pub(crate) fn status(self, status: &'static str) -> Self {+ self.field("status", status)+ }++ pub(crate) fn count(self, n: usize) -> Self {+ self.field("count", n)+ }++ /// 列出来的少于有的:`count` of `total`+ pub(crate) fn total(self, n: usize) -> Self {+ self.field("total", n)+ }++ /// 参数不对,这次调用什么也没做。`param` 是哪一个——参数名是数据,界面照写+ pub(crate) fn invalid(self, param: &str) -> Self {+ self.status("invalid").field("param", param)+ }++ /// 参数没给,或给的是空的+ pub(crate) fn missing(self, param: &str) -> Self {+ self.invalid(param).field("missing", true)+ }++ /// 截在上限、总数不知道(「40+」)+ pub(crate) fn more(self, more: bool) -> Self {+ if more {+ self.field("more", true)+ } else {+ self+ }+ }++ /// 世界轴的时刻写作 `valid_at`,记录轴写 `before` 或 `as_of`。给了 before 就只写+ /// before:那是人问的那一刻,as_of 是从它减了一微秒算出来的。+ ///+ /// **世界轴那个不能叫 `at`**:对话落库的每一步都有 `at`——这一步发生时正文已有多长+ /// (UTF-16 码元),回放靠它把轨迹穿回正文;写进来会被它覆盖+ pub(crate) fn moments(+ mut self,+ at: Option<chrono::DateTime<chrono::Utc>>,+ as_of: Option<chrono::DateTime<chrono::Utc>>,+ before: Option<chrono::DateTime<chrono::Utc>>,+ ) -> Self {+ use crate::time_text::instant;+ if let Some(t) = at {+ self = self.field("valid_at", instant(t));+ }+ match (before, as_of) {+ (Some(b), _) => self.field("before", instant(b)),+ (None, Some(r)) => self.field("as_of", instant(r)),+ (None, None) => self,+ }+ }++ pub(crate) fn field(mut self, key: &str, value: impl serde::Serialize) -> Self {+ self.0.insert(+ key.into(),+ serde_json::to_value(value).unwrap_or(serde_json::Value::Null),+ );+ self+ }++ pub(crate) fn json(self) -> serde_json::Value {+ serde_json::Value::Object(self.0)+ }+}+/// 一次调用的文本、界面步骤与可选机器读取结果;不放进跨调用累计的 ToolSink。pub struct ToolResult {pub text: String,@@ -138,7 +228,9 @@ pub async fn dispatch("remember" if ctx.can_write => remember(ctx, args).await,other => ToolResult::new(format!("Unknown tool: {other}"),- json!({ "kind": "tool", "label": other, "detail": "unknown" }),+ Step::new("tool", other, "unknown")+ .status("not_found")+ .json(),),}}@@ -182,7 +274,7 @@ pub async fn search_chunks(tracing::warn!(error = %e, "MCP chunk search failed");return ToolResult::new("Could not search the documents.".into(),- json!({"kind": "search", "label": q, "detail": "failed"}),+ Step::new("search", q, "failed").status("failed").json(),).error();}@@ -206,7 +298,9 @@ pub async fn search_chunks(};ToolResult::new(text,- json!({ "kind": "search", "label": q, "detail": format!("{} sources", chunks.len()) }),+ Step::new("search", q.as_str(), format!("{} sources", chunks.len()))+ .count(chunks.len())+ .json(),).structured(json!({"kb_id": ctx.kb_id, "as_of": as_of,@@ -228,27 +322,27 @@ pub async fn get_document(sink: &mut ToolSink,args: &serde_json::Value,) -> ToolResult {- let refuse = |detail: &str| {+ let refuse = |step: Step| {ToolResult::new("No document with that id in this knowledge base.".to_string(),- json!({ "kind": "document", "label": "?", "detail": detail }),+ step.json(),)};let Some(id) = args["document_id"].as_str().and_then(|s| s.trim().parse::<Uuid>().ok())else {- return refuse("invalid id");+ return refuse(Step::new("document", "?", "invalid id").invalid("document_id"));};// 本库之外的 id 一律当作不存在——分不出「没有」和「不给你看」才是对的let doc = match utopia_store::documents::find_in_kb(&ctx.state.pool, ctx.kb_id, id).await {Ok(Some(doc)) => doc,- Ok(None) => return refuse("not found"),+ Ok(None) => return refuse(Step::new("document", "?", "not found").status("not_found")),Err(e) => {tracing::warn!(error = %e, "MCP document lookup failed");return ToolResult::new("Could not read the document.".into(),- json!({"kind": "document", "label": "?", "detail": "failed"}),+ Step::new("document", "?", "failed").status("failed").json(),).error();}@@ -260,7 +354,9 @@ pub async fn get_document(tracing::warn!(error = %e, "MCP document chunk read failed");return ToolResult::new("Could not read the document.".into(),- json!({"kind": "document", "label": doc.filename, "detail": "failed"}),+ Step::new("document", doc.filename, "failed")+ .status("failed")+ .json(),).error();}@@ -313,10 +409,13 @@ pub async fn get_document(};ToolResult::new(text,- json!({- "kind": "document", "label": doc.filename,- "detail": format!("{} sections", chunks.len()),- }),+ Step::new(+ "document",+ doc.filename.as_str(),+ format!("{} sections", chunks.len()),+ )+ .count(chunks.len())+ .json(),)}@@ -356,7 +455,9 @@ pub async fn search_docs(};ToolResult::new(text,- json!({ "kind": "docs", "label": q, "detail": format!("{} sections", hits.len()) }),+ Step::new("docs", q.as_str(), format!("{} sections", hits.len()))+ .count(hits.len())+ .json(),)}@@ -366,14 +467,16 @@ pub async fn list_rules(ctx: &ToolCtx<'_>) -> ToolResult {let Ok(rules) = utopia_store::business_rules::list(&ctx.state.pool, ctx.kb_id).await else {return ToolResult::new("Could not read the rules.".to_string(),- json!({ "kind": "tool", "label": "list_rules", "detail": "failed" }),+ Step::new("tool", "list_rules", "failed")+ .status("failed")+ .json(),).error();};if rules.is_empty() {return ToolResult::new("This base has no business rules.".to_string(),- json!({ "kind": "tool", "label": "list_rules", "detail": "none" }),+ Step::new("tool", "list_rules", "none").count(0).json(),);}let expressions: Vec<_> = rules@@ -390,7 +493,9 @@ pub async fn list_rules(ctx: &ToolCtx<'_>) -> ToolResult {else {return ToolResult::new("Could not read the rules.".to_string(),- json!({ "kind": "tool", "label": "list_rules", "detail": "failed" }),+ Step::new("tool", "list_rules", "failed")+ .status("failed")+ .json(),).error();};@@ -481,7 +586,9 @@ pub async fn list_rules(ctx: &ToolCtx<'_>) -> ToolResult {let n = rules.len();ToolResult::new(text,- json!({ "kind": "tool", "label": "list_rules", "detail": format!("{n} rules") }),+ Step::new("tool", "list_rules", format!("{n} rules"))+ .count(n)+ .json(),)}@@ -493,7 +600,9 @@ pub async fn rule_matches(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolReelse {return ToolResult::new("Invalid rule_id (expected the uuid returned by list_rules).".to_string(),- json!({ "kind": "tool", "label": "rule_matches", "detail": "invalid id" }),+ Step::new("tool", "rule_matches", "invalid id")+ .invalid("rule_id")+ .json(),);};let limit = args["limit"].as_i64().unwrap_or(50).clamp(1, 200);@@ -502,14 +611,16 @@ pub async fn rule_matches(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolReelse {return ToolResult::new("Could not read what that rule marks.".to_string(),- json!({ "kind": "tool", "label": "rule_matches", "detail": "failed" }),+ Step::new("tool", "rule_matches", "failed")+ .status("failed")+ .json(),).error();};if rows.is_empty() {return ToolResult::new("That rule marks nothing right now.".to_string(),- json!({ "kind": "tool", "label": "rule_matches", "detail": "0" }),+ Step::new("tool", "rule_matches", "0").count(0).json(),);}let text = rows@@ -566,7 +677,9 @@ pub async fn rule_matches(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe};ToolResult::new(text,- json!({ "kind": "tool", "label": "rule_matches", "detail": format!("{total} matches") }),+ Step::new("tool", "rule_matches", format!("{total} matches"))+ .field("count", total)+ .json(),)}@@ -581,10 +694,14 @@ pub async fn changes(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult.as_str().and_then(utopia_extract::parse_time).map(|(t, p)| period_last_day(t.date_naive(), p));+ // 窗口的两头按问的那天交给界面:label 里的 "now" 是英文+ let (since_day, until_day) = (since, until);let Some((since, until, window)) = changes_window(since, until, chrono::Utc::now()) else {return ToolResult::new("Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),- json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),+ Step::new("changes", "?", "invalid since")+ .invalid("since")+ .json(),).error();};@@ -613,7 +730,9 @@ pub async fn changes(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResulttracing::warn!(error = %e, "Graph changes lookup failed");return ToolResult::new("Could not read the graph changes.".into(),- json!({"kind": "changes", "label": window, "detail": "failed"}),+ Step::new("changes", window, "failed")+ .status("failed")+ .json(),).error();}@@ -638,11 +757,16 @@ pub async fn changes(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult} else {format!("{} changes", rows.len())};- ToolResult::new(- text,- json!({ "kind": "changes", "label": window, "detail": detail }),- )- .structured(json!({+ let mut step = Step::new("changes", window.as_str(), detail)+ .count(rows.len())+ .more(rows.len() as i64 == CHANGES_LIMIT);+ if let Some(day) = since_day {+ step = step.field("since", day.to_string());+ }+ if let Some(day) = until_day {+ step = step.field("until", day.to_string());+ }+ ToolResult::new(text, step.json()).structured(json!({"kb_id": ctx.kb_id, "since": since, "until": until,"limit": CHANGES_LIMIT, "limit_reached": rows.len() as i64 == CHANGES_LIMIT,"changes": rows.iter().map(|r| json!({@@ -668,30 +792,36 @@ pub async fn query_data(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResu.mounted_sources.iter().find(|d| d.name.eq_ignore_ascii_case(ds_name));- let text = match found {- None => format!(- "Unknown data source '{ds_name}'. Mounted sources: {}",- ctx.mounted_sources- .iter()- .map(|d| d.name.as_str())- .collect::<Vec<_>>()- .join(", ")- ),- Some(ds) => match run_query(ctx.state, ds.id, sql).await {- Ok(out) => out,- // 错误透传:模型可据此修正 SQL 重试- Err(e) => format!("Query failed: {e}"),- },- };let detail = if purpose.is_empty() {sql.chars().take(60).collect::<String>()} else {purpose.to_string()};- ToolResult::new(- text,- json!({ "kind": "query", "label": ds_name, "detail": detail }),- )+ // 界面上的这一步带着写下的那条 SQL(#936):读者能展开看到数是怎么算出来的;+ // 查询出错、源不存在各是一种结果,不再和「查到了」长得一样+ let step = Step::new("query", ds_name, detail).field("sql", sql);+ let (text, step) = match found {+ None => (+ format!(+ "Unknown data source '{ds_name}'. Mounted sources: {}",+ ctx.mounted_sources+ .iter()+ .map(|d| d.name.as_str())+ .collect::<Vec<_>>()+ .join(", ")+ ),+ step.status("not_found"),+ ),+ Some(ds) => match execute_query(ctx.state, ds.id, sql).await {+ Ok(result) => (+ query_text(&result),+ step.count(result.rows.len()).more(result.truncated),+ ),+ // 错误透传:模型可据此修正 SQL 重试+ Err(e) => (format!("Query failed: {e}"), step.status("failed")),+ },+ };+ ToolResult::new(text, step.json())}pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {@@ -728,7 +858,9 @@ pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResultif text.is_empty() {return ToolResult::new("remember requires non-empty text.".to_string(),- json!({ "kind": "tool", "label": "remember", "detail": "empty" }),+ Step::new("tool", "remember", "empty")+ .missing("text")+ .json(),).error();}@@ -758,17 +890,21 @@ pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResultany fact has been added to the knowledge graph.",occurred_text),- json!({- "kind": "tool", "label": "remember",- "detail": text.chars().take(60).collect::<String>(),- // 对话里那张确认卡按它取待确认项;回放时也据此重画- "chunk_id": chunk_id,- }),+ // 对话里那张确认卡按 chunk_id 取待确认项;回放时也据此重画+ Step::new(+ "tool",+ "remember",+ text.chars().take(60).collect::<String>(),+ )+ .field("chunk_id", chunk_id)+ .json(),)}Err(e) => ToolResult::new(format!("Failed to record: {e}"),- json!({ "kind": "tool", "label": "remember", "detail": "failed" }),+ Step::new("tool", "remember", "failed")+ .status("failed")+ .json(),).error(),}@@ -803,12 +939,25 @@ pub(super) fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> s/// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。pub(crate) async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> {+ Ok(query_text(&execute_query(state, ds_id, sql).await?))+}++/// 同 `run_query`,但交回行与截断标记本身:对话里那一步要行数和截断(#936)+async fn execute_query(+ state: &AppState,+ ds_id: Uuid,+ sql: &str,+) -> anyhow::Result<crate::query_engine::QueryResult> {let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;// 闸门按引擎选方言:Databricks 的反引号、Snowflake 的 :: 转型都得先过得了解析let guarded = crate::query_engine::guard_sql_for(&engine, sql)?;- let result = crate::query_engine::engine_for(&engine, &conn)?+ crate::query_engine::engine_for(&engine, &conn)?.execute(&guarded)- .await?;+ .await+}++/// 结果给模型读的样子:每行一个 JSON 对象,末尾是行数与截断说明+fn query_text(result: &crate::query_engine::QueryResult) -> String {let mut out = String::new();if result.rows.is_empty() {out.push_str("(no rows)");@@ -823,7 +972,7 @@ pub(crate) async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyho}out.push(')');}- Ok(out)+ out}/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。diff --git a/crates/utopia-server/src/api/tools_graph.rs b/crates/utopia-server/src/api/tools_graph.rsindex 0d02380d..c5e411c3 100644--- a/crates/utopia-server/src/api/tools_graph.rs+++ b/crates/utopia-server/src/api/tools_graph.rs@@ -12,8 +12,8 @@//! 写在结果最上面,模型不同意就拿 id 再来一次。use super::tools::{- entity_facts_detail, fact_line, just_before, literal_text, parse_when, ToolCtx, ToolResult,- ToolSink,+ entity_facts_detail, fact_line, just_before, literal_text, parse_when, Step, ToolCtx,+ ToolResult, ToolSink,};use serde_json::{json, Value};use std::collections::{BTreeMap, HashMap, HashSet};@@ -213,7 +213,7 @@ pub async fn find_entities(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)tracing::warn!(error = %e, "Entity lookup failed");return ToolResult::new("Could not look up entities.".into(),- json!({"kind": "entity", "label": name, "detail": "failed"}),+ Step::new("entity", name, "failed").status("failed").json(),).error();}@@ -252,11 +252,12 @@ pub async fn find_entities(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)if let Some(best) = ranked.first().filter(|_| clear) {remember(sink, best);}- ToolResult::new(- text,- json!({ "kind": "entity", "label": name, "detail": format!("{} matches", ranked.len()) }),- )- .structured(json!({+ let mut step =+ Step::new("entity", name.as_str(), format!("{} matches", ranked.len())).count(ranked.len());+ if let Some(total) = total.filter(|t| *t > read as i64) {+ step = step.total(total as usize);+ }+ ToolResult::new(text, step.json()).structured(json!({"kb_id": ctx.kb_id,"entities": ranked.iter().map(|n| json!({"id": n.id, "name": n.name, "type_key": n.type_key,@@ -599,7 +600,7 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)Err(ResolveError::ReadFailed) => {return ToolResult::new("Could not look up entities.".into(),- json!({ "kind": "facts", "label": "?", "detail": "failed" }),+ Step::new("facts", "?", "failed").status("failed").json(),).error();}@@ -608,7 +609,9 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)format!("Invalid entity: {e} (expected a name, or the uuid returned by find_entities)."),- json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),+ Step::new("facts", "?", "invalid id")+ .status("not_found")+ .json(),).error()}@@ -630,7 +633,7 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)};return ToolResult::new(text.into(),- json!({"kind": "facts", "label": "?", "detail": "failed"}),+ Step::new("facts", "?", "failed").status("failed").json(),).error();}@@ -654,7 +657,7 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)Err(e) => {tracing::warn!(error = %e, "Derived facts lookup failed");return ToolResult::new("Could not read the derived facts.".into(),- json!({"kind": "facts", "label": node.name, "detail": "failed"})).error();+ Step::new("facts", node.name, "failed").status("failed").json()).error();}};let derived_lines: Vec<String> = derived@@ -741,7 +744,10 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)let detail = entity_facts_detail(shown.len(), m.at, m.as_of, m.before);ToolResult::new(lines.join("\n"),- json!({ "kind": "facts", "label": node.name, "detail": detail }),+ Step::new("facts", node.name.as_str(), detail)+ .count(shown.len())+ .moments(m.at, m.as_of, m.before)+ .json(),).structured(json!({"kb_id": ctx.kb_id,@@ -799,14 +805,18 @@ pub async fn neighbors(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) ->Err(ResolveError::ReadFailed) => {return ToolResult::new("Could not look up entities.".into(),- json!({ "kind": "neighbors", "label": "?", "detail": "failed" }),+ Step::new("neighbors", "?", "failed")+ .status("failed")+ .json(),).error();}Err(ResolveError::Unresolved(e)) => {return ToolResult::new(format!("Unknown entity: {e}."),- json!({ "kind": "neighbors", "label": "?", "detail": "unknown entity" }),+ Step::new("neighbors", "?", "unknown entity")+ .status("not_found")+ .json(),)}};@@ -821,14 +831,18 @@ pub async fn neighbors(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) ->Err(utopia_core::AppError::NotFound) => {return ToolResult::new("Entity not found.".to_string(),- json!({ "kind": "neighbors", "label": "?", "detail": "not found" }),+ Step::new("neighbors", "?", "not found")+ .status("not_found")+ .json(),);}Err(e) => {tracing::warn!(error = %e, "Entity neighbors lookup failed");return ToolResult::new("Could not read the entity facts.".into(),- json!({ "kind": "neighbors", "label": "?", "detail": "failed" }),+ Step::new("neighbors", "?", "failed")+ .status("failed")+ .json(),).error();}@@ -910,7 +924,10 @@ pub async fn neighbors(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) ->let detail = format!("{} of {} linked", shown.len(), linked.len());ToolResult::new(lines.join("\n"),- json!({ "kind": "neighbors", "label": node.name, "detail": detail }),+ Step::new("neighbors", node.name, detail)+ .count(shown.len())+ .total(linked.len())+ .json(),)}@@ -926,14 +943,16 @@ pub async fn timeline(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> TErr(ResolveError::ReadFailed) => {return ToolResult::new("Could not look up entities.".into(),- json!({ "kind": "timeline", "label": "?", "detail": "failed" }),+ Step::new("timeline", "?", "failed").status("failed").json(),).error();}Err(ResolveError::Unresolved(e)) => {return ToolResult::new(format!("Unknown entity: {e}."),- json!({ "kind": "timeline", "label": "?", "detail": "unknown entity" }),+ Step::new("timeline", "?", "unknown entity")+ .status("not_found")+ .json(),)}};@@ -948,14 +967,16 @@ pub async fn timeline(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> TErr(utopia_core::AppError::NotFound) => {return ToolResult::new("Entity not found.".to_string(),- json!({ "kind": "timeline", "label": "?", "detail": "not found" }),+ Step::new("timeline", "?", "not found")+ .status("not_found")+ .json(),);}Err(e) => {tracing::warn!(error = %e, "Entity timeline lookup failed");return ToolResult::new("Could not read the entity facts.".into(),- json!({ "kind": "timeline", "label": "?", "detail": "failed" }),+ Step::new("timeline", "?", "failed").status("failed").json(),).error();}@@ -1017,7 +1038,10 @@ pub async fn timeline(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> Tlet detail = format!("{} of {} dated", shown.len(), dated.len());ToolResult::new(lines.join("\n"),- json!({ "kind": "timeline", "label": node.name, "detail": detail }),+ Step::new("timeline", node.name, detail)+ .count(shown.len())+ .total(dated.len())+ .json(),)}@@ -1088,14 +1112,16 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)Err(ResolveError::ReadFailed) => {return ToolResult::new("Could not look up entities.".into(),- json!({ "kind": "path", "label": "?", "detail": "failed" }),+ Step::new("path", "?", "failed").status("failed").json(),).error();}Err(ResolveError::Unresolved(e)) => {return ToolResult::new(format!("Unknown `{key}`: {e}."),- json!({ "kind": "path", "label": "?", "detail": "unknown entity" }),+ Step::new("path", "?", "unknown entity")+ .status("not_found")+ .json(),)}}@@ -1126,7 +1152,7 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)tracing::warn!(error = %e, "Path search failed");return ToolResult::new("Could not search paths.".into(),- json!({ "kind": "path", "label": "?", "detail": "failed" }),+ Step::new("path", "?", "failed").status("failed").json(),).error();}@@ -1152,14 +1178,16 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)"Unknown `{key}`: no entity with id {} in this base.",end.id),- json!({ "kind": "path", "label": "?", "detail": "unknown entity" }),+ Step::new("path", "?", "unknown entity")+ .status("not_found")+ .json(),)}Err(e) => {tracing::warn!(error = %e, "Entity lookup failed");return ToolResult::new("Could not look up entities.".into(),- json!({ "kind": "path", "label": "?", "detail": "failed" }),+ Step::new("path", "?", "failed").status("failed").json(),).error();}@@ -1184,7 +1212,7 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)));return ToolResult::new(lines.join("\n"),- json!({ "kind": "path", "label": label, "detail": "no path" }),+ Step::new("path", label, "no path").count(0).json(),);}let shortest = paths[0].hops();@@ -1212,7 +1240,11 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value));ToolResult::new(lines.join("\n"),- json!({ "kind": "path", "label": label, "detail": detail }),+ Step::new("path", label, detail)+ .count(paths.len())+ .more(paths.len() >= limits.max_paths)+ .field("hops", shortest)+ .json(),)}diff --git a/docs/decisions/0004-language-and-localization.md b/docs/decisions/0004-language-and-localization.mdindex 108238fe..aeb95f42 100644--- a/docs/decisions/0004-language-and-localization.md+++ b/docs/decisions/0004-language-and-localization.md@@ -4,8 +4,9 @@`code` (`AppError::Invalid`, 81 sites; 23 `Validation` guards stay English), and so dothe chat stream's `error` frames, in the same `{error, code}` body (2026-09-26);`description` follows `knowledge_bases.ontology_lang`; LLM output for people takes- `locale` from the request; extracted data stays verbatim; the UI does not guess the- browser language yet.+ `locale` from the request; extracted data stays verbatim; the chat's step trail carries+ fields the client words (`status`, counts, moments), and keeps its English `detail` for+ stored messages (2026-09-26); the UI does not guess the browser language yet.- **Written**: 2026-08-29 · condensed into English 2026-09-03- **Related**: [0001](0001-ontology-import-and-governance.md) made `description`load-bearing; [0003](0003-ontology-growth-loop.md) separated `reason` fromdiff --git a/docs/design/chat-and-mcp.md b/docs/design/chat-and-mcp.mdindex eba35270..1b50d59b 100644--- a/docs/design/chat-and-mcp.md+++ b/docs/design/chat-and-mcp.md@@ -9,7 +9,8 @@ Records: [0042] (the loop), [0014] (MCP tools and scope), [0015] (`remember` and**The loop** is rig's multi-turn runner (`rig-core` / `rig-agent`, no default features); everypolicy is one `AgentHook` in `api/agent.rs`: `tool_choice: required` until a tool has run, then thebudget withdraws the tools and orders an answer; a malformed call is refused with the same message-as before; a tool's UI step goes to the stream; an empty turn is asked again once; a text-only first+as before; a tool's UI step goes to the stream, with fields the client words (#942); an empty turn is+asked again once; a text-only firstturn from an endpoint that ignored `required` is sent back once; a turn that writes its tool call astext is held back from the stream and sent back once, and a second one is an error [0042]. A turncannot end before a tool has run; `no_evidence_needed` is the exit for a greeting or "make itdiff --git a/web/src/api.ts b/web/src/api.tsindex ab33ad74..a4bb051b 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -1463,6 +1463,7 @@ export interface Source {export interface ChatStep {kind:| "search"+ | "document"| "docs"| "entity"| "facts"@@ -1472,8 +1473,32 @@ export interface ChatStep {| "changes"| "query"| "tool";+ /** 数据:查询、实体名、来源名、工具名。照原样显示 */label: string;+ /** 服务端写的英文。**有 `status` 的步骤不读它**,界面按下面的字段自己说(#942);+ * 那之前存下的消息只有它。问数与 remember 的 detail 是数据(目的、记下的那句话) */detail: string;+ status?: "ok" | "failed" | "not_found" | "invalid";+ /** 列出了几个;`total` 是一共有几个(列出来的少于有的时候) */+ count?: number;+ total?: number;+ /** 列到上限就停了,后面可能还有,总数不知道 */+ more?: boolean;+ /** 世界时间:问的是那时成立的事实。RFC 3339 */+ valid_at?: string;+ /** 记录时间:按那时(`as_of`)或那之前(`before`)记下的。RFC 3339 */+ as_of?: string;+ before?: string;+ /** changes 的窗口,YYYY-MM-DD;没有 until 就是开到现在 */+ since?: string;+ until?: string;+ /** paths_between:最短的那条几跳 */+ hops?: number;+ /** 参数不对时是哪一个;`missing` 分开没给与给错了 */+ param?: string;+ missing?: boolean;+ /** 问数跑的那条 SQL(#936) */+ sql?: string;/** `remember` 那一步带着它:那句记忆落成的 chunk。对话里的确认卡按它取* 待确认项(0015);回放时也据此重画 */chunk_id?: string;diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 6db266e4..3fa47148 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -806,6 +806,53 @@ export const en = {send: "Send",stop: "Stop",thinking: "Thinking…",+ /* 轨迹上每一步的话(#942)。服务端只给字段:状态、数、时刻,怎么说在这里定。+ 查询、实体名、来源名、问数的目的、记下的那句话是数据,原样显示;+ 没有这些字段的旧消息仍显示当时存下的英文 */+ step: {+ failed: "failed",+ documentNotFound: "document not found",+ entityNotFound: "entity not found",+ sourceNotFound: "no such data source",+ unknownTool: "unknown tool",+ /* 参数整个解析不出来:多半是模型的输出撞上上限,在半路断了 */+ unparsed: "incomplete arguments",+ missing: (param: string) => `missing ${param}`,+ invalid: (param: string) => `invalid ${param}`,+ sources: (n: number) => `${n} source${n === 1 ? "" : "s"}`,+ sections: (n: number) => `${n} section${n === 1 ? "" : "s"}`,+ matches: (n: number, total?: number) =>+ total === undefined+ ? `${n} match${n === 1 ? "" : "es"}`+ : `${n} of ${total} matches`,+ /* `at` 是世界时间(那时成立的),`recorded` 是下面两句之一(那时记下的) */+ facts: (n: number, at: string | null, recorded: string | null) =>+ `${n} fact${n === 1 ? "" : "s"}${at ? ` at ${at}` : ""}${recorded ? `, ${recorded}` : ""}`,+ recordedBy: (t: string) => `as recorded by ${t}`,+ recordedBefore: (t: string) => `as recorded before ${t}`,+ linked: (n: number, total: number) =>+ n === total ? `${n} linked` : `${n} of ${total} linked`,+ dated: (n: number, total: number) =>+ n === total+ ? `${n} dated fact${n === 1 ? "" : "s"}`+ : `${n} of ${total} dated facts`,+ /* `more`:列到上限就停了,后面可能还有 */+ paths: (n: number, more: boolean, hops: number) =>+ n === 0+ ? "no path"+ : `${n}${more ? "+" : ""} path${n === 1 && !more ? "" : "s"}, shortest ${hops} hop${hops === 1 ? "" : "s"}`,+ changes: (n: number, more: boolean) =>+ n === 0 ? "no changes" : `${n}${more ? "+" : ""} change${n === 1 && !more ? "" : "s"}`,+ /* 没给 until 的窗口开到现在:「2026-09-01 → now」 */+ now: "now",+ rows: (n: number, more: boolean) =>+ `${n}${more ? "+" : ""} row${n === 1 && !more ? "" : "s"}`,+ rules: (n: number) => (n === 0 ? "none" : `${n} rule${n === 1 ? "" : "s"}`),+ /* rule_matches:这条规则此刻标出了几处 */+ marked: (n: number) => `${n} marked`,+ /* 问数那一步可以展开看它跑的 SQL(#936) */+ sql: "SQL",+ },newChat: "New chat",recent: "Recent",untitled: "Untitled",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 2061ecaf..d77e6979 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -742,6 +742,37 @@ export const zh: Strings = {send: "发送",stop: "停止",thinking: "思考中…",+ step: {+ failed: "失败",+ documentNotFound: "未找到文档",+ entityNotFound: "未找到实体",+ sourceNotFound: "没有这个数据源",+ unknownTool: "未知工具",+ unparsed: "参数不完整",+ missing: (param: string) => `缺少 ${param}`,+ invalid: (param: string) => `${param} 无效`,+ sources: (n: number) => `${n} 个来源`,+ sections: (n: number) => `${n} 段`,+ matches: (n: number, total?: number) =>+ total === undefined ? `${n} 个匹配` : `${n} 个匹配(共 ${total} 个)`,+ facts: (n: number, at: string | null, recorded: string | null) =>+ `${at ? `${at} 时的 ` : ""}${n} 条事实${recorded ? `,${recorded}` : ""}`,+ recordedBy: (t: string) => `按 ${t} 时的记录`,+ recordedBefore: (t: string) => `按 ${t} 之前的记录`,+ linked: (n: number, total: number) =>+ n === total ? `关联 ${n} 个` : `关联 ${total} 个,列出 ${n} 个`,+ dated: (n: number, total: number) =>+ n === total ? `${n} 条有日期的事实` : `${total} 条有日期的事实,列出 ${n} 条`,+ paths: (n: number, more: boolean, hops: number) =>+ n === 0 ? "没有路径" : `${n}${more ? "+" : ""} 条路径,最短 ${hops} 跳`,+ changes: (n: number, more: boolean) =>+ n === 0 ? "没有变更" : `${n}${more ? "+" : ""} 处变更`,+ now: "现在",+ rows: (n: number, more: boolean) => `${n}${more ? "+" : ""} 行`,+ rules: (n: number) => (n === 0 ? "无" : `${n} 条规则`),+ marked: (n: number) => `标出 ${n} 处`,+ sql: "SQL",+ },newChat: "新对话",recent: "最近",untitled: "未命名",diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsxindex cf9bd515..04337d5d 100644--- a/web/src/pages/Chat.tsx+++ b/web/src/pages/Chat.tsx@@ -57,6 +57,7 @@ import {DangerConfirm,IconButton,Input,+ LinkButton,RAIL_CLS,REVEAL,Row,@@ -71,6 +72,7 @@ import {type Turn,} from "../liveAnswer";import { NodCard } from "./PendingFacts";+import { stepDetail, stepLabel } from "../steps";import { NextStep, nextStep, useReadiness } from "./NextStep";/* `Turn` 定义在 liveAnswer 里:进行中的那一次也是一串 Turn,@@ -893,6 +895,47 @@ function stepIcon(kind: ChatStep["kind"]) {return <Wrench size={11} />;}+/** 轨迹上的一行。话按读者的语言说(`stepDetail`,#942);没做成的那一步用危险色。+ *+ * 问数那一步可以展开它跑的 SQL(#936):答案里的数是这条语句算出来的,+ * 读的人该能自己核,而不只看到一句「查了一下」。 */+function StepRow({ step, kbId }: { step: ChatStep; kbId: string }) {+ const [sqlOpen, setSqlOpen] = useState(false);+ return (+ <div>+ <div className="flex items-center gap-2 text-small">+ <span className="text-ink-2">{stepIcon(step.kind)}</span>+ <span className="text-ink-2 truncate">{stepLabel(step)}</span>+ <span+ className={cn(+ "shrink-0",+ step.status === "failed" ? "text-danger" : "text-ink-2",+ )}+ >+ · {stepDetail(step)}+ </span>+ {step.sql && (+ <LinkButton+ className="shrink-0"+ aria-expanded={sqlOpen}+ onClick={() => setSqlOpen((open) => !open)}+ >+ {S.ask.step.sql}+ </LinkButton>+ )}+ </div>+ {sqlOpen && step.sql && (+ <pre className="mt-1 rounded-panel bg-well px-3 py-2 font-mono text-small text-ink-2 whitespace-pre-wrap break-words">+ {step.sql}+ </pre>+ )}+ {/* remember 那一步后面跟着确认卡(0015):这句话抽出的事实先等人点头。+ 抽取是异步的,卡片在任务完成时才长出来;回放时按同一个 chunk 重画 */}+ {step.chunk_id && <NodCard kbId={kbId} chunkId={step.chunk_id} />}+ </div>+ );+}+/** 工具步骤 → 球体状态:思考球讲当前动作的语言 *//** 一段 markdown。**按文本记忆化**:一次生成里每来一个词元,整条消息都要重渲染,* 而 react-markdown 每次都把那一段从头解析一遍——答案越长每个词元越贵,读起来@@ -928,7 +971,7 @@ const Segment = memo(function Segment({ text }: { text: string }) {function Thinking({ step }: { step?: ChatStep }) {return (<span className="u-thinking text-small truncate">- {step ? `${step.label} · ${step.detail}` : S.ask.thinking}+ {step ? `${stepLabel(step)} · ${stepDetail(step)}` : S.ask.thinking}</span>);}@@ -969,16 +1012,7 @@ function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {className="my-3 space-y-1 border-l border-line-strong pl-3">{seg.steps.map((s, j) => (- <div key={j}>- <div className="flex items-center gap-2 text-small">- <span className="text-ink-2">{stepIcon(s.kind)}</span>- <span className="text-ink-2 truncate">{s.label}</span>- <span className="text-ink-2 shrink-0">· {s.detail}</span>- </div>- {/* remember 那一步后面跟着确认卡(0015):这句话抽出的事实先等人点头。- 抽取是异步的,卡片在任务完成时才长出来;回放时按同一个 chunk 重画 */}- {s.chunk_id && <NodCard kbId={kbId} chunkId={s.chunk_id} />}- </div>+ <StepRow key={j} step={s} kbId={kbId} />))}</div>) : (diff --git a/web/src/steps.test.ts b/web/src/steps.test.tsnew file mode 100644index 00000000..c8d279f2--- /dev/null+++ b/web/src/steps.test.ts@@ -0,0 +1,101 @@+import { beforeAll, describe, expect, it } from "vitest";+import type { ChatStep } from "./api";+import { en } from "./i18n/en";+import { zh } from "./i18n/zh";+import { stepDetail, stepLabel } from "./steps";++// UTC 与本地读出来不是同一天、同一钟点的时区:世界时间与记录时间用错了读法就看得出来+beforeAll(() => {+ process.env.TZ = "America/New_York";+});++const step = (s: Partial<ChatStep>): ChatStep => ({+ kind: "tool",+ label: "",+ detail: "",+ ...s,+});++describe("stepDetail", () => {+ it("shows the stored English of a step saved before the fields existed", () => {+ const old = step({ kind: "facts", label: "Acme", detail: "12 facts as of 2024-08-01T00:00:00Z" });+ expect(stepDetail(old, en)).toBe("12 facts as of 2024-08-01T00:00:00Z");+ expect(stepDetail(old, zh)).toBe("12 facts as of 2024-08-01T00:00:00Z");+ expect(stepLabel(step({ kind: "changes", label: "2026-09-01 → now" }), zh)).toBe(+ "2026-09-01 → now",+ );+ });++ it.each<[Partial<ChatStep>, string, string]>([+ [{ kind: "search", status: "ok", count: 6 }, "6 sources", "6 个来源"],+ [{ kind: "search", status: "ok", count: 1 }, "1 source", "1 个来源"],+ [{ kind: "document", status: "ok", count: 3 }, "3 sections", "3 段"],+ [{ kind: "docs", status: "ok", count: 0 }, "0 sections", "0 段"],+ [{ kind: "entity", status: "ok", count: 3 }, "3 matches", "3 个匹配"],+ [{ kind: "entity", status: "ok", count: 5, total: 12 }, "5 of 12 matches", "5 个匹配(共 12 个)"],+ [{ kind: "facts", status: "ok", count: 12 }, "12 facts", "12 条事实"],+ [{ kind: "neighbors", status: "ok", count: 3, total: 10 }, "3 of 10 linked", "关联 10 个,列出 3 个"],+ [{ kind: "neighbors", status: "ok", count: 4, total: 4 }, "4 linked", "关联 4 个"],+ [{ kind: "timeline", status: "ok", count: 2, total: 5 }, "2 of 5 dated facts", "5 条有日期的事实,列出 2 条"],+ [{ kind: "path", status: "ok", count: 0 }, "no path", "没有路径"],+ [{ kind: "path", status: "ok", count: 1, hops: 2 }, "1 path, shortest 2 hops", "1 条路径,最短 2 跳"],+ [{ kind: "path", status: "ok", count: 5, hops: 1, more: true }, "5+ paths, shortest 1 hop", "5+ 条路径,最短 1 跳"],+ [{ kind: "changes", status: "ok", count: 0 }, "no changes", "没有变更"],+ [{ kind: "changes", status: "ok", count: 40, more: true }, "40+ changes", "40+ 处变更"],+ [{ kind: "tool", label: "list_rules", status: "ok", count: 0 }, "none", "无"],+ [{ kind: "tool", label: "list_rules", status: "ok", count: 2 }, "2 rules", "2 条规则"],+ [{ kind: "tool", label: "rule_matches", status: "ok", count: 7 }, "7 marked", "标出 7 处"],+ [{ kind: "search", status: "failed" }, "failed", "失败"],+ [{ kind: "document", status: "not_found" }, "document not found", "未找到文档"],+ [{ kind: "neighbors", status: "not_found" }, "entity not found", "未找到实体"],+ [{ kind: "tool", label: "lookup", status: "not_found" }, "unknown tool", "未知工具"],+ [{ kind: "tool", label: "search_chunks", status: "invalid" }, "incomplete arguments", "参数不完整"],+ [{ kind: "tool", status: "invalid", param: "query", missing: true }, "missing query", "缺少 query"],+ [{ kind: "document", status: "invalid", param: "document_id" }, "invalid document_id", "document_id 无效"],+ ])("words %j in both languages", (fields, english, chinese) => {+ // detail 故意给一句别的:有 status 的步骤不该读它+ const s = step({ detail: "server words", ...fields });+ expect(stepDetail(s, en)).toBe(english);+ expect(stepDetail(s, zh)).toBe(chinese);+ });++ it("keeps what belongs to the user or the model as written", () => {+ const remembered = step({ label: "remember", detail: "我们在 2026 年换了供应商", status: "ok" });+ expect(stepDetail(remembered, zh)).toBe("我们在 2026 年换了供应商");+ const query = step({ kind: "query", label: "warehouse", detail: "按月的收入", status: "ok", count: 12 });+ expect(stepLabel(query, zh)).toBe("warehouse");+ expect(stepDetail(query, zh)).toBe("按月的收入 · 12 行");+ expect(stepDetail(query, en)).toBe("按月的收入 · 12 rows");+ expect(stepDetail({ ...query, count: 200, more: true }, en)).toBe("按月的收入 · 200+ rows");+ expect(stepDetail({ ...query, status: "failed" }, zh)).toBe("按月的收入 · 失败");+ expect(stepDetail({ ...query, status: "not_found" }, en)).toBe("按月的收入 · no such data source");+ });++ it("builds the changes window in the reader's language", () => {+ const open = step({ kind: "changes", label: "2026-09-01 → now", status: "ok", count: 3, since: "2026-09-01" });+ expect(stepLabel(open, zh)).toBe("2026-09-01 → 现在");+ expect(stepLabel(open, en)).toBe("2026-09-01 → now");+ expect(stepLabel({ ...open, until: "2026-09-15" }, zh)).toBe("2026-09-01 → 2026-09-15");+ });++ it("reads the world moment as a calendar day and the record moment in local time", () => {+ // 这条测试靠的就是时区:没设上的话下面的断言什么也证明不了+ expect(new Date("2024-08-01T00:00:00Z").getDate()).toBe(31);+ const facts = step({+ kind: "facts",+ label: "Acme",+ status: "ok",+ count: 12,+ valid_at: "2024-08-01T00:00:00Z",+ before: "2026-09-12T06:03:00Z",+ });+ // 世界时间是 8 月 1 日,不是纽约的 7 月 31 日晚上;记录时刻是纽约的 02:03+ expect(stepDetail(facts, en)).toBe("12 facts at 2024-08-01, as recorded before 2026-09-12 02:03");+ expect(stepDetail(facts, zh)).toBe("2024-08-01 时的 12 条事实,按 2026-09-12 02:03 之前的记录");+ const asOf = step({ kind: "facts", status: "ok", count: 1, as_of: "2026-09-12T06:03:00Z" });+ expect(stepDetail(asOf, en)).toBe("1 fact, as recorded by 2026-09-12 02:03");+ // 带钟点的世界时间写到钟点,仍按 UTC+ const clocked = step({ kind: "facts", status: "ok", count: 2, valid_at: "2024-08-01T14:30:00Z" });+ expect(stepDetail(clocked, en)).toBe("2 facts at 2024-08-01T14:30Z");+ });+});diff --git a/web/src/steps.ts b/web/src/steps.tsnew file mode 100644index 00000000..36496e31--- /dev/null+++ b/web/src/steps.ts@@ -0,0 +1,94 @@+/** 轨迹上的一步怎么说(#942)。+ *+ * 服务端每一步只给字段(0004):`status`、数、时刻,外加个别步骤自己的几样。+ * 话在这里按读者的语言说。`label` 与问数、remember 的 `detail` 是数据,原样显示。+ *+ * **没有 `status` 的是这之前存下的消息**,它们只有服务端当时写的那句英文,+ * 原样显示;不去解析那句英文再说一遍。 */+import type { ChatStep } from "./api";+import { S, type Strings } from "./i18n";+import { fmtTime } from "./time";+import { localDateTime } from "./ui";++/** 世界时间:日历上的日子,按 UTC 读(见 fmtTime)。带了钟点的才写钟点 */+function worldMoment(iso: string): string {+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return iso;+ const precision =+ d.getUTCSeconds() || d.getUTCMilliseconds()+ ? "second"+ : d.getUTCHours() || d.getUTCMinutes()+ ? "minute"+ : "day";+ return fmtTime(iso, precision) ?? iso;+}++/** 记录时间:一个真实的时刻,按看的人所在的时区(见 localDateTime) */+function recordMoment(iso: string): string {+ return Number.isNaN(new Date(iso).getTime()) ? iso : localDateTime(iso);+}++/** 这一步的对象。只有 changes 要改:服务端拼的「2026-09-01 → now」里 now 是英文 */+export function stepLabel(step: ChatStep, T: Strings = S): string {+ if (step.status && step.kind === "changes" && step.since) {+ return `${step.since} → ${step.until ?? T.ask.step.now}`;+ }+ return step.label;+}++/** 这一步的结果 */+export function stepDetail(step: ChatStep, T: Strings = S): string {+ const W = T.ask.step;+ if (!step.status) return step.detail;+ // 问数的 detail 是这次查询的目的,结果跟在它后面+ const withPurpose = (result: string) =>+ step.kind === "query" && step.detail ? `${step.detail} · ${result}` : result;+ if (step.status === "failed") return withPurpose(W.failed);+ if (step.status === "not_found") {+ if (step.kind === "document") return W.documentNotFound;+ if (step.kind === "query") return withPurpose(W.sourceNotFound);+ if (step.kind === "tool") return W.unknownTool;+ return W.entityNotFound;+ }+ if (step.status === "invalid") {+ if (!step.param) return W.unparsed;+ return step.missing ? W.missing(step.param) : W.invalid(step.param);+ }+ const n = step.count ?? 0;+ const more = step.more === true;+ switch (step.kind) {+ case "search":+ return W.sources(n);+ case "document":+ case "docs":+ return W.sections(n);+ case "entity":+ return W.matches(n, step.total);+ case "facts": {+ const record = step.before+ ? W.recordedBefore(recordMoment(step.before))+ : step.as_of+ ? W.recordedBy(recordMoment(step.as_of))+ : null;+ return W.facts(n, step.valid_at ? worldMoment(step.valid_at) : null, record);+ }+ case "neighbors":+ return W.linked(n, step.total ?? n);+ case "timeline":+ return W.dated(n, step.total ?? n);+ case "path":+ return W.paths(n, more, step.hops ?? 0);+ case "changes":+ return W.changes(n, more);+ case "query":+ return withPurpose(W.rows(n, more));+ case "tool":+ if (step.label === "list_rules") return W.rules(n);+ if (step.label === "rule_matches") return W.marked(n);+ // remember 的 detail 是记下的那句话+ return step.detail;+ default:+ // 以后的服务端多出来的 kind:它的 detail 仍是一句能读的英文+ return step.detail;+ }+}diff --git a/web/tests/chat-view.test.mjs b/web/tests/chat-view.test.mjsindex 43d85d15..b84eb55b 100644--- a/web/tests/chat-view.test.mjs+++ b/web/tests/chat-view.test.mjs@@ -855,5 +855,51 @@ test(}}});+ await t.test("a query step says what it read and opens the SQL it ran", async () => {+ const sql =+ "SELECT month, sum(amount) AS revenue FROM orders GROUP BY month ORDER BY month";+ const f = await open("/kb/one/chat/a", async (route, p) => {+ if (p.endsWith("/conversations/a")) {+ await route.fulfill({+ json: {+ messages: [+ {+ ...message("Revenue grew every month."),+ steps: [+ { kind: "query", label: "warehouse", detail: "revenue by month",+ status: "ok", count: 12, sql, at: 0 },+ { kind: "query", label: "warehouse", detail: "revenue by region",+ status: "failed", sql: "SELECT region FROM nowhere", at: 0 },+ ],+ },+ ],+ },+ });+ return true;+ }+ });+ try {+ await f.page+ .getByText("· revenue by month · 12 rows", { exact: true })+ .waitFor();+ const failed = f.page.getByText("· revenue by region · failed", {+ exact: true,+ });+ assert.match(await failed.getAttribute("class"), /\btext-danger\b/);+ assert.equal(await f.page.getByText(sql, { exact: true }).count(), 0);+ const toggles = f.page.getByRole("button", { name: "SQL", exact: true });+ assert.equal(await toggles.count(), 2);+ await toggles.first().click();+ await f.page.getByText(sql, { exact: true }).waitFor();+ assert.equal(await toggles.first().getAttribute("aria-expanded"), "true");+ assert.equal(+ await f.page.getByText("SELECT region FROM nowhere", { exact: true }).count(),+ 0,+ );+ assert.deepEqual(f.errors, []);+ } finally {+ await f.close();+ }+ });},);