Skip to main content

trusty_code/serve/rest/
tasks.rs

1//! `POST /tasks` REST route over the `task.run` JSON-RPC method (#2983
2//! Slice 4).
3//!
4//! Why: Slices 2-3 (`super::sessions`/`super::sessions_write`) cover the
5//! `session.*` resource — but a REST-only client also needs the explicit
6//! "start executing" entry point `task.run` names (see
7//! `crate::task::protocol` module docs): mint-or-reuse a session and kick off
8//! a background LLM run against it. As with every route in this gateway, the
9//! handler stays thin — extract the body, build the JSON-RPC `params`, call
10//! `super::respond`/[`respond_accepted`] — because the actual behaviour
11//! (session resolution, `HarnessMode` precedence, slot reservation, …)
12//! already lives in `crate::task::protocol::task_run`; duplicating it here
13//! would fork the two surfaces (see `super` module docs).
14//! What: [`routes`] builds a standalone `axum::Router<()>` (its own
15//! `TasksState` carrying just the `Arc<Router>`, `with_state`-erased before
16//! return, mirroring `super::sessions::SessionsState`) mapping
17//! `POST /tasks` -> `task.run`.
18//! `crate::serve::http::build_axum_router` merges this into the daemon's main
19//! router alongside `POST /rpc`, `GET /health`, `GET /sessions/{id}/events`,
20//! and the `session.*` REST routes — `/tasks` collides with none of them.
21//! Test: `tests::*`.
22
23use std::sync::Arc;
24
25use axum::Json;
26use axum::Router as AxumRouter;
27use axum::extract::State;
28use axum::http::StatusCode;
29use axum::routing::post;
30use serde::Deserialize;
31use serde_json::{Value, json};
32use trusty_mcp::Response;
33
34use crate::jsonrpc::Router;
35
36use super::respond;
37
38/// Shared axum state for every route in this module: just the JSON-RPC
39/// router, mirroring `super::sessions::SessionsState` — the handler goes
40/// through [`respond_accepted`] rather than touching `SessionRegistry`
41/// directly.
42#[derive(Clone)]
43struct TasksState {
44    router: Arc<Router>,
45}
46
47/// Build the `POST /tasks` route group.
48///
49/// Why: kept separate from `crate::serve::http::build_axum_router` so this
50/// resource group is unit-testable via `tower::util::ServiceExt::oneshot` on
51/// its own, exactly like every other `rest::*` group.
52/// What: one `POST` route, `TasksState { router }`, `with_state`-erased to
53/// `axum::Router<()>` so the caller can `.merge()` it alongside the other
54/// resource groups into the daemon's main router.
55/// Test: `tests::run_task_returns_202_with_running_session`.
56pub fn routes(router: Arc<Router>) -> AxumRouter {
57    AxumRouter::new()
58        .route("/tasks", post(run_task))
59        .with_state(TasksState { router })
60}
61
62/// Request body for `POST /tasks`, shaped like `task::protocol`'s private
63/// `TaskRunRequestParams` — forwarded verbatim into the RPC `params` `Value`,
64/// so `task.run`'s own validation (empty `task_description`, unknown
65/// `session_id`, invalid `project`, …) applies identically either way.
66/// `project` stays a `String` here (mirroring `sessions_write::CreateBody`'s
67/// identical choice) — it is forwarded verbatim into the RPC `params`
68/// `Value`, and `task.run`'s own `PathBuf` deserialization +
69/// `ProjectBinding::resolve` apply identically either way (#3178).
70#[derive(Deserialize)]
71struct RunTaskBody {
72    task_description: String,
73    #[serde(default)]
74    agent_name: Option<String>,
75    #[serde(default)]
76    context: Option<String>,
77    #[serde(default)]
78    model_override: Option<String>,
79    #[serde(default)]
80    session_id: Option<String>,
81    #[serde(default)]
82    mode: Option<String>,
83    #[serde(default)]
84    deadline_secs: Option<u64>,
85    #[serde(default)]
86    project: Option<String>,
87    /// (Issue #3298) Forwarded verbatim to `task.run`'s own `workstream_id`
88    /// param — see `task::protocol`'s docs for the mint-vs-reuse resolution
89    /// rules.
90    #[serde(default)]
91    workstream_id: Option<String>,
92}
93
94/// Like [`super::respond`] but reports `202 Accepted` on success instead of
95/// the implicit `200` `Json<Value>` carries.
96///
97/// Why: `task.run` is deliberately asynchronous — it reserves the execution
98/// slot synchronously and then returns immediately, before the LLM run
99/// itself has produced any result; the caller observes progress via
100/// `session.attach`/`GET /sessions/{id}/events`, not this response body (see
101/// `crate::task::protocol` module docs). That is the textbook `202 Accepted`
102/// case ("the request has been accepted for processing, but the processing
103/// has not been completed") rather than `201 Created`: unlike `POST
104/// /sessions` (Slice 3), this route does not always mint a brand-new
105/// resource — a `session_id` in the body reuses an EXISTING session — so
106/// `201`'s "a new resource now exists at a location" framing does not fit
107/// uniformly. `200` would also be wrong: it implies the body already
108/// reflects the run's outcome, which it never does.
109/// What: delegates to [`respond`], then rewraps a successful `Json<Value>` as
110/// `(StatusCode::ACCEPTED, Json<Value>)`; the error arm is untouched —
111/// `rpc_error_to_status` already returns the correct 4xx/5xx.
112/// Test: `tests::run_task_returns_202_with_running_session`.
113async fn respond_accepted(
114    router: &Router,
115    method: &str,
116    params: Value,
117) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
118    respond(router, method, params)
119        .await
120        .map(|Json(v)| (StatusCode::ACCEPTED, Json(v)))
121}
122
123/// `POST /tasks` -> `task.run`.
124///
125/// Why: the REST entry point for "start executing a task", mint-or-reuse a
126/// session per `crate::task::protocol::task_run`'s docs.
127/// What: `202 Accepted` with `{session_id, status, mode, binding}` on
128/// success (see [`respond_accepted`] for the status-code rationale); `400`
129/// for an empty `task_description` or an invalid `project` (both `-32003
130/// invalid_argument`, #3178) or a syntactically malformed body (rejected by
131/// axum's `Json` extractor before this handler runs); `404` for an unknown
132/// `session_id` (`-32007 session_not_found`). `project` is forwarded
133/// verbatim to `task.run` — no independent resolution happens in this REST
134/// layer (see the module docs' "duplicating it here would fork the two
135/// surfaces" rationale).
136/// Test: `tests::run_task_returns_202_with_running_session`,
137/// `tests::run_task_empty_task_description_returns_400`,
138/// `tests::run_task_unknown_session_id_returns_404`,
139/// `tests::run_task_malformed_body_returns_400`,
140/// `tests::run_task_with_project_binds_a_real_directory`,
141/// `tests::run_task_invalid_project_returns_400`.
142async fn run_task(
143    State(state): State<TasksState>,
144    Json(body): Json<RunTaskBody>,
145) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
146    respond_accepted(
147        &state.router,
148        "task.run",
149        json!({
150            "task_description": body.task_description,
151            "agent_name": body.agent_name,
152            "context": body.context,
153            "model_override": body.model_override,
154            "session_id": body.session_id,
155            "mode": body.mode,
156            "deadline_secs": body.deadline_secs,
157            "project": body.project,
158            "workstream_id": body.workstream_id,
159        }),
160    )
161    .await
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use axum::body::{Body, to_bytes};
168    use axum::http::Request;
169    use std::sync::Arc as StdArc;
170    use tower::util::ServiceExt;
171
172    use crate::binding::ProjectBinding;
173    use crate::session::SessionRegistry;
174
175    /// Build a router wired with a real `task.run` (mock LLM, so no real
176    /// subprocess/network call happens), then this module's route group over
177    /// it — mirrors `sessions::tests::app_and_registry`.
178    async fn app_and_registry() -> (AxumRouter, StdArc<SessionRegistry>, tempfile::TempDir) {
179        let sessions = StdArc::new(SessionRegistry::new());
180        let agents = tempfile::tempdir().expect("agents tempdir");
181        std::fs::write(
182            agents.path().join("pm.md"),
183            "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM.\n",
184        )
185        .expect("write pm.md");
186        let project = tempfile::tempdir().expect("project tempdir");
187        let workstreams = crate::workstreams::test_shared_store().await;
188        let mut router = Router::new();
189        crate::session::protocol::register(&mut router, sessions.clone(), workstreams.clone());
190        crate::task::protocol::register(
191            &mut router,
192            sessions.clone(),
193            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
194            agents.path().to_path_buf(),
195            workstreams,
196        );
197        let app = routes(StdArc::new(router));
198        (app, sessions, project)
199    }
200
201    async fn body_json(response: axum::response::Response) -> Value {
202        let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
203        serde_json::from_slice(&bytes).unwrap()
204    }
205
206    async fn post(app: &AxumRouter, uri: &str, body: &str) -> axum::response::Response {
207        app.clone()
208            .oneshot(
209                Request::builder()
210                    .method("POST")
211                    .uri(uri)
212                    .header("content-type", "application/json")
213                    .body(Body::from(body.to_string()))
214                    .unwrap(),
215            )
216            .await
217            .unwrap()
218    }
219
220    /// A well-formed `POST /tasks` must return `202 Accepted` with a running
221    /// session.
222    #[tokio::test]
223    async fn run_task_returns_202_with_running_session() {
224        let _guard = crate::task::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
225        // SAFETY: test-only env mutation; serialized by `ENV_LOCK` above.
226        unsafe {
227            std::env::set_var(
228                crate::task::mock_llm::MOCK_LLM_ENV,
229                crate::task::mock_llm::MOCK_LLM_ECHO,
230            );
231        }
232        let (app, _sessions, _project) = app_and_registry().await;
233
234        let resp = post(&app, "/tasks", r#"{"task_description": "say hi"}"#).await;
235        unsafe {
236            std::env::remove_var(crate::task::mock_llm::MOCK_LLM_ENV);
237        }
238        assert_eq!(resp.status(), StatusCode::ACCEPTED);
239        let v = body_json(resp).await;
240        assert_eq!(v["status"], "running");
241    }
242
243    /// An empty `task_description` must map to `400` (`-32003
244    /// invalid_argument`).
245    #[tokio::test]
246    async fn run_task_empty_task_description_returns_400() {
247        let (app, _sessions, _project) = app_and_registry().await;
248
249        let resp = post(&app, "/tasks", r#"{"task_description": "   "}"#).await;
250        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
251        let v = body_json(resp).await;
252        assert_eq!(v["error"]["code"], -32003);
253    }
254
255    /// A `session_id` naming a session that does not exist must be a real
256    /// `404` with a `session_not_found` envelope — distinct from the `400`
257    /// above.
258    #[tokio::test]
259    async fn run_task_unknown_session_id_returns_404() {
260        let (app, _sessions, _project) = app_and_registry().await;
261
262        let resp = post(
263            &app,
264            "/tasks",
265            r#"{"task_description": "say hi", "session_id": "does-not-exist"}"#,
266        )
267        .await;
268        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
269        let v = body_json(resp).await;
270        assert_eq!(v["error"]["code"], -32007);
271    }
272
273    /// Syntactically invalid JSON must never reach the handler — axum's
274    /// `Json` extractor rejects it with a client error before `task.run`
275    /// runs, matching `sessions_write_tests::create_session_malformed_body_returns_400`'s
276    /// identical case for `POST /sessions`.
277    #[tokio::test]
278    async fn run_task_malformed_body_returns_400() {
279        let (app, _sessions, _project) = app_and_registry().await;
280
281        let resp = post(&app, "/tasks", "{not valid json").await;
282        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
283    }
284
285    /// A `project` in the body must bind a real directory, overriding the
286    /// daemon's boot-time binding for this call, and the response must
287    /// reflect it (#3178) — the REST-level half of the `task.run` RPC
288    /// coverage in `task::protocol::tests::task_run_with_project_overrides_boot_binding`.
289    #[tokio::test]
290    async fn run_task_with_project_binds_a_real_directory() {
291        let _guard = crate::task::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
292        unsafe {
293            std::env::set_var(
294                crate::task::mock_llm::MOCK_LLM_ENV,
295                crate::task::mock_llm::MOCK_LLM_ECHO,
296            );
297        }
298        let (app, _sessions, _boot_project) = app_and_registry().await;
299        let call_project = tempfile::tempdir().expect("call project tempdir");
300
301        let body = json!({
302            "task_description": "say hi",
303            "project": call_project.path().to_string_lossy(),
304        })
305        .to_string();
306        let resp = post(&app, "/tasks", &body).await;
307        unsafe {
308            std::env::remove_var(crate::task::mock_llm::MOCK_LLM_ENV);
309        }
310        assert_eq!(resp.status(), StatusCode::ACCEPTED);
311        let v = body_json(resp).await;
312        assert_eq!(
313            v["binding"]["state"], "directory",
314            "the per-call project must bind: {v}"
315        );
316    }
317
318    /// A `project` naming a nonexistent path must map to `400` (`-32003
319    /// invalid_argument`), matching `task.run`'s RPC-level error mapping.
320    #[tokio::test]
321    async fn run_task_invalid_project_returns_400() {
322        let (app, _sessions, _project) = app_and_registry().await;
323
324        let resp = post(
325            &app,
326            "/tasks",
327            r#"{"task_description": "say hi", "project": "/no/such/path/anywhere"}"#,
328        )
329        .await;
330        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
331        let v = body_json(resp).await;
332        assert_eq!(v["error"]["code"], -32003);
333    }
334
335    /// A `session_id` reusing an existing session, paired with a `project`
336    /// naming a DIFFERENT root than that session's own persisted binding,
337    /// must be rejected with `400`/`-32003 invalid_argument` (#3178,
338    /// code-critic HIGH finding, PR #3189) — the REST-level half of
339    /// `task::protocol::tests::task_run_session_id_with_mismatched_project_is_rejected`.
340    #[tokio::test]
341    async fn run_task_session_id_with_mismatched_project_returns_400() {
342        let (app, sessions, _boot_project) = app_and_registry().await;
343        let session_project = tempfile::tempdir().expect("session project tempdir");
344        let other_project = tempfile::tempdir().expect("other project tempdir");
345        let session_binding = ProjectBinding::resolve(Some(session_project.path().to_path_buf()))
346            .expect("tempdir must bind");
347        let existing = sessions.create("say hi".to_string(), None, session_binding);
348
349        let body = json!({
350            "task_description": "say hi",
351            "session_id": existing.id,
352            "project": other_project.path().to_string_lossy(),
353        })
354        .to_string();
355        let resp = post(&app, "/tasks", &body).await;
356        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
357        let v = body_json(resp).await;
358        assert_eq!(v["error"]["code"], -32003);
359        assert!(
360            v["error"]["message"]
361                .as_str()
362                .unwrap_or_default()
363                .contains("does not match session"),
364            "error message must name the mismatch: {v}"
365        );
366    }
367}