fix(chat): validate slot sends before writing history

send_connection_slot_message wrote the optimistic user row from the
runtime snapshot alone, then called send_slot_message, which can still
refuse the send for an empty message, a busy slot or a disconnected
slot. The rejected question stayed in history with no failure marker,
and because each attempt minted a fresh local- id, retrying appended a
second copy rather than replacing the first.

Add a read-only pre-flight, ensure_slot_can_send, and run it before any
database write. The conditions it checks are extracted into
slot_send_precondition, which send_slot_message now uses inside its own
critical section, so the two cannot drift. Mint the message id once so
the failure path can address the row it wrote.

A send that fails after AstrBot accepted it must keep its question:
cancelled and streamInterrupted both mean the message is already in the
remote conversation and a partial reply may already be stored. Those
two keep the row; every other code marks it failed. server_received
encodes that rule and is covered by a test that walks every
AstrBotClientError variant through astrbot_send_error, so a future
rename of an R2 error code cannot silently change the classification.

Marking rather than deleting keeps chat_sessions.last_message_id valid,
re-uses the idempotent upsert, and leaves unread counts alone since they
already ignore user rows. The queue sanctions either choice.

The R2 retry loop and its error mapping are untouched; all five R2
transport sentinels still pass.

Refs: F-18 (audit P2-3).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
YokiiroBW 2026-07-27 00:20:09 +08:00
父节点 0fadc699e2
当前提交 02ac2046d6
共有 3 个文件被更改,包括 160 次插入 和 25 次删除

查看文件

@ -8,7 +8,7 @@ use tracing::{info, warn};
use super::{
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest, SlotKind,
SlotRuntimeSnapshot,
SlotRuntimeSnapshot, server_received,
};
use crate::credentials::{CredentialCommandError, load_profile_secret};
use crate::database::ApplicationDatabase;
@ -709,31 +709,50 @@ pub async fn send_connection_slot_message(
runtime: State<'_, DualSlotRuntime>,
request: SendConnectionSlotMessageRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
// Validate before touching history. This used to run the other way round,
// so a send rejected for an empty message, a busy slot, or a disconnected
// slot still left an unmarked `user` row behind — and each retry minted a
// fresh `local-` id, appending another copy of the same question.
runtime
.ensure_slot_can_send(request.slot, &request.message)
.await?;
let message_for_history = request.message.clone();
let status = runtime.status().await;
let initial_session = match request.slot {
SlotKind::Companion => status.companion,
SlotKind::Operations => status.operations,
};
if let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
// One id for this send, so the failure path can address the row it wrote.
let message_id = format!("local-{}", uuid::Uuid::new_v4());
let persisted = match (
initial_session.profile_id.as_deref(),
initial_session.server_instance_id.as_deref(),
initial_session.active_session_id.as_deref(),
) {
let _ = database.upsert_chat_message(
"local-default",
profile_id,
slot_name(request.slot),
server_instance_id,
None,
session_id,
&format!("local-{}", uuid::Uuid::new_v4()),
"user",
&message_for_history,
false,
false,
);
}
(Some(profile_id), Some(server_instance_id), Some(session_id)) => {
let _ = database.upsert_chat_message(
"local-default",
profile_id,
slot_name(request.slot),
server_instance_id,
None,
session_id,
&message_id,
"user",
&message_for_history,
false,
false,
);
Some((
profile_id.to_owned(),
server_instance_id.to_owned(),
session_id.to_owned(),
))
}
_ => None,
};
let result = runtime
.send_slot_message(
request.slot,
@ -742,7 +761,8 @@ pub async fn send_connection_slot_message(
request.attachments,
)
.await;
if initial_session.active_session_id.is_none()
if persisted.is_none()
&& let Ok(snapshot) = &result
&& let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
snapshot.profile_id.as_deref(),
@ -757,13 +777,35 @@ pub async fn send_connection_slot_message(
server_instance_id,
None,
session_id,
&format!("local-{}", uuid::Uuid::new_v4()),
&message_id,
"user",
&message_for_history,
false,
false,
);
}
// A send the server never accepted must not leave a clean-looking row.
// Marking rather than deleting keeps `chat_sessions.last_message_id` valid
// and re-uses the idempotent upsert; unread counts ignore `user` rows.
if let (Some((profile_id, server_instance_id, session_id)), Err(error)) = (&persisted, &result)
&& !server_received(error.code)
{
let _ = database.upsert_chat_message(
"local-default",
profile_id,
slot_name(request.slot),
server_instance_id,
None,
session_id,
&message_id,
"user",
&message_for_history,
false,
true,
);
}
if let Ok(snapshot) = &result {
persist_session_identity(&database, snapshot);
}

查看文件

