diff --git a/src-tauri/src/networking/runtime.rs b/src-tauri/src/networking/runtime.rs index 15dcd17..580cd17 100644 --- a/src-tauri/src/networking/runtime.rs +++ b/src-tauri/src/networking/runtime.rs @@ -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 ( client, profile_id, @@ -583,7 +591,13 @@ impl DualSlotRuntime { ) = { let mut guard = self.inner.lock().await; 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.") })?; let cancellation = Arc::new(tokio_util::sync::CancellationToken::new()); @@ -601,15 +615,9 @@ impl DualSlotRuntime { }; let send_result = match client { - ActiveClient::Desktop(client) => { - let restored = ActiveClient::Desktop(client); - Err(( - restored, - RuntimeCommandError::unavailable( - "Desktop mock chat send is not activated in this runtime path yet.", - ), - )) - } + ActiveClient::Desktop(_) => Err(RuntimeCommandError::unavailable( + "Desktop mock chat send is not activated in this runtime path yet.", + )), ActiveClient::AstrBot(client) => { let mut attempts = 0; loop { @@ -624,25 +632,19 @@ impl DualSlotRuntime { .await { Ok(_session) if cancellation.is_cancelled() => { - break Err(( - ActiveClient::AstrBot(client), - RuntimeCommandError { - code: "cancelled", - message: "The chat request was cancelled.", - }, - )); + break Err(RuntimeCommandError { + 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)) if status.as_u16() == 401 || status.as_u16() == 403 => { - break Err(( - ActiveClient::AstrBot(client), - RuntimeCommandError { - code: "authExpired", - message: "AstrBot authentication has expired. Re-login is required.", - }, - )); + break Err(RuntimeCommandError { + code: "authExpired", + message: "AstrBot authentication has expired. Re-login is required.", + }); } Err(error) if should_retry_astrbot(&error) && attempts < 2 => { attempts += 1; @@ -652,12 +654,7 @@ impl DualSlotRuntime { drop(guard); tokio::time::sleep(Duration::from_millis(250 * attempts)).await; } - Err(_) => { - break Err(( - ActiveClient::AstrBot(client), - RuntimeCommandError::unavailable("AstrBot chat send failed."), - )); - } + Err(error) => break Err(astrbot_send_error(&error)), } } } @@ -673,8 +670,7 @@ impl DualSlotRuntime { } runtime.message_cancellation = None; match send_result { - Ok((client, session)) => { - runtime.client = Some(client); + Ok(session) => { runtime.snapshot.profile_id = profile_id; runtime.snapshot.transport = transport; runtime.snapshot.server_instance_id = server_instance_id; @@ -683,8 +679,7 @@ impl DualSlotRuntime { runtime.snapshot.last_error = None; Ok(runtime.snapshot.clone()) } - Err((client, error)) => { - runtime.client = Some(client); + Err(error) => { runtime.snapshot.profile_id = profile_id; runtime.snapshot.transport = transport; 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 { match error { - AstrBotClientError::Request(_) | AstrBotClientError::ChannelClosed => true, - AstrBotClientError::HttpStatus(status) => { - status.is_server_error() || status.as_u16() == 408 || status.as_u16() == 429 - } + AstrBotClientError::Request(error) => error.is_connect(), _ => 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 { match slot { SlotKind::Companion => &mut inner.companion, @@ -763,6 +785,43 @@ mod tests { 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] async fn status_starts_disconnected() { let runtime = DualSlotRuntime::new();