|
| 1 | +//! `/btw` side-question HostInvoke handlers. |
| 2 | +//! |
| 3 | +//! The turn runs on the Core coordinator as a child session and flows through |
| 4 | +//! the normal agentic event pipeline, so a controller observes it exactly like |
| 5 | +//! a side question on a Desktop host. Peer ownership follows the dialog turn |
| 6 | +//! contract: it is registered before submission and released if that fails. |
| 7 | +
|
| 8 | +use std::future::Future; |
| 9 | +use std::sync::{Arc, OnceLock}; |
| 10 | +use std::time::Duration; |
| 11 | + |
| 12 | +use openbitfun_core::agentic::coordination::{ |
| 13 | + btw_turn_id, get_global_coordinator, ConversationCoordinator, DialogSubmissionPolicy, |
| 14 | + DialogTriggerSource, |
| 15 | +}; |
| 16 | +use openbitfun_core::agentic::core::SessionState; |
| 17 | +use openbitfun_core::agentic::image_analysis::ImageContextData; |
| 18 | +use openbitfun_core::agentic::side_question::SideQuestionRuntime; |
| 19 | +use serde::Deserialize; |
| 20 | +use serde_json::{json, Value}; |
| 21 | + |
| 22 | +use crate::peer_host::args::{get_string, request_value}; |
| 23 | +use crate::peer_host::state::{PeerHostState, PeerTurnKey, PeerTurnTracker}; |
| 24 | + |
| 25 | +#[derive(Debug, Deserialize)] |
| 26 | +#[serde(rename_all = "camelCase")] |
| 27 | +struct BtwAskStreamRequest { |
| 28 | + request_id: String, |
| 29 | + session_id: String, |
| 30 | + question: String, |
| 31 | + child_session_id: String, |
| 32 | + child_session_name: Option<String>, |
| 33 | + parent_dialog_turn_id: Option<String>, |
| 34 | + parent_turn_index: Option<usize>, |
| 35 | + model_id: Option<String>, |
| 36 | + #[serde(default)] |
| 37 | + image_contexts: Option<Vec<ImageContextData>>, |
| 38 | + #[serde(default)] |
| 39 | + initial_model_selection: Option<openbitfun_runtime_ports::AgentSessionModelSelection>, |
| 40 | + #[serde(default)] |
| 41 | + initial_model_target: Option<openbitfun_runtime_ports::AgentSessionModelTargetSelection>, |
| 42 | +} |
| 43 | + |
| 44 | +fn side_questions() -> &'static Arc<SideQuestionRuntime> { |
| 45 | + static RUNTIME: OnceLock<Arc<SideQuestionRuntime>> = OnceLock::new(); |
| 46 | + RUNTIME.get_or_init(|| Arc::new(SideQuestionRuntime::new())) |
| 47 | +} |
| 48 | + |
| 49 | +fn coordinator() -> Result<Arc<ConversationCoordinator>, String> { |
| 50 | + get_global_coordinator() |
| 51 | + .ok_or_else(|| "Side questions are unavailable: the agent runtime is not running".into()) |
| 52 | +} |
| 53 | + |
| 54 | +fn parse_ask_request(request: &Value) -> Result<BtwAskStreamRequest, String> { |
| 55 | + let parsed: BtwAskStreamRequest = serde_json::from_value(request.clone()) |
| 56 | + .map_err(|error| format!("Invalid side question request: {error}"))?; |
| 57 | + for (value, name) in [ |
| 58 | + (&parsed.request_id, "requestId"), |
| 59 | + (&parsed.session_id, "sessionId"), |
| 60 | + (&parsed.child_session_id, "childSessionId"), |
| 61 | + (&parsed.question, "question"), |
| 62 | + ] { |
| 63 | + if value.trim().is_empty() { |
| 64 | + return Err(format!("{name} is required")); |
| 65 | + } |
| 66 | + } |
| 67 | + Ok(parsed) |
| 68 | +} |
| 69 | + |
| 70 | +/// Own the turn for the duration of `start`, returning the stream generation it |
| 71 | +/// was admitted under. A failed start releases the turn: it will never emit the |
| 72 | +/// terminal event that would otherwise release it. |
| 73 | +async fn start_owned_turn<F, Fut>( |
| 74 | + turns: &PeerTurnTracker, |
| 75 | + turn: &PeerTurnKey, |
| 76 | + start: F, |
| 77 | +) -> Result<u64, String> |
| 78 | +where |
| 79 | + F: FnOnce() -> Fut, |
| 80 | + Fut: Future<Output = Result<(), String>>, |
| 81 | +{ |
| 82 | + let generation = turns.register_root(turn.clone())?; |
| 83 | + if !turns.is_event_stream_generation_current(generation) { |
| 84 | + turns.finish_turn(turn); |
| 85 | + return Err("Peer event stream continuity was lost before side question start".to_string()); |
| 86 | + } |
| 87 | + if let Err(error) = start().await { |
| 88 | + turns.finish_turn(turn); |
| 89 | + return Err(error); |
| 90 | + } |
| 91 | + Ok(generation) |
| 92 | +} |
| 93 | + |
| 94 | +pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Result<Value, String> { |
| 95 | + let raw = request_value(args); |
| 96 | + let request = parse_ask_request(raw)?; |
| 97 | + // Same reserved-key policy as a Peer dialog turn: routing metadata belongs |
| 98 | + // to this host and a controller's copy of it is dropped. |
| 99 | + let metadata = match raw.get("userMessageMetadata") { |
| 100 | + None | Some(Value::Null) => None, |
| 101 | + Some(_) => Some(Value::Object(super::dialog::peer_dialog_metadata(raw)?)), |
| 102 | + }; |
| 103 | + let coordinator = coordinator()?; |
| 104 | + let child_session_id = request.child_session_id.trim().to_string(); |
| 105 | + let turn_id = btw_turn_id(&request.request_id); |
| 106 | + let turn = PeerTurnKey::new(child_session_id.clone(), turn_id.clone()); |
| 107 | + let submit = coordinator.clone(); |
| 108 | + let child = child_session_id.clone(); |
| 109 | + let request_id = request.request_id.clone(); |
| 110 | + let parent_session_id = request.session_id.clone(); |
| 111 | + let generation = start_owned_turn(&state.turns, &turn, || async move { |
| 112 | + submit |
| 113 | + .start_btw_turn( |
| 114 | + &request_id, |
| 115 | + &parent_session_id, |
| 116 | + &child, |
| 117 | + request.child_session_name.as_deref(), |
| 118 | + &request.question, |
| 119 | + DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi), |
| 120 | + request.model_id.as_deref(), |
| 121 | + request.image_contexts, |
| 122 | + request.parent_dialog_turn_id.as_deref(), |
| 123 | + request.parent_turn_index, |
| 124 | + metadata, |
| 125 | + request.initial_model_selection, |
| 126 | + request.initial_model_target, |
| 127 | + ) |
| 128 | + .await |
| 129 | + .map(|_| ()) |
| 130 | + .map_err(|error| error.to_string()) |
| 131 | + }) |
| 132 | + .await?; |
| 133 | + if !state.turns.is_event_stream_generation_current(generation) { |
| 134 | + coordinator |
| 135 | + .cancel_dialog_turn(&child_session_id, &turn_id) |
| 136 | + .await |
| 137 | + .map_err(|error| { |
| 138 | + format!( |
| 139 | + "Peer continuity was lost after side question start and cancellation could not be confirmed: session_id={child_session_id}, turn_id={turn_id}, error={error}" |
| 140 | + ) |
| 141 | + })?; |
| 142 | + return Err("Peer event stream lost continuity while starting the side question".into()); |
| 143 | + } |
| 144 | + |
| 145 | + let runtime = side_questions().clone(); |
| 146 | + let request_id = request.request_id; |
| 147 | + runtime |
| 148 | + .register_btw_turn( |
| 149 | + request_id.clone(), |
| 150 | + child_session_id.clone(), |
| 151 | + turn_id.clone(), |
| 152 | + ) |
| 153 | + .await; |
| 154 | + tokio::spawn(async move { |
| 155 | + // The registration only serves cancellation; release it once the turn settles. |
| 156 | + loop { |
| 157 | + let processing = coordinator |
| 158 | + .get_session_manager() |
| 159 | + .get_session(&child_session_id) |
| 160 | + .is_some_and(|session| { |
| 161 | + matches!( |
| 162 | + session.state, |
| 163 | + SessionState::Processing { current_turn_id, .. } |
| 164 | + if current_turn_id == turn_id |
| 165 | + ) |
| 166 | + }); |
| 167 | + if !processing { |
| 168 | + runtime.remove(&request_id).await; |
| 169 | + break; |
| 170 | + } |
| 171 | + tokio::time::sleep(Duration::from_millis(250)).await; |
| 172 | + } |
| 173 | + }); |
| 174 | + Ok(json!({ "ok": true })) |
| 175 | +} |
| 176 | + |
| 177 | +pub(crate) async fn btw_cancel(args: &Value) -> Result<Value, String> { |
| 178 | + let request_id = get_string(request_value(args), "requestId")?; |
| 179 | + if request_id.trim().is_empty() { |
| 180 | + return Err("requestId is required".to_string()); |
| 181 | + } |
| 182 | + let runtime = side_questions(); |
| 183 | + runtime.cancel(&request_id).await; |
| 184 | + if let Some(active) = runtime.get_btw_turn(&request_id).await { |
| 185 | + coordinator()? |
| 186 | + .cancel_dialog_turn(&active.session_id, &active.turn_id) |
| 187 | + .await |
| 188 | + .map_err(|error| error.to_string())?; |
| 189 | + runtime.remove(&request_id).await; |
| 190 | + } |
| 191 | + Ok(Value::Null) |
| 192 | +} |
| 193 | + |
| 194 | +#[cfg(test)] |
| 195 | +mod tests { |
| 196 | + use super::*; |
| 197 | + |
| 198 | + fn turn() -> PeerTurnKey { |
| 199 | + PeerTurnKey::new("child-1", btw_turn_id("request-1")) |
| 200 | + } |
| 201 | + |
| 202 | + #[test] |
| 203 | + fn the_registered_turn_id_is_the_one_the_coordinator_assigns() { |
| 204 | + assert_eq!(btw_turn_id(" request-1 "), "btw-turn-request-1"); |
| 205 | + } |
| 206 | + |
| 207 | + #[tokio::test] |
| 208 | + async fn a_started_turn_stays_owned_until_its_terminal_event() { |
| 209 | + let turns = PeerTurnTracker::new(); |
| 210 | + turns.mark_event_stream_ready(); |
| 211 | + start_owned_turn(&turns, &turn(), || async { Ok(()) }) |
| 212 | + .await |
| 213 | + .unwrap(); |
| 214 | + assert!(turns.owns("child-1", Some(&turn().turn_id))); |
| 215 | + } |
| 216 | + |
| 217 | + #[tokio::test] |
| 218 | + async fn the_turn_is_owned_while_it_starts_and_released_when_that_fails() { |
| 219 | + let turns = PeerTurnTracker::new(); |
| 220 | + turns.mark_event_stream_ready(); |
| 221 | + let observer = turns.clone(); |
| 222 | + let error = start_owned_turn(&turns, &turn(), || async move { |
| 223 | + assert!(observer.owns("child-1", Some(&turn().turn_id))); |
| 224 | + Err("model unavailable".to_string()) |
| 225 | + }) |
| 226 | + .await |
| 227 | + .unwrap_err(); |
| 228 | + assert_eq!(error, "model unavailable"); |
| 229 | + assert!(!turns.owns("child-1", Some(&turn().turn_id))); |
| 230 | + } |
| 231 | + |
| 232 | + #[tokio::test] |
| 233 | + async fn a_turn_cannot_start_before_the_event_stream_is_ready() { |
| 234 | + let turns = PeerTurnTracker::new(); |
| 235 | + let result = start_owned_turn(&turns, &turn(), || async { |
| 236 | + panic!("must not start an unobservable turn") |
| 237 | + }) |
| 238 | + .await; |
| 239 | + assert!(result.is_err()); |
| 240 | + assert!(!turns.owns("child-1", Some(&turn().turn_id))); |
| 241 | + } |
| 242 | + |
| 243 | + #[test] |
| 244 | + fn ask_request_reads_legacy_payloads_and_ignores_future_fields() { |
| 245 | + let request = parse_ask_request(&json!({ |
| 246 | + "requestId": "request-1", |
| 247 | + "sessionId": "parent-1", |
| 248 | + "childSessionId": "child-1", |
| 249 | + "question": "Why?", |
| 250 | + "futureField": true, |
| 251 | + })) |
| 252 | + .unwrap(); |
| 253 | + assert!(request.initial_model_selection.is_none()); |
| 254 | + assert!(request.initial_model_target.is_none()); |
| 255 | + assert!(request.image_contexts.is_none()); |
| 256 | + } |
| 257 | + |
| 258 | + #[test] |
| 259 | + fn ask_request_accepts_typed_model_targets() { |
| 260 | + let request = parse_ask_request(&json!({ |
| 261 | + "requestId": "request-1", |
| 262 | + "sessionId": "parent-1", |
| 263 | + "childSessionId": "child-1", |
| 264 | + "question": "Why?", |
| 265 | + "initialModelTarget": { "selection": { "kind": "pool", "pool_id": "pool-a" } }, |
| 266 | + })) |
| 267 | + .unwrap(); |
| 268 | + assert!(request.initial_model_target.is_some()); |
| 269 | + } |
| 270 | + |
| 271 | + #[test] |
| 272 | + fn ask_request_rejects_blank_identity_fields() { |
| 273 | + for field in ["requestId", "sessionId", "childSessionId", "question"] { |
| 274 | + let mut payload = json!({ |
| 275 | + "requestId": "request-1", |
| 276 | + "sessionId": "parent-1", |
| 277 | + "childSessionId": "child-1", |
| 278 | + "question": "Why?", |
| 279 | + }); |
| 280 | + payload[field] = json!(" "); |
| 281 | + let error = parse_ask_request(&payload).unwrap_err(); |
| 282 | + assert_eq!(error, format!("{field} is required")); |
| 283 | + } |
| 284 | + } |
| 285 | + |
| 286 | + #[tokio::test] |
| 287 | + async fn cancel_of_an_unknown_request_is_a_no_op() { |
| 288 | + assert_eq!( |
| 289 | + btw_cancel(&json!({ "request": { "requestId": "unknown-request" } })) |
| 290 | + .await |
| 291 | + .unwrap(), |
| 292 | + Value::Null |
| 293 | + ); |
| 294 | + } |
| 295 | +} |
0 commit comments