Skip to main content

ironflow_api/routes/
human_input.rs

1//! `POST /api/v1/runs/:id/steps/:step_id/input` -- Answer a human input step.
2//!
3//! `POST /api/v1/runs/:id/steps/:step_id/reject` -- Reject a human input step.
4
5use axum::Json;
6use axum::extract::{Path, State};
7use axum::response::IntoResponse;
8use chrono::Utc;
9use ironflow_auth::extractor::Authenticated;
10use ironflow_engine::config::HUMAN_INPUT_SCHEMA_KEY;
11use ironflow_engine::engine::ExecutionMode;
12use ironflow_store::models::{
13    Run, RunStatus, Step, StepApproval, StepKind, StepStatus, StepUpdate,
14};
15use jsonschema::validator_for;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18use tokio::spawn;
19use tracing::error;
20use uuid::Uuid;
21
22use crate::entities::RunResponse;
23use crate::error::ApiError;
24use crate::response::ok;
25use crate::routes::approve_run::authorize_gate;
26use crate::state::AppState;
27
28/// Request body for rejecting a human input step.
29#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
30#[derive(Debug, Default, Deserialize, Serialize)]
31pub struct RejectHumanInputRequest {
32    /// Why the input is refused. Passed to the handler.
33    #[serde(default)]
34    pub reason: Option<String>,
35}
36
37/// Answer a human input step with a value matching its JSON schema.
38///
39/// The answer is validated against the schema stored on the step. The caller
40/// must be allowed to resolve the step like an approval gate (admin, approver
41/// groups, assignee or delegation). The first valid answer wins: the step
42/// completes, the run moves from `AwaitingApproval` back to `Running` and
43/// resumes, and the handler receives the typed answer.
44///
45/// # Errors
46///
47/// - 400 if the step is not a human input or is not awaiting input
48/// - 403 if the caller may not answer the step
49/// - 404 if the run or the step does not exist
50/// - 409 if the input was already answered or rejected
51/// - 422 if the answer does not match the schema
52#[cfg_attr(
53    feature = "openapi",
54    utoipa::path(
55        post,
56        path = "/api/v1/runs/{id}/steps/{step_id}/input",
57        tags = ["runs"],
58        params(
59            ("id" = Uuid, Path, description = "Run ID"),
60            ("step_id" = Uuid, Path, description = "Step ID")
61        ),
62        request_body(content = Value, content_type = "application/json", description = "Answer matching the JSON schema stored on the step"),
63        responses(
64            (status = 200, description = "Answer recorded, the run resumes", body = RunResponse),
65            (status = 400, description = "Step is not a human input awaiting input"),
66            (status = 401, description = "Unauthorized"),
67            (status = 403, description = "Forbidden"),
68            (status = 404, description = "Run or step not found"),
69            (status = 409, description = "Input already answered or rejected"),
70            (status = 422, description = "Answer does not match the schema")
71        ),
72        security(("Bearer" = []))
73    )
74)]
75pub async fn submit_human_input(
76    auth: Authenticated,
77    State(state): State<AppState>,
78    Path((id, step_id)): Path<(Uuid, Uuid)>,
79    Json(answer): Json<Value>,
80) -> Result<impl IntoResponse, ApiError> {
81    let (run, step) = open_input_step(&state, id, step_id).await?;
82    let actor = authorize_gate(&auth, &state, &run, &step).await?;
83    validate_answer(step.input.as_ref(), &answer)?;
84
85    // Like approve, two concurrent answers are not serialized: both may pass
86    // the status check above before either is written. This is an accepted
87    // limitation of the gate routes.
88    let now = Utc::now();
89    state
90        .store
91        .record_step_approval(
92            step.id,
93            StepApproval {
94                user_id: auth.user_id,
95                approved_by: actor,
96                at: now,
97            },
98        )
99        .await?;
100    state
101        .store
102        .update_step(
103            step.id,
104            StepUpdate {
105                status: Some(StepStatus::Completed),
106                output: Some(answer),
107                completed_at: Some(now),
108                clear_approval_deadline: true,
109                ..StepUpdate::default()
110            },
111        )
112        .await?;
113    state
114        .store
115        .update_run_status(id, resume_status(&state))
116        .await?;
117
118    resume_in_background(&state, id);
119
120    Ok(ok(RunResponse::from(state.get_run_or_404(id).await?)))
121}
122
123/// Reject a human input step.
124///
125/// The step is marked `Rejected` with the reason, the run moves from
126/// `AwaitingApproval` back to `Running` and resumes: the handler receives a
127/// `HumanInputRejected` error and decides what happens next. The body is
128/// optional; without a reason, one naming the caller is recorded.
129///
130/// # Errors
131///
132/// - 400 if the step is not a human input or is not awaiting input
133/// - 403 if the caller may not resolve the step
134/// - 404 if the run or the step does not exist
135/// - 409 if the input was already answered or rejected
136#[cfg_attr(
137    feature = "openapi",
138    utoipa::path(
139        post,
140        path = "/api/v1/runs/{id}/steps/{step_id}/reject",
141        tags = ["runs"],
142        params(
143            ("id" = Uuid, Path, description = "Run ID"),
144            ("step_id" = Uuid, Path, description = "Step ID")
145        ),
146        request_body(content = RejectHumanInputRequest, description = "Optional rejection reason"),
147        responses(
148            (status = 200, description = "Input rejected, the run resumes", body = RunResponse),
149            (status = 400, description = "Step is not a human input awaiting input"),
150            (status = 401, description = "Unauthorized"),
151            (status = 403, description = "Forbidden"),
152            (status = 404, description = "Run or step not found"),
153            (status = 409, description = "Input already answered or rejected")
154        ),
155        security(("Bearer" = []))
156    )
157)]
158pub async fn reject_human_input(
159    auth: Authenticated,
160    State(state): State<AppState>,
161    Path((id, step_id)): Path<(Uuid, Uuid)>,
162    body: Option<Json<RejectHumanInputRequest>>,
163) -> Result<impl IntoResponse, ApiError> {
164    let (run, step) = open_input_step(&state, id, step_id).await?;
165    let actor = authorize_gate(&auth, &state, &run, &step).await?;
166
167    let reason = body
168        .and_then(|Json(b)| b.reason)
169        .filter(|r| !r.trim().is_empty())
170        .unwrap_or_else(|| format!("input rejected by {actor}"));
171
172    state
173        .store
174        .update_step(
175            step.id,
176            StepUpdate {
177                status: Some(StepStatus::Rejected),
178                error: Some(reason),
179                completed_at: Some(Utc::now()),
180                clear_approval_deadline: true,
181                ..StepUpdate::default()
182            },
183        )
184        .await?;
185    state
186        .store
187        .update_run_status(id, resume_status(&state))
188        .await?;
189
190    resume_in_background(&state, id);
191
192    Ok(ok(RunResponse::from(state.get_run_or_404(id).await?)))
193}
194
195/// Load the run and the human input step, and check the step can be resolved.
196///
197/// A resolved step returns 409 whatever the run status, so replaying an
198/// accepted request is reported as a conflict rather than a bad request.
199async fn open_input_step(
200    state: &AppState,
201    run_id: Uuid,
202    step_id: Uuid,
203) -> Result<(Run, Step), ApiError> {
204    let run = state.get_run_or_404(run_id).await?;
205    let step = state
206        .store
207        .get_step(step_id)
208        .await?
209        .filter(|s| s.run_id == run_id)
210        .ok_or(ApiError::StepNotFound(step_id))?;
211
212    if step.kind != StepKind::HumanInput {
213        return Err(ApiError::BadRequest(
214            "step does not wait for input".to_string(),
215        ));
216    }
217
218    match step.status.state {
219        StepStatus::Completed => {
220            return Err(ApiError::Conflict("input already provided".to_string()));
221        }
222        StepStatus::Rejected => {
223            return Err(ApiError::Conflict("input already rejected".to_string()));
224        }
225        _ => {}
226    }
227
228    if step.status.state != StepStatus::AwaitingApproval
229        || run.status.state != RunStatus::AwaitingApproval
230    {
231        return Err(ApiError::BadRequest(
232            "step is not awaiting input".to_string(),
233        ));
234    }
235
236    Ok((run, step))
237}
238
239/// Validate `answer` against the JSON schema stored in the step input.
240fn validate_answer(input: Option<&Value>, answer: &Value) -> Result<(), ApiError> {
241    let schema = input
242        .and_then(|i| i.get(HUMAN_INPUT_SCHEMA_KEY))
243        .ok_or_else(|| ApiError::Internal("input step has no stored schema".to_string()))?;
244    let validator = validator_for(schema)
245        .map_err(|e| ApiError::Internal(format!("input step has an invalid schema: {e}")))?;
246
247    let errors: Vec<String> = validator
248        .iter_errors(answer)
249        .map(|e| e.to_string())
250        .collect();
251    if errors.is_empty() {
252        Ok(())
253    } else {
254        Err(ApiError::InvalidInput(errors))
255    }
256}
257
258/// The status a run moves to once its input is answered or rejected:
259/// `Running` to resume it here, `Pending` to requeue it for a worker.
260fn resume_status(state: &AppState) -> RunStatus {
261    match state.engine.execution_mode() {
262        ExecutionMode::Local => RunStatus::Running,
263        ExecutionMode::Workers => RunStatus::Pending,
264    }
265}
266
267/// Under [`ExecutionMode::Local`], resume the run in the background; the
268/// handler replays up to the input. Under [`ExecutionMode::Workers`], do
269/// nothing: the run is already `Pending` and a worker picks it up.
270fn resume_in_background(state: &AppState, id: Uuid) {
271    if !matches!(state.engine.execution_mode(), ExecutionMode::Local) {
272        return;
273    }
274    let engine = state.engine.clone();
275    spawn(async move {
276        if let Err(err) = engine.resume_run(id).await {
277            error!(run_id = %id, error = %err, "failed to resume run after human input");
278        }
279    });
280}
281
282#[cfg(test)]
283mod tests {
284    use std::collections::HashMap;
285    use std::sync::Arc;
286
287    use axum::Router;
288    use axum::body::Body;
289    use axum::http::{Request, StatusCode};
290    use axum::routing::post;
291    use http_body_util::BodyExt;
292    use ironflow_auth::jwt::{AccessToken, JwtConfig};
293    use ironflow_auth::password;
294    use ironflow_core::providers::claude::ClaudeCodeProvider;
295    use ironflow_engine::engine::Engine;
296    use ironflow_engine::handler::input_schema_for;
297    use ironflow_engine::notify::Event;
298    use ironflow_store::memory::InMemoryStore;
299    use ironflow_store::models::{
300        Assignee, NewRun, NewStep, NewUser, TriggerKind, User, step_trace_id,
301    };
302    use ironflow_store::store::RunStore;
303    use ironflow_store::user_store::UserStore;
304    use schemars::JsonSchema;
305    use serde_json::{from_slice, json};
306    use tokio::sync::broadcast;
307    use tower::ServiceExt;
308
309    use super::*;
310    use crate::routes::test_helpers::create_user_auth_header;
311
312    /// The answer type the test steps ask for.
313    #[allow(dead_code)]
314    #[derive(Deserialize, JsonSchema)]
315    struct Answers {
316        answers: Vec<String>,
317    }
318
319    /// An answer type whose schema carries a `$defs` reference.
320    #[allow(dead_code)]
321    #[derive(Deserialize, JsonSchema)]
322    struct Nested {
323        target: Target,
324    }
325
326    #[allow(dead_code)]
327    #[derive(Deserialize, JsonSchema)]
328    struct Target {
329        env: String,
330    }
331
332    fn test_state(store: Arc<InMemoryStore>) -> AppState {
333        let provider = Arc::new(ClaudeCodeProvider::new());
334        let engine = Arc::new(Engine::new(store.clone(), provider));
335        let jwt_config = Arc::new(JwtConfig {
336            secret: "test-secret".to_string(),
337            access_token_ttl_secs: 900,
338            refresh_token_ttl_secs: 604800,
339            cookie_domain: None,
340            cookie_secure: false,
341        });
342        let (event_sender, _) = broadcast::channel::<Event>(1);
343        AppState::new(
344            store,
345            engine,
346            jwt_config,
347            "test-worker-token".to_string(),
348            event_sender,
349        )
350    }
351
352    async fn member(store: &Arc<InMemoryStore>, username: &str) -> User {
353        let password_hash = password::hash("password123").expect("hash");
354        store
355            .create_user(NewUser {
356                email: format!("{username}@example.com"),
357                username: username.to_string(),
358                password_hash,
359                // The first user would otherwise become an implicit admin.
360                is_admin: Some(false),
361            })
362            .await
363            .expect("create user")
364    }
365
366    fn member_header(user: &User, state: &AppState) -> String {
367        let token = AccessToken::for_user(user.id, &user.username, false, &state.jwt_config)
368            .expect("token");
369        format!("Bearer {}", token.0)
370    }
371
372    async fn awaiting_run(store: &Arc<InMemoryStore>) -> Uuid {
373        let run = store
374            .create_run(NewRun {
375                created_by: None,
376                workflow_name: "test".to_string(),
377                trigger: TriggerKind::Manual,
378                payload: json!({}),
379                max_retries: 0,
380                handler_version: None,
381                labels: HashMap::new(),
382                scheduled_at: None,
383                idempotency_key: None,
384                concurrency_key: None,
385                concurrency_limits: Vec::new(),
386                max_cost_usd: None,
387            })
388            .await
389            .unwrap()
390            .into_run();
391        store
392            .update_run_status(run.id, RunStatus::Running)
393            .await
394            .unwrap();
395        store
396            .update_run_status(run.id, RunStatus::AwaitingApproval)
397            .await
398            .unwrap();
399        run.id
400    }
401
402    /// A step of `kind` awaiting approval on `run_id`.
403    async fn awaiting_step(
404        store: &Arc<InMemoryStore>,
405        run_id: Uuid,
406        kind: StepKind,
407        assignee: Option<Assignee>,
408    ) -> Uuid {
409        let step = store
410            .create_step(NewStep {
411                run_id,
412                trace_id: step_trace_id(run_id, "clarify", 0),
413                name: "clarify".to_string(),
414                kind,
415                position: 0,
416                input: Some(json!({
417                    "message": "Answer the questions",
418                    HUMAN_INPUT_SCHEMA_KEY: input_schema_for::<Answers>(),
419                })),
420                is_error_handler: false,
421            })
422            .await
423            .unwrap();
424        store
425            .update_step(
426                step.id,
427                StepUpdate {
428                    status: Some(StepStatus::Running),
429                    ..StepUpdate::default()
430                },
431            )
432            .await
433            .unwrap();
434        store
435            .update_step(
436                step.id,
437                StepUpdate {
438                    status: Some(StepStatus::AwaitingApproval),
439                    approval_assignee: assignee,
440                    ..StepUpdate::default()
441                },
442            )
443            .await
444            .unwrap();
445        step.id
446    }
447
448    /// A run awaiting a human input step, with an admin header.
449    async fn setup() -> (Arc<InMemoryStore>, AppState, Uuid, Uuid) {
450        let store = Arc::new(InMemoryStore::new());
451        let run_id = awaiting_run(&store).await;
452        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, None).await;
453        let state = test_state(store.clone());
454        (store, state, run_id, step_id)
455    }
456
457    fn app(state: AppState) -> Router {
458        Router::new()
459            .route("/{id}/steps/{step_id}/input", post(submit_human_input))
460            .route("/{id}/steps/{step_id}/reject", post(reject_human_input))
461            .with_state(state)
462    }
463
464    /// POST `body` (or nothing) to `/{run_id}/steps/{step_id}/{verb}`.
465    async fn call(
466        state: &AppState,
467        auth: &str,
468        run_id: Uuid,
469        step_id: Uuid,
470        verb: &str,
471        body: Option<Value>,
472    ) -> (StatusCode, Value) {
473        let builder = Request::builder()
474            .method("POST")
475            .uri(format!("/{run_id}/steps/{step_id}/{verb}"))
476            .header("authorization", auth);
477        let req = match body {
478            Some(body) => builder
479                .header("content-type", "application/json")
480                .body(Body::from(body.to_string()))
481                .unwrap(),
482            None => builder.body(Body::empty()).unwrap(),
483        };
484
485        let resp = app(state.clone()).oneshot(req).await.unwrap();
486        let status = resp.status();
487        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
488        let json_val = if bytes.is_empty() {
489            Value::Null
490        } else {
491            from_slice(&bytes).unwrap()
492        };
493        (status, json_val)
494    }
495
496    #[tokio::test]
497    async fn human_input_submit_valid_answer_resumes_the_run() {
498        let (store, state, run_id, step_id) = setup().await;
499        let auth = create_user_auth_header(&state, "admin", true).await;
500        let answer = json!({"answers": ["staging"]});
501
502        let (status, body) = call(
503            &state,
504            &auth,
505            run_id,
506            step_id,
507            "input",
508            Some(answer.clone()),
509        )
510        .await;
511
512        assert_eq!(status, StatusCode::OK);
513        assert_eq!(body["data"]["status"], "running");
514        let step = store.get_step(step_id).await.unwrap().unwrap();
515        assert_eq!(step.status.state, StepStatus::Completed);
516        assert_eq!(step.output, Some(answer));
517        assert_eq!(step.approvals.len(), 1);
518        assert_eq!(step.approvals[0].approved_by, "admin");
519    }
520
521    #[tokio::test]
522    async fn human_input_submit_invalid_answer_returns_422() {
523        let (store, state, run_id, step_id) = setup().await;
524        let auth = create_user_auth_header(&state, "admin", true).await;
525
526        for answer in [json!({"answers": 3}), json!({})] {
527            let (status, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
528
529            assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
530            assert_eq!(body["error"]["code"], "INVALID_INPUT");
531            let errors = body["error"]["details"]["errors"]
532                .as_array()
533                .expect("errors array");
534            assert!(!errors.is_empty());
535        }
536
537        let step = store.get_step(step_id).await.unwrap().unwrap();
538        assert_eq!(step.status.state, StepStatus::AwaitingApproval);
539        let run = store.get_run(run_id).await.unwrap().unwrap();
540        assert_eq!(run.status.state, RunStatus::AwaitingApproval);
541    }
542
543    #[tokio::test]
544    async fn human_input_submit_twice_returns_409() {
545        let (_store, state, run_id, step_id) = setup().await;
546        let auth = create_user_auth_header(&state, "admin", true).await;
547        let answer = json!({"answers": ["yes"]});
548
549        let (first, _) = call(
550            &state,
551            &auth,
552            run_id,
553            step_id,
554            "input",
555            Some(answer.clone()),
556        )
557        .await;
558        assert_eq!(first, StatusCode::OK);
559
560        let (second, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
561        assert_eq!(second, StatusCode::CONFLICT);
562        assert_eq!(body["error"]["message"], "input already provided");
563    }
564
565    #[tokio::test]
566    async fn human_input_submit_on_an_approval_step_returns_400() {
567        let store = Arc::new(InMemoryStore::new());
568        let run_id = awaiting_run(&store).await;
569        let step_id = awaiting_step(&store, run_id, StepKind::Approval, None).await;
570        let state = test_state(store);
571        let auth = create_user_auth_header(&state, "admin", true).await;
572
573        let answer = json!({"answers": []});
574        let (status, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
575        assert_eq!(status, StatusCode::BAD_REQUEST);
576    }
577
578    #[tokio::test]
579    async fn human_input_submit_on_a_run_not_awaiting_returns_400() {
580        let (store, state, run_id, step_id) = setup().await;
581        store
582            .update_run_status(run_id, RunStatus::Running)
583            .await
584            .unwrap();
585        let auth = create_user_auth_header(&state, "admin", true).await;
586
587        let answer = json!({"answers": []});
588        let (status, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
589        assert_eq!(status, StatusCode::BAD_REQUEST);
590    }
591
592    #[tokio::test]
593    async fn human_input_unknown_step_or_step_of_another_run_returns_404() {
594        let (store, state, run_id, step_id) = setup().await;
595        let auth = create_user_auth_header(&state, "admin", true).await;
596        let answer = json!({"answers": []});
597
598        let unknown = Uuid::now_v7();
599        let (status, body) = call(
600            &state,
601            &auth,
602            run_id,
603            unknown,
604            "input",
605            Some(answer.clone()),
606        )
607        .await;
608        assert_eq!(status, StatusCode::NOT_FOUND);
609        assert_eq!(body["error"]["code"], "STEP_NOT_FOUND");
610
611        let other_run = awaiting_run(&store).await;
612        let (status, _) = call(&state, &auth, other_run, step_id, "input", Some(answer)).await;
613        assert_eq!(status, StatusCode::NOT_FOUND);
614    }
615
616    #[tokio::test]
617    async fn human_input_unknown_run_returns_404() {
618        let (_store, state, _run_id, step_id) = setup().await;
619        let auth = create_user_auth_header(&state, "admin", true).await;
620
621        let answer = json!({"answers": []});
622        let (status, body) = call(
623            &state,
624            &auth,
625            Uuid::now_v7(),
626            step_id,
627            "input",
628            Some(answer),
629        )
630        .await;
631        assert_eq!(status, StatusCode::NOT_FOUND);
632        assert_eq!(body["error"]["code"], "RUN_NOT_FOUND");
633    }
634
635    #[tokio::test]
636    async fn human_input_non_admin_non_assignee_is_forbidden() {
637        let store = Arc::new(InMemoryStore::new());
638        let alice = member(&store, "alice").await;
639        let bob = member(&store, "bob").await;
640        let run_id = awaiting_run(&store).await;
641        let assignee = Some(Assignee::user(&alice.username));
642        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, assignee).await;
643        let state = test_state(store.clone());
644
645        let answer = json!({"answers": ["yes"]});
646        let bob_auth = member_header(&bob, &state);
647        let (status, _) = call(
648            &state,
649            &bob_auth,
650            run_id,
651            step_id,
652            "input",
653            Some(answer.clone()),
654        )
655        .await;
656        assert_eq!(status, StatusCode::FORBIDDEN);
657
658        let alice_auth = member_header(&alice, &state);
659        let (status, _) = call(&state, &alice_auth, run_id, step_id, "input", Some(answer)).await;
660        assert_eq!(status, StatusCode::OK);
661        let step = store.get_step(step_id).await.unwrap().unwrap();
662        assert_eq!(step.approvals[0].user_id, alice.id);
663    }
664
665    #[tokio::test]
666    async fn human_input_reject_marks_the_step_and_resumes_the_run() {
667        let (store, state, run_id, step_id) = setup().await;
668        let auth = create_user_auth_header(&state, "admin", true).await;
669
670        let body = json!({"reason": "out of scope"});
671        let (status, resp) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;
672
673        assert_eq!(status, StatusCode::OK);
674        assert_eq!(resp["data"]["status"], "running");
675        let step = store.get_step(step_id).await.unwrap().unwrap();
676        assert_eq!(step.status.state, StepStatus::Rejected);
677        assert_eq!(step.error.as_deref(), Some("out of scope"));
678        assert!(step.approval_deadline_at.is_none());
679    }
680
681    /// A run awaiting a human input assigned to a member, on an engine that
682    /// requeues resumed runs for a worker.
683    async fn workers_setup() -> (Arc<InMemoryStore>, AppState, Uuid, Uuid, String) {
684        let store = Arc::new(InMemoryStore::new());
685        let alice = member(&store, "alice").await;
686        let run_id = awaiting_run(&store).await;
687        let assignee = Some(Assignee::user(&alice.username));
688        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, assignee).await;
689        let provider = Arc::new(ClaudeCodeProvider::new());
690        let engine =
691            Engine::new(store.clone(), provider).with_execution_mode(ExecutionMode::Workers);
692        let jwt_config = Arc::new(JwtConfig {
693            secret: "test-secret".to_string(),
694            access_token_ttl_secs: 900,
695            refresh_token_ttl_secs: 604800,
696            cookie_domain: None,
697            cookie_secure: false,
698        });
699        let (event_sender, _) = broadcast::channel::<Event>(1);
700        let state = AppState::new(
701            store.clone(),
702            Arc::new(engine),
703            jwt_config,
704            "test-worker-token".to_string(),
705            event_sender,
706        );
707        let auth = member_header(&alice, &state);
708        (store, state, run_id, step_id, auth)
709    }
710
711    #[tokio::test]
712    async fn human_input_submit_in_workers_mode_requeues_the_run() {
713        let (store, state, run_id, step_id, auth) = workers_setup().await;
714
715        let answer = json!({"answers": ["ok"]});
716        let (status, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
717
718        assert_eq!(status, StatusCode::OK);
719        assert_eq!(body["data"]["status"], "pending");
720        let run = store.get_run(run_id).await.unwrap().unwrap();
721        assert_eq!(run.status.state, RunStatus::Pending);
722        let step = store.get_step(step_id).await.unwrap().unwrap();
723        assert_eq!(step.status.state, StepStatus::Completed);
724    }
725
726    #[tokio::test]
727    async fn human_input_reject_in_workers_mode_requeues_the_run() {
728        let (store, state, run_id, step_id, auth) = workers_setup().await;
729
730        let body = json!({"reason": "out of scope"});
731        let (status, resp) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;
732
733        assert_eq!(status, StatusCode::OK);
734        assert_eq!(resp["data"]["status"], "pending");
735        let run = store.get_run(run_id).await.unwrap().unwrap();
736        assert_eq!(run.status.state, RunStatus::Pending);
737        let step = store.get_step(step_id).await.unwrap().unwrap();
738        assert_eq!(step.status.state, StepStatus::Rejected);
739    }
740
741    #[tokio::test]
742    async fn human_input_reject_without_body_uses_the_default_reason() {
743        let (store, state, run_id, step_id) = setup().await;
744        let auth = create_user_auth_header(&state, "admin", true).await;
745
746        let (status, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
747
748        assert_eq!(status, StatusCode::OK);
749        let step = store.get_step(step_id).await.unwrap().unwrap();
750        assert_eq!(step.error.as_deref(), Some("input rejected by admin"));
751    }
752
753    #[tokio::test]
754    async fn human_input_reject_with_a_blank_reason_uses_the_default_reason() {
755        let (store, state, run_id, step_id) = setup().await;
756        let auth = create_user_auth_header(&state, "admin", true).await;
757
758        let body = json!({"reason": "   "});
759        let (status, _) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;
760
761        assert_eq!(status, StatusCode::OK);
762        let step = store.get_step(step_id).await.unwrap().unwrap();
763        assert_eq!(step.error.as_deref(), Some("input rejected by admin"));
764    }
765
766    #[tokio::test]
767    async fn human_input_reject_after_submit_returns_409() {
768        let (_store, state, run_id, step_id) = setup().await;
769        let auth = create_user_auth_header(&state, "admin", true).await;
770
771        let answer = json!({"answers": ["yes"]});
772        let (first, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
773        assert_eq!(first, StatusCode::OK);
774
775        let (second, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
776        assert_eq!(second, StatusCode::CONFLICT);
777    }
778
779    #[tokio::test]
780    async fn human_input_submit_after_reject_returns_409() {
781        let (_store, state, run_id, step_id) = setup().await;
782        let auth = create_user_auth_header(&state, "admin", true).await;
783
784        let (first, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
785        assert_eq!(first, StatusCode::OK);
786
787        let answer = json!({"answers": ["yes"]});
788        let (second, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
789        assert_eq!(second, StatusCode::CONFLICT);
790        assert_eq!(body["error"]["message"], "input already rejected");
791    }
792
793    #[test]
794    fn human_input_validate_answer_without_a_schema_is_internal() {
795        let err = validate_answer(Some(&json!({"message": "Answer?"})), &json!({}))
796            .expect_err("no schema");
797        assert!(matches!(err, ApiError::Internal(_)), "got {err:?}");
798
799        let err = validate_answer(None, &json!({})).expect_err("no input");
800        assert!(matches!(err, ApiError::Internal(_)), "got {err:?}");
801    }
802
803    #[test]
804    fn human_input_validate_answer_resolves_defs_references() {
805        let schema = input_schema_for::<Nested>();
806        assert!(schema.get("$defs").is_some(), "schema: {schema}");
807        let input = json!({ HUMAN_INPUT_SCHEMA_KEY: schema });
808
809        let valid = validate_answer(Some(&input), &json!({"target": {"env": "prod"}}));
810        assert!(valid.is_ok(), "got {valid:?}");
811
812        let err = validate_answer(Some(&input), &json!({"target": {"env": 1}}))
813            .expect_err("wrong nested type");
814        match err {
815            ApiError::InvalidInput(errors) => assert_eq!(errors.len(), 1, "got {errors:?}"),
816            other => panic!("expected InvalidInput, got {other:?}"),
817        }
818    }
819}