@ -16,5 +16,5 @@ pub use gateway_client::{BoundGatewayEvent, GatewayClient, GatewayClientConfig,
pub use manager::{DualConnectionManager, SlotKind};
pub use runtime::{
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest,
SlotRuntimeSnapshot,
SlotRuntimeSnapshot, server_received,
};

查看文件

@ -151,6 +151,40 @@ fn other_slot(slot: SlotKind) -> SlotKind {
}
}
/// Whether AstrBot already holds the message despite the send reporting an error.
///
/// `POST /api/v1/chat` appends the user's message as soon as it is accepted, so
/// a cancellation or a mid-body break leaves the question in the remote
/// conversation. The local history must match: those two codes keep the user
/// row, everything else means the send never landed and the row is marked
/// failed. Kept next to `astrbot_send_error`, which mints the codes.
pub fn server_received(code: &str) -> bool {
matches!(code, "cancelled" | "streamInterrupted")
}
/// The conditions under which a slot will accept a chat send.
///
/// Shared by the read-only pre-flight and the send itself so the two cannot
/// drift: the pre-flight is what lets the caller decide whether to write the
/// optimistic user row at all.
fn slot_send_precondition(runtime: &SlotRuntime) -> Result<(), RuntimeCommandError> {
if runtime.message_cancellation.is_some() {
return Err(RuntimeCommandError {
code: "slotBusy",
message: "This slot is already sending a message.",
});
}
match runtime.client {
Some(ActiveClient::AstrBot(_)) => Ok(()),
Some(ActiveClient::Desktop(_)) => Err(RuntimeCommandError::unavailable(
"Desktop mock chat send is not activated in this runtime path yet.",
)),
None => Err(RuntimeCommandError::unavailable(
"The selected slot is not connected.",
)),
}
}
/// A client that has been constructed but not yet published into its slot.
///
/// Building the client is pure, so it happens before the slot lock is taken.
@ -685,6 +719,24 @@ impl DualSlotRuntime {
.map_err(|_| RuntimeCommandError::unavailable("AstrBot file upload failed."))
}
/// Read-only pre-flight for a chat send.
///
/// Lets the caller learn that a send will be refused *before* it writes the
/// optimistic user row into history, so a rejected send leaves no trace.
pub async fn ensure_slot_can_send(
&self,
slot: SlotKind,
message: &str,
) -> Result<(), RuntimeCommandError> {
if message.trim().is_empty() {
return Err(RuntimeCommandError::validation(
"message must not be empty.",
));
}
let guard = self.inner.lock().await;
slot_send_precondition(slot_ref(&guard, slot))
}
pub async fn send_slot_message(
&self,
slot: SlotKind,
@ -718,12 +770,7 @@ impl DualSlotRuntime {
) = {
let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, slot);
if runtime.message_cancellation.is_some() {
return Err(RuntimeCommandError {
code: "slotBusy",
message: "This slot is already sending a message.",
});
}
slot_send_precondition(runtime)?;
let client = runtime.client.clone().ok_or_else(|| {
RuntimeCommandError::unavailable("The selected slot is not connected.")
})?;
@ -1065,6 +1112,52 @@ mod tests {
assert!(companion.profile_id.is_none());
}
#[tokio::test]
async fn a_disconnected_slot_rejects_sends_before_any_history_write() {
let runtime = DualSlotRuntime::new();
let error = runtime
.ensure_slot_can_send(SlotKind::Companion, "hello")
.await
.expect_err("a disconnected slot must refuse the send up front");
assert_eq!(error.code, "runtimeUnavailable");
let error = runtime
.ensure_slot_can_send(SlotKind::Companion, " ")
.await
.expect_err("an empty message must be refused up front");
assert_eq!(error.code, "validationFailed");
}
#[test]
fn server_received_covers_every_send_error_code() {
// The two codes that mean AstrBot already appended the question, so the
// local user row must survive the failure.
assert!(server_received(
astrbot_send_error(&AstrBotClientError::StreamInterrupted).code
));
assert!(server_received("cancelled"));
// Everything else means the send never landed. If R2 ever renames one
// of these codes, this assertion is what catches the silent change.
for error in [
AstrBotClientError::CredentialExpired,
AstrBotClientError::HttpStatus(reqwest::StatusCode::INTERNAL_SERVER_ERROR),
AstrBotClientError::ApiStatus("rejected".into()),
AstrBotClientError::Map("bad frame".into()),
AstrBotClientError::ServerIdentityChanged,
AstrBotClientError::ChannelClosed,
AstrBotClientError::InvalidConfig("bad config"),
] {
let mapped = astrbot_send_error(&error);
assert!(
!server_received(mapped.code),
"{} must not be treated as delivered",
mapped.code
);
}
}
#[test]
fn a_stale_session_switch_does_not_write_into_a_new_generation() {
let mut runtime = SlotRuntime::empty_with_generation(SlotKind::Companion, 7);