diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index 32dece76e0..27817281ee 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -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) @@ -1525,6 +1527,7 @@ impl CoreAgentRuntimeCompatibility { last_turn: metadata.last_turn, unread_completion: metadata.unread_completion, unread_turn, + read_turn, } }) .collect(), diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs index 90ab439a46..3259b1f02e 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs @@ -89,11 +89,81 @@ pub struct ForwardRequest { } pub struct ForwardedTurnResult { + pub completion_kind: Option<&'static str>, + pub turn_id: Option, pub completed_remote_tools: Vec, 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 { + 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>, +) -> 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 { @@ -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(), @@ -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, @@ -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, @@ -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(), @@ -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() @@ -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(), @@ -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(), @@ -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(), @@ -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!( "{}{}", @@ -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, @@ -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!( "{}{}", @@ -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(), @@ -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(), @@ -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"); @@ -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 diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs b/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs index 1e39d3512b..10d01b687f 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs @@ -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::{ @@ -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(); @@ -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}"); } } diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs b/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs index de92d8b5fa..331162ebd8 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs @@ -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::{ @@ -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(); @@ -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, diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs index a72f110baf..3402968ea0 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs @@ -20,9 +20,10 @@ use std::time::Duration; use tokio::sync::{Mutex, Notify, RwLock}; use super::command_router::{ - complete_im_bot_pairing, current_bot_language, execute_forwarded_turn_with_submission, - handle_command, parse_command, welcome_message, BotChatState, BotInteractionHandler, - BotInteractiveRequest, BotMessageSender, HandleResult, + acknowledge_delivered_result, complete_im_bot_pairing, current_bot_language, + deliver_final_reply, execute_forwarded_turn_with_submission, handle_command, parse_command, + welcome_message, BotChatState, BotInteractionHandler, BotInteractiveRequest, BotMessageSender, + HandleResult, }; use super::{ load_bot_persistence, update_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, @@ -77,6 +78,7 @@ const MAX_PROACTIVE_PUSH_BYTES: usize = weixin_provider::MAX_TEXT_CHUNK; struct PendingOutbound { id: String, session_id: String, + turn_id: Option, text: String, queued_at: i64, } @@ -204,8 +206,8 @@ fn bounded_proactive_text(text: &str) -> String { /// oldest outputs are dropped first, and when the newest output alone exceeds /// the cap its head is sent, because the newest answer is the one the user is /// waiting for. -fn merge_pending(pending: &[PendingOutbound]) -> String { - let mut kept: Vec<&str> = Vec::new(); +fn merged_delivery(pending: &[PendingOutbound]) -> (String, Vec<&PendingOutbound>) { + let mut kept = Vec::new(); let mut bytes = 0usize; // Walk newest first so the byte cap drops the oldest output. for item in pending.iter().rev() { @@ -222,19 +224,29 @@ fn merge_pending(pending: &[PendingOutbound]) -> String { break; } bytes += separator + text.len(); - kept.push(text); + kept.push(item); } if kept.is_empty() { return pending .iter() .rev() - .map(|item| item.text.trim()) - .find(|text| !text.is_empty()) - .map(bounded_proactive_text) + .find(|item| !item.text.trim().is_empty()) + .map(|item| (bounded_proactive_text(&item.text), vec![item])) .unwrap_or_default(); } kept.reverse(); - kept.join(PENDING_SEPARATOR) + ( + kept.iter() + .map(|item| item.text.trim()) + .collect::>() + .join(PENDING_SEPARATOR), + kept, + ) +} + +#[cfg(test)] +fn merge_pending(pending: &[PendingOutbound]) -> String { + merged_delivery(pending).0 } #[derive(Debug, Clone)] @@ -459,8 +471,14 @@ impl WeixinBot { return; } for peer_id in self.peers_for_session(session_id).await { - self.queue_proactive(&peer_id, session_id, text, &format!("session {session_id}")) - .await; + self.queue_proactive( + &peer_id, + session_id, + None, + text, + &format!("session {session_id}"), + ) + .await; } } @@ -482,18 +500,32 @@ impl WeixinBot { return; } for peer_id in peers { - self.queue_proactive(&peer_id, &session_id, &text, &format!("turn {turn_id}")) - .await; + self.queue_proactive( + &peer_id, + &session_id, + Some(&turn_id), + &text, + &format!("turn {turn_id}"), + ) + .await; } } - async fn queue_proactive(&self, peer_id: &str, session_id: &str, text: &str, source: &str) { + async fn queue_proactive( + &self, + peer_id: &str, + session_id: &str, + turn_id: Option<&str>, + text: &str, + source: &str, + ) { if text.trim().is_empty() { debug!("weixin: proactive push skipped for peer {peer_id}: {source} has no text"); return; } info!("weixin: queueing proactive push for peer {peer_id} from {source}"); - self.enqueue_outbound(peer_id, session_id, text).await; + self.enqueue_turn_outbound(peer_id, session_id, turn_id, text) + .await; self.outbound_wakeup.notify_one(); } @@ -552,7 +584,13 @@ impl WeixinBot { turns.iter().any(|tracked| tracked == turn_id) } - async fn enqueue_outbound(&self, peer_id: &str, session_id: &str, text: &str) { + async fn enqueue_turn_outbound( + &self, + peer_id: &str, + session_id: &str, + turn_id: Option<&str>, + text: &str, + ) { let now = chrono::Utc::now().timestamp(); let dropped = { let mut pending = self.pending_outbound.lock().await; @@ -562,6 +600,7 @@ impl WeixinBot { PendingOutbound { id: uuid::Uuid::new_v4().to_string(), session_id: session_id.to_string(), + turn_id: turn_id.map(str::to_owned), text: bounded_proactive_text(text), queued_at: now, }, @@ -603,7 +642,7 @@ impl WeixinBot { if pending.is_empty() { return; } - let merged = merge_pending(&pending); + let (merged, delivered) = merged_delivery(&pending); if merged.trim().is_empty() { // Nothing deliverable in the backlog, so it is not worth a reply. self.confirm_pending_sent(peer_id, &pending).await; @@ -628,6 +667,15 @@ impl WeixinBot { } return; } + for item in delivered { + if let Some(turn_id) = item.turn_id.as_deref() { + if let Err(error) = + acknowledge_delivered_result(&item.session_id, turn_id, None, None).await + { + warn!("Failed to acknowledge proactive IM result for turn {turn_id}: {error}"); + } + } + } info!( "weixin: proactive push delivered to peer {peer_id} (one reply for {} queued message(s))", pending.len() @@ -1385,6 +1433,7 @@ impl WeixinBot { // hook from delivering the same answer a second time. self.mark_own_turn(&forward.turn_id).await; 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(); @@ -1453,7 +1502,15 @@ impl WeixinBot { .await; } if !turn_result.display_text.is_empty() { - if let Err(err) = bot.send_text(&peer, &turn_result.display_text).await { + if let Err(err) = deliver_final_reply( + &output_session_id, + &output_turn_id, + output_remote_target.as_ref(), + &turn_result, + bot.send_text(&peer, &turn_result.display_text), + ) + .await + { warn!("weixin: send final reply to peer {peer} failed: {err}"); } } @@ -1598,6 +1655,7 @@ mod tests { PendingOutbound { id: uuid::Uuid::new_v4().to_string(), session_id: "session".to_string(), + turn_id: None, text: text.to_string(), queued_at, } @@ -1611,6 +1669,23 @@ mod tests { .collect() } + #[test] + fn merged_delivery_only_acknowledges_results_included_in_the_im_reply() { + let old = "a".repeat(MAX_PROACTIVE_PUSH_BYTES); + let mut pending = backlog(&[&old, "latest"]); + pending[0].turn_id = Some("old-turn".into()); + pending[1].turn_id = Some("new-turn".into()); + let (text, delivered) = merged_delivery(&pending); + assert_eq!(text, "latest"); + assert_eq!( + delivered + .iter() + .filter_map(|item| item.turn_id.as_deref()) + .collect::>(), + vec!["new-turn"] + ); + } + #[test] fn proactive_push_waits_for_durable_completion_and_ignores_history_edits() { let early = AgenticEvent::DialogTurnCompleted { diff --git a/src/crates/assembly/core/src/service_agent_runtime.rs b/src/crates/assembly/core/src/service_agent_runtime.rs index 07bcaa998a..cdfdf38660 100644 --- a/src/crates/assembly/core/src/service_agent_runtime.rs +++ b/src/crates/assembly/core/src/service_agent_runtime.rs @@ -3797,6 +3797,51 @@ impl RemoteSessionRuntimeHost for CoreRemoteSessionRuntimeHost { .map_err(|error| format!("Failed to restore session: {error}")) } + async fn acknowledge_session_result( + &self, + session_id: &str, + turn_id: &str, + completion_kind: Option<&str>, + ) -> Result { + let binding = CoreServiceAgentRuntime::resolve_session_workspace_binding(session_id) + .await + .ok_or_else(|| { + format!("Session workspace binding not available for session: {session_id}") + })?; + ensure_remote_binding_runtime_ownership(self.coordinator.as_ref(), &binding).await?; + let mut receipt = None; + self.coordinator + .get_session_manager() + .update_session_metadata(&binding.session_storage_dir(), session_id, |metadata| { + receipt = openbitfun_services_core::session::acknowledge_session_result( + metadata, + turn_id, + completion_kind, + ); + }) + .await + .map_err(|error| error.to_string())?; + let Some(receipt) = receipt else { + return Ok(false); + }; + let completion_kind = match receipt.status { + openbitfun_services_core::session::TurnStatus::Completed => "completed", + openbitfun_services_core::session::TurnStatus::Error => "error", + openbitfun_services_core::session::TurnStatus::Cancelled => "interrupted", + openbitfun_services_core::session::TurnStatus::InProgress => return Ok(false), + }; + self.coordinator + .emit_event(AgenticEvent::SessionResultRead { + session_id: session_id.to_string(), + turn_id: receipt.turn_id, + execution_generation: receipt.execution_generation.unwrap_or(0), + completion_kind: completion_kind.to_string(), + recovery_pending: receipt.recovery_pending, + }) + .await; + Ok(true) + } + async fn update_session_title(&self, session_id: &str, title: &str) -> Result { self.coordinator .update_session_title(session_id, title) diff --git a/src/crates/contracts/events/AGENTS.md b/src/crates/contracts/events/AGENTS.md index 39e889afa5..381f953491 100644 --- a/src/crates/contracts/events/AGENTS.md +++ b/src/crates/contracts/events/AGENTS.md @@ -21,6 +21,7 @@ It describes events; it does not own event delivery or product decisions. ```bash cargo check -p openbitfun-events +cargo test --locked -p openbitfun-events --lib frontend_projection::tests::result_read_projects_the_same_turn_identity_for_peer_and_local_consumers node scripts/check-core-boundaries.mjs ``` diff --git a/src/crates/contracts/events/src/agentic.rs b/src/crates/contracts/events/src/agentic.rs index 03f00f4e11..16c2dc9558 100644 --- a/src/crates/contracts/events/src/agentic.rs +++ b/src/crates/contracts/events/src/agentic.rs @@ -126,6 +126,16 @@ pub enum AgenticEvent { new_state: String, }, + /// An owning host durably acknowledged a result through another surface. + SessionResultRead { + session_id: String, + turn_id: String, + execution_generation: u32, + completion_kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + recovery_pending: Option, + }, + /// The authoritative visible history for a session changed outside the /// append-only turn lifecycle (for example, after restoring a checkpoint). /// Consumers should invalidate cached transcript projections for this @@ -708,6 +718,7 @@ impl AgenticEvent { Self::SessionCreated { session_id, .. } | Self::SessionStateChanged { session_id, .. } | Self::SessionHistoryChanged { session_id, .. } + | Self::SessionResultRead { session_id, .. } | Self::SessionDeleted { session_id } | Self::SessionTitleGenerated { session_id, .. } | Self::PromptSuggestionGenerated { session_id, .. } @@ -743,6 +754,7 @@ impl AgenticEvent { pub fn turn_id(&self) -> Option<&str> { match self { Self::DialogTurnStarted { turn_id, .. } + | Self::SessionResultRead { turn_id, .. } | Self::DialogTurnCompleted { turn_id, .. } | Self::DialogTurnCancelled { turn_id, .. } | Self::DialogTurnInterrupted { turn_id, .. } @@ -777,6 +789,7 @@ impl AgenticEvent { Self::SessionStateChanged { .. } | Self::SessionHistoryChanged { .. } + | Self::SessionResultRead { .. } | Self::SessionTitleGenerated { .. } | Self::SessionModelFallbackApplied { .. } | Self::SessionReasoningPresetAutoCleared { .. } diff --git a/src/crates/contracts/events/src/frontend_projection.rs b/src/crates/contracts/events/src/frontend_projection.rs index d9ad0c6442..3250c5427e 100644 --- a/src/crates/contracts/events/src/frontend_projection.rs +++ b/src/crates/contracts/events/src/frontend_projection.rs @@ -408,6 +408,18 @@ pub fn project_agentic_frontend_event(event: AgenticEvent) -> Option Some(AgenticFrontendEvent::new( + "agentic://session-result-read", + json!({ "sessionId": session_id, "turnId": turn_id, + "executionGeneration": execution_generation, "completionKind": completion_kind, + "recoveryPending": recovery_pending }), + )), AgenticEvent::SessionHistoryChanged { session_id, settled_turn_id, @@ -895,6 +907,27 @@ mod tests { ); } + #[test] + fn result_read_projects_the_same_turn_identity_for_peer_and_local_consumers() { + let event = AgenticEvent::SessionResultRead { + session_id: "session".into(), + turn_id: "turn".into(), + execution_generation: 2, + completion_kind: "completed".into(), + recovery_pending: Some(false), + }; + let event: AgenticEvent = + serde_json::from_value(serde_json::to_value(event).unwrap()).unwrap(); + assert_eq!(event.session_id(), Some("session")); + assert_eq!(event.turn_id(), Some("turn")); + let projected = project_agentic_frontend_event(event).unwrap(); + assert_eq!(projected.event_name, "agentic://session-result-read"); + assert_eq!( + projected.payload, + json!({"sessionId":"session", "turnId":"turn", "executionGeneration":2, "completionKind":"completed", "recoveryPending":false}) + ); + } + #[test] fn reasoning_preset_auto_clear_projects_canonical_auto_transition() { let projected = diff --git a/src/crates/services/services-core/src/session/metadata.rs b/src/crates/services/services-core/src/session/metadata.rs index 8513bc7a7f..81dd6777f1 100644 --- a/src/crates/services/services-core/src/session/metadata.rs +++ b/src/crates/services/services-core/src/session/metadata.rs @@ -347,6 +347,8 @@ fn refresh_latest_turn(metadata: &mut SessionMetadata, turn: &DialogTurnData) { .is_some_and(|delivery| delivery.execution_generation == turn.recovery_epoch.unwrap_or(0) && delivery.disposition == openbitfun_core_types::background_delivery::BackgroundReportDisposition::Quiet && delivery.suppresses_report()); let mut unread_target = previous_unread_target; + let read = + read_completion_target(metadata).is_some_and(|receipt| same_completion(&receipt, &next)); if !same_outcome && !quiet { if let Some(outcome) = match turn.status { TurnStatus::Completed => Some("completed"), @@ -354,9 +356,11 @@ fn refresh_latest_turn(metadata: &mut SessionMetadata, turn: &DialogTurnData) { TurnStatus::Cancelled => Some("interrupted"), TurnStatus::InProgress => None, } { - metadata.unread_completion = Some(outcome.to_string()); metadata.needs_user_attention = None; - unread_target = Some(next.clone()); + if !read { + metadata.unread_completion = Some(outcome.to_string()); + unread_target = Some(next.clone()); + } } } let custom = metadata @@ -394,6 +398,167 @@ pub fn unread_completion_target(metadata: &SessionMetadata) -> Option Option { + metadata + .custom_metadata + .as_ref()? + .get("readCompletionTarget") + .and_then(|value| serde_json::from_value(value.clone()).ok()) +} + +fn same_completion(left: &SessionLastTurn, right: &SessionLastTurn) -> bool { + left.turn_id == right.turn_id + && left.execution_generation.unwrap_or(0) == right.execution_generation.unwrap_or(0) + && left.status == right.status + && left + .recovery_pending + .zip(right.recovery_pending) + .is_none_or(|(a, b)| a == b) +} + +#[cfg(test)] +mod delivered_result_contracts { + use super::super::types::UserMessageData; + use super::*; + + fn turn(id: &str, index: usize, status: TurnStatus) -> DialogTurnData { + let mut turn = DialogTurnData::new( + id.into(), + index, + "session".into(), + UserMessageData { + id: format!("{id}-input"), + content: "hello".into(), + timestamp: index as u64, + metadata: Some(serde_json::json!({"submissionSource":"bot"})), + }, + ); + turn.status = status; + turn + } + + #[test] + fn only_successful_delivery_clears_a_result_and_survives_reload_and_old_writers() { + for (kind, status) in [ + ("completed", TurnStatus::Completed), + ("error", TurnStatus::Error), + ("interrupted", TurnStatus::Cancelled), + ] { + let mut metadata = SessionMetadata::new( + "session".into(), + "Bot".into(), + "Standard".into(), + "model".into(), + ); + let turn = turn("bot", 0, status); + refresh_latest_turn(&mut metadata, &turn); + assert_eq!(metadata.unread_completion.as_deref(), Some(kind)); + let old_observer = metadata.clone(); + assert!(acknowledge_session_result(&mut metadata, "bot", Some(kind)).is_some()); + assert!(metadata.unread_completion.is_none()); + let mut reloaded: SessionMetadata = + serde_json::from_value(serde_json::to_value(metadata).unwrap()).unwrap(); + refresh_latest_turn(&mut reloaded, &turn); + apply_session_unread_completion(&mut reloaded, &old_observer); + assert!(reloaded.unread_completion.is_none()); + assert!(acknowledge_session_result(&mut reloaded, "bot", Some(kind)).is_some()); + } + } + + #[test] + fn delivery_before_terminal_persistence_does_not_lose_the_receipt() { + let mut metadata = SessionMetadata::new( + "session".into(), + "Bot".into(), + "Standard".into(), + "model".into(), + ); + let mut turn = turn("bot", 0, TurnStatus::InProgress); + refresh_latest_turn(&mut metadata, &turn); + assert!(acknowledge_session_result(&mut metadata, "bot", Some("completed")).is_some()); + turn.status = TurnStatus::Completed; + refresh_latest_turn(&mut metadata, &turn); + assert!(metadata.unread_completion.is_none()); + turn.recovery_epoch = Some(1); + refresh_latest_turn(&mut metadata, &turn); + assert_eq!(metadata.unread_completion.as_deref(), Some("completed")); + } + + #[test] + fn delayed_delivery_does_not_clear_another_turn_or_pending_interaction() { + let mut metadata = SessionMetadata::new( + "session".into(), + "Mixed".into(), + "Standard".into(), + "model".into(), + ); + refresh_latest_turn(&mut metadata, &turn("bot", 0, TurnStatus::Completed)); + refresh_latest_turn(&mut metadata, &turn("desktop", 1, TurnStatus::Error)); + metadata.needs_user_attention = Some("tool_confirm".into()); + assert!(acknowledge_session_result(&mut metadata, "bot", Some("completed")).is_none()); + assert_eq!(metadata.unread_completion.as_deref(), Some("error")); + assert_eq!( + metadata.needs_user_attention.as_deref(), + Some("tool_confirm") + ); + } +} + +/// Acknowledge only the delivered Turn, preserving another Turn's unread result. +/// The terminal event can precede its metadata write. A known completion kind +/// records that receipt first, and the subsequent save honors it. +pub fn acknowledge_session_result( + metadata: &mut SessionMetadata, + turn_id: &str, + completion_kind: Option<&str>, +) -> Option { + let unread = unread_completion_target(metadata); + let mut receipt = unread + .as_ref() + .filter(|turn| turn.turn_id == turn_id) + .or_else(|| { + metadata + .last_turn + .as_ref() + .filter(|turn| turn.turn_id == turn_id) + })? + .clone(); + let status = match completion_kind { + Some("completed") => TurnStatus::Completed, + Some("error") => TurnStatus::Error, + Some("interrupted") => TurnStatus::Cancelled, + Some(_) => return None, + None => receipt.status.clone(), + }; + if status == TurnStatus::InProgress + || (receipt.status != TurnStatus::InProgress && receipt.status != status) + { + return None; + } + receipt.status = status; + if receipt.status != TurnStatus::Cancelled { + receipt.recovery_pending = Some(false); + } + let should_clear = unread + .as_ref() + .is_some_and(|turn| same_completion(turn, &receipt)); + let custom = metadata + .custom_metadata + .get_or_insert_with(|| serde_json::json!({})); + let object = custom.as_object_mut()?; + object.insert( + "readCompletionTarget".into(), + serde_json::to_value(&receipt).ok()?, + ); + if should_clear { + metadata.unread_completion = None; + object.remove("unreadCompletionTarget"); + } + Some(receipt) +} + fn receipt_target(metadata: &SessionMetadata) -> Option { metadata .custom_metadata @@ -510,6 +675,14 @@ mod background_delivery_contracts { pub fn apply_session_unread_completion(current: &mut SessionMetadata, incoming: &SessionMetadata) { let current_target = unread_completion_target(current); let incoming_target = receipt_target(incoming); + if incoming.unread_completion.is_some() + && read_completion_target(current) + .as_ref() + .zip(incoming_target.as_ref()) + .is_some_and(|(read, incoming)| same_completion(read, incoming)) + { + return; + } // An older observer may still mark a quiet completion as new unread work. // Read receipts remain client-owned, while the host owns result creation. let suppressed_latest = current diff --git a/src/crates/services/services-core/src/session/mod.rs b/src/crates/services/services-core/src/session/mod.rs index 4a95bde9b5..a91a5a9221 100644 --- a/src/crates/services/services-core/src/session/mod.rs +++ b/src/crates/services/services-core/src/session/mod.rs @@ -26,11 +26,11 @@ pub use memory_workspace::{ MemoryWorkspaceDiff, MemoryWorkspaceGitError, }; pub use metadata::{ - apply_session_title_metadata, apply_session_unread_completion, build_session_index_snapshot, - build_session_metadata, estimate_turn_message_count, merge_session_custom_metadata, - normalized_session_relationship, refresh_session_metadata_from_turns, - remove_session_index_entry, set_deep_review_cache, set_deep_review_run_manifest, - set_review_target_evidence, set_session_relationship, + acknowledge_session_result, apply_session_title_metadata, apply_session_unread_completion, + build_session_index_snapshot, build_session_metadata, estimate_turn_message_count, + merge_session_custom_metadata, normalized_session_relationship, read_completion_target, + refresh_session_metadata_from_turns, remove_session_index_entry, set_deep_review_cache, + set_deep_review_run_manifest, set_review_target_evidence, set_session_relationship, try_refresh_session_metadata_for_saved_turn, unread_completion_target, upsert_session_index_entry, SessionMetadataBuildFacts, }; diff --git a/src/crates/services/services-core/src/session/page.rs b/src/crates/services/services-core/src/session/page.rs index 2e52a79cdf..305e8574e9 100644 --- a/src/crates/services/services-core/src/session/page.rs +++ b/src/crates/services/services-core/src/session/page.rs @@ -88,6 +88,9 @@ pub struct SessionActivitySummary { pub unread_completion: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub unread_turn: Option, + /// Durable read receipt, including results delivered through another surface. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read_turn: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -479,6 +482,17 @@ fn session_metadata_page_cursor(metadata: &SessionMetadata, revision: Option Vec { "workspace_id_references_v1".to_string(), REMOTE_CAPABILITY_HARNESS_PROFILES_V1.to_string(), REMOTE_CAPABILITY_DIALOG_STEER_V1.to_string(), + REMOTE_CAPABILITY_SESSION_RESULT_ACK_V1.to_string(), "dialog_queue_v1".to_string(), REMOTE_CAPABILITY_PLAN_BUILD_V1.to_string(), REMOTE_CAPABILITY_SESSION_ATTACHMENTS_V1.to_string(), @@ -1519,6 +1521,14 @@ pub trait RemoteSessionRuntimeHost: Send + Sync { } async fn ensure_session_loaded(&self, session_id: &str) -> Result<(), String>; async fn update_session_title(&self, session_id: &str, title: &str) -> Result; + async fn acknowledge_session_result( + &self, + _session_id: &str, + _turn_id: &str, + _completion_kind: Option<&str>, + ) -> Result { + Err("Host does not support session result acknowledgement".into()) + } async fn resolve_session_storage_dir(&self, session_id: &str) -> Option; async fn load_remote_chat_messages( &self, @@ -1816,6 +1826,31 @@ where Err(message) => RemoteResponse::Error { message }, } } + RemoteCommand::AcknowledgeSessionResult { + session_id, + turn_id, + completion_kind, + } => { + if completion_kind + .as_deref() + .is_some_and(|kind| !matches!(kind, "completed" | "error" | "interrupted")) + { + return RemoteResponse::Error { + message: "Invalid session completion kind".into(), + }; + } + match host + .acknowledge_session_result(session_id, turn_id, completion_kind.as_deref()) + .await + { + Ok(acknowledged) => RemoteResponse::SessionResultAcknowledged { + session_id: session_id.clone(), + turn_id: turn_id.clone(), + acknowledged, + }, + Err(message) => RemoteResponse::Error { message }, + } + } RemoteCommand::UpdateSessionTitle { session_id, title } => { if let Err(message) = host.ensure_session_loaded(session_id).await { return RemoteResponse::Error { message }; @@ -2943,6 +2978,13 @@ pub enum RemoteCommand { session_id: String, title: String, }, + /// Idempotent acknowledgement of a result successfully delivered to a controller. + AcknowledgeSessionResult { + session_id: String, + turn_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + completion_kind: Option, + }, GetSessionMessages { session_id: String, limit: Option, @@ -3200,6 +3242,11 @@ pub enum RemoteResponse { sessions: Vec, has_more: bool, }, + SessionResultAcknowledged { + session_id: String, + turn_id: String, + acknowledged: bool, + }, SessionCreated { session_id: String, /// Owning workspace record ID; authoritative for controllers that pin @@ -3473,6 +3520,7 @@ where | RemoteCommand::SetSessionModel { .. } | RemoteCommand::SetModelDefaults { .. } | RemoteCommand::UpdateSessionTitle { .. } + | RemoteCommand::AcknowledgeSessionResult { .. } | RemoteCommand::GetSessionMessages { .. } | RemoteCommand::DeleteSession { .. } | RemoteCommand::RollbackSessionToTurn { .. } => host.handle_session_command(command).await, @@ -5110,6 +5158,7 @@ mod tests { #[derive(Default)] struct FakeSessionHost { + read_receipts: Mutex)>>, created_requests: Mutex>, list_identities: Mutex>, model_updates: Mutex>)>>, @@ -5127,6 +5176,33 @@ mod tests { rollback_requests: Mutex)>>, } + #[tokio::test] + async fn delivered_result_ack_routes_the_named_turn_and_validates_completion_kind() { + let host = FakeSessionHost::default(); + let payload = serde_json::json!({"cmd":"acknowledge_session_result", "session_id":"session", "turn_id":"delivered"}); + let command: RemoteCommand = serde_json::from_value(payload.clone()).unwrap(); + assert_eq!(serde_json::to_value(&command).unwrap(), payload); + assert!(matches!( + handle_remote_session_command(&host, &command).await, + RemoteResponse::SessionResultAcknowledged { + acknowledged: true, + .. + } + )); + assert_eq!( + *host.read_receipts.lock().unwrap(), + vec![("session".into(), "delivered".into(), None)] + ); + let invalid: RemoteCommand = serde_json::from_value(serde_json::json!({ + "cmd":"acknowledge_session_result", "session_id":"session", "turn_id":"delivered", "completion_kind":"running" + })).unwrap(); + assert!(matches!( + handle_remote_session_command(&host, &invalid).await, + RemoteResponse::Error { .. } + )); + assert_eq!(host.read_receipts.lock().unwrap().len(), 1); + } + fn fake_workspace( workspace_id: &str, path: &str, @@ -5329,6 +5405,20 @@ mod tests { }) } + async fn acknowledge_session_result( + &self, + session_id: &str, + turn_id: &str, + completion_kind: Option<&str>, + ) -> Result { + self.read_receipts.lock().unwrap().push(( + session_id.into(), + turn_id.into(), + completion_kind.map(str::to_owned), + )); + Ok(true) + } + async fn update_session_title( &self, _session_id: &str, diff --git a/src/crates/services/services-integrations/src/remote_connect/session_records.rs b/src/crates/services/services-integrations/src/remote_connect/session_records.rs index 68ca128807..2738b46441 100644 --- a/src/crates/services/services-integrations/src/remote_connect/session_records.rs +++ b/src/crates/services/services-integrations/src/remote_connect/session_records.rs @@ -23,9 +23,11 @@ pub fn session_event_publication(name: &str, payload: &Value) -> SessionEventPub persist_control: false, }; } - // A next-input suggestion is not transcript content; its source turn was - // already synchronized by the completion event that precedes it. - if name == "agentic://prompt-suggestion" { + // Suggestions and read receipts are controls, not transcript mutations. + if matches!( + name, + "agentic://prompt-suggestion" | "agentic://session-result-read" + ) { return SessionEventPublication { synchronize_records: false, persist_control: true, @@ -181,4 +183,14 @@ mod publication_tests { assert!(!policy.synchronize_records); assert!(policy.persist_control); } + + #[test] + fn read_receipts_replay_without_rebuilding_transcripts() { + let policy = session_event_publication( + "agentic://session-result-read", + &json!({"sessionId":"session", "turnId":"turn"}), + ); + assert!(policy.persist_control); + assert!(!policy.synchronize_records); + } } diff --git a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs index bd02a6201c..e6799dfb83 100644 --- a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs +++ b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs @@ -2364,6 +2364,7 @@ fn remote_connect_workspace_response_helpers_own_wire_shape() { "workspace_id_references_v1", REMOTE_CAPABILITY_HARNESS_PROFILES_V1, REMOTE_CAPABILITY_DIALOG_STEER_V1, + "session_result_ack_v1", "dialog_queue_v1", REMOTE_CAPABILITY_PLAN_BUILD_V1, "session_attachments_v1", @@ -2615,6 +2616,7 @@ fn remote_connect_session_response_helpers_own_pagination_and_timestamps() { "workspace_id_references_v1", REMOTE_CAPABILITY_HARNESS_PROFILES_V1, REMOTE_CAPABILITY_DIALOG_STEER_V1, + "session_result_ack_v1", "dialog_queue_v1", REMOTE_CAPABILITY_PLAN_BUILD_V1, "session_attachments_v1", diff --git a/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts b/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts index 31778d0cbd..5bca88db9c 100644 --- a/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts +++ b/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts @@ -21,7 +21,7 @@ const sources = vi.hoisted(() => ({ machineListeners: new Set<(sessionId: string, machine: SessionStateMachine) => void>(), })); vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({ agentAPI: Object.fromEntries([ - 'onSessionStateChanged', 'onSessionHistoryChanged', 'onSessionDeleted', 'onDialogTurnStarted', + 'onSessionStateChanged', 'onSessionHistoryChanged', 'onSessionResultRead', 'onSessionDeleted', 'onDialogTurnStarted', 'onDialogTurnCompleted', 'onDialogTurnFailed', 'onDialogTurnCancelled', 'onDialogTurnInterrupted', 'onDialogTurnRecovered', 'onToolEvent', ].map(name => [name, (callback: (event: unknown) => void) => { sources.events.set(name, callback); @@ -285,7 +285,7 @@ describe('navigation status synchronization', () => { await vi.advanceTimersByTimeAsync(100); expect(sources.read).toHaveBeenCalledTimes(1); expect(sources.read.mock.calls[0][0].sessionIds).toHaveLength(40); - expect(sources.events.size).toBe(10); + expect(sources.events.size).toBe(11); for (const id of ids) { expect(sessionNavStatusService.getSnapshot(id).kind).toBe('running'); expect(sources.sessions.get(id)?.dialogTurns).toHaveLength(0); @@ -305,6 +305,23 @@ describe('navigation status synchronization', () => { expect(sources.sessions.get(id)?.unreadCompletionTurnId).toBe('new'); }); + it('clears an unopened row only after the host confirms IM delivery', async () => { + const id = 'im-delivered'; + sources.sessions.set(id, row(id)); + sources.read.mockResolvedValue(response([activity(id, 'idle')])); + install(id); + await vi.advanceTimersByTimeAsync(100); + sources.events.get('onDialogTurnStarted')!({ sessionId: id, turnId: 'turn', userMessageMetadata: { submissionSource: 'bot' } }); + sources.events.get('onDialogTurnCompleted')!({ sessionId: id, turnId: 'turn' }); + expect(sessionNavStatusService.getSnapshot(id).kind).toBe('unread'); + sources.events.get('onSessionResultRead')!({ sessionId: id, turnId: 'turn', executionGeneration: 0, completionKind: 'completed' }); + expect(sessionNavStatusService.getSnapshot(id).kind).toBe('idle'); + sources.events.get('onDialogTurnCompleted')!({ sessionId: id, turnId: 'turn' }); + expect(sessionNavStatusService.getSnapshot(id).kind).toBe('idle'); + expect(sources.sessions.get(id)?.hasUnreadCompletion).toBeUndefined(); + expect(sources.sessions.get(id)?.dialogTurns).toHaveLength(0); + }); + it('reconciles only the permission owner and delegated parent when their mailbox changes', async () => { const ids = ['approval-owner', 'delegated-parent', 'unaffected']; ids.forEach(id => sources.sessions.set(id, row(id))); diff --git a/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts b/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts index 83f097dac5..770cf1a5bc 100644 --- a/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts +++ b/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts @@ -164,6 +164,7 @@ export function installSessionNavStatusService(): () => void { const events: Array<[string, (callback: (event: AgenticEvent) => void) => () => void]> = [ ['agentic://session-state-changed', callback => agentAPI.onSessionStateChanged(callback)], ['agentic://session-history-changed', callback => agentAPI.onSessionHistoryChanged(callback)], + ['agentic://session-result-read', callback => agentAPI.onSessionResultRead(callback)], ['agentic://session-deleted', callback => agentAPI.onSessionDeleted(callback)], ['agentic://dialog-turn-started', callback => agentAPI.onDialogTurnStarted(callback)], ['agentic://dialog-turn-completed', callback => agentAPI.onDialogTurnCompleted(callback)], diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index 6af88ef7c7..2e491d68f6 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -797,6 +797,26 @@ describe('FlowChatStore metadata persistence callbacks', () => { }); }); + it.each(['ready', 'metadata-only'] as const)('honors a delivered IM receipt before a late completion with %s history', historyState => { + const session = { ...completedSession(), sessionId: `im-delivery-${historyState}`, historyState, + hasUnreadCompletion: undefined, unreadCompletionTurnId: undefined }; + if (historyState === 'metadata-only') session.dialogTurns = []; + flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]) })); + const persist = vi.fn(); + flowChatStore.registerPersistUnreadCompletionCallback(persist); + const lastTurn = { turnId: 'finished-turn', turnIndex: 0, status: 'completed' as const, executionGeneration: 2 }; + sessionActivityStore.applyRead(sessionActivityStore.beginRead(), [{ + sessionId: session.sessionId, execution: 'idle', pendingApprovals: 1, pendingQuestions: 0, + lastTurn, readTurn: lastTurn, + }]); + flowChatStore.markSessionUnreadCompletion(session.sessionId, 'completed', 'finished-turn'); + expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBeUndefined(); + expect(persist).not.toHaveBeenCalled(); + flowChatStore.markSessionUnreadCompletion(session.sessionId, 'completed', 'next-turn'); + expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBe('completed'); + expect(persist).toHaveBeenCalledOnce(); + }); + it.each(['new', 'metadata-only', 'ready'] as const)( 'explicitly acknowledges a %s session and keeps a refreshed result read', (historyState) => { const session = { ...completedSession(), sessionId: `explicit-read-${historyState}`, historyState }; diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 82e4fffbb6..e77eee5c6f 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -7420,6 +7420,20 @@ export class FlowChatStore { completionKind: 'completed' | 'error' | 'interrupted', turnId?: string, ): void { + const session = this.state.sessions.get(sessionId); + const turn = turnId ? session?.dialogTurns.find(candidate => candidate.id === turnId) + : session && lastUserDialogTurn(session); + const summary = sessionActivityStore.get(sessionId)?.summary; + const resultTurnId = turnId ?? turn?.id; + const generation = Math.max(turn?.recovery?.executionGeneration ?? turn?.recoveryEpoch ?? 0, + summary?.lastTurn?.turnId === resultTurnId ? summary?.lastTurn?.executionGeneration ?? 0 : 0); + if (resultTurnId && summary?.readTurn?.turnId === resultTurnId + && (summary.readTurn.executionGeneration ?? 0) === (generation ?? 0) + && summary.readTurn.status === (completionKind === 'interrupted' ? 'cancelled' : completionKind) + && (summary.readTurn.recoveryPending === undefined || summary.lastTurn?.turnId !== resultTurnId + || summary.lastTurn.recoveryPending === undefined + || summary.readTurn.recoveryPending === summary.lastTurn.recoveryPending)) return; + this.setState(prev => { const session = prev.sessions.get(sessionId); if (!session) return prev; diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts index 9f055973c5..32be106ac4 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts @@ -8,6 +8,50 @@ const summary = (execution = 'idle', id = 'session'): SessionActivitySummary => }); describe('session activity read projection', () => { + it.each(['completed', 'error', 'interrupted'] as const)('keeps %s unread until successful IM delivery and accepts the receipt before completion', (kind) => { + for (const receiptFirst of [false, true]) { + const store = new SessionActivityStore(); + const terminal = kind === 'completed' ? 'completed' : kind === 'error' ? 'failed' : 'cancelled'; + const complete = () => store.observe('peer', `agentic://dialog-turn-${terminal}`, { sessionId: 'session', turnId: 'bot', executionGeneration: 0 }); + store.observe('peer', 'agentic://dialog-turn-started', { sessionId: 'session', turnId: 'bot', userMessageMetadata: { submissionSource: 'bot' } }); + if (!receiptFirst) { + complete(); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBe(kind); + } + const stale = store.beginRead('peer'); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'bot', executionGeneration: 0, completionKind: kind }); + complete(); + store.applyRead(stale, [{ ...summary(), unreadCompletion: kind }]); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + const snapshot = store.get('session', 'peer')!.summary!; + const reconnected = new SessionActivityStore(); + reconnected.applyRead(reconnected.beginRead('peer'), [snapshot]); + reconnected.observe('peer', `agentic://dialog-turn-${terminal}`, { sessionId: 'session', turnId: 'bot', executionGeneration: 0 }); + expect(reconnected.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + reconnected.observe('peer', 'agentic://dialog-turn-recovered', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); + reconnected.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); + expect(reconnected.get('session', 'peer')?.summary?.unreadCompletion).toBe('completed'); + } + }); + + it('does not let an old IM receipt clear a newer result or a different device', () => { + const store = new SessionActivityStore(); + for (const surface of ['local', 'peer']) store.observe(surface, 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'desktop' }); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'bot', executionGeneration: 0, completionKind: 'completed' }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBe('completed'); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'desktop', executionGeneration: 0, completionKind: 'completed' }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + expect(store.get('session', 'local')?.summary?.unreadCompletion).toBe('completed'); + }); + + it('keeps a cancellation unread after an interrupted checkpoint was delivered', () => { + const store = new SessionActivityStore(); + store.observe('peer', 'agentic://dialog-turn-interrupted', { sessionId: 'session', turnId: 'turn', executionGeneration: 1 }); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'turn', executionGeneration: 1, completionKind: 'interrupted', recoveryPending: true }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + store.observe('peer', 'agentic://dialog-turn-cancelled', { sessionId: 'session', turnId: 'turn', executionGeneration: 1 }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBe('interrupted'); + }); it('keeps a prior unread result across a newer quiet run and acknowledges its original identity', () => { activateSurface('local'); const store = new SessionActivityStore(); diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts index 3a9ae055d4..03bb76a328 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts @@ -151,7 +151,19 @@ export class SessionActivityStore { const settling = ['agentic://dialog-turn-completed', 'agentic://dialog-turn-failed', 'agentic://dialog-turn-cancelled', 'agentic://dialog-turn-interrupted'].includes(eventName); let newResult = false; - if (starting) { + if (eventName === 'agentic://session-result-read') { + if (!turnId || !['completed', 'error', 'interrupted'].includes(String(event.completionKind))) return; + const status = event.completionKind === 'interrupted' ? 'cancelled' : event.completionKind as 'completed' | 'error'; + const unread = summary.unreadTurn ?? summary.lastTurn; + const matches = unread?.turnId === turnId && (unread.executionGeneration ?? 0) === (generation ?? 0) + && unread.status === status; + summary = { ...summary, + readTurn: { turnId, turnIndex: unread?.turnIndex ?? 0, status, executionGeneration: generation, + recoveryPending: typeof event.recoveryPending === 'boolean' ? event.recoveryPending : undefined }, + unreadCompletion: matches ? undefined : summary.unreadCompletion, + unreadTurn: matches ? undefined : summary.unreadTurn, + }; + } else if (starting) { summary = { ...summary, execution: 'running', activeTurnId: turnId, pendingApprovals: 0, pendingQuestions: 0, unreadTurn: summary.unreadCompletion ? summary.unreadTurn ?? summary.lastTurn : undefined, @@ -173,6 +185,10 @@ export class SessionActivityStore { // Learning an optional recovery fact from a replay is not a new result. // A known paused -> cancelled transition is, even within one generation. newResult = (!sameOutcome || summary.lastTurn?.recoveryPending !== undefined) + && !(turnId && summary.readTurn?.turnId === turnId + && (summary.readTurn.executionGeneration ?? 0) === (generation ?? summary.lastTurn?.executionGeneration ?? 0) + && summary.readTurn.status === (outcome === 'interrupted' ? 'cancelled' : outcome) + && (summary.readTurn.recoveryPending === undefined || summary.readTurn.recoveryPending === recoveryPending)) && (outcome !== 'completed' || shouldDeliverBackgroundCompletion(event)); summary = { ...summary, execution: outcome === 'error' ? 'error' : 'idle', activeTurnId: undefined, diff --git a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts index f0bba2373b..35a861a8c8 100644 --- a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts @@ -1446,6 +1446,10 @@ export class AgentAPI { return api.listen('agentic://session-history-changed', callback); } + onSessionResultRead(callback: (event: AgenticEvent) => void): () => void { + return api.listen('agentic://session-result-read', callback); + } + onSessionModelFallbackApplied( callback: (event: SessionModelFallbackAppliedEvent) => void ): () => void { diff --git a/src/web-ui/src/shared/types/session-history.ts b/src/web-ui/src/shared/types/session-history.ts index 0ddfa6d96e..9d40848e39 100644 --- a/src/web-ui/src/shared/types/session-history.ts +++ b/src/web-ui/src/shared/types/session-history.ts @@ -165,6 +165,8 @@ export interface SessionActivitySummary { unreadCompletion?: 'completed' | 'error' | 'interrupted'; /** A quiet run can be newer than the unread user-facing result. */ unreadTurn?: SessionLastTurn; + /** Durable acknowledgement from another delivery surface, such as IM. */ + readTurn?: SessionLastTurn; } export interface ReviewActionPersistedState {