//! The room turn runner. Filled in below. use std::collections::HashMap; use std::sync::atomic::AtomicBool; use std::sync::{Arc, Mutex}; use tokio::sync::mpsc; use crate::state::Shared; /// A wake signal for a room's turn task. #[derive(Debug, Clone, Copy)] pub enum Wake { /// A message was posted without mentioning the agent. Chat, /// A message mentioned the agent. Mention, } struct Handle { tx: mpsc::UnboundedSender, } /// The live turn tasks, one per room. #[derive(Default)] pub struct RoomRunner { handles: Mutex>, current: Mutex>>, } impl RoomRunner { /// Notifies the room's task that new work may be pending, spawning /// the task on first use. pub fn wake(&self, state: &Shared, room: &str, wake: Wake) { let mut handles = self.handles.lock().unwrap_or_else(|err| err.into_inner()); if let Some(handle) = handles.get(room) { let _ = handle.tx.send(wake); return; } let (tx, rx) = mpsc::unbounded_channel(); let _ = tx.send(wake); handles.insert(room.to_owned(), Handle { tx }); let room = room.to_owned(); let weak = std::sync::Arc::downgrade(state); tokio::spawn(async move { let Some(state) = weak.upgrade() else { return }; crate::room::runner::run(state, room, rx).await; }); } /// Records the cancel flag of the turn now running in `room`. pub fn set_current(&self, room: &str, cancel: Arc) { self.current .lock() .unwrap_or_else(|err| err.into_inner()) .insert(room.to_owned(), cancel); } /// Forgets the running turn. pub fn clear_current(&self, room: &str) { self.current .lock() .unwrap_or_else(|err| err.into_inner()) .remove(room); } /// Flips the running turn's cancel flag. False when nothing runs. pub fn interrupt(&self, room: &str) -> bool { let current = self.current.lock().unwrap_or_else(|err| err.into_inner()); match current.get(room) { Some(flag) => { flag.store(true, std::sync::atomic::Ordering::SeqCst); true } None => false, } } } pub mod agent; pub mod message_tool; pub mod preview_tool; pub mod runner;