use std::sync::atomic::Ordering;
use agent_client_protocol::{
v1::schema::{
CloseSessionRequest, CloseSessionResponse, DeleteSessionRequest, DeleteSessionResponse,
SessionId as AcpSessionId,
},
Error as AcpError,
};
use rho_protocol::{
methods::{SessionBackgroundHold, SessionBackgroundStop, SessionDelete, SessionDetach},
BackgroundItem, DeleteWork, ErrorCode, SessionBackgroundHoldParams,
SessionBackgroundStopParams, SessionDeleteParams, SessionDetachParams, SessionId,
};
use super::{lock, Attachment, Live};
use crate::app::acp::{daemon, Adapter};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::app::acp) enum Close {
Detach,
Stop,
}
impl Close {
fn delete_work(self) -> DeleteWork {
match self {
Self::Detach => DeleteWork::Refuse,
Self::Stop => DeleteWork::Stop,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Wait {
Prompt,
Job,
}
impl Adapter {
pub(super) async fn detach(&self, live: &Live, wait: Wait) {
live.closing.store(true, Ordering::Release);
if live.prompt.try_lock().is_err() {
self.cancel_live(live).await;
drop(live.prompt.lock().await);
if wait == Wait::Job {
let mut attachment = live.shared.attachment.subscribe();
let _ = attachment.wait_for(|attachment| !attachment.busy()).await;
}
}
self.release(live).await;
}
async fn stop(&self, live: &Live) {
live.closing.store(true, Ordering::Release);
self.hold_results(live).await;
self.cancel_live(live).await;
drop(live.prompt.lock().await);
let mut attachment = live.shared.attachment.subscribe();
let _ = attachment.wait_for(|attachment| !attachment.busy()).await;
self.hold_results(live).await;
let attached = matches!(*live.shared.attachment.borrow(), Attachment::Attached(_));
if let (true, Some(link)) = (attached, self.daemon.current().await) {
let running: Vec<BackgroundItem> = lock(&live.shared.background)
.iter()
.filter(|work| work.status.is_running())
.map(|work| work.item.clone())
.collect();
for work in running {
let params = SessionBackgroundStopParams {
session: live.id.clone(),
work,
};
if let Err(error) = link.request::<SessionBackgroundStop>(¶ms).await {
tracing::debug!(%error, "could not stop an ACP session's background work");
}
}
}
self.release(live).await;
}
async fn hold_results(&self, live: &Live) {
let Some(link) = self.daemon.current().await else {
return;
};
let params = SessionBackgroundHoldParams {
session: live.id.clone(),
};
if let Err(error) = link.request::<SessionBackgroundHold>(¶ms).await {
tracing::debug!(%error, "could not hold an ACP session's background results");
}
}
async fn release(&self, live: &Live) {
let attachment = *live.shared.attachment.borrow();
self.forget(live);
live.inbound.closed().await;
live.asks.withdrawn().await;
if let Some(port) = self.negotiated.client() {
port.released(&AcpSessionId::new(live.id.as_str()));
}
if !matches!(attachment, Attachment::Attached(_)) {
return;
}
if let Some(link) = self.daemon.current().await {
let params = SessionDetachParams {
session: live.id.clone(),
};
if let Err(error) = link.request::<SessionDetach>(¶ms).await {
tracing::debug!(%error, "could not detach an ACP session");
}
}
}
pub(super) fn forget(&self, live: &Live) {
self.daemon.unroute(&live.id);
live.pump.abort();
}
pub(in crate::app::acp) async fn close_session(
&self,
request: &CloseSessionRequest,
close: Close,
) -> Result<CloseSessionResponse, AcpError> {
if let Some(live) = self.sessions.remove(&request.session_id.0) {
match close {
Close::Detach => self.detach(&live, Wait::Prompt).await,
Close::Stop => self.stop(&live).await,
}
}
Ok(CloseSessionResponse::new())
}
pub(in crate::app::acp) async fn close_all(&self) {
for live in self.sessions.take_all() {
self.detach(&live, Wait::Prompt).await;
}
let _ = self.herdr.release().await;
}
pub(in crate::app::acp) async fn delete_session(
&self,
request: &DeleteSessionRequest,
close: Close,
) -> Result<DeleteSessionResponse, AcpError> {
if let Some(live) = self.sessions.remove(&request.session_id.0) {
match close {
Close::Detach => self.detach(&live, Wait::Job).await,
Close::Stop => self.stop(&live).await,
}
}
let params = SessionDeleteParams {
session: SessionId::new(request.session_id.0.as_ref()),
unless_attached: false,
work: close.delete_work(),
};
let link = self.daemon.link().await?;
match link.request::<SessionDelete>(¶ms).await {
Ok(_) => {}
Err(error) if error.error_code() == Some(ErrorCode::SessionNotFound) => {}
Err(error) => return Err(daemon::daemon_error(&error)),
}
Ok(DeleteSessionResponse::new())
}
}