use std::{sync::Arc, time::Duration};
use rho_protocol::{
methods::SessionMcp, SessionId, SessionMcpInventory, SessionMcpParams, SessionMcpStatus,
};
use crate::app::daemon_client::Link;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::tui) enum ToolSources {
Loading,
Loaded,
}
impl ToolSources {
fn of(inventory: &SessionMcpInventory) -> Self {
if inventory.tool_sources_loading
|| inventory
.servers
.iter()
.any(|server| server.status == SessionMcpStatus::Connecting)
{
Self::Loading
} else {
Self::Loaded
}
}
pub(super) async fn read(link: &Link, session: &SessionId) -> Self {
link.request::<SessionMcp>(&SessionMcpParams {
session: session.clone(),
})
.await
.map_or(Self::Loaded, |inventory| Self::of(&inventory))
}
}
const CHECK: Duration = Duration::from_millis(100);
pub(super) struct Watch(tokio::task::JoinHandle<()>);
impl Watch {
pub(super) fn of(
tool_sources: ToolSources,
link: &Arc<Link>,
session: &SessionId,
) -> Option<Self> {
match tool_sources {
ToolSources::Loading => {
let link = Arc::clone(link);
let session = session.clone();
Some(Self(tokio::spawn(async move {
loop {
tokio::time::sleep(CHECK).await;
match ToolSources::read(&link, &session).await {
ToolSources::Loading => {}
ToolSources::Loaded => break,
}
}
})))
}
ToolSources::Loaded => None,
}
}
}
impl Drop for Watch {
fn drop(&mut self) {
self.0.abort();
}
}
pub(super) async fn loaded(watch: &mut Option<Watch>) {
match watch {
Some(watch) => {
let _ = (&mut watch.0).await;
}
None => std::future::pending().await,
}
*watch = None;
}