Skip to content

World's first open-source enterprise world model.

Let a question whose answer failed be answered again in place, without storing it a second time (#960)

Maya Kid23ad91fb53b7
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 6c6bb698..738662df 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -120,7 +120,74 @@ pub struct ChatReq {
/// 缺省 = 新建会话(SSE 首个 `conversation` 事件回传 id)
#[serde(default)]
pub conversation_id: Option<Uuid>,
+ /// 新问题的正文。重答时不读它:问的是库里存着的那一句
pub message: String,
+ /// 重答这场对话最后那个还没有回答的问题(#936):不再存一遍,就地回答它
+ #[serde(default)]
+ pub retry_message_id: Option<Uuid>,
+}
+
+/// 要重答的那一问
+struct Retry {
+ conversation_id: Uuid,
+ question_id: Uuid,
+ question: String,
+}
+
+/// 重答(#936)之前的检查:要答的必须是这场对话最后那条消息,而且是一个问题,
+/// 这场对话也没有在跑的生成。
+///
+/// 每一步都只读不写:在这里被拒,库里什么也没变,模型也没被调用。从前想再问一次
+/// 只能重发,同一个问题就在历史里存了两遍,没有回答的那一遍还会在之后每一问里
+/// 作为「没回答的一轮」回放给模型
+async fn retry_question(
+ state: &AppState,
+ kb_id: Uuid,
+ user_id: Uuid,
+ conversation_id: Option<Uuid>,
+ question_id: Uuid,
+) -> Result<Retry, AppError> {
+ let Some(conversation_id) = conversation_id else {
+ return Err(AppError::invalid(
+ "retry_needs_conversation",
+ "A retry names the conversation its question is in",
+ ));
+ };
+ utopia_store::conversations::require_owned(&state.pool, kb_id, user_id, conversation_id)
+ .await?;
+ let target =
+ utopia_store::conversations::retry_target(&state.pool, conversation_id, question_id)
+ .await?
+ .ok_or(AppError::NotFound)?;
+ if target.role != "user" {
+ return Err(AppError::invalid(
+ "retry_not_question",
+ "Only a question can be answered again",
+ ));
+ }
+ if !target.last {
+ return Err(AppError::CodedConflict {
+ code: "retry_answered",
+ message: "That question already has an answer, or the conversation went on after it"
+ .into(),
+ });
+ }
+ if state.live.is_running(conversation_id).await {
+ return Err(answer_running());
+ }
+ Ok(Retry {
+ conversation_id,
+ question_id,
+ question: target.content,
+ })
+}
+
+/// 这场对话里正有一个回答在写。#961 给「生成中又来一个新问题」的也是 409;后落地的那个沿用先落地的 code
+fn answer_running() -> AppError {
+ AppError::CodedConflict {
+ code: "answer_running",
+ message: "An answer is already being written in this conversation".into(),
+ }
}
/// 工具清单。**MCP 也用这一份**(`mcp.rs`):名字、描述、参数 schema 抄成
@@ -623,7 +690,18 @@ pub async fn chat(
let client = llm_util::chat_client(&settings)
.ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?;
- let query = req.message.trim().to_string();
+ // 重答(#936)问的是库里那一句还没有回答的问题,不是请求里的正文
+ let retry = match req.retry_message_id {
+ Some(question_id) => {
+ Some(retry_question(&state, kb_id, user.id, req.conversation_id, question_id).await?)
+ }
+ None => None,
+ };
+ let retrying = retry.is_some();
+ let query = match &retry {
+ Some(retry) => retry.question.trim().to_string(),
+ None => req.message.trim().to_string(),
+ };
if query.is_empty() {
return Err(AppError::Validation("Missing user message".into()).into());
}
@@ -646,21 +724,31 @@ pub async fn chat(
// 会话持久化:有 id 则校验归属,无则以首句为题新建;用户消息即刻落库,
// 上下文由服务端从库里拼——前端只送新消息
- let conversation_id = match req.conversation_id {
- Some(id) => {
- utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, id).await?;
- id
+ // 重答的那一问已经在库里,就地回答它,不再存一遍
+ let (conversation_id, user_message_id) = match retry {
+ Some(retry) => (retry.conversation_id, retry.question_id),
+ None => {
+ let conversation_id = match req.conversation_id {
+ Some(id) => {
+ utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, id)
+ .await?;
+ id
+ }
+ None => {
+ utopia_store::conversations::create(&state.pool, kb_id, user.id, &query).await?
+ }
+ };
+ let user_message_id = utopia_store::conversations::append_message(
+ &state.pool,
+ conversation_id,
+ "user",
+ &query,
+ &utopia_store::conversations::TurnRecord::empty(),
+ )
+ .await?;
+ (conversation_id, user_message_id)
}
- None => utopia_store::conversations::create(&state.pool, kb_id, user.id, &query).await?,
};
- let user_message_id = utopia_store::conversations::append_message(
- &state.pool,
- conversation_id,
- "user",
- &query,
- &utopia_store::conversations::TurnRecord::empty(),
- )
- .await?;
let history = utopia_store::conversations::recent_context(
&state.pool,
conversation_id,
@@ -759,7 +847,8 @@ pub async fn chat(
}
// 会话 id 先行下发(新会话由此告知前端)
- yield ProducerEvent::Progress(Frame::new("conversation", json!({ "id": conversation_id }).to_string()));
+ // 这一问存下的 id 一起下发:答到一半失败了,界面凭它重答(#936)
+ yield ProducerEvent::Progress(Frame::new("conversation", json!({ "id": conversation_id, "message_id": user_message_id }).to_string()));
// 循环是 rig 的(#546):工具、策略钩子、历史、实体清单都交给它;
// 这里只把它的事件翻成前端认得的帧,并在结束时落库
@@ -1075,7 +1164,15 @@ pub async fn chat(
// 生成登记在案,然后**这条连接也只是去「接上」它**——与刷新之后
// 那条重连走的是同一段代码。两条路分开写的话,迟早只有一条是对的
- let handle = live.begin(conversation_id).await;
+ let handle = if retrying {
+ // 上面检查过没有在跑的生成,但两次检查之间别的请求可能已经开了一次(比如连按
+ // 两下重试)。查和登记在一把锁下再做一次;这条路到这里还没写过任何东西
+ live.begin_if_idle(conversation_id)
+ .await
+ .ok_or_else(answer_running)?
+ } else {
+ live.begin(conversation_id).await
+ };
let attached = live.attach(conversation_id).await;
tokio::spawn(async move {
let mut producer = std::pin::pin!(producer);
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 54c719ff..1c95954b 100644
--- a/crates/utopia-server/src/api/chat_empty_reply_tests.rs
+++ b/crates/utopia-server/src/api/chat_empty_reply_tests.rs
@@ -252,6 +252,7 @@ impl Fx {
Json(ChatReq {
conversation_id: None,
message: message.into(),
+ retry_message_id: None,
}),
)
.await
@@ -388,6 +389,8 @@ mod registry_tests;
mod resolved_tests;
#[path = "chat_restated_tests.rs"]
mod restated_tests;
+#[path = "chat_retry_tests.rs"]
+mod retry_tests;
#[path = "chat_sources_tests.rs"]
mod sources_tests;
@@ -560,6 +563,7 @@ async fn budget_finalization_survives_disconnect_and_reattach() -> anyhow::Resul
Json(ChatReq {
conversation_id: Some(id),
message: "What changed at Acme?".into(),
+ retry_message_id: None,
}),
)
.await
diff --git a/crates/utopia-server/src/api/chat_history_tests.rs b/crates/utopia-server/src/api/chat_history_tests.rs
index 4fd8bf16..b42378f6 100644
--- a/crates/utopia-server/src/api/chat_history_tests.rs
+++ b/crates/utopia-server/src/api/chat_history_tests.rs
@@ -36,6 +36,7 @@ pub(super) async fn ask_in(f: &Fx, conversation_id: Uuid, message: &str) -> anyh
Json(ChatReq {
conversation_id: Some(conversation_id),
message: message.into(),
+ retry_message_id: None,
}),
)
.await
diff --git a/crates/utopia-server/src/api/chat_persistence_tests.rs b/crates/utopia-server/src/api/chat_persistence_tests.rs
index ca42b7a6..fcee030a 100644
--- a/crates/utopia-server/src/api/chat_persistence_tests.rs
+++ b/crates/utopia-server/src/api/chat_persistence_tests.rs
@@ -44,6 +44,7 @@ async fn exercise(deny: bool, disconnect: bool) -> anyhow::Result<()> {
Json(ChatReq {
conversation_id: Some(id),
message: "hello".into(),
+ retry_message_id: None,
}),
)
.await
diff --git a/crates/utopia-server/src/api/chat_registry_tests.rs b/crates/utopia-server/src/api/chat_registry_tests.rs
index 2deba455..990d7fdc 100644
--- a/crates/utopia-server/src/api/chat_registry_tests.rs
+++ b/crates/utopia-server/src/api/chat_registry_tests.rs
@@ -51,7 +51,7 @@ async fn finishing_old_chat_preserves_reattachment_to_new_chat() -> anyhow::Resu
let result = tokio::time::timeout(std::time::Duration::from_secs(20), async {
let first = chat(
State(f.state.clone()), AuthUser(f.user.clone()), Path(f.kb),
- Json(ChatReq { conversation_id: None, message: "first greeting".into() }),
+ Json(ChatReq { conversation_id: None, message: "first greeting".into(), retry_message_id: None }),
).await.map_err(|_| anyhow::anyhow!("first chat refused"))?;
gates.ready[0].notified().await;
let id: Uuid = sqlx::query_scalar("SELECT id FROM conversations WHERE kb_id=$1")
@@ -59,7 +59,7 @@ async fn finishing_old_chat_preserves_reattachment_to_new_chat() -> anyhow::Resu
let (_, mut old_events) = f.state.live.attach(id).await.unwrap();
let second = chat(
State(f.state.clone()), AuthUser(f.user.clone()), Path(f.kb),
- Json(ChatReq { conversation_id: Some(id), message: "second greeting".into() }),
+ Json(ChatReq { conversation_id: Some(id), message: "second greeting".into(), retry_message_id: None }),
).await.map_err(|_| anyhow::anyhow!("second chat refused"))?;
gates.ready[1].notified().await;
gates.release[0].notify_one();
diff --git a/crates/utopia-server/src/api/chat_resolved_tests.rs b/crates/utopia-server/src/api/chat_resolved_tests.rs
index 9ff1d320..47bf6dea 100644
--- a/crates/utopia-server/src/api/chat_resolved_tests.rs
+++ b/crates/utopia-server/src/api/chat_resolved_tests.rs
@@ -92,6 +92,7 @@ async fn a_turn_remembers_the_entity_it_read_not_every_candidate() -> anyhow::Re
Json(ChatReq {
conversation_id: Some(id),
message: "When did he join?".into(),
+ retry_message_id: None,
}),
)
.await
diff --git a/crates/utopia-server/src/api/chat_retry_tests.rs b/crates/utopia-server/src/api/chat_retry_tests.rs
new file mode 100644
index 00000000..96e3d4e2
--- /dev/null
+++ b/crates/utopia-server/src/api/chat_retry_tests.rs
@@ -0,0 +1,284 @@
+//! 重答(#936):没有回答的最后一问,就地再答一次。
+//!
+//! 从前答到一半失败,问题留在库里没有回答;想再问只能重发,同一个问题就在历史里存了
+//! 两遍,没回答的那一遍还会在之后每一问里作为「没回答的一轮」回放给模型。重答带着
+//! 那一问存下的 id 来:不再存一遍,答案落在它后面。
+use super::*;
+use axum::response::IntoResponse;
+
+const TOOL: Reply = Reply::Tool("find_entities", r#"{"name":"Acme"}"#);
+const QUESTION: &str = "What changed at Acme?";
+
+/// 一次请求的结果:SSE 全文,或者被拒时的状态码与 `{error, code}`
+enum Outcome {
+ Streamed(String),
+ Refused(u16, serde_json::Value),
+}
+
+async fn post(f: &Fx, body: serde_json::Value) -> anyhow::Result<Outcome> {
+ let req: ChatReq = serde_json::from_value(body)?;
+ match chat(
+ State(f.state.clone()),
+ AuthUser(f.user.clone()),
+ Path(f.kb),
+ Json(req),
+ )
+ .await
+ {
+ Ok(sse) => {
+ let body =
+ axum::body::to_bytes(sse.into_response().into_body(), 4 * 1024 * 1024).await?;
+ Ok(Outcome::Streamed(
+ String::from_utf8_lossy(&body).into_owned(),
+ ))
+ }
+ Err(refused) => {
+ let response = refused.into_response();
+ let status = response.status().as_u16();
+ let body = axum::body::to_bytes(response.into_body(), 1024 * 1024).await?;
+ Ok(Outcome::Refused(
+ status,
+ serde_json::from_slice(&body).unwrap_or_default(),
+ ))
+ }
+ }
+}
+
+/// 这场对话存下的消息:(id, 角色, 正文),按时间序
+async fn stored(f: &Fx, conversation_id: Uuid) -> anyhow::Result<Vec<(Uuid, String, String)>> {
+ Ok(sqlx::query_as(
+ "SELECT id, role, content FROM conversation_messages
+ WHERE conversation_id = $1 ORDER BY created_at, id",
+ )
+ .bind(conversation_id)
+ .fetch_all(&f.pool)
+ .await?)
+}
+
+async fn only_conversation(f: &Fx) -> anyhow::Result<Uuid> {
+ Ok(
+ sqlx::query_scalar("SELECT id FROM conversations WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&f.pool)
+ .await?,
+ )
+}
+
+/// 直接往库里放一条消息:失败之后、接着问之后那些状态,不必每次都让模型演一遍
+async fn append(f: &Fx, conversation_id: Uuid, role: &str, content: &str) -> anyhow::Result<Uuid> {
+ Ok(utopia_store::conversations::append_message(
+ &f.pool,
+ conversation_id,
+ role,
+ content,
+ &utopia_store::conversations::TurnRecord::empty(),
+ )
+ .await?)
+}
+
+fn retry(conversation_id: Uuid, question_id: Uuid) -> serde_json::Value {
+ json!({
+ "conversation_id": conversation_id,
+ "message": QUESTION,
+ "retry_message_id": question_id,
+ })
+}
+
+/// 答到一半失败的那一问,就地再答一次:库里还是一问一答,模型也只看见它一次
+#[tokio::test]
+async fn a_question_whose_answer_failed_is_answered_in_place() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![
+ Reply::Http(401),
+ TOOL,
+ Reply::Text("Retried answer."),
+ ]))
+ .await?
+ else {
+ return Ok(());
+ };
+ let first = f.ask(QUESTION).await?;
+ assert!(
+ first.contains("event: error"),
+ "the first answer fails:\n{first}"
+ );
+ let conversation_id = only_conversation(&f).await?;
+ let before = stored(&f, conversation_id).await?;
+ assert_eq!(before.len(), 1, "only the question is stored: {before:?}");
+ let question_id = before[0].0;
+ let asked_before = f.requests().len();
+
+ let Outcome::Streamed(sse) = post(&f, retry(conversation_id, question_id)).await? else {
+ panic!("the retry was refused");
+ };
+ assert!(sse.contains("event: done"), "{sse}");
+ // `conversation` 那一帧带着这一问存下的 id:界面凭它重答
+ assert!(
+ sse.contains(&format!("\"message_id\":\"{question_id}\"")),
+ "{sse}"
+ );
+ // 还是那一问,后面跟着答案;问题没有存第二遍
+ let after = stored(&f, conversation_id).await?;
+ assert_eq!(after.len(), 2, "{after:?}");
+ assert_eq!(
+ (after[0].0, after[0].1.as_str(), after[0].2.as_str()),
+ (question_id, "user", QUESTION)
+ );
+ assert_eq!(
+ (after[1].1.as_str(), after[1].2.as_str()),
+ ("assistant", "Retried answer.")
+ );
+ // 重答的第一次模型请求里,这个问题只出现一次
+ let request = &f.requests()[asked_before];
+ let asked = request["messages"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|m| {
+ m["role"] == "user" && m["content"].as_str().is_some_and(|c| c.contains(QUESTION))
+ })
+ .count();
+ assert_eq!(asked, 1, "{request}");
+ f.cleanup().await
+}
+
+/// 答过的问题不再答:409,模型不被请求,库里不多一条
+#[tokio::test]
+async fn an_answered_question_is_not_answered_again() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![TOOL, Reply::Text("First answer.")])).await? else {
+ return Ok(());
+ };
+ let sse = f.ask(QUESTION).await?;
+ assert!(sse.contains("event: done"), "{sse}");
+ let conversation_id = only_conversation(&f).await?;
+ let before = stored(&f, conversation_id).await?;
+ let asked = f.requests().len();
+ let Outcome::Refused(status, body) = post(&f, retry(conversation_id, before[0].0)).await?
+ else {
+ panic!("an answered question was answered again");
+ };
+ assert_eq!(
+ (status, body["code"].as_str()),
+ (409, Some("retry_answered")),
+ "{body}"
+ );
+ assert_eq!(
+ stored(&f, conversation_id).await?,
+ before,
+ "nothing is stored"
+ );
+ assert_eq!(f.requests().len(), asked, "the model is not asked");
+ f.cleanup().await
+}
+
+/// 后面有人接着问了,这一问也不再原地重答:答案会落在后来那些轮之后
+#[tokio::test]
+async fn a_question_the_conversation_went_on_from_is_not_answered_again() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![])).await? else {
+ return Ok(());
+ };
+ let conversation_id =
+ utopia_store::conversations::create(&f.pool, f.kb, f.user.id, QUESTION).await?;
+ let first = append(&f, conversation_id, "user", QUESTION).await?;
+ append(&f, conversation_id, "user", "And at Globex?").await?;
+ let before = stored(&f, conversation_id).await?;
+ let Outcome::Refused(status, body) = post(&f, retry(conversation_id, first)).await? else {
+ panic!("a question the conversation went on from was answered again");
+ };
+ assert_eq!(
+ (status, body["code"].as_str()),
+ (409, Some("retry_answered")),
+ "{body}"
+ );
+ assert_eq!(stored(&f, conversation_id).await?, before);
+ assert!(f.requests().is_empty(), "the model is not asked");
+ f.cleanup().await
+}
+
+/// 这场对话里正有一个回答在写:409;它结束之后,同一个请求就能答
+#[tokio::test]
+async fn a_question_is_not_answered_twice_at_once() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![TOOL, Reply::Text("Retried answer.")])).await? else {
+ return Ok(());
+ };
+ let conversation_id =
+ utopia_store::conversations::create(&f.pool, f.kb, f.user.id, QUESTION).await?;
+ let question = append(&f, conversation_id, "user", QUESTION).await?;
+ let running = f.state.live.begin(conversation_id).await;
+ let Outcome::Refused(status, body) = post(&f, retry(conversation_id, question)).await? else {
+ panic!("a retry started while an answer was running");
+ };
+ assert_eq!(
+ (status, body["code"].as_str()),
+ (409, Some("answer_running")),
+ "{body}"
+ );
+ assert!(f.requests().is_empty(), "the model is not asked");
+ assert_eq!(stored(&f, conversation_id).await?.len(), 1);
+
+ running.finish().await;
+ let Outcome::Streamed(sse) = post(&f, retry(conversation_id, question)).await? else {
+ panic!("the retry was refused after the running answer finished");
+ };
+ assert!(sse.contains("event: done"), "{sse}");
+ let after = stored(&f, conversation_id).await?;
+ assert_eq!(after.len(), 2, "{after:?}");
+ assert_eq!(after[0].0, question);
+ f.cleanup().await
+}
+
+/// 重答点名的必须是这场对话里的一个问题
+#[tokio::test]
+async fn a_retry_names_a_question_of_this_conversation() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![])).await? else {
+ return Ok(());
+ };
+ let conversation_id =
+ utopia_store::conversations::create(&f.pool, f.kb, f.user.id, QUESTION).await?;
+ let question = append(&f, conversation_id, "user", QUESTION).await?;
+ let answer = append(&f, conversation_id, "assistant", "An answer.").await?;
+ let elsewhere =
+ utopia_store::conversations::create(&f.pool, f.kb, f.user.id, "Another").await?;
+ let foreign = append(&f, elsewhere, "user", "Another question").await?;
+ for (body, status, code) in [
+ (
+ json!({ "message": QUESTION, "retry_message_id": question }),
+ 422,
+ Some("retry_needs_conversation"),
+ ),
+ (
+ retry(conversation_id, answer),
+ 422,
+ Some("retry_not_question"),
+ ),
+ (retry(conversation_id, foreign), 404, None),
+ (retry(conversation_id, Uuid::now_v7()), 404, None),
+ ] {
+ let Outcome::Refused(got, refusal) = post(&f, body.clone()).await? else {
+ panic!("{body} was not refused");
+ };
+ assert_eq!(got, status, "{body}: {refusal}");
+ if let Some(code) = code {
+ assert_eq!(refusal["code"], code, "{body}");
+ }
+ }
+ assert!(f.requests().is_empty(), "the model is not asked");
+ assert_eq!(stored(&f, conversation_id).await?.len(), 2);
+ assert_eq!(stored(&f, elsewhere).await?.len(), 1);
+ f.cleanup().await
+}
+
+/// 每一问都把它存下的 id 交给界面:答到一半失败时,界面凭它重答
+#[tokio::test]
+async fn every_question_tells_the_interface_its_stored_id() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![TOOL, Reply::Text("An answer.")])).await? else {
+ return Ok(());
+ };
+ let sse = f.ask(QUESTION).await?;
+ let conversation_id = only_conversation(&f).await?;
+ let question = stored(&f, conversation_id).await?[0].0;
+ assert!(
+ sse.contains(&format!("\"message_id\":\"{question}\"")),
+ "{sse}"
+ );
+ f.cleanup().await
+}
diff --git a/crates/utopia-server/src/api/chat_sources_tests.rs b/crates/utopia-server/src/api/chat_sources_tests.rs
index f2c2f31b..4bd309bd 100644
--- a/crates/utopia-server/src/api/chat_sources_tests.rs
+++ b/crates/utopia-server/src/api/chat_sources_tests.rs
@@ -112,6 +112,7 @@ async fn exercise(search_first: bool) -> anyhow::Result<()> {
Json(ChatReq {
conversation_id: None,
message: "Read the second section".into(),
+ retry_message_id: None,
}),
)
.await
diff --git a/crates/utopia-server/src/live.rs b/crates/utopia-server/src/live.rs
index 3b69aadd..e8a7e508 100644
--- a/crates/utopia-server/src/live.rs
+++ b/crates/utopia-server/src/live.rs
@@ -91,6 +91,12 @@ struct Entry {
snap: Arc<RwLock<Snapshot>>,
}
+/// 登记还在、终态还没发出,才算在跑。发出终态之后到生成者注销之间还有一小段,
+/// 那时的登记已经说完了:出错之后马上按重试,不该被它挡住
+async fn running(entry: &Entry) -> bool {
+ entry.snap.read().await.terminal.is_none()
+}
+
/// 进行中的生成,按会话查。
#[derive(Default)]
pub struct Registry(RwLock<HashMap<Uuid, Entry>>);
@@ -144,9 +150,38 @@ impl Registry {
/// 登记一次生成。同一个会话重复登记会顶掉旧的——正常情况下不会发生,
/// 真发生了也是新的那次说了算
pub async fn begin(self: &Arc<Self>, conversation_id: Uuid) -> Handle {
+ let mut entries = self.0.write().await;
+ self.register(&mut entries, conversation_id)
+ }
+
+ /// 只在这个会话没有在跑的生成时登记(#936 的重答)。**查和登记在同一把写锁下**:
+ /// 连按两次重试,只有一次拿得到把手,另一次得到 `None`
+ pub async fn begin_if_idle(self: &Arc<Self>, conversation_id: Uuid) -> Option<Handle> {
+ let mut entries = self.0.write().await;
+ if let Some(entry) = entries.get(&conversation_id) {
+ if running(entry).await {
+ return None;
+ }
+ }
+ Some(self.register(&mut entries, conversation_id))
+ }
+
+ /// 这个会话此刻有没有在跑的生成
+ pub async fn is_running(&self, conversation_id: Uuid) -> bool {
+ match self.0.read().await.get(&conversation_id) {
+ Some(entry) => running(entry).await,
+ None => false,
+ }
+ }
+
+ fn register(
+ self: &Arc<Self>,
+ entries: &mut HashMap<Uuid, Entry>,
+ conversation_id: Uuid,
+ ) -> Handle {
let (tx, _) = broadcast::channel(256);
let snap = Arc::new(RwLock::new(Snapshot::default()));
- self.0.write().await.insert(
+ entries.insert(
conversation_id,
Entry {
tx: tx.clone(),
diff --git a/crates/utopia-store/src/conversations.rs b/crates/utopia-store/src/conversations.rs
index c4d069fd..bfdd1291 100644
--- a/crates/utopia-store/src/conversations.rs
+++ b/crates/utopia-store/src/conversations.rs
@@ -125,6 +125,42 @@ pub async fn messages(pool: &PgPool, conversation_id: Uuid) -> AppResult<Vec<Con
Ok(rows)
}
+/// 重答(#936)要找的那条消息:它的角色、正文,以及它是不是这场对话的最后一条。
+pub struct RetryTarget {
+ pub role: String,
+ pub content: String,
+ pub last: bool,
+}
+
+/// 读出要重答的那条消息;不在这场对话里的 id 交回 `None`。
+///
+/// 回答与问题之间没有连线,靠的是顺序(`created_at`,同一刻再按 id)。所以「还没有
+/// 回答」只能这样判断:这一问后面什么也没有。后面有回答,是答过了;后面有人接着问,
+/// 这时再答,答案会落在那些轮之后,顺序就乱了。两种都不能原地重答
+pub async fn retry_target(
+ pool: &PgPool,
+ conversation_id: Uuid,
+ message_id: Uuid,
+) -> AppResult<Option<RetryTarget>> {
+ let row: Option<(String, String, bool)> = sqlx::query_as(
+ "SELECT m.role, m.content, NOT EXISTS (
+ SELECT 1 FROM conversation_messages later
+ WHERE later.conversation_id = m.conversation_id
+ AND (later.created_at, later.id) > (m.created_at, m.id))
+ FROM conversation_messages m
+ WHERE m.id = $2 AND m.conversation_id = $1",
+ )
+ .bind(conversation_id)
+ .bind(message_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(role, content, last)| RetryTarget {
+ role,
+ content,
+ last,
+ }))
+}
+
/// 一轮回放的历史。
///
/// 三样东西,各自回答一个不同的问题:正文(说过什么)、实体(认下了谁)、
diff --git a/docs/design/chat-and-mcp.md b/docs/design/chat-and-mcp.md
index 1b50d59b..1632d45c 100644
--- a/docs/design/chat-and-mcp.md
+++ b/docs/design/chat-and-mcp.md
@@ -19,7 +19,9 @@ shorter"; `STALL_NUDGE` and `DONE` are gone [0042 d3]. The wire stays `LlmClient
error bodies, the classification of a failure as out of credit, rate limited, unavailable or nothing
of the kind, and cache logging; earlier
entities become a `system` message right before the question; degradation to one-shot RAG happens
-only on a 400 or 422 to the first request with tools [0042 d2].
+only on a 400 or 422 to the first request with tools [0042 d2]. A question whose answer failed stays
+stored without one; a retry names it (`retry_message_id`) and answers it in place, only while it is
+the conversation's last message and no answer is being written there (#936).
**Tools** live once in `tools.rs` and serve chat and MCP alike: `search_chunks`, `search_docs`,
`find_entities`, `entity_facts` (names marked as names, derived rows with their rule, `as_of` and
diff --git a/web/src/api.ts b/web/src/api.ts
index a4bb051b..64913d3c 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -2797,7 +2797,8 @@ export const conversationsApi = {
};
export interface ChatHandlers {
- onConversation: (id: string) => void;
+ /** `messageId`:这一问存下的 id。答到一半失败了,凭它重答(#936);老的服务端不发 */
+ onConversation: (id: string, messageId?: string) => void;
onSources: (s: Source[]) => void;
onStep: (s: ChatStep) => void;
onDelta: (text: string) => void;
@@ -2830,7 +2831,8 @@ export function reattachChat(
export function streamChat(
kbId: string,
- body: { conversation_id?: string; message: string },
+ /** `retry_message_id`:重答这场对话最后那个没有回答的问题(#936),不再存一遍 */
+ body: { conversation_id?: string; message: string; retry_message_id?: string },
handlers: ChatHandlers,
): () => void {
return consumeChatStream(
@@ -2885,7 +2887,10 @@ function consumeChatStream(
else if (event === "idle") {
if (allowIdle) { terminal = true; handlers.onIdle?.(); }
else fail(S.ask.streamInterrupted);
- } else if (event === "conversation") handlers.onConversation(JSON.parse(value).id);
+ } else if (event === "conversation") {
+ const frame = JSON.parse(value);
+ handlers.onConversation(frame.id, frame.message_id);
+ }
else if (event === "sources") handlers.onSources(JSON.parse(value));
else if (event === "step") handlers.onStep(JSON.parse(value));
else if (event === "delta") handlers.onDelta(JSON.parse(value).text);
diff --git a/web/src/chatStream.test.ts b/web/src/chatStream.test.ts
index 0f67c11c..f29e617a 100644
--- a/web/src/chatStream.test.ts
+++ b/web/src/chatStream.test.ts
@@ -117,6 +117,17 @@ describe("application chat terminal outcomes", () => {
await vi.waitFor(() => expect(cancel).toHaveBeenCalledTimes(1));
expect(h.onDone).toHaveBeenCalledTimes(1); expect(h.onError).not.toHaveBeenCalled();
});
+ // 这一问存下的 id 随 conversation 帧一起到:答到一半失败时,页面凭它重答(#936)
+ it("hands the stored id of the question to the page with the conversation", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
+ 'event: conversation\ndata: {"id":"c1","message_id":"m1"}\n\nevent: done\ndata: {}\n\n',
+ )));
+ const h = {onConversation:vi.fn(),onSources:vi.fn(),onStep:vi.fn(),onDelta:vi.fn(),onDone:vi.fn(),onError:vi.fn()};
+ streamChat("kb", {message:"hello"}, h);
+ await vi.waitFor(() => expect(h.onDone).toHaveBeenCalledTimes(1));
+ expect(h.onConversation).toHaveBeenCalledWith("c1", "m1");
+ expect(h.onError).not.toHaveBeenCalled();
+ });
it("active abort is silent and cancels the reader", async () => {
const cancelled = vi.fn();
const body = new ReadableStream<Uint8Array>({ cancel: cancelled });
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 3ff8f7ec..154e2ad9 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -74,6 +74,11 @@ export const en = {
"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.",
+ // 重答(#936)被拒。生成中又来一个新问题(#961)也是 409;两边用同一个 code
+ answer_running: "An answer is still being written in this conversation. Wait for it to finish.",
+ retry_answered: "That question already has an answer, or the conversation went on after it.",
+ retry_not_question: "Only a question can be answered again.",
+ retry_needs_conversation: "A retry needs the conversation its question is in.",
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.",
@@ -790,9 +795,12 @@ export const en = {
},
ask: {
streamInterrupted: "The answer stream was interrupted. Reopen the conversation to check its status.",
- noActiveAnswer: "No active answer was found. You can send a new message.",
+ /* 重开会话时,最后一问没有回答、也没有在写的回答(多半是答到一半失败了) */
+ noActiveAnswer: "The last question has no answer. Retry it, or send a new message.",
historyLoadFailed: "Could not load this conversation.",
retryHistory: "Retry",
+ // 重答最后那个没有回答的问题(#936)
+ retryQuestion: "Retry",
loadingHistory: "Loading conversation…",
loadEarlierConversations: "Load earlier conversations",
conversationsLoadFailed: "Could not load conversations.",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 4f77d365..9854eb8b 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -70,6 +70,10 @@ export const zh: Strings = {
model_unavailable: "模型端点暂时不可用,请稍后再试。",
model_unreachable: "模型端点没有给出可用的回答。去「管理 → 模型」里检查端点地址。",
model_rejected: "模型端点拒绝了这次请求。去「管理 → 模型」里检查模型设置。",
+ answer_running: "这个对话里还有一个回答正在生成,等它写完再试。",
+ retry_answered: "这个问题已经有回答了,或者后面已经接着问了别的。",
+ retry_not_question: "只有问题可以重答。",
+ retry_needs_conversation: "重答要指明问题所在的对话。",
bad_upload: "这次上传读不出来。",
upload_read_failed: "文件没能读完。",
no_files: "没有附带文件。",
@@ -726,9 +730,10 @@ export const zh: Strings = {
},
ask: {
streamInterrupted: "回答连接已中断,请重新打开会话查看状态。",
- noActiveAnswer: "未发现正在生成的回答,你可以发送新消息。",
+ noActiveAnswer: "最后一个问题没有回答。可以重试,或发送新消息。",
historyLoadFailed: "无法读取此会话。",
retryHistory: "重试",
+ retryQuestion: "重试",
loadingHistory: "正在读取会话…",
loadEarlierConversations: "加载更早的会话",
conversationsLoadFailed: "无法读取会话列表。",
diff --git a/web/src/liveAnswer.ts b/web/src/liveAnswer.ts
index de8c2717..eb60f25f 100644
--- a/web/src/liveAnswer.ts
+++ b/web/src/liveAnswer.ts
@@ -23,6 +23,9 @@ import { citedNumbers } from "./citations";
export interface Turn {
role: "user" | "assistant";
+ /** 这一条存下的 id。问题要有它才能重答(#936):库里的历史带着,刚发出的那一问
+ * 由服务端的 `conversation` 帧告诉 */
+ id?: string;
content: string;
steps?: ChatStep[];
sources?: Source[];
@@ -111,8 +114,9 @@ function flush() {
let pendingSeq = 0;
export interface LiveHandle {
- /** 新会话从服务端拿到 id:把这个条目从占位 token 重映射到真 id */
- identify: (conversationId: string) => void;
+ /** 新会话从服务端拿到 id:把这个条目从占位 token 重映射到真 id。
+ * `questionId` 是这一问存下的 id,记到最后那条用户消息上 */
+ identify: (conversationId: string, questionId?: string) => void;
/** 改这场回答的最后一条(助手那一轮)。生成期间只有它在变 */
patchLast: (f: (t: Turn) => Turn) => void;
/** 结束(正常、出错、或人按了停止)。
@@ -163,12 +167,20 @@ export const liveAnswer = {
// stream must still belong to its original slot, not the replacement.
const owned = () => (lives.get(key) === slot ? slot : undefined);
return {
- identify: (id: string) => {
+ identify: (id: string, questionId?: string) => {
const current = owned();
if (!current) return;
lives.delete(key);
key = id;
- current.live = { ...current.live, conversationId: id };
+ let turns = current.live.turns;
+ if (questionId) {
+ const at = turns.map((t) => t.role).lastIndexOf("user");
+ if (at >= 0) {
+ turns = [...turns];
+ turns[at] = { ...turns[at], id: questionId };
+ }
+ }
+ current.live = { ...current.live, conversationId: id, turns };
lives.set(key, current);
flush();
},
diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsx
index a6d17a69..c97ddf2f 100644
--- a/web/src/pages/Chat.tsx
+++ b/web/src/pages/Chat.tsx
@@ -19,6 +19,7 @@ import {
History,
Layers,
MoreHorizontal,
+ RotateCcw,
Search,
Search as SearchIcon,
Square,
@@ -90,12 +91,27 @@ const NO_SOURCES: Source[] = [];
type ViewRequest = { kbId: string; id: string | null };
const historyTurns = (messages: ConversationMessage[]): Turn[] => messages.map((m) => ({
role: m.role,
+ id: m.id,
content: m.content,
steps: m.steps.length ? m.steps : undefined,
sources: m.sources.length ? m.sources : undefined,
}));
const viewKey = (kbId: string, id: string | null) => `${kbId}/${id ?? ""}`;
+/** 能重答的那一问在屏上的位置(#936),没有就是 -1。只看最后一问:它后面要么什么
+ * 也没有(重开会话时的样子),要么只有一条出错的回答(刚答到一半失败)。
+ * 服务端同样只答会话的最后一条,答过的、后面又有人接着问的都不答 */
+function retryableQuestion(shown: Turn[]): number {
+ const last = shown.at(-1);
+ const at =
+ last?.role === "assistant" && last.error
+ ? shown.length - 2
+ : last?.role === "user"
+ ? shown.length - 1
+ : -1;
+ return at >= 0 && shown[at].role === "user" && shown[at].id ? at : -1;
+}
+
export function Chat() {
const kbId = useKbId();
const { kb, kbs, setKb } = useKb();
@@ -180,6 +196,7 @@ export function Chat() {
一个正在别处生成的回答不该改变这里的任何东西 */
const streaming = liveHere?.streaming ?? false;
const shown = liveHere ? liveHere.turns : loadedKey === viewKey(kbId, currentId) ? turns : [];
+ const retryAt = retryableQuestion(shown);
const [scopeOpen, setScopeOpen] = useState(false);
const [pendingDelete, setPendingDelete] = useState<ConversationRow | null>(null);
// 会话搜索。**搜标题也搜正文**——人记得住的往往是问过的那句话
@@ -450,53 +467,74 @@ export function Chat() {
sessionStorage.removeItem(DRAFT_KEY);
if (inputRef.current) inputRef.current.style.height = "auto";
- /* **结果留在 store 里,不交回组件状态。**
- 交回去要经过一个 `setTurns`,而流结束时这个组件可能早就卸载了——
- 那一下是空操作,内容就此消失(切回来一片空白,问题气泡都没有)。
- 留在 store 里,谁挂载谁认领。这一场从开场起就有名有姓:先建条目、
- 后开流,回调顺着句柄只写自己这一场 */
- const handle = liveAnswer.begin(
+ answer(
+ owner,
kb.id,
- activeId,
// 从屏上正在显示的那些轮续接,而不是组件 state——流结束后内容只落在
// store 里,state 还是上次装 conversation 时的库内历史,用它会让
// 上一条回答从画面里消失
[...(liveHere?.turns ?? turns), { role: "user", content: q }, { role: "assistant", content: "" }],
- () => {},
- );
- const abort = streamChat(
- kb.id,
{ conversation_id: activeId ?? undefined, message: q },
- {
- onConversation: (id) => {
- handle.identify(id);
- invalidateList();
- if (!ownsView(owner)) return;
- // 先 identify 生成句柄再换 URL;layout effect 重置视图后,loadConversation 会认领该句柄。
- activeIdRef.current = id;
- setActiveId(id);
- sessionStorage.setItem(lastKey(kb.id), id);
- navigate({
- to: "/kb/$kbId/chat/$conversationId",
- params: { kbId, conversationId: id },
- replace: true,
- });
- },
- onSources: (sources) => handle.patchLast((t) => ({ ...t, sources })),
- onStep: (step) =>
- handle.patchLast((t) => ({ ...t, steps: [...(t.steps ?? []), step] })),
- onDelta: (text) =>
- handle.patchLast((t) => ({ ...t, content: t.content + text })),
- onDone: () => {
- handle.finish();
- invalidateList();
- },
- onError: (message) => {
- handle.patchLast((t) => ({ ...t, error: message }));
- handle.finish();
- },
- },
);
+ };
+
+ /** 重答最后那个没有回答的问题(#936)。问题已经在库里,不再存一遍:屏上它后面
+ * 若挂着一条出错的回答,换成一条空的,带着它存下的 id 重新开流 */
+ const retry = () => {
+ const at = retryableQuestion(shown);
+ if (at < 0 || streaming || !kb || kb.id !== kbId || !activeId || loadingHistory || historyError) return;
+ const question = shown[at];
+ const owner = claimView(activeId);
+ following.current = true;
+ setIdleHistoryKey(null);
+ answer(owner, kb.id, [...shown.slice(0, at + 1), { role: "assistant", content: "" }], {
+ conversation_id: activeId,
+ message: question.content,
+ retry_message_id: question.id,
+ });
+ };
+
+ /* **结果留在 store 里,不交回组件状态。**
+ 交回去要经过一个 `setTurns`,而流结束时这个组件可能早就卸载了——
+ 那一下是空操作,内容就此消失(切回来一片空白,问题气泡都没有)。
+ 留在 store 里,谁挂载谁认领。这一场从开场起就有名有姓:先建条目、
+ 后开流,回调顺着句柄只写自己这一场。新问题与重答走同一段 */
+ const answer = (
+ owner: ViewRequest,
+ kbNow: string,
+ start: Turn[],
+ body: Parameters<typeof streamChat>[1],
+ ) => {
+ const handle = liveAnswer.begin(kbNow, activeId, start, () => {});
+ const abort = streamChat(kbNow, body, {
+ onConversation: (id, questionId) => {
+ handle.identify(id, questionId);
+ invalidateList();
+ if (!ownsView(owner)) return;
+ // 先 identify 生成句柄再换 URL;layout effect 重置视图后,loadConversation 会认领该句柄。
+ activeIdRef.current = id;
+ setActiveId(id);
+ sessionStorage.setItem(lastKey(kbNow), id);
+ navigate({
+ to: "/kb/$kbId/chat/$conversationId",
+ params: { kbId, conversationId: id },
+ replace: true,
+ });
+ },
+ onSources: (sources) => handle.patchLast((t) => ({ ...t, sources })),
+ onStep: (step) =>
+ handle.patchLast((t) => ({ ...t, steps: [...(t.steps ?? []), step] })),
+ onDelta: (text) =>
+ handle.patchLast((t) => ({ ...t, content: t.content + text })),
+ onDone: () => {
+ handle.finish();
+ invalidateList();
+ },
+ onError: (message) => {
+ handle.patchLast((t) => ({ ...t, error: message }));
+ handle.finish();
+ },
+ });
// streamChat 的 abort 要等它返回才有;真 abort 到手前,句柄上先占着空操作
handle.setAbort(abort);
};
@@ -775,7 +813,14 @@ export function Chat() {
有消息后 composer 停靠底部 */}
<div className="flex-1 min-w-0 flex flex-col">
{idleHistoryKey === loadedKey && idleHistoryKey === viewKey(kbId, currentId) && !streaming && (
- <p role="status" className="px-4 pt-4 text-body text-ink-2">{S.ask.noActiveAnswer}</p>
+ <div role="status" className="px-4 pt-4 flex flex-wrap items-center gap-2 text-body text-ink-2">
+ <span>{S.ask.noActiveAnswer}</span>
+ {retryAt === shown.length - 1 && (
+ <Button variant="secondary" size="sm" icon={<RotateCcw size={12} />} onClick={retry}>
+ {S.ask.retryQuestion}
+ </Button>
+ )}
+ </div>
)}
{historyError ? (
<div role="alert" className="p-6 text-body">
@@ -814,7 +859,16 @@ export function Chat() {
>
<div className="max-w-3xl mx-auto space-y-4">
{shown.map((t, i) => (
- <TurnView key={i} turn={t} live={streaming && i === shown.length - 1} />
+ <TurnView
+ key={i}
+ turn={t}
+ live={streaming && i === shown.length - 1}
+ onRetry={
+ !streaming && i === shown.length - 1 && t.role === "assistant" && retryAt >= 0
+ ? retry
+ : undefined
+ }
+ />
))}
<div ref={bottomRef} />
</div>
@@ -977,7 +1031,16 @@ function Thinking({ step }: { step?: ChatStep }) {
);
}
-function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {
+function TurnView({
+ turn,
+ live,
+ onRetry,
+}: {
+ turn: Turn;
+ live?: boolean;
+ /** 这是出错的最后一轮、它的问题存着 id 时才有:重答那一问(#936) */
+ onRetry?: () => void;
+}) {
const kbId = useKbId();
if (turn.role === "user") {
return (
@@ -1044,10 +1107,16 @@ function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {
<div className="mt-2 text-small text-ink-2">{S.ask.noSources}</div>
)}
{/* 回答上的动作(#936),同样等说完了才出。复制的是存下的 Markdown,
- 角标 `[n]` 照写——表格、代码块贴到别处还是原样 */}
- {!live && turn.content && (
- <div className="mt-2 flex items-center">
- <CopyButton label={S.ask.copyAnswer} text={() => turn.content} />
+ 角标 `[n]` 照写——表格、代码块贴到别处还是原样。答到一半失败的那一轮
+ 多一个重试:问题已经在库里,重答不再存一遍 */}
+ {!live && (turn.content || onRetry) && (
+ <div className="mt-2 flex items-center gap-2">
+ {turn.content && <CopyButton label={S.ask.copyAnswer} text={() => turn.content} />}
+ {onRetry && (
+ <Button variant="secondary" size="sm" icon={<RotateCcw size={12} />} onClick={onRetry}>
+ {S.ask.retryQuestion}
+ </Button>
+ )}
</div>
)}
</div>
diff --git a/web/tests/chat-view.test.mjs b/web/tests/chat-view.test.mjs
index 7d726f4e..cdc6a762 100644
--- a/web/tests/chat-view.test.mjs
+++ b/web/tests/chat-view.test.mjs
@@ -504,7 +504,7 @@ test(
try {
await f.page
.getByText(
- "No active answer was found. You can send a new message.",
+ "The last question has no answer. Retry it, or send a new message.",
{ exact: true },
)
.waitFor();
@@ -901,6 +901,79 @@ test(
await f.close();
}
});
+ // #936 (2): a question whose answer failed is answered again in place, under its own id
+ const answered = (id, text) =>
+ `event: conversation\ndata: {"id":"${id}","message_id":"q1"}\n\n` +
+ `event: delta\ndata: ${JSON.stringify({ text })}\n\nevent: done\ndata: {}\n\n`;
+ await t.test("a reopened question left without an answer can be retried in place", async () => {
+ const asked = [];
+ const f = await open("/kb/one/chat/a", async (route, p) => {
+ if (p.endsWith("/conversations/a")) {
+ await route.fulfill({
+ json: { messages: [{ ...message("What changed at Acme?", "user"), id: "q1" }] },
+ });
+ return true;
+ }
+ if (p === "/api/v1/kbs/one/chat") {
+ asked.push(route.request().postDataJSON());
+ await route.fulfill({
+ contentType: "text/event-stream",
+ body: answered("a", "Acme moved to Berlin."),
+ });
+ return true;
+ }
+ });
+ try {
+ await f.page.getByRole("button", { name: "Retry", exact: true }).click();
+ await f.page.getByText("Acme moved to Berlin.", { exact: true }).waitFor();
+ assert.deepEqual(asked, [
+ { conversation_id: "a", message: "What changed at Acme?", retry_message_id: "q1" },
+ ]);
+ assert.equal(
+ await f.page.getByText("What changed at Acme?", { exact: true }).count(),
+ 1,
+ );
+ assert.deepEqual(f.errors, []);
+ } finally {
+ await f.close();
+ }
+ });
+ await t.test("an answer that failed can be retried from under its error", async () => {
+ const asked = [];
+ const failed = "The model endpoint is unavailable right now. Try again shortly.";
+ const f = await open("/kb/one/chat/b", async (route, p) => {
+ if (p === "/api/v1/kbs/one/chat") {
+ const body = route.request().postDataJSON();
+ asked.push(body);
+ await route.fulfill({
+ contentType: "text/event-stream",
+ body: body.retry_message_id
+ ? answered("b", "Globex is fine.")
+ : 'event: conversation\ndata: {"id":"b","message_id":"q1"}\n\n' +
+ 'event: error\ndata: {"error":"Model unavailable","code":"model_unavailable"}\n\n',
+ });
+ return true;
+ }
+ });
+ try {
+ await f.page.getByText("Answer beta", { exact: true }).waitFor();
+ await f.page.locator("textarea").fill("How is Globex?");
+ await f.page.locator("textarea").press("Enter");
+ await f.page.getByText(failed, { exact: true }).waitFor();
+ await f.page.getByRole("button", { name: "Retry", exact: true }).click();
+ await f.page.getByText("Globex is fine.", { exact: true }).waitFor();
+ assert.deepEqual(asked, [
+ { conversation_id: "b", message: "How is Globex?" },
+ { conversation_id: "b", message: "How is Globex?", retry_message_id: "q1" },
+ ]);
+ // One question, one answer: the failed turn is replaced, not repeated
+ assert.equal(await f.page.getByText("How is Globex?", { exact: true }).count(), 1);
+ assert.equal(await f.page.getByText(failed, { exact: true }).count(), 0);
+ assert.deepEqual(f.errors, []);
+ } finally {
+ await f.close();
+ }
+ });
await t.test("a conversation's title is copied from its menu, with or without the Clipboard API", async () => {
for (const init of [withApi, withoutApi]) {
const f = await open("/kb/one/chat/b", undefined, init);