//! A connection's subscription to one Session: a listener on the Session //! broadcast channel, pending approval replay, branch states, owners' notices //! and the end. use super::*; use crate::tree_protocol as wire; use dim_agent_capabilities::prompt_state::PromptSnapshot; use dim_agent_capabilities::session_broadcast::{ SessionBroadcast, SessionBroadcastEvent, session_channel, }; use dim_agent_runtime::{BranchStatus, ModelProgress}; use dim_agent_types::{AgentEvent, EventKind, ROOT_BRANCH_ID}; use futures_util::{StreamExt, future::BoxFuture as Pending, stream::FuturesUnordered}; use rutis::Disposer; use rutis::host::FiberStatusChanged; use std::{collections::HashMap, sync::atomic::AtomicBool}; use tokio::sync::{mpsc, watch}; use tokio_util::task::TaskTracker; /// Replacing, detaching or closing ends the subscription and its listener. pub(super) struct Attachment { pub generation: u64, /// Released when the attachment is dropped, after `retire` awaited the /// work below. pub _usage: crate::agents::SessionUse, pub cancel: CancellationToken, pub listener: Option, /// v3: signals plugin activation, so a reloaded progress cell is reacquired. pub availability: Option, /// The `follow` and `follow_mcp` tasks this subscription spawned. pub tasks: TaskTracker, pub delivery: Arc, } impl Attachment { /// Ends the subscription and waits until nothing of it remains: the /// listeners are disposed, the tasks it spawned have returned, and the /// usage is released last, so a later attach, detach or finish starts /// from none of it. Disposal errors are logged, never dropped. When the /// follow task ends the Session itself it removes its own attachment and /// this value is dropped instead; that runs off-thread, so `finish` /// settles such a subscription by its absence from the map. pub(super) async fn retire(mut self) { self.cancel.cancel(); for disposer in [self.listener.take(), self.availability.take()] .into_iter() .flatten() { if let Err(error) = disposer.dispose().await { tracing::warn!(%error, "subscription listener disposal failed"); } } self.tasks.close(); self.tasks.wait().await; } } impl Drop for Attachment { /// The fallback that cannot wait: the Session ended and the follow task /// removed its own attachment, or the attach reply could not be sent. /// Cancels and runs the listener disposal off-thread. fn drop(&mut self) { self.cancel.cancel(); for listener in [self.listener.take(), self.availability.take()] .into_iter() .flatten() { tokio::spawn(listener.dispose()); } } } /// Changes within this interval reach a connection as one progress notice. const PROGRESS_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50); type ProgressChange = Pending<'static, (String, Option>)>; fn progress_change(branch: String, mut receiver: watch::Receiver) -> ProgressChange { Box::pin(async move { if receiver.changed().await.is_err() { return (branch, None); } tokio::time::sleep(PROGRESS_INTERVAL).await; (branch, Some(receiver)) }) } /// v3 model progress of the watched branches (ADR agent-029). ModelProvider /// owns the cell and a reload replaces it, so every branch's current cell is /// looked up again when a plugin becomes active. #[derive(Default)] struct Progress { changes: FuturesUnordered, /// Watched branches and the cell each currently follows, if any. cells: HashMap>>, sent: HashMap, } impl Progress { /// Follows the branch's current cell, reporting its snapshot when the /// cell is new; false once the subscription is gone. fn follow( &mut self, connection: &Connection, session: &Session, generation: u64, branch: String, ) -> bool { let current = session.on::(&branch).ok().flatten(); let followed = self.cells.entry(branch.clone()).or_default(); let Some(mut receiver) = current else { *followed = None; return true; }; if followed .as_ref() .is_some_and(|old| old.same_channel(&receiver)) { return true; } *followed = Some(receiver.clone()); let snapshot = receiver.borrow_and_update().clone(); self.changes.push(progress_change(branch.clone(), receiver)); self.report(connection, session, generation, branch, snapshot) } /// Reports a change of a followed cell; a replaced cell's change is dropped. fn changed( &mut self, connection: &Connection, session: &Session, generation: u64, branch: String, receiver: Option>, ) -> bool { let Some(mut receiver) = receiver else { return true; }; let followed = matches!( self.cells.get(&branch), Some(Some(followed)) if followed.same_channel(&receiver) ); if !followed { return true; } let snapshot = receiver.borrow_and_update().clone(); self.changes.push(progress_change(branch.clone(), receiver)); self.report(connection, session, generation, branch, snapshot) } /// A plugin became active: a reloaded ModelProvider has a new cell. fn reacquire(&mut self, connection: &Connection, session: &Session, generation: u64) -> bool { let branches: Vec<_> = self.cells.keys().cloned().collect(); branches .into_iter() .all(|branch| self.follow(connection, session, generation, branch)) } fn report( &mut self, connection: &Connection, session: &Session, generation: u64, branch: String, progress: ModelProgress, ) -> bool { if self.sent.get(&branch) == Some(&progress) { return true; } self.sent.insert(branch.clone(), progress.clone()); connection.notify( session.id(), generation, Notification::ModelProgress(wire::ModelProgressNotice::new( session.id().to_owned(), branch, progress, )), ) } } enum Signal { /// A v2 branch without a state watch produced an event. Branch(String), /// The Session channel ended: every broadcast event was delivered. Closed, } /// One subscription's observation progress, independent of Session execution. pub(super) struct Delivery { ctx: Ctx, session_id: String, recipient: String, issued: Mutex, reached: watch::Sender, cancel: CancellationToken, } impl Delivery { pub async fn wait(&self) -> Result<(), RpcError> { let mut reached = self.reached.subscribe(); let token = { let mut issued = self.issued.lock().expect("delivery fence"); if *reached.borrow() == u64::MAX { return Ok(()); } if self.cancel.is_cancelled() { return Err(subscription_changed()); } *issued += 1; let _ = self.ctx.emit(SessionBroadcast::new( &self.session_id, SessionBroadcastEvent::Fence { recipient: self.recipient.clone(), token: *issued, }, )); *issued }; loop { if *reached.borrow_and_update() >= token { return Ok(()); } tokio::select! { _ = self.cancel.cancelled() => { return if *reached.borrow() >= token { Ok(()) } else { Err(subscription_changed()) }; } _ = reached.changed() => {}, } } } } fn subscription_changed() -> RpcError { RpcError::app( -32000, "subscription_changed", "Session subscription changed before delivery completed", ) } /// Projects broadcast records to this connection's notifications; never waits. struct Forward { connection: Weak, session_id: String, generation: u64, display: bool, /// `Closed` was seen: the subscription forwards no later notice, so /// `session.closed` stays its last Session notification. ended: AtomicBool, watched: Arc>>, signals: mpsc::UnboundedSender, delivery: Arc, } impl Forward { async fn on_event(&self, event: &SessionBroadcast) -> Result, Error> { match &event.record { SessionBroadcastEvent::Closed => { self.ended.store(true, Ordering::Relaxed); self.acknowledge(u64::MAX); let _ = self.signals.send(Signal::Closed); } // v3 only: the v1 and v2 notification sets are frozen (#278). SessionBroadcastEvent::Notice(notice) => { if !self.ended.load(Ordering::Relaxed) && let Some(connection) = self.connection.upgrade() && connection.protocol_version() >= 3 { connection.notify( &self.session_id, self.generation, Notification::Notice(wire::ForwardedNotice { session_id: self.session_id.clone(), notice: notice.clone(), }), ); } } SessionBroadcastEvent::Fence { recipient, token } => { if recipient == &self.delivery.recipient { self.acknowledge(*token); } } SessionBroadcastEvent::Event { branch_id, event } => { if let Some(connection) = self.connection.upgrade() { let version = connection.protocol_version(); if version >= 2 && !self.watched.lock().expect("watched").contains(branch_id) { let _ = self.signals.send(Signal::Branch(branch_id.clone())); } if let Some(notice) = project( version, self.display, &self.session_id, branch_id, event.clone(), ) { connection.notify(&self.session_id, self.generation, notice); } } } } Ok(None) } } impl Forward { fn acknowledge(&self, token: u64) { if let Some(connection) = self.connection.upgrade() { let attachments = connection.attachments.lock().expect("attachments"); if !connection.closed.is_cancelled() && attachments .get(&self.session_id) .is_some_and(|a| a.generation == self.generation) { self.delivery.reached.send_if_modified(|reached| { if token > *reached { *reached = token; true } else { false } }); } } } } /// v1 carries main business events; approvals of every branch keep their /// v1 notifications. v2 carries every branch. fn project( version: u32, display: bool, session_id: &str, branch_id: &str, event: Arc, ) -> Option { if display && let Some(item) = wire::CompactionItem::new(&event) { return Some(Notification::Display(wire::DisplayNotice { session_id: session_id.to_owned(), branch_id: branch_id.to_owned(), item, })); } match &event.kind { EventKind::ApprovalRequest(data) => Some(approval_request( version, session_id, branch_id.to_owned(), data.clone(), )), EventKind::ApprovalCancelled(data) if version == 1 => { Some(Notification::ApprovalCancelled(ApprovalCancelled { session_id: session_id.to_owned(), request_id: data.approval_id.clone(), reason: data.reason.clone(), })) } EventKind::ApprovalCancelled(data) => Some(Notification::TreeApprovalCancelled( wire::ApprovalCancelled { session_id: session_id.to_owned(), branch_id: branch_id.to_owned(), request_id: data.approval_id.clone(), reason: data.reason.clone(), }, )), // v3 only: the v1 and v2 notification sets are frozen (#278). EventKind::ApprovalRespond(data) if version >= 3 => { Some(Notification::TreeApprovalResolved(wire::ApprovalResolved { session_id: session_id.to_owned(), branch_id: branch_id.to_owned(), request_id: data.approval_id.clone(), decision: data.decision, })) } _ if version == 1 => (branch_id == ROOT_BRANCH_ID && event.parent_call_id.is_none()) .then(|| dim_agent_types::v1::SharedEvent::new(event)) .flatten() .map(|event| { Notification::Event(EventNotice { session_id: session_id.to_owned(), event, }) }), _ => wire::ProductEvent::new(event, version).map(|event| { Notification::TreeEvent(wire::EventNotice { session_id: session_id.to_owned(), branch_id: branch_id.to_owned(), event, }) }), } } fn approval_request( version: u32, session_id: &str, branch_id: String, request: dim_agent_types::ApprovalRequestData, ) -> Notification { if version == 1 { Notification::ApprovalRequest(ApprovalRequest { session_id: session_id.to_owned(), request_id: request.approval_id, call: ApprovalCall { name: request.call.name, input: request.call.input, }, reason: request.reason, }) } else { Notification::TreeApprovalRequest(wire::ApprovalRequest { session_id: session_id.to_owned(), branch_id, request_id: request.approval_id, source: request.source, call: request.call, reason: request.reason, }) } } fn state_notice( version: u32, session_id: &str, branch_id: &str, status: &BranchStatus, ) -> Notification { if version == 1 { Notification::State(StateNotice { session_id: session_id.to_owned(), running: status.running, stopping: status.stopping, }) } else { Notification::BranchState(wire::StateNotice { session_id: session_id.to_owned(), state: wire::BranchState::new(branch_id.to_owned(), status), }) } } /// One branch's next state, or `None` for its receiver, which means the line /// is gone: it is reported once as ended instead of being dropped unread /// ([#2027]). /// A watched line's next status change. The selected [`Line`] travels with /// its receiver, so a change is read from the line that was watched, also /// while that line is closing, instead of selecting it again by id ([#2227]). /// /// [`Line`]: dim_agent_runtime::Line /// [#2227]: https://github.com/arcships/dim/pull/2227 type StateChange = Pending< 'static, Option<( String, Option<(dim_agent_runtime::Line, watch::Receiver<()>)>, )>, >; fn state_change( id: String, line: dim_agent_runtime::Line, mut receiver: watch::Receiver<()>, ) -> StateChange { Box::pin(async move { match receiver.changed().await { // The status sender went with the line: report that it ended. Err(_) => Some((id, None)), Ok(()) => Some((id, Some((line, receiver)))), } }) } impl Connection { /// Replies the attached Session's directory record, then forwards the /// Session broadcast from this point on. Events before the listener are /// not replayed; pending approvals are. pub(super) async fn attach( self: &Arc, rpc: &Arc, id: RequestId, params: Attach, usage: crate::agents::SessionUse, ) -> Result<(), RpcError> { let (host, session) = rpc .index .session(¶ms.session_id) .ok_or_else(RpcError::closed)?; let version = self.protocol_version(); if params.display && version < 3 { return Err(RpcError::invalid("display requires protocol v3")); } let session_id = session.id().to_owned(); let _transition = self.transitions.lock().await; if session.is_closing() { return Err(RpcError::closed()); } let mut record = rpc .index .session_record(&host, &session, version) .await .map_err(RpcError::from)?; // The transition lock keeps one attach, detach or finish in flight per // connection. When this attach replaces an existing attachment, the new // one is in place before the previous retires, so every event committed // after this reply's pin has a listener: the previous one until the map // changes, this one after. With no previous attachment — a first // attach, or a detach that completed first — events committed between // the pin and the new listener have none. if let Some(expected) = ¶ms.expected_config { // Feature `testing`: a test holds the check after this record is // captured, moves the default away and ends the former default, // then releases it. #[cfg(feature = "testing")] if let Some(hold) = self.hub.take_attach_check_hold() { hold.entered.notify_one(); hold.release.notified().await; } crate::agents::check_configuration( &session, session.config(), &record.default_branch, expected, ) .await?; } let mut scoped_admission = None; if let Some(provider) = rpc.ctx.get::() { let current = session .get::(ROOT_BRANCH_ID)? .and_then(|snapshot| snapshot.configuration); let model = current.map_or_else( || session.config().model.clone(), |model| dim_agent_types::ModelSelection { provider_id: model.provider_id, model_id: model.model_id, capability_snapshot: model.capability_snapshot, config: model.config, metadata: model.metadata, }, ); provider.scoped_connection_owner(&self.id, model.metadata.as_ref(), false)?; if !self.is_attached(&session_id) && let Some(route) = provider.scoped_model(&self.id, &model)? { let admission = self.scoped_route_admission(rpc, &usage).await?; if rpc_line(rpc.index.as_ref(), session.id(), ROOT_BRANCH_ID)?.sequence() != record.info.sequence { return Err(RpcError::service( "provider_route_conflict", "Session advanced before temporary route adoption", )); } let outcome = session .configure( dim_agent_runtime::ConfigureUpdate { model: Some(route.model.clone()), ..Default::default() }, ROOT_BRANCH_ID, ) .await?; configuration_outcome(outcome)?; if let Err(error) = provider.retain_startup(&session, &route.model) { let rollback = session .configure( dim_agent_runtime::ConfigureUpdate { model: Some(model), ..Default::default() }, ROOT_BRANCH_ID, ) .await?; configuration_outcome(rollback)?; return Err(provider_error(error)); } record.info.sequence = rpc_line(rpc.index.as_ref(), session.id(), ROOT_BRANCH_ID)?.sequence(); if record.default_branch.branch_id == ROOT_BRANCH_ID { record.default_branch.sequence = record.info.sequence; } scoped_admission = Some(admission); } } let SessionRecord { info: record_info, default_branch: record_default, } = record; let generation = self.next_attachment.fetch_add(1, Ordering::Relaxed); let cancel = self.closed.child_token(); let watched = Arc::new(Mutex::new(HashSet::new())); let (signals, receiver) = mpsc::unbounded_channel(); let delivery = Arc::new(Delivery { ctx: host.ctx.clone(), session_id: session_id.clone(), recipient: uuid::Uuid::new_v4().to_string(), issued: Mutex::new(0), reached: watch::channel(0).0, cancel: cancel.clone(), }); let forward = Arc::new(Forward { connection: Arc::downgrade(self), session_id: session_id.clone(), generation, display: params.display, ended: AtomicBool::new(false), watched: watched.clone(), signals, delivery: delivery.clone(), }); #[cfg(feature = "testing")] if self.hub.take_attach_failure_before_registration() { return Err(RpcError::closed()); } // An idle shutdown that has decided to close the daemon refuses the // attach; before that decision, the attachment below is registered // and counted. The guard covers the registration only, so it is // dropped before the previous subscription settles. let admitted = self.hub.admit()?; let listener = host .ctx .listen::() .name(session_channel(&session_id)) .on(move |event, _| { let forward = forward.clone(); async move { forward.on_event(&event).await } }) .map_err(|_| RpcError::closed())?; let (signal, active) = watch::channel(()); let availability = if version >= 3 { let availability = Arc::new(super::mcp::Availability(signal)); match host.ctx.on::(move |event, call| { let availability = availability.clone(); async move { let ctx = call.ctx().clone(); availability.on_event(&ctx, &event, call).await } }) { Ok(availability) => Some((availability, active)), Err(_) => { tokio::spawn(listener.dispose()); return Err(RpcError::closed()); } } } else { None }; let (availability, active) = availability.unzip(); let ended = session.is_closing(); let tasks = TaskTracker::new(); // The reply carries the count this attach produces. The hub reads every // connection's attachment map, including this one's, and the reply must // be sent under that same map so no notice precedes it. let attached_clients = self.hub.attached_clients(&session_id) + usize::from(!self.is_attached(&session_id)); let previous = { let mut attachments = self.attachments.lock().expect("attachments"); let previous = attachments.insert( session_id.clone(), Attachment { _usage: usage, generation, cancel: cancel.clone(), listener: Some(listener), availability, tasks: tasks.clone(), delivery, }, ); let adopted = session .get::(ROOT_BRANCH_ID) .ok() .flatten() .and_then(|snapshot| snapshot.configuration); let (model, model_preferences, capability_snapshot, catalog_provider_id) = match adopted { Some(configuration) => ( dim_agent_types::ModelId { provider_id: configuration.provider_id.clone(), model_id: configuration.model_id.clone(), }, crate::provider::adopted_selection_preferences( configuration.config.as_ref(), configuration.metadata.as_ref(), ), configuration.capability_snapshot, crate::provider::scoped_routes::logical_provider( configuration.metadata.as_ref(), ) .map(str::to_owned), ), None => ( record_info.model.clone(), crate::provider::adopted_selection_preferences( session.config().model.config.as_ref(), session.config().model.metadata.as_ref(), ), session.config().model.capability_snapshot.clone(), crate::provider::scoped_routes::logical_provider( session.config().model.metadata.as_ref(), ) .map(str::to_owned), ), }; let record = SessionInfo { attached_clients, model, ..record_info }; let reply = AttachResult { session: record, default_branch: record_default, model_preferences, capability_snapshot: capability_snapshot.map(Box::new), catalog_provider_id, }; if self .sender .send(Outbound::result(id, Ok(Reply::Attach(reply))), false) .is_err() { attachments.remove(&session_id); return Err(RpcError::wire(-32603, "Connection closed")); } previous }; drop(admitted); drop(scoped_admission); // The previous subscription settles before this attach returns, but // after the new one is in place: its own listeners and tasks cannot // strand an event committed from now on. if let Some(previous) = previous { previous.retire().await; } self.hub.notify_clients(&session_id); crate::approval::replay(&session, |branch_id, request| { self.notify( &session_id, generation, approval_request(version, &session_id, branch_id.to_owned(), request.clone()), ); }); if version >= 3 && rpc.mcp.is_some() { let this = self.clone(); let host = host.clone(); let session = session.clone(); let cancel = cancel.clone(); tasks.spawn(async move { this.follow_mcp(host, session, generation, cancel).await; }); } let this = self.clone(); let followed = session_id.clone(); tasks.spawn(async move { this.follow( session, generation, cancel, watched, receiver, active, ended, ) .await; let mut attachments = this.attachments.lock().expect("attachments"); if attachments .get(&followed) .is_some_and(|a| a.generation == generation) { attachments.remove(&followed); this.hub.ui.detach(&this.id, &followed); this.hub.notify_clients(&followed); } }); Ok(()) } /// The line `session` names, through the current holder's index: a /// reloaded handler is read again, so a following connection sees the /// generation that holds the Session now. /// The line `session` names, answering `branch_ended` for a line the tree /// has ended: a read or write on it is the one the facade refused before. pub(super) fn line_ended_aware( &self, session: &Session, branch: &str, ) -> Result { match self.line(session, branch) { Ok(line) => Ok(line), Err(_) if session.ended_head(branch).is_some() => Err(RpcError::from( dim_agent_runtime::AgentError::BranchEnded(branch.to_owned()), )), Err(error) => Err(error), } } pub(super) fn line( &self, session: &Session, branch: &str, ) -> Result { self.hub .with_rpc(|rpc| rpc.index.line(session.id(), branch))? .map_err(RpcError::from) } /// Branch states (v3: and model progress) until the Session channel /// ends, then `session.closed`. #[expect( clippy::too_many_arguments, reason = "one parameter per part of the follow loop's state" )] async fn follow( &self, session: Session, generation: u64, cancel: CancellationToken, watched: Arc>>, mut signals: mpsc::UnboundedReceiver, mut active: Option>, mut ended: bool, ) { #[cfg(feature = "testing")] if let Some(hold) = self.hub.take_follow_hold() { hold.waiting.notify_one(); tokio::select! { _ = cancel.cancelled() => { hold.cancelled.notify_one(); hold.release.notified().await; } _ = hold.release.notified() => {} } } let version = self.protocol_version(); let id = session.id().to_owned(); let mut watches = FuturesUnordered::::new(); let mut reported = HashMap::::new(); let mut progress = active.is_some().then(Progress::default); let watch_branch = |branch: String, watches: &mut FuturesUnordered, reported: &mut HashMap, progress: &mut Option| { let Ok(line) = self.line(&session, &branch) else { if session.ended_head(&branch).is_some() { let closed = BranchStatus { closed: true, ..Default::default() }; if reported.get(&branch) != Some(&closed) { if !self.notify( &id, generation, state_notice(version, &id, &branch, &closed), ) { return false; } reported.insert(branch.clone(), closed); } } return true; }; let mut receiver = line.watch(); watched.lock().expect("watched").insert(branch.clone()); receiver.borrow_and_update(); let sent = match line.context().state() { Ok(current) => { let sent = self.notify( &id, generation, state_notice(version, &id, &branch, ¤t), ); reported.insert(branch.clone(), current); sent } Err(dim_agent_runtime::AgentError::Reloading(_)) => true, Err(_) => return true, }; watches.push(state_change(branch.clone(), line, receiver)); match progress { Some(progress) if sent => progress.follow(self, &session, generation, branch), _ => sent, } }; let branches: Vec<_> = if version == 1 { vec![ROOT_BRANCH_ID.to_owned()] } else { session.branches().into_iter().map(|info| info.id).collect() }; for branch in branches { if !watch_branch(branch, &mut watches, &mut reported, &mut progress) { return; } } while !ended { tokio::select! { biased; _ = cancel.cancelled() => return, signal = signals.recv() => match signal { Some(Signal::Branch(branch)) => { let known = watched.lock().expect("watched").contains(&branch); if !known && !watch_branch(branch, &mut watches, &mut reported, &mut progress) { return; } } Some(Signal::Closed) | None => ended = true, }, changed = watches.next(), if !watches.is_empty() => { let Some(Some((branch, receiver))) = changed else { continue; }; let Some((line, mut receiver)) = receiver else { // The line's status sender went with it: the branch // ended, and a client attached to it still needs that // answer ([#2027]). let gone = BranchStatus { closed: true, ..Default::default() }; if reported.get(&branch) != Some(&gone) { let notice = state_notice(version, &id, &branch, &gone); if !self.notify(&id, generation, notice) { return; } reported.insert(branch, gone); } continue; }; receiver.borrow_and_update(); match line.context().state() { Ok(next) => { if reported.get(&branch) != Some(&next) { let notice = state_notice(version, &id, &branch, &next); if !self.notify(&id, generation, notice) { return; } reported.insert(branch.clone(), next.clone()); } if !next.closed { watches.push(state_change(branch, line, receiver)); } } // The owner reloads under the line: the next change // reads it again. Err(dim_agent_runtime::AgentError::Reloading(_)) => { watches.push(state_change(branch, line, receiver)); } // The line's state is no longer readable: it ended, or // it went with its Session. A client that was watching // it still needs that answer, so it is reported as // ended rather than dropped unread ([#2027]). Err(_) => { let closed = BranchStatus { closed: true, ..Default::default() }; if reported.get(&branch) != Some(&closed) { let notice = state_notice(version, &id, &branch, &closed); if !self.notify(&id, generation, notice) { return; } reported.insert(branch, closed); } } } } changed = async { match &mut progress { Some(progress) if !progress.changes.is_empty() => { progress.changes.next().await } _ => std::future::pending().await, } } => { let progress = progress.as_mut().expect("progress follows v3"); if let Some((branch, receiver)) = changed && !progress.changed(self, &session, generation, branch, receiver) { return; } } result = async { match &mut active { Some(active) => active.changed().await, None => std::future::pending().await, } } => { if result.is_err() { active = None; continue; } let progress = progress.as_mut().expect("progress follows v3"); if !progress.reacquire(self, &session, generation) { return; } } } } let cleanup = tokio::select! { biased; _ = cancel.cancelled() => return, result = session.closed() => result, }; let branches: Vec<_> = if version == 1 { vec![ROOT_BRANCH_ID.to_owned()] } else { session.branches().into_iter().map(|info| info.id).collect() }; for branch in branches { // A line that went with the Session reads closed: the client still // needs the notice that ends its branch, and the Session's own // `closed` notice follows. let status = self .line(&session, &branch) .and_then(|line| line.context().state().map_err(RpcError::from)) .unwrap_or(dim_agent_runtime::BranchStatus { closed: true, ..Default::default() }); if !self.notify( &id, generation, state_notice(version, &id, &branch, &status), ) { return; } } self.notify( &id, generation, Notification::Closed(ClosedNotice { session_id: id.clone(), reason: cleanup .err() .map(|_| "Session cleanup failed".to_owned()) .or_else(|| session.failure().map(|_| "Session failed".to_owned())), }), ); } pub(super) fn notify(&self, id: &str, generation: u64, notice: Notification) -> bool { let attachments = self.attachments.lock().expect("attachments"); if !attachments .get(id) .is_some_and(|a| a.generation == generation) { return false; } self.sender.send(Outbound::notice(notice), false).is_ok() } }