171 lines
6.2 KiB
Rust
171 lines
6.2 KiB
Rust
//! The open todos an agent holds, for the swarm UI's agent card:
|
|
//! `GET /api/agents/{name}/todos`.
|
|
//!
|
|
//! The list is what the agent's harness last published into the `agent-todos`
|
|
//! bucket (`swarm_wire::agent_todos`); the controller only reads it. It comes
|
|
//! from the agent and is untrusted, so [`build`] cuts it down before serving
|
|
//! it. An agent that never published, or a host with no swarm queue, has no
|
|
//! todos to show: an empty list, not an error.
|
|
|
|
use axum::Json;
|
|
use axum::extract::{Path, State};
|
|
use axum::http::StatusCode;
|
|
use serde::Serialize;
|
|
use swarm_wire::agent_todos::{self, Todos};
|
|
use utoipa::ToSchema;
|
|
|
|
use crate::routes::AppState;
|
|
|
|
/// One open todo.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, ToSchema)]
|
|
pub(crate) struct TodoEntry {
|
|
/// The harness's own id for it.
|
|
pub id: i64,
|
|
/// What produced it: `matrix`, `forge`, `bash`, …
|
|
pub subsystem: String,
|
|
/// What it says, as one line.
|
|
pub summary: String,
|
|
/// Where it came from, when the producer says.
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub source: Option<String>,
|
|
/// When it was last updated, in seconds since the Unix epoch.
|
|
pub updated_unix: i64,
|
|
}
|
|
|
|
/// The list for an agent whose harness published `published` (or nothing),
|
|
/// newest first, cut to [`agent_todos::MAX_TODOS`] with each text one short
|
|
/// line.
|
|
fn build(published: Option<Todos>) -> Vec<TodoEntry> {
|
|
let mut entries: Vec<TodoEntry> = published
|
|
.unwrap_or_default()
|
|
.todos
|
|
.into_iter()
|
|
.map(|t| TodoEntry {
|
|
id: t.id,
|
|
subsystem: agent_todos::clip(&t.subsystem, agent_todos::MAX_LABEL_CHARS),
|
|
summary: agent_todos::clip(&t.summary, agent_todos::MAX_SUMMARY_CHARS),
|
|
source: t
|
|
.source
|
|
.map(|s| agent_todos::clip(&s, agent_todos::MAX_LABEL_CHARS))
|
|
.filter(|s| !s.is_empty()),
|
|
updated_unix: t.updated_unix,
|
|
})
|
|
.collect();
|
|
entries.sort_by_key(|e| std::cmp::Reverse(e.updated_unix));
|
|
entries.truncate(agent_todos::MAX_TODOS);
|
|
entries
|
|
}
|
|
|
|
#[utoipa::path(
|
|
get,
|
|
path = "/api/agents/{name}/todos",
|
|
params(("name" = String, Path, description = "agent whose open todos to list")),
|
|
responses(
|
|
(status = 200, description = "the open todos the agent's harness last published, \
|
|
newest first; empty when it has published none and on a host with no swarm queue",
|
|
body = Vec<TodoEntry>),
|
|
(status = 400, description = "the agent name is not shaped like an identifier \
|
|
(problem+json)", body = String),
|
|
(status = 503, description = "the swarm queue could not be reached \
|
|
(problem+json)", body = String),
|
|
(status = 500, description = "reading the agent's todos failed (problem+json)",
|
|
body = String),
|
|
),
|
|
tag = "agents"
|
|
)]
|
|
pub(crate) async fn list_todos(
|
|
State(state): State<AppState>,
|
|
Path(agent): Path<String>,
|
|
) -> Result<Json<Vec<TodoEntry>>, problem_details::ProblemDetails> {
|
|
let agent = hive_types::Ident::parse(&agent)
|
|
.map(hive_types::Ident::into_string)
|
|
.map_err(|reason| crate::routes::error_problem(StatusCode::BAD_REQUEST, reason))?;
|
|
let Some(status) = state.status.as_ref() else {
|
|
return Ok(Json(build(None)));
|
|
};
|
|
let client = status.queue_client();
|
|
swarm_queue_client::ensure_connected(&client).map_err(|e| {
|
|
crate::routes::error_problem(
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
&swarm_queue_client::chain(&e),
|
|
)
|
|
})?;
|
|
let js = async_nats::jetstream::new(client);
|
|
// The controller creates the bucket on a pass of `subagent_term::spawn`;
|
|
// until then nothing has published.
|
|
let published = match js.get_key_value(agent_todos::BUCKET).await {
|
|
Ok(store) => match store.get(&agent).await {
|
|
Ok(Some(bytes)) => serde_json::from_slice::<Todos>(&bytes)
|
|
.map_err(|e| {
|
|
tracing::warn!(%agent, error = %e, "agent todos: the published list is not readable");
|
|
})
|
|
.ok(),
|
|
Ok(None) => None,
|
|
Err(e) => return Err(read_failed(&agent, &e)),
|
|
},
|
|
Err(e) => {
|
|
tracing::debug!(%agent, error = %swarm_queue_client::chain(&e), "agent todos: the bucket is not readable");
|
|
None
|
|
}
|
|
};
|
|
Ok(Json(build(published)))
|
|
}
|
|
|
|
fn read_failed(agent: &str, e: &dyn std::error::Error) -> problem_details::ProblemDetails {
|
|
let detail = swarm_queue_client::chain(e);
|
|
tracing::warn!(%agent, error = %detail, "listing todos: reading the agent's todos failed");
|
|
crate::routes::error_problem(StatusCode::INTERNAL_SERVER_ERROR, &detail)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use swarm_wire::agent_todos::Todo;
|
|
|
|
fn todo(id: i64, summary: &str, updated_unix: i64) -> Todo {
|
|
Todo {
|
|
id,
|
|
subsystem: "forge".to_owned(),
|
|
summary: summary.to_owned(),
|
|
source: None,
|
|
updated_unix,
|
|
}
|
|
}
|
|
|
|
/// An agent that published nothing has nothing to show.
|
|
#[test]
|
|
fn nothing_published_is_an_empty_list() {
|
|
assert!(build(None).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn the_newest_todo_comes_first() {
|
|
let list = build(Some(Todos {
|
|
todos: vec![
|
|
todo(1, "old", 100),
|
|
todo(2, "new", 300),
|
|
todo(3, "mid", 200),
|
|
],
|
|
}));
|
|
let ids: Vec<i64> = list.iter().map(|e| e.id).collect();
|
|
assert_eq!(ids, [2, 3, 1]);
|
|
}
|
|
|
|
/// What the agent publishes is untrusted: the list and each text are cut.
|
|
#[test]
|
|
fn the_list_and_the_texts_are_cut() {
|
|
let many: Vec<Todo> = (0..i64::try_from(agent_todos::MAX_TODOS).expect("fits") + 20)
|
|
.map(|i| todo(i, &"w ".repeat(1000), i))
|
|
.collect();
|
|
let list = build(Some(Todos { todos: many }));
|
|
assert_eq!(list.len(), agent_todos::MAX_TODOS);
|
|
assert!(list[0].summary.chars().count() <= agent_todos::MAX_SUMMARY_CHARS);
|
|
}
|
|
|
|
#[test]
|
|
fn a_blank_source_is_left_out() {
|
|
let mut t = todo(1, "x", 1);
|
|
t.source = Some(" ".to_owned());
|
|
assert_eq!(build(Some(Todos { todos: vec![t] }))[0].source, None);
|
|
}
|
|
}
|