Skip to main content

trusty_code/serve/rest/
agents.rs

1//! `GET /sessions/{id}/agents` REST route over the `session.get_agents`
2//! JSON-RPC method (#2983 Slice 6).
3//!
4//! Why: DOC-39 §5.4 names `session.get_agents` "the principled endpoint" a
5//! late-attaching UI client needs to ask "who is running right now?" for one
6//! session, without folding the SSE ring-buffer replay itself (see
7//! `crate::session::protocol_agents` module docs). As with every route in
8//! this gateway, the handler stays thin — extract the path param, call
9//! `super::respond` — because the actual behaviour (the live per-agent
10//! roster fold, `-32007 session_not_found` mapping) already lives in
11//! `crate::session::registry_agents`/`protocol_agents`; duplicating it here
12//! would fork the two surfaces (see `super` module docs).
13//! What: [`routes`] builds a standalone `axum::Router<()>` (its own
14//! `AgentsState` carrying just the `Arc<Router>`, `with_state`-erased before
15//! return, mirroring `super::sessions::SessionsState`) mapping
16//! `GET /sessions/{id}/agents` -> `session.get_agents`.
17//!
18//! **Deviation from the literal `GET /agents` shape:** `session.get_agents`
19//! REQUIRES a `session_id` param (verified in
20//! `crate::session::protocol_agents::get_agents` and
21//! `crate::session::protocol::SessionIdParams`) — there is no roster
22//! independent of a session. A bare `GET /agents` route would therefore have
23//! nothing to forward as `session_id`. Nesting it under `/sessions/{id}`
24//! instead is both correct per the RPC's actual signature AND consistent
25//! with how Slice 2 (`super::sessions`) already nests every other
26//! session-scoped read route (`.../transcript`, `.../readiness`,
27//! `.../goals`) — `/sessions/{id}/agents` slots into that same family.
28//! `crate::serve::http::build_axum_router` merges this into the daemon's main
29//! router alongside `POST /rpc`, `GET /health`, `GET /sessions/{id}/events`,
30//! and the other REST resource groups. `/sessions/{id}/agents` does not
31//! collide with any path Slice 2/3 already registered under `/sessions/{id}`.
32//! Test: `tests::*`.
33
34use std::sync::Arc;
35
36use axum::Router as AxumRouter;
37use axum::extract::{Path, State};
38use axum::routing::get;
39use serde_json::json;
40
41use crate::jsonrpc::Router;
42
43use super::{RestResult, respond};
44
45/// Shared axum state for the route in this module: just the JSON-RPC
46/// router, mirroring `super::sessions::SessionsState` — the handler goes
47/// through [`super::respond`] rather than touching `SessionRegistry`
48/// directly.
49#[derive(Clone)]
50struct AgentsState {
51    router: Arc<Router>,
52}
53
54/// Build the `GET /sessions/{id}/agents` route group.
55///
56/// Why: kept separate from `crate::serve::http::build_axum_router` so this
57/// resource group is unit-testable via `tower::util::ServiceExt::oneshot` on
58/// its own, exactly like every other `rest::*` group.
59/// What: one `GET` route, `AgentsState { router }`, `with_state`-erased to
60/// `axum::Router<()>` so the caller can `.merge()` it alongside the other
61/// resource groups into the daemon's main router.
62/// Test: `tests::get_agents_found_returns_200_with_empty_roster`.
63pub fn routes(router: Arc<Router>) -> AxumRouter {
64    AxumRouter::new()
65        .route("/sessions/{id}/agents", get(get_agents))
66        .with_state(AgentsState { router })
67}
68
69/// `GET /sessions/{id}/agents` -> `session.get_agents`.
70///
71/// Why: lets an operator/UI inspect who is running (or has run) within a
72/// session without pulling the larger transcript payload.
73/// What: `404` for an unknown `id`; otherwise `{"agents": [...]}` — `[]` for
74/// a session with no tool activity yet.
75/// Test: `tests::get_agents_found_returns_200_with_empty_roster`,
76/// `tests::get_agents_missing_returns_404_session_not_found`.
77async fn get_agents(State(state): State<AgentsState>, Path(id): Path<String>) -> RestResult {
78    respond(
79        &state.router,
80        "session.get_agents",
81        json!({"session_id": id}),
82    )
83    .await
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use axum::body::{Body, to_bytes};
90    use axum::http::{Request, StatusCode};
91    use serde_json::Value;
92    use tower::util::ServiceExt;
93
94    /// Build a router wired with every `session.*` method plus a fresh
95    /// `SessionRegistry`, then this module's route group over it — mirrors
96    /// `sessions::tests::app_and_registry`.
97    async fn app_and_registry() -> (AxumRouter, Arc<crate::session::SessionRegistry>) {
98        let sessions = Arc::new(crate::session::SessionRegistry::new());
99        let mut router = Router::new();
100        crate::session::protocol::register(
101            &mut router,
102            sessions.clone(),
103            crate::workstreams::test_shared_store().await,
104        );
105        let app = routes(Arc::new(router));
106        (app, sessions)
107    }
108
109    async fn body_json(response: axum::response::Response) -> Value {
110        let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
111        serde_json::from_slice(&bytes).unwrap()
112    }
113
114    async fn get(app: &AxumRouter, uri: &str) -> axum::response::Response {
115        app.clone()
116            .oneshot(
117                Request::builder()
118                    .method("GET")
119                    .uri(uri)
120                    .body(Body::empty())
121                    .unwrap(),
122            )
123            .await
124            .unwrap()
125    }
126
127    /// `GET /sessions/{id}/agents` on a real session with no tool activity
128    /// yet must return `200` with an empty `agents` array, not an error.
129    #[tokio::test]
130    async fn get_agents_found_returns_200_with_empty_roster() {
131        let (app, sessions) = app_and_registry().await;
132        let session = sessions.create("t".to_string(), None, crate::binding::ProjectBinding::None);
133
134        let resp = get(&app, &format!("/sessions/{}/agents", session.id)).await;
135        assert_eq!(resp.status(), StatusCode::OK);
136        let v = body_json(resp).await;
137        assert_eq!(v["agents"].as_array().unwrap().len(), 0);
138    }
139
140    /// `GET /sessions/{id}/agents` on an unknown id must be a real `404` with
141    /// a `session_not_found` envelope.
142    #[tokio::test]
143    async fn get_agents_missing_returns_404_session_not_found() {
144        let (app, _sessions) = app_and_registry().await;
145
146        let resp = get(&app, "/sessions/does-not-exist/agents").await;
147        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
148        let v = body_json(resp).await;
149        assert_eq!(v["error"]["code"], -32007);
150    }
151}