trusty_code/serve/rest/workstreams.rs
1//! `GET`/`POST /workstreams*` REST routes over the full `workstream.*`
2//! JSON-RPC surface (issues #3294, #3295, epic #3292).
3//!
4//! # Spec References
5//!
6//! - [`SPEC-WS-05~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-05~draft)
7//!
8//! Why: mirrors every other resource group in this gateway (`super::sessions`,
9//! `super::tasks`, …) — a REST-only client gets the same `workstream.*`
10//! surface `POST /rpc` exposes, without duplicating
11//! `crate::workstreams::protocol`'s business logic as bespoke axum handlers
12//! (see `super` module docs' "forking the two surfaces" rationale). This is
13//! where BOTH concurrent tickets against that RPC surface land their REST
14//! twins: #3295's CRUD/inspection routes (`create`/`get`/`list`/`close`) and
15//! #3294's activation-lock routes (`activate`/`deactivate`).
16//!
17//! **Path prefix deviation from DOC-48 §5.2 (documented, deliberate):** the
18//! spec's table writes `/api/v1/workstreams`, but every REST resource group
19//! this crate has shipped since #2983 (`/sessions`, `/tasks`, `/fs`, …) is
20//! UNPREFIXED — there is no `/api/v1` anywhere in `crate::serve::rest`. today.
21//! Introducing a prefix for exactly one resource group would make the API
22//! surface internally inconsistent (a client would need to special-case
23//! which resource lives under which prefix) for no behavioural gain; this
24//! ticket follows the shipped convention instead of the spec's literal path,
25//! matching every curl example in §12 except for the prefix itself.
26//!
27//! What: [`routes`] builds a standalone `axum::Router<()>` (its own
28//! `WorkstreamsState` carrying just the `Arc<Router>`, `with_state`-erased
29//! before return, mirroring `super::sessions::SessionsState`) mapping:
30//! - `POST /workstreams` -> `workstream.create` (`201 Created`)
31//! - `GET /workstreams/{id}` -> `workstream.get`
32//! - `GET /workstreams?include_closed=..` -> `workstream.list`
33//! - `POST /workstreams/{id}/close` -> `workstream.close`
34//! - `POST /workstreams/{id}/activate` -> `workstream.activate{id, force?}`
35//! (JSON body `{"force": bool}`, defaulting `force` to `false` when the
36//! body omits it or is `{}`)
37//! - `POST /workstreams/{id}/deactivate` -> `workstream.deactivate{id}`
38//! (no body, mirroring `super::sessions_write`'s `POST
39//! /sessions/{id}/cancel`)
40//! - `POST /workstreams/{id}/rename` -> `workstream.rename{id, name}`
41//! (JSON body `{"name": string}`, issue #3300, Phase C — DOC-48 §5.1
42//! marked this verb "future, Phase C" when Phase 1A shipped; this is
43//! that phase)
44//!
45//! `crate::serve::http::build_axum_router` merges this into the daemon's main
46//! router alongside `POST /rpc`, `GET /health`, and the other REST resource
47//! groups — none of those paths collide with the ones here.
48//! Test: `tests::*`.
49
50use std::sync::Arc;
51
52use axum::Json;
53use axum::Router as AxumRouter;
54use axum::extract::{Path, Query, State};
55use axum::http::StatusCode;
56use axum::routing::{get, post};
57use serde::Deserialize;
58use serde_json::{Value, json};
59use trusty_mcp::Response;
60
61use crate::jsonrpc::Router;
62
63use super::{RestResult, respond};
64
65/// Shared axum state for every route in this module: just the JSON-RPC
66/// router, mirroring `super::sessions::SessionsState` — every handler here
67/// goes through [`super::respond`]/[`respond_created`] rather than touching
68/// `WorkstreamStore` directly.
69#[derive(Clone)]
70struct WorkstreamsState {
71 router: Arc<Router>,
72}
73
74/// Build the `GET`/`POST /workstreams*` route group.
75///
76/// Why: kept separate from `crate::serve::http::build_axum_router` so this
77/// resource group is unit-testable via `tower::util::ServiceExt::oneshot` on
78/// its own, exactly like every other `rest::*` group.
79/// What: six routes (see module docs), all sharing one
80/// `WorkstreamsState { router }`, `with_state`-erased to `axum::Router<()>`
81/// so the caller can `.merge()` it alongside the other resource groups.
82/// Test: `tests::create_workstream_returns_201_with_id`,
83/// `tests::activate_returns_200_with_active_id`.
84pub fn routes(router: Arc<Router>) -> AxumRouter {
85 AxumRouter::new()
86 .route(
87 "/workstreams",
88 get(list_workstreams).post(create_workstream),
89 )
90 .route("/workstreams/{id}", get(get_workstream))
91 .route("/workstreams/{id}/close", post(close_workstream))
92 .route("/workstreams/{id}/activate", post(activate))
93 .route("/workstreams/{id}/deactivate", post(deactivate))
94 .route("/workstreams/{id}/rename", post(rename))
95 .with_state(WorkstreamsState { router })
96}
97
98/// Request body for `POST /workstreams`, shaped like
99/// `workstreams::protocol`'s private `CreateParams`.
100#[derive(Deserialize, Default)]
101struct CreateBody {
102 #[serde(default)]
103 name: Option<String>,
104}
105
106/// Query params for `GET /workstreams`, shaped like
107/// `workstreams::protocol`'s private `ListParams`.
108#[derive(Deserialize, Default)]
109struct ListQuery {
110 #[serde(default)]
111 include_closed: bool,
112}
113
114/// Request body for `POST /workstreams/{id}/activate` — `id` comes from the
115/// path, so only `force` remains. `#[serde(default)]` means `{}` (or a body
116/// that just omits the field) is a valid, non-`force` request.
117#[derive(Deserialize, Default)]
118struct ActivateBody {
119 #[serde(default)]
120 force: bool,
121}
122
123/// Request body for `POST /workstreams/{id}/rename` — `id` comes from the
124/// path, so only `name` remains.
125#[derive(Deserialize)]
126struct RenameBody {
127 name: String,
128}
129
130/// Like [`super::respond`] but reports `201 Created` on success — the one
131/// route in this module that mints a brand-new resource (mirrors
132/// `sessions_write::respond_created`, `tasks::respond_accepted`).
133async fn respond_created(
134 router: &Router,
135 method: &str,
136 params: Value,
137) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
138 respond(router, method, params)
139 .await
140 .map(|Json(v)| (StatusCode::CREATED, Json(v)))
141}
142
143/// `POST /workstreams` -> `workstream.create`.
144///
145/// Why: the REST entry point for minting a new workstream in the daemon's
146/// project — no `project_id` in the body, matching the RPC twin (§2.3: the
147/// daemon's own `ProjectBinding` is implicit).
148/// What: `201 Created` with `{"id": ..}` on success. An empty JSON body
149/// (`{}`) is valid — `name` defaults to empty (§5.1); a syntactically
150/// malformed or missing body is rejected by axum's `Json` extractor before
151/// this handler runs, matching every other `POST` route in this gateway
152/// (`sessions_write::create_session`, `tasks::run_task`).
153/// Test: `tests::create_workstream_returns_201_with_id`,
154/// `tests::create_workstream_empty_body_defaults_name`.
155async fn create_workstream(
156 State(state): State<WorkstreamsState>,
157 Json(body): Json<CreateBody>,
158) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
159 respond_created(
160 &state.router,
161 "workstream.create",
162 json!({ "name": body.name }),
163 )
164 .await
165}
166
167/// `GET /workstreams/{id}` -> `workstream.get`.
168///
169/// Why: point lookup for one workstream's current (inferred) state.
170/// What: `404` with a `not_found` envelope for an unknown `id`; otherwise the
171/// `Workstream` JSON (id, name, computed `state`, `session_ids`, timestamps).
172/// Test: `tests::get_workstream_found_returns_200`,
173/// `tests::get_workstream_missing_returns_404`.
174async fn get_workstream(
175 State(state): State<WorkstreamsState>,
176 Path(id): Path<String>,
177) -> RestResult {
178 respond(&state.router, "workstream.get", json!({"id": id})).await
179}
180
181/// `GET /workstreams?include_closed=..` -> `workstream.list`.
182///
183/// Why: enumerates every workstream in the daemon's project for a switcher
184/// UI/CLI, without a `get` per id.
185/// What: `200` with `{"active_workstream_id", "workstreams": [...]}`;
186/// `include_closed` defaults to `false` (§4.4).
187/// Test: `tests::list_workstreams_returns_active_id_and_records`.
188async fn list_workstreams(
189 State(state): State<WorkstreamsState>,
190 Query(q): Query<ListQuery>,
191) -> RestResult {
192 respond(
193 &state.router,
194 "workstream.list",
195 json!({"include_closed": q.include_closed}),
196 )
197 .await
198}
199
200/// `POST /workstreams/{id}/close` -> `workstream.close`.
201///
202/// Why: the REST entry point for irreversibly closing a workstream (§4.4);
203/// no body needed, `id` from the path is the whole request.
204/// What: `200` with `{}` on success; `404` for an unknown `id`.
205/// Test: `tests::close_workstream_returns_200_empty_object`,
206/// `tests::close_workstream_missing_returns_404`.
207async fn close_workstream(
208 State(state): State<WorkstreamsState>,
209 Path(id): Path<String>,
210) -> RestResult {
211 respond(&state.router, "workstream.close", json!({"id": id})).await
212}
213
214/// `POST /workstreams/{id}/activate` -> `workstream.activate`.
215///
216/// Why: the REST entry point for DOC-48 §6.1's activation-lock exclusivity
217/// model.
218/// What: `200` with `{"active_id", "prior_id"}` on success; `404` for an
219/// unknown `id` (`-32002 not_found`); `409` when a DIFFERENT workstream is
220/// active and `force` was not set (`-32008 active_conflict`, see
221/// `crate::jsonrpc::error::RpcError::active_conflict`'s docs and
222/// `super::rpc_error_to_status`'s `-32008 -> 409` mapping).
223/// Test: `tests::activate_returns_200_with_active_id`,
224/// `tests::activate_conflict_returns_409`,
225/// `tests::activate_unknown_id_returns_404`.
226async fn activate(
227 State(state): State<WorkstreamsState>,
228 Path(id): Path<String>,
229 Json(body): Json<ActivateBody>,
230) -> RestResult {
231 respond(
232 &state.router,
233 "workstream.activate",
234 json!({"id": id, "force": body.force}),
235 )
236 .await
237}
238
239/// `POST /workstreams/{id}/deactivate` -> `workstream.deactivate`.
240///
241/// Why: the REST entry point for clearing the active pointer — never needs
242/// a body, `id` from the path is the whole request (mirrors
243/// `super::sessions_write::cancel_session`).
244/// What: `200` with `{}` on success — idempotent for an idle/unknown `id`
245/// (see `crate::workstreams::activation::deactivate`'s docs), so this route
246/// has no documented error path of its own beyond a lower-level store
247/// failure (`500`).
248/// Test: `tests::deactivate_returns_200_empty_object`.
249async fn deactivate(State(state): State<WorkstreamsState>, Path(id): Path<String>) -> RestResult {
250 respond(&state.router, "workstream.deactivate", json!({"id": id})).await
251}
252
253/// `POST /workstreams/{id}/rename` -> `workstream.rename`.
254///
255/// Why: the REST entry point for the GUI switcher's rename action (issue
256/// #3300, Phase C).
257/// What: `200` with the updated `Workstream` JSON on success; `404` for an
258/// unknown `id`.
259/// Test: `tests::rename_returns_200_with_updated_name`,
260/// `tests::rename_missing_returns_404`.
261async fn rename(
262 State(state): State<WorkstreamsState>,
263 Path(id): Path<String>,
264 Json(body): Json<RenameBody>,
265) -> RestResult {
266 respond(
267 &state.router,
268 "workstream.rename",
269 json!({"id": id, "name": body.name}),
270 )
271 .await
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277 use axum::body::{Body, to_bytes};
278 use axum::http::Request;
279 use tower::util::ServiceExt;
280
281 /// Build the route group over a fresh, tempdir-backed workstream store
282 /// with no workstreams yet — used by the `create`/`get`/`list`/`close`
283 /// tests, which each create whatever records they need via `POST
284 /// /workstreams`.
285 async fn app() -> AxumRouter {
286 let dir = tempfile::tempdir().expect("tempdir");
287 let store =
288 crate::workstreams::WorkstreamStore::load(dir.path().join("workstreams-test.json"))
289 .await
290 .expect("load");
291 std::mem::forget(dir);
292 let mut router = Router::new();
293 crate::workstreams::protocol::register(
294 &mut router,
295 std::sync::Arc::new(tokio::sync::Mutex::new(store)),
296 );
297 routes(Arc::new(router))
298 }
299
300 /// Like [`app`] but pre-seeds one workstream directly through the store
301 /// (bypassing the REST layer) and returns its id — used by the
302 /// `activate`/`deactivate` tests, which need an existing workstream to
303 /// act on. Also returns the backing `TempDir` so a test can reload the
304 /// same file directly (e.g. to seed a SECOND workstream for a conflict
305 /// scenario).
306 async fn app_and_id() -> (AxumRouter, String, tempfile::TempDir) {
307 let dir = tempfile::tempdir().expect("tempdir");
308 let path = dir.path().join("workstreams-test.json");
309 let mut store = crate::workstreams::WorkstreamStore::load(path)
310 .await
311 .expect("load fresh store");
312 let id = store.create("t").await.expect("create");
313 let store = Arc::new(tokio::sync::Mutex::new(store));
314
315 let mut router = Router::new();
316 crate::workstreams::protocol::register(&mut router, store);
317 let app = routes(Arc::new(router));
318 (app, id.to_string(), dir)
319 }
320
321 async fn body_json(response: axum::response::Response) -> Value {
322 let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
323 serde_json::from_slice(&bytes).unwrap()
324 }
325
326 async fn post(app: &AxumRouter, uri: &str, body: &str) -> axum::response::Response {
327 app.clone()
328 .oneshot(
329 Request::builder()
330 .method("POST")
331 .uri(uri)
332 .header("content-type", "application/json")
333 .body(Body::from(body.to_string()))
334 .unwrap(),
335 )
336 .await
337 .unwrap()
338 }
339
340 async fn get(app: &AxumRouter, uri: &str) -> axum::response::Response {
341 app.clone()
342 .oneshot(
343 Request::builder()
344 .method("GET")
345 .uri(uri)
346 .body(Body::empty())
347 .unwrap(),
348 )
349 .await
350 .unwrap()
351 }
352
353 #[tokio::test]
354 async fn create_workstream_returns_201_with_id() {
355 let app = app().await;
356 let resp = post(&app, "/workstreams", r#"{"name": "Token rotation"}"#).await;
357 assert_eq!(resp.status(), StatusCode::CREATED);
358 let v = body_json(resp).await;
359 assert!(v["id"].is_string());
360 }
361
362 #[tokio::test]
363 async fn create_workstream_empty_body_defaults_name() {
364 let app = app().await;
365 let resp = post(&app, "/workstreams", "{}").await;
366 assert_eq!(resp.status(), StatusCode::CREATED);
367 let id = body_json(resp).await["id"].as_str().unwrap().to_string();
368
369 let get_resp = get(&app, &format!("/workstreams/{id}")).await;
370 let v = body_json(get_resp).await;
371 assert_eq!(v["name"], "");
372 }
373
374 #[tokio::test]
375 async fn get_workstream_found_returns_200() {
376 let app = app().await;
377 let created = body_json(post(&app, "/workstreams", r#"{"name": "A"}"#).await).await;
378 let id = created["id"].as_str().unwrap();
379
380 let resp = get(&app, &format!("/workstreams/{id}")).await;
381 assert_eq!(resp.status(), StatusCode::OK);
382 let v = body_json(resp).await;
383 assert_eq!(v["name"], "A");
384 assert_eq!(v["state"], "idle");
385 }
386
387 #[tokio::test]
388 async fn get_workstream_missing_returns_404() {
389 let app = app().await;
390 let resp = get(&app, "/workstreams/00000000-0000-0000-0000-000000000000").await;
391 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
392 let v = body_json(resp).await;
393 assert_eq!(v["error"]["code"], -32002);
394 }
395
396 #[tokio::test]
397 async fn list_workstreams_returns_active_id_and_records() {
398 let app = app().await;
399 post(&app, "/workstreams", r#"{"name": "A"}"#).await;
400 post(&app, "/workstreams", r#"{"name": "B"}"#).await;
401
402 let resp = get(&app, "/workstreams").await;
403 assert_eq!(resp.status(), StatusCode::OK);
404 let v = body_json(resp).await;
405 assert_eq!(v["active_workstream_id"], Value::Null);
406 assert_eq!(v["workstreams"].as_array().unwrap().len(), 2);
407 }
408
409 #[tokio::test]
410 async fn close_workstream_returns_200_empty_object() {
411 let app = app().await;
412 let created = body_json(post(&app, "/workstreams", r#"{"name": "A"}"#).await).await;
413 let id = created["id"].as_str().unwrap();
414
415 let resp = post(&app, &format!("/workstreams/{id}/close"), "").await;
416 assert_eq!(resp.status(), StatusCode::OK);
417 assert_eq!(body_json(resp).await, json!({}));
418
419 let get_resp = get(&app, &format!("/workstreams/{id}")).await;
420 assert_eq!(body_json(get_resp).await["state"], "closed");
421 }
422
423 #[tokio::test]
424 async fn close_workstream_missing_returns_404() {
425 let app = app().await;
426 let resp = post(
427 &app,
428 "/workstreams/00000000-0000-0000-0000-000000000000/close",
429 "",
430 )
431 .await;
432 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
433 let v = body_json(resp).await;
434 assert_eq!(v["error"]["code"], -32002);
435 }
436
437 /// `GET /workstreams?include_closed=..` must round-trip the query param
438 /// through to `workstream.list` (proving the merge/extraction wiring,
439 /// not just the RPC layer `protocol_tests` already cover).
440 #[tokio::test]
441 async fn list_include_closed_query_param_includes_closed_workstream() {
442 let app = app().await;
443 let created = body_json(post(&app, "/workstreams", r#"{"name": "A"}"#).await).await;
444 let id = created["id"].as_str().unwrap();
445 post(&app, &format!("/workstreams/{id}/close"), "").await;
446
447 let default_resp = get(&app, "/workstreams").await;
448 assert!(
449 body_json(default_resp).await["workstreams"]
450 .as_array()
451 .unwrap()
452 .is_empty(),
453 "closed workstream must be excluded by default"
454 );
455
456 let included_resp = get(&app, "/workstreams?include_closed=true").await;
457 let v = body_json(included_resp).await;
458 assert_eq!(v["workstreams"].as_array().unwrap().len(), 1);
459 }
460
461 /// Activating with no prior active workstream must return `200` with
462 /// the new `active_id` and a null `prior_id`.
463 #[tokio::test]
464 async fn activate_returns_200_with_active_id() {
465 let (app, id, _dir) = app_and_id().await;
466
467 let resp = post(&app, &format!("/workstreams/{id}/activate"), "{}").await;
468 assert_eq!(resp.status(), StatusCode::OK);
469 let v = body_json(resp).await;
470 assert_eq!(v["active_id"], json!(id));
471 assert_eq!(v["prior_id"], Value::Null);
472 }
473
474 /// Activating a DIFFERENT workstream without `force` while one is
475 /// active must return a real HTTP `409`, not a 200-wrapped error.
476 #[tokio::test]
477 async fn activate_conflict_returns_409() {
478 let (app, id, dir) = app_and_id().await;
479 let mut store =
480 crate::workstreams::WorkstreamStore::load(dir.path().join("workstreams-test.json"))
481 .await
482 .expect("reload store");
483 let other = store.create("other").await.expect("create other");
484
485 post(&app, &format!("/workstreams/{id}/activate"), "{}").await;
486
487 let resp = post(
488 &app,
489 &format!("/workstreams/{other}/activate"),
490 r#"{"force": false}"#,
491 )
492 .await;
493 assert_eq!(resp.status(), StatusCode::CONFLICT);
494 let v = body_json(resp).await;
495 assert_eq!(v["error"]["code"], -32008);
496 }
497
498 /// Activating an id that names no existing workstream must return a
499 /// real HTTP `404`.
500 #[tokio::test]
501 async fn activate_unknown_id_returns_404() {
502 let (app, _id, _dir) = app_and_id().await;
503
504 let resp = post(
505 &app,
506 &format!("/workstreams/{}/activate", uuid::Uuid::new_v4()),
507 "{}",
508 )
509 .await;
510 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
511 let v = body_json(resp).await;
512 assert_eq!(v["error"]["code"], -32002);
513 }
514
515 /// Deactivating must return `200` with an empty JSON object.
516 #[tokio::test]
517 async fn deactivate_returns_200_empty_object() {
518 let (app, id, _dir) = app_and_id().await;
519 post(&app, &format!("/workstreams/{id}/activate"), "{}").await;
520
521 let resp = app
522 .clone()
523 .oneshot(
524 Request::builder()
525 .method("POST")
526 .uri(format!("/workstreams/{id}/deactivate"))
527 .body(Body::empty())
528 .unwrap(),
529 )
530 .await
531 .unwrap();
532 assert_eq!(resp.status(), StatusCode::OK);
533 let v = body_json(resp).await;
534 assert_eq!(v, json!({}));
535 }
536
537 /// Renaming must return `200` with the updated `name` (issue #3300).
538 #[tokio::test]
539 async fn rename_returns_200_with_updated_name() {
540 let (app, id, _dir) = app_and_id().await;
541
542 let resp = post(
543 &app,
544 &format!("/workstreams/{id}/rename"),
545 r#"{"name": "renamed"}"#,
546 )
547 .await;
548 assert_eq!(resp.status(), StatusCode::OK);
549 let v = body_json(resp).await;
550 assert_eq!(v["name"], "renamed");
551 }
552
553 /// Renaming an unknown id must return a real HTTP `404`.
554 #[tokio::test]
555 async fn rename_missing_returns_404() {
556 let app = app().await;
557
558 let resp = post(
559 &app,
560 "/workstreams/00000000-0000-0000-0000-000000000000/rename",
561 r#"{"name": "renamed"}"#,
562 )
563 .await;
564 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
565 let v = body_json(resp).await;
566 assert_eq!(v["error"]["code"], -32002);
567 }
568}