Skip to content

World's first open-source enterprise world model.

Give each chat stream failure a stable code so the interface words it in the reader's language (#951)

Maya Kid5838437018eb
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index bd62e974..c0644531 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -41,7 +41,68 @@ const MAX_ROUNDS: usize = 6;
enum ProducerEvent {
Progress(Frame),
- Outcome(Result<Uuid, String>),
+ Outcome(Result<Uuid, Failure>),
+}
+
+/// 一次没答成的生成(0004):`code` 给界面去 `err.*` 表里查措辞,英文原句留给日志、
+/// MCP 和不做本地化的客户端。**服务端不出显示文本**——`error` 帧与请求被拒用的是
+/// 同一个信封 `{error, code}`,前端用同一个函数读
+struct Failure {
+ code: &'static str,
+ message: String,
+}
+
+impl Failure {
+ fn new(code: &'static str, message: impl Into<String>) -> Self {
+ Self {
+ code,
+ message: message.into(),
+ }
+ }
+
+ /// 模型那一侧的失败,按 `utopia_llm` 的错误类型给 code;认不出的算作答失败
+ fn model(err: &anyhow::Error, message: impl Into<String>) -> Self {
+ Self::new(model_failure_code(err).unwrap_or("answer_failed"), message)
+ }
+}
+
+/// 模型端点的失败换成稳定的 code。类型是 `utopia_llm` 早就分好的:欠费、限流、
+/// 暂时不可用、请求没送到或断在半路、其余的拒绝。这里只是把它们说给界面听
+fn model_failure_code(err: &anyhow::Error) -> Option<&'static str> {
+ if utopia_llm::out_of_credit(err).is_some() {
+ Some("model_out_of_credit")
+ } else if utopia_llm::rate_limited(err).is_some() {
+ Some("model_rate_limited")
+ } else if utopia_llm::unavailable(err).is_some() {
+ Some("model_unavailable")
+ } else if utopia_llm::is_unreachable(err)
+ || err.chain().any(|e| e.is::<utopia_llm::Interrupted>())
+ {
+ Some("model_unreachable")
+ } else if utopia_llm::rejected(err).is_some() {
+ Some("model_rejected")
+ } else {
+ None
+ }
+}
+
+/// 收尾关口(`agent::finalization_error`)拦下候选答案时说的那几句,换成 code。
+/// 这几句以文本的形式穿过 `chat_finalization` 的边界,所以按原文认;测试直接拿
+/// `finalization_error` 的输出来对,改了措辞会在那里失败,而不是悄悄丢掉 code
+fn unpublishable_code(message: &str) -> Option<&'static str> {
+ if message.contains("tool-control text") {
+ Some("answer_tool_text")
+ } else if message.contains("attempted a tool call")
+ || message.contains("Tool calls are not answers")
+ {
+ Some("answer_tool_call")
+ } else if message.contains("empty answer") {
+ Some("answer_empty")
+ } else if message.contains("size limit") {
+ Some("answer_too_long")
+ } else {
+ None
+ }
}
/// `remember` 曾整个停用过一段(见 `docs/decisions/0015`):它那时会把一句话直接
@@ -774,7 +835,7 @@ pub async fn chat(
// protocol garbage.
if shared.finalizing() {
if turn_text.len().saturating_add(t.text.len()) > agent::MAX_FINAL_ANSWER_BYTES {
- yield ProducerEvent::Outcome(Err("Model final answer exceeded the size limit".into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("answer_too_long", "Model final answer exceeded the size limit")));
return;
}
turn_text.push_str(&t.text);
@@ -893,7 +954,7 @@ pub async fn chat(
Ok(MultiTurnStreamItem::FinalResponse(_)) => finished = true,
Ok(_) => {}
Err(e) => {
- let (message, rejected) = describe(&e);
+ let (failure, rejected) = describe(&e);
if matches!(&e, StreamingError::Prompt(pe) if matches!(pe.as_ref(), PromptError::PromptCancelled { .. }))
&& shared.take_answer_request() {
answer_requested = true;
@@ -903,7 +964,7 @@ pub async fn chat(
// 的任何错误都走这条路:一次到 SiliconFlow 的网络抖动被记成
// 「tool-calling 不可用」,然后 RAG 死在同一个抖动上
if rejected && answer_acc.is_empty() && steps_acc.is_empty() {
- tracing::warn!(error = %message, "端点拒绝工具调用,降级为一次性 RAG");
+ tracing::warn!(error = %failure.message, "端点拒绝工具调用,降级为一次性 RAG");
let mut legacy = std::pin::pin!(legacy_rag(
state.clone(),
kb_id,
@@ -918,7 +979,7 @@ pub async fn chat(
}
return;
}
- yield ProducerEvent::Outcome(Err(message));
+ yield ProducerEvent::Outcome(Err(failure));
return;
}
}
@@ -937,18 +998,25 @@ pub async fn chat(
};
match finalization::answer(&client, input).await {
Ok(answer) => { turn_text = answer; turn_calls.clear(); finished = true; }
- Err(e) => { yield ProducerEvent::Outcome(Err(format!("Model could not produce a final answer: {e}"))); return; }
+ Err(e) => {
+ let message = format!("Model could not produce a final answer: {e}");
+ let code = model_failure_code(&e)
+ .or_else(|| unpublishable_code(&message))
+ .unwrap_or("answer_failed");
+ yield ProducerEvent::Outcome(Err(Failure::new(code, message)));
+ return;
+ }
}
}
if !finished {
- yield ProducerEvent::Outcome(Err("LLM stream ended unexpectedly".into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("answer_failed", "LLM stream ended unexpectedly")));
return;
}
// Check the terminal candidate, not earlier narration. The hook is the
// policy boundary; this is the last guard before publication and storage.
if shared.finalizing() {
if let Some(reason) = agent::finalization_error(&turn_text, !turn_calls.is_empty(), &query) {
- yield ProducerEvent::Outcome(Err(reason.into()));
+ yield ProducerEvent::Outcome(Err(Failure::new(unpublishable_code(reason).unwrap_or("answer_failed"), reason)));
return;
}
answer_acc.push_str(&turn_text);
@@ -957,7 +1025,7 @@ pub async fn chat(
// 一次,这是第二次:报错,不存(#937)。不是(例如围栏里的示例),补发
if turn_published < turn_text.len() {
if agent::tool_call_text(&turn_text, &query) {
- yield ProducerEvent::Outcome(Err(agent::CONTROL_TEXT.into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("answer_tool_text", agent::CONTROL_TEXT)));
return;
}
let rest = turn_text[turn_published..].to_string();
@@ -965,7 +1033,7 @@ pub async fn chat(
yield ProducerEvent::Progress(delta_event(&rest));
}
if turn_text.trim().is_empty() {
- yield ProducerEvent::Outcome(Err("Model returned an empty answer".into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("answer_empty", "Model returned an empty answer")));
return;
}
}
@@ -986,7 +1054,7 @@ pub async fn chat(
Ok(id) => id,
Err(error) => {
tracing::error!(%error, %conversation_id, "Could not persist final answer");
- yield ProducerEvent::Outcome(Err("Could not save the answer. Please try again later.".into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("answer_not_saved", "Could not save the answer. Please try again later.")));
return;
}
};
@@ -1008,7 +1076,10 @@ pub async fn chat(
match event {
ProducerEvent::Progress(frame) => {
if matches!(frame.event, "done" | "error") {
- outcome = Some(Err("Producer sent a terminal as progress".into()));
+ outcome = Some(Err(Failure::new(
+ "answer_failed",
+ "Producer sent a terminal as progress",
+ )));
break;
}
handle.emit(frame).await;
@@ -1021,12 +1092,15 @@ pub async fn chat(
}
let terminal = match outcome {
Some(Ok(_saved_id)) => done_event(),
- Some(Err(message)) => error_event(if message.trim().is_empty() {
- "Answer failed"
- } else {
- &message
- }),
- None => error_event("Answer stream ended unexpectedly"),
+ Some(Err(failure)) => error_event(
+ failure.code,
+ if failure.message.trim().is_empty() {
+ "Answer failed"
+ } else {
+ &failure.message
+ },
+ ),
+ None => error_event("stream_ended", "Answer stream ended unexpectedly"),
};
handle.emit(terminal).await;
// 注销之后再接上的人得到「没有在跑的」,那时答案已经落库
@@ -1036,21 +1110,26 @@ pub async fn chat(
Ok(sse_from(attached))
}
-/// rig 的错误变成给用户的一句话,外加「是不是端点拒绝了工具调用」。
+/// rig 的错误变成一次失败(code 与英文原句),外加「是不是端点拒绝了工具调用」。
/// 我们自己的错误链(限流、欠费、被拒)从 `rig_model` 里取回来,文本与从前一样
-fn describe(err: &StreamingError) -> (String, bool) {
- fn completion(ce: &CompletionError) -> (String, bool) {
+fn describe(err: &StreamingError) -> (Failure, bool) {
+ fn completion(ce: &CompletionError) -> (Failure, bool) {
match rig_model::llm_failure(ce) {
- Some(ours) => (ours.to_string(), rig_model::tool_calling_rejected(ce)),
- None => (ce.to_string(), false),
+ Some(ours) => (
+ Failure::model(ours, ours.to_string()),
+ rig_model::tool_calling_rejected(ce),
+ ),
+ None => (Failure::new("answer_failed", ce.to_string()), false),
}
}
match err {
StreamingError::Completion(ce) => completion(ce),
StreamingError::Prompt(pe) => match pe.as_ref() {
PromptError::CompletionError(ce) => completion(ce),
- PromptError::PromptCancelled { reason, .. } => (reason.clone(), false),
- other => (other.to_string(), false),
+ PromptError::PromptCancelled { reason, .. } => {
+ (Failure::new("answer_failed", reason.clone()), false)
+ }
+ other => (Failure::new("answer_failed", other.to_string()), false),
},
}
}
@@ -1071,7 +1150,7 @@ fn legacy_rag(
Ok(chunks) => chunks,
Err(error) => {
tracing::warn!(%error, "fallback document retrieval failed");
- yield ProducerEvent::Outcome(Err("Could not search the documents.".into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("search_failed", "Could not search the documents.")));
return;
}
};
@@ -1095,11 +1174,11 @@ fn legacy_rag(
while let Some(item) = deltas.next().await {
match item {
Ok(text) => { answer_acc.push_str(&text); yield ProducerEvent::Progress(delta_event(&text)); }
- Err(e) => { yield ProducerEvent::Outcome(Err(e.to_string())); return; }
+ Err(e) => { yield ProducerEvent::Outcome(Err(Failure::model(&e, e.to_string()))); return; }
}
}
if answer_acc.trim().is_empty() {
- yield ProducerEvent::Outcome(Err("Model returned an empty answer".into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("answer_empty", "Model returned an empty answer")));
return;
}
let saved = utopia_store::conversations::append_message(
@@ -1115,11 +1194,11 @@ fn legacy_rag(
Ok(id) => yield ProducerEvent::Outcome(Ok(id)),
Err(error) => {
tracing::error!(%error, "fallback answer persistence was not confirmed");
- yield ProducerEvent::Outcome(Err("Could not confirm that the answer was saved.".into()));
+ yield ProducerEvent::Outcome(Err(Failure::new("answer_not_saved", "Could not confirm that the answer was saved.")));
}
}
}
- Err(e) => yield ProducerEvent::Outcome(Err(e.to_string())),
+ Err(e) => yield ProducerEvent::Outcome(Err(Failure::model(&e, e.to_string()))),
}
}
}
@@ -1152,15 +1231,15 @@ fn sse_from(
if done { return; }
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
- yield to_event(&error_event("Answer stream ended unexpectedly"));
+ yield to_event(&error_event("stream_ended", "Answer stream ended unexpectedly"));
return;
}
// 这个客户端读得太慢,被广播缓冲甩下了。**说出来**——
// 静默继续会让它少掉中间一段而毫不知情
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
- yield to_event(&Frame::new(
- "error",
- format!("Fell behind the stream by {n} messages; reopen the conversation"),
+ yield to_event(&error_event(
+ "stream_lagged",
+ &format!("Fell behind the stream by {n} messages; reopen the conversation"),
));
return;
}
@@ -1200,8 +1279,12 @@ fn done_event() -> Frame {
Frame::new("done", "{}".into())
}
-fn error_event(message: &str) -> Frame {
- Frame::new("error", message.into())
+/// 与请求被拒同一个信封:`error` 是英文原句,`code` 给界面查措辞(0004)
+fn error_event(code: &str, message: &str) -> Frame {
+ Frame::new(
+ "error",
+ json!({ "error": message, "code": code }).to_string(),
+ )
}
fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
diff --git a/crates/utopia-server/src/api/chat_empty_reply_tests.rs b/crates/utopia-server/src/api/chat_empty_reply_tests.rs
index bc2c6a35..893a73f4 100644
--- a/crates/utopia-server/src/api/chat_empty_reply_tests.rs
+++ b/crates/utopia-server/src/api/chat_empty_reply_tests.rs
@@ -370,6 +370,8 @@ async fn a_reply_that_stays_empty_is_an_error_after_one_retry() -> anyhow::Resul
f.cleanup().await
}
+#[path = "chat_error_code_tests.rs"]
+mod error_code_tests;
#[path = "chat_fallback_tests.rs"]
mod fallback_tests;
#[path = "chat_history_tests.rs"]
diff --git a/crates/utopia-server/src/api/chat_error_code_tests.rs b/crates/utopia-server/src/api/chat_error_code_tests.rs
new file mode 100644
index 00000000..6d0106dc
--- /dev/null
+++ b/crates/utopia-server/src/api/chat_error_code_tests.rs
@@ -0,0 +1,121 @@
+//! 对话流的失败带 code(0004)。
+//!
+//! 服务端不出显示文本:`error` 帧与请求被拒是同一个信封 `{error, code}`,界面拿 code
+//! 去 `err.*` 表里查措辞,英文原句留给日志、MCP 与不做本地化的客户端。从前这一帧只有
+//! 一句英文,于是中文界面上欠费、限流、空答案、存不下都是英文。
+//!
+//! 这里逐项核对用户会撞上的那几种失败各是哪个 code;每个 `error` 帧都带 code 这件事
+//! 由终态契约(`chat_terminal_tests.rs`)对整张表检查。
+use super::*;
+
+const TOOL: Reply = Reply::Tool("find_entities", r#"{"name":"Acme"}"#);
+
+/// 这条 SSE 里那个 `error` 帧的 code 与英文原句
+fn failure(sse: &str) -> (String, String) {
+ let data = sse
+ .split("\n\n")
+ .find_map(|frame| frame.strip_prefix("event: error\ndata: "))
+ .unwrap_or_else(|| panic!("no error frame:\n{sse}"));
+ let body: serde_json::Value = serde_json::from_str(data)
+ .unwrap_or_else(|e| panic!("the error frame is not JSON ({e}): {data}"));
+ (
+ body["code"].as_str().unwrap_or_default().to_string(),
+ body["error"].as_str().unwrap_or_default().to_string(),
+ )
+}
+
+#[tokio::test]
+async fn each_failure_a_user_can_meet_carries_its_code() -> anyhow::Result<()> {
+ let mut budget = vec![Reply::NarratedTool; 6];
+ budget.extend([Reply::Text(DSML), Reply::Text(DSML)]);
+ for (what, replies, code) in [
+ (
+ "empty after a retry",
+ vec![TOOL, Reply::Empty, Reply::Empty],
+ "answer_empty",
+ ),
+ (
+ "tool-control text at the budget",
+ budget,
+ "answer_tool_text",
+ ),
+ (
+ "a tool call written as text twice (#946)",
+ vec![TOOL, Reply::Text(DSML), Reply::Text(DSML)],
+ "answer_tool_text",
+ ),
+ (
+ "out of credit",
+ vec![Reply::Http(402)],
+ "model_out_of_credit",
+ ),
+ ("rate limited", vec![Reply::Http(429)], "model_rate_limited"),
+ ("unavailable", vec![Reply::Http(503)], "model_unavailable"),
+ ("key rejected", vec![Reply::Http(401)], "model_rejected"),
+ ] {
+ let Some(f) = fixture(Scripted::new(replies)).await? else {
+ return Ok(());
+ };
+ let sse = f.ask("What changed at Acme?").await?;
+ let (got, message) = failure(&sse);
+ assert_eq!(got, code, "{what}: {message}");
+ assert!(
+ !message.is_empty(),
+ "{what}: the English sentence stays for logs and MCP"
+ );
+ f.cleanup().await?;
+ }
+ Ok(())
+}
+
+#[tokio::test]
+async fn an_answer_that_cannot_be_saved_says_so_with_its_code() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![TOOL, Reply::Text("Accepted answer.")])).await? else {
+ return Ok(());
+ };
+ let name = format!("reject_assistant_{}", f.kb.simple());
+ sqlx::raw_sql(&format!(
+ "CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN \
+ IF NEW.role='assistant' AND EXISTS(SELECT 1 FROM conversations \
+ WHERE id=NEW.conversation_id AND kb_id='{}') THEN \
+ RAISE EXCEPTION 'injected persistence failure'; END IF; RETURN NEW; END $$; \
+ CREATE TRIGGER {name} BEFORE INSERT ON conversation_messages \
+ FOR EACH ROW EXECUTE FUNCTION {name}();",
+ f.kb
+ ))
+ .execute(&f.pool)
+ .await?;
+ let sse = f.ask("What happened?").await?;
+ sqlx::raw_sql(&format!(
+ "DROP TRIGGER {name} ON conversation_messages; DROP FUNCTION {name}();"
+ ))
+ .execute(&f.pool)
+ .await?;
+ assert_eq!(failure(&sse).0, "answer_not_saved");
+ f.cleanup().await
+}
+
+/// 收尾关口的理由以文本穿过 `chat_finalization`,所以按原文认。这里直接拿
+/// `finalization_error` 的输出来对:改了措辞在这里失败,而不是悄悄变成「作答失败」
+#[test]
+fn the_finalization_reasons_keep_their_codes() {
+ for (text, calls, code) in [
+ ("", false, "answer_empty"),
+ ("Answer.", true, "answer_tool_call"),
+ (DSML, false, "answer_tool_text"),
+ ] {
+ let reason = agent::finalization_error(text, calls, "What changed?").expect("a reason");
+ assert_eq!(unpublishable_code(reason), Some(code), "{reason}");
+ // `chat_finalization` 修一次还不成时,理由包在两层话里交回来
+ let wrapped = format!(
+ "Model could not produce a final answer: Model could not produce a final answer \
+ after one recovery: {reason}"
+ );
+ assert_eq!(unpublishable_code(&wrapped), Some(code), "{wrapped}");
+ }
+ assert_eq!(
+ unpublishable_code("Model final answer exceeded the size limit"),
+ Some("answer_too_long")
+ );
+ assert_eq!(unpublishable_code("Final answer timed out"), None);
+}
diff --git a/crates/utopia-server/src/api/chat_stream_tests.rs b/crates/utopia-server/src/api/chat_stream_tests.rs
index dcf4b843..8e1311f6 100644
--- a/crates/utopia-server/src/api/chat_stream_tests.rs
+++ b/crates/utopia-server/src/api/chat_stream_tests.rs
@@ -75,6 +75,7 @@ async fn producer_disappearing_without_an_outcome_ends_in_one_error() {
assert_eq!(text.matches("event: error").count(), 1, "{text}");
assert!(!text.contains("event: done"), "{text}");
assert!(text.contains("Answer stream ended unexpectedly"), "{text}");
+ assert!(text.contains(r#""code":"stream_ended""#), "{text}");
}
#[tokio::test]
@@ -83,7 +84,9 @@ async fn first_terminal_freezes_the_snapshot_and_broadcast() {
let id = Uuid::now_v7();
let handle = registry.begin(id).await;
handle.emit(delta_event("kept")).await;
- handle.emit(error_event("original error")).await;
+ handle
+ .emit(error_event("answer_failed", "original error"))
+ .await;
handle.emit(delta_event("discarded")).await;
handle.emit(done_event()).await;
let (snapshot, _) = registry.attach(id).await.unwrap();
diff --git a/crates/utopia-server/src/api/chat_terminal_tests.rs b/crates/utopia-server/src/api/chat_terminal_tests.rs
index ced0edd5..21f18caf 100644
--- a/crates/utopia-server/src/api/chat_terminal_tests.rs
+++ b/crates/utopia-server/src/api/chat_terminal_tests.rs
@@ -9,7 +9,7 @@
//!
//! 1. 客户端收不到 `event: done`
//! 2. 恰好观察到一个终结(`done` 与 `error` 加起来正好一次)
-//! 3. 那个终结说得出理由(`error` 的 data 不为空)
+//! 3. 那个终结说得出理由:`error` 的 data 是带 `code` 与英文原句的 JSON(0004)
//!
//! **新增一条会失败的路,代价是加一行**;加不出那一行,说明这条路自己也没想清楚
//! 该怎么收尾。评审该盯的就是「新开了会失败的路却没加行」。
@@ -94,6 +94,13 @@ fn assert_one_earned_terminal(what: &str, ends: Ends, sse: &str) {
!reason.is_empty(),
"{what}:终结得说得出理由,不能是个空 error\n{sse}"
);
+ // 理由带 code:界面拿它查措辞,英文原句只给日志与不做本地化的客户端(0004)
+ let body: serde_json::Value = serde_json::from_str(reason).unwrap_or_default();
+ assert!(
+ body["code"].as_str().is_some_and(|c| !c.is_empty())
+ && body["error"].as_str().is_some_and(|e| !e.is_empty()),
+ "{what}:error 帧要带 code 和原句:{reason}"
+ );
}
}
}
diff --git a/docs/decisions/0004-language-and-localization.md b/docs/decisions/0004-language-and-localization.md
index b6fe5a24..108238fe 100644
--- a/docs/decisions/0004-language-and-localization.md
+++ b/docs/decisions/0004-language-and-localization.md
@@ -1,7 +1,8 @@
# 0004 · Language follows the reader of each text
- **Status**: Built · UI strings in `web/src/i18n/`; user-reachable server errors carry a
- `code` (`AppError::Invalid`, 81 sites; 23 `Validation` guards stay English);
+ `code` (`AppError::Invalid`, 81 sites; 23 `Validation` guards stay English), and so do
+ the 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.
diff --git a/web/src/api.ts b/web/src/api.ts
index ecfd69e0..d36e5267 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -33,6 +33,16 @@ function refusalMessage(body: Refusal, fallback: string): string {
return message;
}
+/** 对话流里的 `error` 帧:与请求被拒是同一个信封 `{error, code}`,用同一个函数读。
+ * 读不成 JSON 的是旧格式的一句英文,原样显示 */
+function streamFailure(data: string): string {
+ try {
+ const body: unknown = JSON.parse(data);
+ if (body && typeof body === "object") return refusalMessage(body as Refusal, data);
+ } catch { /* 旧格式:纯文本 */ }
+ return data;
+}
+
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(path, {
credentials: "include",
@@ -2823,7 +2833,7 @@ function consumeChatStream(
const parser = createParser({ onEvent: ({ event, data: value }) => {
if (terminal || controller.signal.aborted) return;
if (event === "done") { terminal = true; handlers.onDone(); }
- else if (event === "error") fail(value);
+ else if (event === "error") fail(streamFailure(value));
else if (event === "idle") {
if (allowIdle) { terminal = true; handlers.onIdle?.(); }
else fail(S.ask.streamInterrupted);
diff --git a/web/src/chatStream.test.ts b/web/src/chatStream.test.ts
index 8bba3876..0f67c11c 100644
--- a/web/src/chatStream.test.ts
+++ b/web/src/chatStream.test.ts
@@ -3,7 +3,10 @@ import { reattachChat, streamChat, type ChatHandlers } from "./api";
vi.mock("./i18n", () => ({
S: {
ask: { streamInterrupted: "Stream interrupted" },
- err: { no_chat_model: "Worded: configure a chat model" },
+ err: {
+ no_chat_model: "Worded: configure a chat model",
+ model_out_of_credit: "Worded: the model account cannot pay",
+ },
errDetail: (message: string, detail: string) => `${message} (${detail})`,
},
lang: "en",
@@ -61,6 +64,23 @@ describe("a refused chat request", () => {
});
});
+describe("a chat stream that fails", () => {
+ const failed = (body: unknown) => `event: error\ndata: ${JSON.stringify(body)}\n\n`;
+ it("is worded from its stable code, as a refused request is", async () => {
+ const text = failed({ error: "LLM account cannot pay for this request (402): x", code: "model_out_of_credit" });
+ expect(await replay(text)).toEqual([["error", "Worded: the model account cannot pay"]]);
+ expect(await replay(text, true)).toEqual([["error", "Worded: the model account cannot pay"]]);
+ });
+ it("keeps the server's sentence for a code the table does not have", async () => {
+ expect(await replay(failed({ error: "Some new failure", code: "unlisted_code" })))
+ .toEqual([["error", "Some new failure"]]);
+ });
+ it("shows a plain-text error frame as it came", async () => {
+ expect(await replay("event: error\ndata: Model returned an empty answer\n\n"))
+ .toEqual([["error", "Model returned an empty answer"]]);
+ });
+});
+
describe("application chat terminal outcomes", () => {
it.each(["\n", "\r\n", "\r"])("reads %j line endings once, including split UTF-8", async (nl) => {
const text = 'event: delta\ndata: {"text":"中文🙂"}\n\nevent: done\ndata: {}\n\n'.replaceAll("\n", nl);
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index ebd5ccec..f2e1dc43 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -55,6 +55,25 @@ export const en = {
"Sign-up is closed on this deployment — ask an administrator for an account.",
no_chat_model:
"No chat model configured yet. Set one under Administration → Models.",
+ // 对话流里没答成的那一轮:`error` 帧带的 code(服务端的英文原句只给日志)
+ answer_empty: "The model returned an empty answer. Ask again.",
+ answer_tool_text: "The model wrote a tool call as text instead of answering. Ask again.",
+ answer_tool_call: "The model kept calling tools after its lookups ran out. Ask again.",
+ answer_too_long: "The answer went past the size limit and was not kept.",
+ answer_failed: "The answer could not be completed. Ask again.",
+ answer_not_saved: "The answer could not be saved. Try again later.",
+ search_failed: "The documents could not be searched.",
+ stream_ended:
+ "The answer stream ended unexpectedly. Reopen the conversation to check its status.",
+ stream_lagged: "This page fell behind the answer stream. Reopen the conversation.",
+ model_out_of_credit:
+ "The model account cannot pay for this request. Top it up, or pick another endpoint under Administration → Models.",
+ model_rate_limited: "The model endpoint is rate limiting. Wait a moment and ask again.",
+ model_unavailable: "The model endpoint is unavailable right now. Try again shortly.",
+ model_unreachable:
+ "The model endpoint gave no usable answer. Check its address under Administration → Models.",
+ model_rejected:
+ "The model endpoint refused the request. Check the model settings under Administration → 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.",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 929946bb..232fe3c9 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -55,6 +55,21 @@ export const zh: Strings = {
wrong_password: "当前密码不对。",
registration_closed: "本部署已关闭自助注册——请找管理员开通账户。",
no_chat_model: "还没有配置对话模型。到「管理 → 模型」里配一个。",
+ // 对话流里没答成的那一轮:`error` 帧带的 code(服务端的英文原句只给日志)
+ answer_empty: "模型没有给出回答,请再问一次。",
+ answer_tool_text: "模型把工具调用写成了正文,没有作答,请再问一次。",
+ answer_tool_call: "查证次数用完后模型仍在调用工具,请再问一次。",
+ answer_too_long: "回答超出了长度上限,没有保留。",
+ answer_failed: "这次没能答完,请再问一次。",
+ answer_not_saved: "回答没能保存,请稍后再试。",
+ search_failed: "没能检索文档。",
+ stream_ended: "回答的连接意外中断了。重新打开这个对话,看看结果如何。",
+ stream_lagged: "这个页面跟不上回答的速度,请重新打开这个对话。",
+ model_out_of_credit: "模型账号付不起这次请求。去给账号充值,或者在「管理 → 模型」里换一个能用的端点。",
+ model_rate_limited: "模型端点在限流,稍等一会儿再问。",
+ model_unavailable: "模型端点暂时不可用,请稍后再试。",
+ model_unreachable: "模型端点没有给出可用的回答。去「管理 → 模型」里检查端点地址。",
+ model_rejected: "模型端点拒绝了这次请求。去「管理 → 模型」里检查模型设置。",
bad_upload: "这次上传读不出来。",
upload_read_failed: "文件没能读完。",
no_files: "没有附带文件。",