Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/crates/assembly/core/src/product_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1510,6 +1510,8 @@ impl CoreAgentRuntimeCompatibility {
};
let unread_turn =
openbitfun_services_core::session::unread_completion_target(&metadata);
let read_turn =
openbitfun_services_core::session::read_completion_target(&metadata);
SessionActivitySummary {
pending_approvals: approvals
.get(&metadata.session_id)
Expand All @@ -1525,6 +1527,7 @@ impl CoreAgentRuntimeCompatibility {
last_turn: metadata.last_turn,
unread_completion: metadata.unread_completion,
unread_turn,
read_turn,
}
})
.collect(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,81 @@ pub struct ForwardRequest {
}

pub struct ForwardedTurnResult {
pub completion_kind: Option<&'static str>,
pub turn_id: Option<String>,
pub completed_remote_tools: Vec<String>,
pub display_text: String,
pub full_text: String,
}

pub(crate) async fn acknowledge_delivered_result(
session_id: &str,
turn_id: &str,
completion_kind: Option<&str>,
target: Option<&RemoteBotTarget>,
) -> Result<bool, String> {
use openbitfun_services_integrations::remote_connect::{
RemoteSessionRuntimeHost, REMOTE_CAPABILITY_SESSION_RESULT_ACK_V1,
};
if let Some(target) = target {
let info = target
.rpc(serde_json::json!({"cmd":"get_workspace_info"}))
.await?;
if !info["capabilities"].as_array().is_some_and(|values| {
values
.iter()
.any(|value| value.as_str() == Some(REMOTE_CAPABILITY_SESSION_RESULT_ACK_V1))
}) {
return Err(
"Execution host does not support result acknowledgement; upgrade that device"
.into(),
);
}
let reply = target
.rpc(serde_json::json!({
"cmd":"acknowledge_session_result", "session_id":session_id,
"turn_id":turn_id, "completion_kind":completion_kind,
}))
.await?;
if reply["resp"] != "session_result_acknowledged"
|| reply["session_id"] != session_id
|| reply["turn_id"] != turn_id
{
return Err("Invalid session result acknowledgement response".into());
}
return reply["acknowledged"]
.as_bool()
.ok_or_else(|| "Missing result acknowledgement".into());
}
crate::service_agent_runtime::CoreServiceAgentRuntime::remote_session_host()?
.acknowledge_session_result(session_id, turn_id, completion_kind)
.await
}

/// All provider chunks must succeed before acknowledging the final reply.
/// A receipt failure never resends an already delivered IM message.
pub(crate) async fn deliver_final_reply(
session_id: &str,
turn_id: &str,
target: Option<&RemoteBotTarget>,
result: &ForwardedTurnResult,
send: impl std::future::Future<Output = anyhow::Result<()>>,
) -> anyhow::Result<()> {
if result.display_text.is_empty() {
return Ok(());
}
send.await?;
if let Some(kind) = result.completion_kind {
let turn_id = result.turn_id.as_deref().unwrap_or(turn_id);
if let Err(error) =
acknowledge_delivered_result(session_id, turn_id, Some(kind), target).await
{
warn!("Failed to acknowledge delivered IM result for session {session_id}, turn {turn_id}: {error}");
}
}
Ok(())
}

// ── BotCommand ─────────────────────────────────────────────────────

pub fn welcome_message(language: BotLanguage) -> &'static str {
Expand Down Expand Up @@ -3529,6 +3599,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission(
) -> ForwardedTurnResult {
if !runtime_fence.is_lifecycle_current() || runtime_fence.identity_epoch() != identity_epoch {
return ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: String::new(),
full_text: String::new(),
Expand Down Expand Up @@ -3572,6 +3644,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission(
if let Err(e) = submission {
let msg = format!("{}{e}", s.send_failed_prefix);
return ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: msg.clone(),
full_text: msg,
Expand Down Expand Up @@ -3678,6 +3752,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission(
if turn_id == target_turn_id {
let msg = format!("{}{}", s.error_prefix, error);
return ForwardedTurnResult {
completion_kind: Some("error"),
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: msg.clone(),
full_text: msg,
Expand All @@ -3687,6 +3763,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission(
TrackerEvent::TurnCancelled { turn_id } => {
if turn_id == target_turn_id {
return ForwardedTurnResult {
completion_kind: Some("interrupted"),
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: s.task_cancelled.to_string(),
full_text: s.task_cancelled.to_string(),
Expand Down Expand Up @@ -3738,6 +3816,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission(
let display_text = full_text.clone();

ForwardedTurnResult {
completion_kind: Some("completed"),
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: if display_text.is_empty() {
s.no_response.to_string()
Expand All @@ -3750,6 +3830,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission(
.await;

result.unwrap_or_else(|_| ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: s.timeout_one_hour.to_string(),
full_text: String::new(),
Expand All @@ -3768,6 +3850,8 @@ async fn execute_remote_forward(
let target = forward.remote_target.as_ref().unwrap();
let current = || fence.is_lifecycle_current() && fence.identity_epoch() == epoch;
let empty = || ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: String::new(),
full_text: String::new(),
Expand Down Expand Up @@ -3795,6 +3879,8 @@ async fn execute_remote_forward(
Some(id) => id.to_string(),
None => {
return ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: format!("{}Missing remote turn ID", s.send_failed_prefix),
full_text: String::new(),
Expand All @@ -3804,6 +3890,8 @@ async fn execute_remote_forward(
}
result => {
return ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: format!(
"{}{}",
Expand Down Expand Up @@ -3844,6 +3932,12 @@ async fn execute_remote_forward(
_ => turn.text.clone(),
};
return ForwardedTurnResult {
completion_kind: Some(match turn.status.as_str() {
"failed" | "error" => "error",
"cancelled" => "interrupted",
_ => "completed",
}),
turn_id: Some(turn_id.clone()),
completed_remote_tools: shown.into_keys().collect(),
display_text,
full_text: turn.text,
Expand Down Expand Up @@ -3925,6 +4019,8 @@ async fn execute_remote_forward(
}
Ok(reply) => {
return ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: format!(
"{}{}",
Expand All @@ -3942,6 +4038,8 @@ async fn execute_remote_forward(
) || error.contains("HTTP 403")
{
return ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: format!("{}{error}", s.error_prefix),
full_text: String::new(),
Expand All @@ -3957,6 +4055,8 @@ async fn execute_remote_forward(
})
.await;
result.unwrap_or_else(|_| ForwardedTurnResult {
completion_kind: None,
turn_id: None,
completed_remote_tools: Vec::new(),
display_text: s.timeout_one_hour.to_string(),
full_text: String::new(),
Expand Down Expand Up @@ -5109,8 +5209,15 @@ mod handle_chat_tests {
}
}
"get_workspace_info" => serde_json::json!({"resp":"workspace_info", "capabilities":
if supports_interaction { vec!["user_question_interaction_v1", "session_attachments_v1"] } else { vec![] }
if supports_interaction { vec!["user_question_interaction_v1", "session_attachments_v1", "session_result_ack_v1"] } else { vec![] }
}),
"acknowledge_session_result" => {
assert!(supports_interaction);
assert_eq!(command["session_id"], "session-a");
assert_eq!(command["turn_id"], "accepted-turn");
assert_eq!(command["completion_kind"], "completed");
serde_json::json!({"resp":"session_result_acknowledged","session_id":"session-a","turn_id":"accepted-turn","acknowledged":true})
}
"store_session_attachment" => {
assert!(supports_interaction);
assert_eq!(command["session_id"], "session-a");
Expand Down Expand Up @@ -5249,6 +5356,40 @@ mod handle_chat_tests {
.await
.unwrap();
assert_eq!(result.full_text, "![image](result.png)");
let ack_count = || {
calls
.lock()
.unwrap()
.iter()
.filter(|call| call["cmd"] == "acknowledge_session_result")
.count()
};
assert_eq!(
ack_count(),
0,
"completion alone must not acknowledge delivery"
);
assert!(deliver_final_reply(
"session-a",
"requested-turn",
Some(&target),
&result,
async { Err(anyhow::anyhow!("provider rejected final chunk")) }
)
.await
.is_err());
assert_eq!(ack_count(), 0, "a partial or failed IM send stays unread");
deliver_final_reply(
"session-a",
"requested-turn",
Some(&target),
&result,
async { Ok(()) },
)
.await
.unwrap();
assert_eq!(ack_count(), usize::from(supports_interaction));

assert_eq!(result.completed_remote_tools.len(), 2);
assert!(result
.completed_remote_tools
Expand Down
15 changes: 12 additions & 3 deletions src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ use std::sync::Arc;
use tokio::sync::RwLock;

use super::command_router::{
complete_im_bot_pairing, current_bot_language, execute_forwarded_turn, handle_command,
parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler,
complete_im_bot_pairing, current_bot_language, deliver_final_reply, execute_forwarded_turn,
handle_command, parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler,
BotInteractiveRequest, BotLanguage, BotMessageSender, HandleResult,
};
use super::{
Expand Down Expand Up @@ -605,6 +605,7 @@ impl FeishuBot {

if let Some(forward) = result.forward_to_session {
let output_session_id = forward.session_id.clone();
let output_turn_id = forward.turn_id.clone();
let output_remote_target = forward.remote_target.clone();
let output_identity_epoch = command_identity_epoch;
let bot = self.clone();
Expand Down Expand Up @@ -671,7 +672,15 @@ impl FeishuBot {
.await;
}
if !result.display_text.is_empty() {
if let Err(err) = bot.send_message(&cid, &result.display_text).await {
if let Err(err) = deliver_final_reply(
&output_session_id,
&output_turn_id,
output_remote_target.as_ref(),
&result,
bot.send_message(&cid, &result.display_text),
)
.await
{
warn!("Failed to send Feishu final message to {cid}: {err}");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use std::sync::Arc;
use tokio::sync::RwLock;

use super::command_router::{
complete_im_bot_pairing, current_bot_language, execute_forwarded_turn, handle_command,
parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler,
complete_im_bot_pairing, current_bot_language, deliver_final_reply, execute_forwarded_turn,
handle_command, parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler,
BotInteractiveRequest, BotLanguage, BotMessageSender, HandleResult,
};
use super::{
Expand Down Expand Up @@ -440,6 +440,7 @@ impl TelegramBot {

if let Some(forward) = result.forward_to_session {
let output_session_id = forward.session_id.clone();
let output_turn_id = forward.turn_id.clone();
let output_remote_target = forward.remote_target.clone();
let output_identity_epoch = command_identity_epoch;
let bot = self.clone();
Expand Down Expand Up @@ -495,7 +496,17 @@ impl TelegramBot {
.await;
}
if !result.display_text.is_empty() {
bot.send_message(chat_id, &result.display_text).await.ok();
if let Err(error) = deliver_final_reply(
&output_session_id,
&output_turn_id,
output_remote_target.as_ref(),
&result,
bot.send_message(chat_id, &result.display_text),
)
.await
{
log::warn!("Failed to send Telegram final message to {chat_id}: {error}");
}
}
bot.notify_files_ready(
chat_id,
Expand Down
Loading
Loading