fix(astrbot): do not resend messages after the response starts
`should_retry_astrbot` treated every `reqwest::Error` as retryable, but that class covers both "the POST never left" and "the response body broke". `POST /api/v1/chat` carries no idempotency key, so retrying the second case appended the user's message to the remote conversation a second time, produced a second answer, and interleaved the two attempts' deltas into one garbled bubble. Retries are now limited to connect-phase failures, the one case where the request provably never reached the server. Anything after that surfaces a `streamInterrupted` code so the UI can offer a manual retry instead. Also stops a send from checking the client out of its slot. The other five slot commands read the client and report "not connected" when it is absent, so a send disabled sessions, capabilities, upload, download, and session switching for its whole duration. That window used to be bounded by the client's 120s total timeout; now that streaming has no total deadline it would last as long as the reply, so an ordinary long answer would disable the rest of the slot. The client is cloned instead and concurrent sends are rejected with `slotBusy`. (P2-13 / F-49, pulled forward from batch R7 because this batch is what made it user-visible.) Refs P1-2 / F-12. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
父节点
6e81a3a7ae
当前提交
c4c40bd561
共有 1 个文件被更改,包括 99 次插入 和 40 次删除
|
|
@ -571,7 +571,15 @@ impl DualSlotRuntime {
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Take the client out so we can await without holding the mutex across network IO.
|
// Clone the client rather than checking it out of the slot.
|
||||||
|
//
|
||||||
|
// `AstrBotClient` is a handle over shared state, and taking it made
|
||||||
|
// every other slot command — sessions, capabilities, upload, download,
|
||||||
|
// session switch — report "not connected" for the whole send. That
|
||||||
|
// window used to be capped by the client's 120s total timeout; now that
|
||||||
|
// streaming has no total deadline it would last as long as the reply,
|
||||||
|
// so an ordinary long answer would disable the rest of the slot.
|
||||||
|
// Concurrency is instead serialized on `message_cancellation`.
|
||||||
let (
|
let (
|
||||||
client,
|
client,
|
||||||
profile_id,
|
profile_id,
|
||||||
|
|
@ -583,7 +591,13 @@ impl DualSlotRuntime {
|
||||||
) = {
|
) = {
|
||||||
let mut guard = self.inner.lock().await;
|
let mut guard = self.inner.lock().await;
|
||||||
let runtime = slot_mut(&mut guard, slot);
|
let runtime = slot_mut(&mut guard, slot);
|
||||||
let client = runtime.client.take().ok_or_else(|| {
|
if runtime.message_cancellation.is_some() {
|
||||||
|
return Err(RuntimeCommandError {
|
||||||
|
code: "slotBusy",
|
||||||
|
message: "This slot is already sending a message.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let client = runtime.client.clone().ok_or_else(|| {
|
||||||
RuntimeCommandError::unavailable("The selected slot is not connected.")
|
RuntimeCommandError::unavailable("The selected slot is not connected.")
|
||||||
})?;
|
})?;
|
||||||
let cancellation = Arc::new(tokio_util::sync::CancellationToken::new());
|
let cancellation = Arc::new(tokio_util::sync::CancellationToken::new());
|
||||||
|
|
@ -601,15 +615,9 @@ impl DualSlotRuntime {
|
||||||
};
|
};
|
||||||
|
|
||||||
let send_result = match client {
|
let send_result = match client {
|
||||||
ActiveClient::Desktop(client) => {
|
ActiveClient::Desktop(_) => Err(RuntimeCommandError::unavailable(
|
||||||
let restored = ActiveClient::Desktop(client);
|
"Desktop mock chat send is not activated in this runtime path yet.",
|
||||||
Err((
|
)),
|
||||||
restored,
|
|
||||||
RuntimeCommandError::unavailable(
|
|
||||||
"Desktop mock chat send is not activated in this runtime path yet.",
|
|
||||||
),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
ActiveClient::AstrBot(client) => {
|
ActiveClient::AstrBot(client) => {
|
||||||
let mut attempts = 0;
|
let mut attempts = 0;
|
||||||
loop {
|
loop {
|
||||||
|
|
@ -624,25 +632,19 @@ impl DualSlotRuntime {
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(_session) if cancellation.is_cancelled() => {
|
Ok(_session) if cancellation.is_cancelled() => {
|
||||||
break Err((
|
break Err(RuntimeCommandError {
|
||||||
ActiveClient::AstrBot(client),
|
code: "cancelled",
|
||||||
RuntimeCommandError {
|
message: "The chat request was cancelled.",
|
||||||
code: "cancelled",
|
});
|
||||||
message: "The chat request was cancelled.",
|
|
||||||
},
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
Ok(session) => break Ok((ActiveClient::AstrBot(client), session)),
|
Ok(session) => break Ok(session),
|
||||||
Err(AstrBotClientError::HttpStatus(status))
|
Err(AstrBotClientError::HttpStatus(status))
|
||||||
if status.as_u16() == 401 || status.as_u16() == 403 =>
|
if status.as_u16() == 401 || status.as_u16() == 403 =>
|
||||||
{
|
{
|
||||||
break Err((
|
break Err(RuntimeCommandError {
|
||||||
ActiveClient::AstrBot(client),
|
code: "authExpired",
|
||||||
RuntimeCommandError {
|
message: "AstrBot authentication has expired. Re-login is required.",
|
||||||
code: "authExpired",
|
});
|
||||||
message: "AstrBot authentication has expired. Re-login is required.",
|
|
||||||
},
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
Err(error) if should_retry_astrbot(&error) && attempts < 2 => {
|
Err(error) if should_retry_astrbot(&error) && attempts < 2 => {
|
||||||
attempts += 1;
|
attempts += 1;
|
||||||
|
|
@ -652,12 +654,7 @@ impl DualSlotRuntime {
|
||||||
drop(guard);
|
drop(guard);
|
||||||
tokio::time::sleep(Duration::from_millis(250 * attempts)).await;
|
tokio::time::sleep(Duration::from_millis(250 * attempts)).await;
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(error) => break Err(astrbot_send_error(&error)),
|
||||||
break Err((
|
|
||||||
ActiveClient::AstrBot(client),
|
|
||||||
RuntimeCommandError::unavailable("AstrBot chat send failed."),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -673,8 +670,7 @@ impl DualSlotRuntime {
|
||||||
}
|
}
|
||||||
runtime.message_cancellation = None;
|
runtime.message_cancellation = None;
|
||||||
match send_result {
|
match send_result {
|
||||||
Ok((client, session)) => {
|
Ok(session) => {
|
||||||
runtime.client = Some(client);
|
|
||||||
runtime.snapshot.profile_id = profile_id;
|
runtime.snapshot.profile_id = profile_id;
|
||||||
runtime.snapshot.transport = transport;
|
runtime.snapshot.transport = transport;
|
||||||
runtime.snapshot.server_instance_id = server_instance_id;
|
runtime.snapshot.server_instance_id = server_instance_id;
|
||||||
|
|
@ -683,8 +679,7 @@ impl DualSlotRuntime {
|
||||||
runtime.snapshot.last_error = None;
|
runtime.snapshot.last_error = None;
|
||||||
Ok(runtime.snapshot.clone())
|
Ok(runtime.snapshot.clone())
|
||||||
}
|
}
|
||||||
Err((client, error)) => {
|
Err(error) => {
|
||||||
runtime.client = Some(client);
|
|
||||||
runtime.snapshot.profile_id = profile_id;
|
runtime.snapshot.profile_id = profile_id;
|
||||||
runtime.snapshot.transport = transport;
|
runtime.snapshot.transport = transport;
|
||||||
runtime.snapshot.server_instance_id = server_instance_id;
|
runtime.snapshot.server_instance_id = server_instance_id;
|
||||||
|
|
@ -720,16 +715,43 @@ fn slot_ref(inner: &DualSlotRuntimeInner, slot: SlotKind) -> &SlotRuntime {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Only a failure to *establish* the connection may be retried automatically.
|
||||||
|
///
|
||||||
|
/// `POST /api/v1/chat` carries no idempotency key. Once the server has accepted
|
||||||
|
/// the request it has already appended the user's message to the conversation,
|
||||||
|
/// so a second attempt duplicates both the question and the answer, and the two
|
||||||
|
/// attempts' deltas interleave into one garbled bubble. A connect error is the
|
||||||
|
/// only case where the request provably never reached the server; everything
|
||||||
|
/// else — a mid-body disconnect, an idle timeout, an HTTP error status — means
|
||||||
|
/// the server responded, and the user decides whether to resend.
|
||||||
fn should_retry_astrbot(error: &AstrBotClientError) -> bool {
|
fn should_retry_astrbot(error: &AstrBotClientError) -> bool {
|
||||||
match error {
|
match error {
|
||||||
AstrBotClientError::Request(_) | AstrBotClientError::ChannelClosed => true,
|
AstrBotClientError::Request(error) => error.is_connect(),
|
||||||
AstrBotClientError::HttpStatus(status) => {
|
|
||||||
status.is_server_error() || status.as_u16() == 408 || status.as_u16() == 429
|
|
||||||
}
|
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Maps a transport failure onto the code the UI uses to offer a manual retry.
|
||||||
|
fn astrbot_send_error(error: &AstrBotClientError) -> RuntimeCommandError {
|
||||||
|
match error {
|
||||||
|
AstrBotClientError::StreamInterrupted => RuntimeCommandError {
|
||||||
|
code: "streamInterrupted",
|
||||||
|
message: "The reply was cut off. AstrBot already received this message, so it was not resent automatically.",
|
||||||
|
},
|
||||||
|
AstrBotClientError::CredentialExpired => RuntimeCommandError {
|
||||||
|
code: "authExpired",
|
||||||
|
message: "AstrBot authentication has expired. Re-login is required.",
|
||||||
|
},
|
||||||
|
AstrBotClientError::HttpStatus(_) | AstrBotClientError::ApiStatus(_) => {
|
||||||
|
RuntimeCommandError {
|
||||||
|
code: "serverUnavailable",
|
||||||
|
message: "AstrBot rejected the chat request.",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => RuntimeCommandError::unavailable("AstrBot chat send failed."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn slot_mut(inner: &mut DualSlotRuntimeInner, slot: SlotKind) -> &mut SlotRuntime {
|
fn slot_mut(inner: &mut DualSlotRuntimeInner, slot: SlotKind) -> &mut SlotRuntime {
|
||||||
match slot {
|
match slot {
|
||||||
SlotKind::Companion => &mut inner.companion,
|
SlotKind::Companion => &mut inner.companion,
|
||||||
|
|
@ -763,6 +785,43 @@ mod tests {
|
||||||
assert_eq!(error.code, "validationFailed");
|
assert_eq!(error.code, "validationFailed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn only_connect_failures_are_resent_automatically() {
|
||||||
|
// A refused connection proves the POST never reached AstrBot.
|
||||||
|
let connect_error = reqwest::Client::builder()
|
||||||
|
.connect_timeout(Duration::from_secs(2))
|
||||||
|
.build()
|
||||||
|
.expect("client")
|
||||||
|
.get("http://127.0.0.1:1/api/v1/chat")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect_err("port 1 refuses connections");
|
||||||
|
assert!(connect_error.is_connect(), "expected a connect-phase error");
|
||||||
|
assert!(should_retry_astrbot(&AstrBotClientError::Request(
|
||||||
|
connect_error
|
||||||
|
)));
|
||||||
|
|
||||||
|
// Everything below means the server already received the message, so
|
||||||
|
// resending would duplicate it in the remote conversation.
|
||||||
|
assert!(!should_retry_astrbot(
|
||||||
|
&AstrBotClientError::StreamInterrupted
|
||||||
|
));
|
||||||
|
assert!(!should_retry_astrbot(&AstrBotClientError::HttpStatus(
|
||||||
|
reqwest::StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
)));
|
||||||
|
assert!(!should_retry_astrbot(&AstrBotClientError::HttpStatus(
|
||||||
|
reqwest::StatusCode::TOO_MANY_REQUESTS
|
||||||
|
)));
|
||||||
|
assert!(!should_retry_astrbot(&AstrBotClientError::ChannelClosed));
|
||||||
|
|
||||||
|
// A break after the response started must surface its own code so the
|
||||||
|
// UI can offer a manual retry instead of silently swallowing it.
|
||||||
|
assert_eq!(
|
||||||
|
astrbot_send_error(&AstrBotClientError::StreamInterrupted).code,
|
||||||
|
"streamInterrupted"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn status_starts_disconnected() {
|
async fn status_starts_disconnected() {
|
||||||
let runtime = DualSlotRuntime::new();
|
let runtime = DualSlotRuntime::new();
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用