use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(dead_code)] pub(crate) enum QueuePriority {
Now = 0,
Next = 1,
Later = 2,
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub(crate) struct QueuedCommand {
pub(crate) content: String,
pub(crate) priority: QueuePriority,
pub(crate) source: CommandSource,
pub(crate) agent_name: Option<String>,
}
impl QueuedCommand {
fn is_visible_to(&self, agent_name: Option<&str>) -> bool {
match (&self.agent_name, agent_name) {
(None, _) => true,
(Some(target), Some(name)) => target == name,
(Some(_), None) => false,
}
}
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub(crate) enum CommandSource {
UserInput,
TaskNotification { task_id: String },
}
pub(crate) struct CommandQueue {
inner: Arc<Mutex<VecDeque<QueuedCommand>>>,
}
impl CommandQueue {
pub(crate) fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(VecDeque::new())),
}
}
pub(crate) fn enqueue(&self, command: QueuedCommand) {
self.inner.lock().unwrap().push_back(command);
}
pub(crate) fn enqueue_notification(&self, task_id: &str, summary: &str) {
self.enqueue(QueuedCommand {
content: format!("Task {task_id} completed: {summary}"),
priority: QueuePriority::Later,
source: CommandSource::TaskNotification {
task_id: task_id.to_string(),
},
agent_name: None,
});
}
pub(crate) fn dequeue_if<F>(&self, agent_name: Option<&str>, pred: F) -> Option<QueuedCommand>
where
F: Fn(&QueuedCommand) -> bool,
{
let mut queue = self.inner.lock().unwrap();
let mut best: Option<(usize, QueuePriority)> = None;
for (i, cmd) in queue.iter().enumerate() {
if !cmd.is_visible_to(agent_name) {
continue;
}
if !pred(cmd) {
continue;
}
if best.as_ref().is_some_and(|(_, p)| *p <= cmd.priority) {
continue;
}
best = Some((i, cmd.priority.clone()));
if cmd.priority == QueuePriority::Now {
break;
}
}
best.and_then(|(i, _)| queue.remove(i))
}
}