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                max_cost_usd: None,
386            })
387            .await
388            .unwrap()
389            .into_run();
390        store
391            .update_run_status(run.id, RunStatus::Running)
392            .await
393            .unwrap();
394        store
395            .update_run_status(run.id, RunStatus::AwaitingApproval)
396            .await
397            .unwrap();
398        run.id
399    }
400
401    /// A step of `kind` awaiting approval on `run_id`.
402    async fn awaiting_step(
403        store: &Arc<InMemoryStore>,
404        run_id: Uuid,
405        kind: StepKind,
406        assignee: Option<Assignee>,
407    ) -> Uuid {
408        let step = store
409            .create_step(NewStep {
410                run_id,
411                trace_id: step_trace_id(run_id, "clarify", 0),
412                name: "clarify".to_string(),
413                kind,
414                position: 0,
415                input: Some(json!({
416                    "message": "Answer the questions",
417                    HUMAN_INPUT_SCHEMA_KEY: input_schema_for::<Answers>(),
418                })),
419                is_error_handler: false,
420            })
421            .await
422            .unwrap();
423        store
424            .update_step(
425                step.id,
426                StepUpdate {
427                    status: Some(StepStatus::Running),
428                    ..StepUpdate::default()
429                },
430            )
431            .await
432            .unwrap();
433        store
434            .update_step(
435                step.id,
436                StepUpdate {
437                    status: Some(StepStatus::AwaitingApproval),
438                    approval_assignee: assignee,
439                    ..StepUpdate::default()
440                },
441            )
442            .await
443            .unwrap();
444        step.id
445    }
446
447    /// A run awaiting a human input step, with an admin header.
448    async fn setup() -> (Arc<InMemoryStore>, AppState, Uuid, Uuid) {
449        let store = Arc::new(InMemoryStore::new());
450        let run_id = awaiting_run(&store).await;
451        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, None).await;
452        let state = test_state(store.clone());
453        (store, state, run_id, step_id)
454    }
455
456    fn app(state: AppState) -> Router {
457        Router::new()
458            .route("/{id}/steps/{step_id}/input", post(submit_human_input))
459            .route("/{id}/steps/{step_id}/reject", post(reject_human_input))
460            .with_state(state)
461    }
462
463    /// POST `body` (or nothing) to `/{run_id}/steps/{step_id}/{verb}`.
464    async fn call(
465        state: &AppState,
466        auth: &str,
467        run_id: Uuid,
468        step_id: Uuid,
469        verb: &str,
470        body: Option<Value>,
471    ) -> (StatusCode, Value) {
472        let builder = Request::builder()
473            .method("POST")
474            .uri(format!("/{run_id}/steps/{step_id}/{verb}"))
475            .header("authorization", auth);
476        let req = match body {
477            Some(body) => builder
478                .header("content-type", "application/json")
479                .body(Body::from(body.to_string()))
480                .unwrap(),
481            None => builder.body(Body::empty()).unwrap(),
482        };
483
484        let resp = app(state.clone()).oneshot(req).await.unwrap();
485        let status = resp.status();
486        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
487        let json_val = if bytes.is_empty() {
488            Value::Null
489        } else {
490            from_slice(&bytes).unwrap()
491        };
492        (status, json_val)
493    }
494
495    #[tokio::test]
496    async fn human_input_submit_valid_answer_resumes_the_run() {
497        let (store, state, run_id, step_id) = setup().await;
498        let auth = create_user_auth_header(&state, "admin", true).await;
499        let answer = json!({"answers": ["staging"]});
500
501        let (status, body) = call(
502            &state,
503            &auth,
504            run_id,
505            step_id,
506            "input",
507            Some(answer.clone()),
508        )
509        .await;
510
511        assert_eq!(status, StatusCode::OK);
512        assert_eq!(body["data"]["status"], "running");
513        let step = store.get_step(step_id).await.unwrap().unwrap();
514        assert_eq!(step.status.state, StepStatus::Completed);
515        assert_eq!(step.output, Some(answer));
516        assert_eq!(step.approvals.len(), 1);
517        assert_eq!(step.approvals[0].approved_by, "admin");
518    }
519
520    #[tokio::test]
521    async fn human_input_submit_invalid_answer_returns_422() {
522        let (store, state, run_id, step_id) = setup().await;
523        let auth = create_user_auth_header(&state, "admin", true).await;
524
525        for answer in [json!({"answers": 3}), json!({})] {
526            let (status, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
527
528            assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
529            assert_eq!(body["error"]["code"], "INVALID_INPUT");
530            let errors = body["error"]["details"]["errors"]
531                .as_array()
532                .expect("errors array");
533            assert!(!errors.is_empty());
534        }
535
536        let step = store.get_step(step_id).await.unwrap().unwrap();
537        assert_eq!(step.status.state, StepStatus::AwaitingApproval);
538        let run = store.get_run(run_id).await.unwrap().unwrap();
539        assert_eq!(run.status.state, RunStatus::AwaitingApproval);
540    }
541
542    #[tokio::test]
543    async fn human_input_submit_twice_returns_409() {
544        let (_store, state, run_id, step_id) = setup().await;
545        let auth = create_user_auth_header(&state, "admin", true).await;
546        let answer = json!({"answers": ["yes"]});
547
548        let (first, _) = call(
549            &state,
550            &auth,
551            run_id,
552            step_id,
553            "input",
554            Some(answer.clone()),
555        )
556        .await;
557        assert_eq!(first, StatusCode::OK);
558
559        let (second, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
560        assert_eq!(second, StatusCode::CONFLICT);
561        assert_eq!(body["error"]["message"], "input already provided");
562    }
563
564    #[tokio::test]
565    async fn human_input_submit_on_an_approval_step_returns_400() {
566        let store = Arc::new(InMemoryStore::new());
567        let run_id = awaiting_run(&store).await;
568        let step_id = awaiting_step(&store, run_id, StepKind::Approval, None).await;
569        let state = test_state(store);
570        let auth = create_user_auth_header(&state, "admin", true).await;
571
572        let answer = json!({"answers": []});
573        let (status, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
574        assert_eq!(status, StatusCode::BAD_REQUEST);
575    }
576
577    #[tokio::test]
578    async fn human_input_submit_on_a_run_not_awaiting_returns_400() {
579        let (store, state, run_id, step_id) = setup().await;
580        store
581            .update_run_status(run_id, RunStatus::Running)
582            .await
583            .unwrap();
584        let auth = create_user_auth_header(&state, "admin", true).await;
585
586        let answer = json!({"answers": []});
587        let (status, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
588        assert_eq!(status, StatusCode::BAD_REQUEST);
589    }
590
591    #[tokio::test]
592    async fn human_input_unknown_step_or_step_of_another_run_returns_404() {
593        let (store, state, run_id, step_id) = setup().await;
594        let auth = create_user_auth_header(&state, "admin", true).await;
595        let answer = json!({"answers": []});
596
597        let unknown = Uuid::now_v7();
598        let (status, body) = call(
599            &state,
600            &auth,
601            run_id,
602            unknown,
603            "input",
604            Some(answer.clone()),
605        )
606        .await;
607        assert_eq!(status, StatusCode::NOT_FOUND);
608        assert_eq!(body["error"]["code"], "STEP_NOT_FOUND");
609
610        let other_run = awaiting_run(&store).await;
611        let (status, _) = call(&state, &auth, other_run, step_id, "input", Some(answer)).await;
612        assert_eq!(status, StatusCode::NOT_FOUND);
613    }
614
615    #[tokio::test]
616    async fn human_input_unknown_run_returns_404() {
617        let (_store, state, _run_id, step_id) = setup().await;
618        let auth = create_user_auth_header(&state, "admin", true).await;
619
620        let answer = json!({"answers": []});
621        let (status, body) = call(
622            &state,
623            &auth,
624            Uuid::now_v7(),
625            step_id,
626            "input",
627            Some(answer),
628        )
629        .await;
630        assert_eq!(status, StatusCode::NOT_FOUND);
631        assert_eq!(body["error"]["code"], "RUN_NOT_FOUND");
632    }
633
634    #[tokio::test]
635    async fn human_input_non_admin_non_assignee_is_forbidden() {
636        let store = Arc::new(InMemoryStore::new());
637        let alice = member(&store, "alice").await;
638        let bob = member(&store, "bob").await;
639        let run_id = awaiting_run(&store).await;
640        let assignee = Some(Assignee::user(&alice.username));
641        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, assignee).await;
642        let state = test_state(store.clone());
643
644        let answer = json!({"answers": ["yes"]});
645        let bob_auth = member_header(&bob, &state);
646        let (status, _) = call(
647            &state,
648            &bob_auth,
649            run_id,
650            step_id,
651            "input",
652            Some(answer.clone()),
653        )
654        .await;
655        assert_eq!(status, StatusCode::FORBIDDEN);
656
657        let alice_auth = member_header(&alice, &state);
658        let (status, _) = call(&state, &alice_auth, run_id, step_id, "input", Some(answer)).await;
659        assert_eq!(status, StatusCode::OK);
660        let step = store.get_step(step_id).await.unwrap().unwrap();
661        assert_eq!(step.approvals[0].user_id, alice.id);
662    }
663
664    #[tokio::test]
665    async fn human_input_reject_marks_the_step_and_resumes_the_run() {
666        let (store, state, run_id, step_id) = setup().await;
667        let auth = create_user_auth_header(&state, "admin", true).await;
668
669        let body = json!({"reason": "out of scope"});
670        let (status, resp) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;
671
672        assert_eq!(status, StatusCode::OK);
673        assert_eq!(resp["data"]["status"], "running");
674        let step = store.get_step(step_id).await.unwrap().unwrap();
675        assert_eq!(step.status.state, StepStatus::Rejected);
676        assert_eq!(step.error.as_deref(), Some("out of scope"));
677        assert!(step.approval_deadline_at.is_none());
678    }
679
680    /// A run awaiting a human input assigned to a member, on an engine that
681    /// requeues resumed runs for a worker.
682    async fn workers_setup() -> (Arc<InMemoryStore>, AppState, Uuid, Uuid, String) {
683        let store = Arc::new(InMemoryStore::new());
684        let alice = member(&store, "alice").await;
685        let run_id = awaiting_run(&store).await;
686        let assignee = Some(Assignee::user(&alice.username));
687        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, assignee).await;
688        let provider = Arc::new(ClaudeCodeProvider::new());
689        let engine =
690            Engine::new(store.clone(), provider).with_execution_mode(ExecutionMode::Workers);
691        let jwt_config = Arc::new(JwtConfig {
692            secret: "test-secret".to_string(),
693            access_token_ttl_secs: 900,
694            refresh_token_ttl_secs: 604800,
695            cookie_domain: None,
696            cookie_secure: false,
697        });
698        let (event_sender, _) = broadcast::channel::<Event>(1);
699        let state = AppState::new(
700            store.clone(),
701            Arc::new(engine),
702            jwt_config,
703            "test-worker-token".to_string(),
704            event_sender,
705        );
706        let auth = member_header(&alice, &state);
707        (store, state, run_id, step_id, auth)
708    }
709
710    #[tokio::test]
711    async fn human_input_submit_in_workers_mode_requeues_the_run() {
712        let (store, state, run_id, step_id, auth) = workers_setup().await;
713
714        let answer = json!({"answers": ["ok"]});
715        let (status, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
716
717        assert_eq!(status, StatusCode::OK);
718        assert_eq!(body["data"]["status"], "pending");
719        let run = store.get_run(run_id).await.unwrap().unwrap();
720        assert_eq!(run.status.state, RunStatus::Pending);
721        let step = store.get_step(step_id).await.unwrap().unwrap();
722        assert_eq!(step.status.state, StepStatus::Completed);
723    }
724
725    #[tokio::test]
726    async fn human_input_reject_in_workers_mode_requeues_the_run() {
727        let (store, state, run_id, step_id, auth) = workers_setup().await;
728
729        let body = json!({"reason": "out of scope"});
730        let (status, resp) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;
731
732        assert_eq!(status, StatusCode::OK);
733        assert_eq!(resp["data"]["status"], "pending");
734        let run = store.get_run(run_id).await.unwrap().unwrap();
735        assert_eq!(run.status.state, RunStatus::Pending);
736        let step = store.get_step(step_id).await.unwrap().unwrap();
737        assert_eq!(step.status.state, StepStatus::Rejected);
738    }
739
740    #[tokio::test]
741    async fn human_input_reject_without_body_uses_the_default_reason() {
742        let (store, state, run_id, step_id) = setup().await;
743        let auth = create_user_auth_header(&state, "admin", true).await;
744
745        let (status, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
746
747        assert_eq!(status, StatusCode::OK);
748        let step = store.get_step(step_id).await.unwrap().unwrap();
749        assert_eq!(step.error.as_deref(), Some("input rejected by admin"));
750    }
751
752    #[tokio::test]
753    async fn human_input_reject_with_a_blank_reason_uses_the_default_reason() {
754        let (store, state, run_id, step_id) = setup().await;
755        let auth = create_user_auth_header(&state, "admin", true).await;
756
757        let body = json!({"reason": "   "});
758        let (status, _) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;
759
760        assert_eq!(status, StatusCode::OK);
761        let step = store.get_step(step_id).await.unwrap().unwrap();
762        assert_eq!(step.error.as_deref(), Some("input rejected by admin"));
763    }
764
765    #[tokio::test]
766    async fn human_input_reject_after_submit_returns_409() {
767        let (_store, state, run_id, step_id) = setup().await;
768        let auth = create_user_auth_header(&state, "admin", true).await;
769
770        let answer = json!({"answers": ["yes"]});
771        let (first, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
772        assert_eq!(first, StatusCode::OK);
773
774        let (second, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
775        assert_eq!(second, StatusCode::CONFLICT);
776    }
777
778    #[tokio::test]
779    async fn human_input_submit_after_reject_returns_409() {
780        let (_store, state, run_id, step_id) = setup().await;
781        let auth = create_user_auth_header(&state, "admin", true).await;
782
783        let (first, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
784        assert_eq!(first, StatusCode::OK);
785
786        let answer = json!({"answers": ["yes"]});
787        let (second, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
788        assert_eq!(second, StatusCode::CONFLICT);
789        assert_eq!(body["error"]["message"], "input already rejected");
790    }
791
792    #[test]
793    fn human_input_validate_answer_without_a_schema_is_internal() {
794        let err = validate_answer(Some(&json!({"message": "Answer?"})), &json!({}))
795            .expect_err("no schema");
796        assert!(matches!(err, ApiError::Internal(_)), "got {err:?}");
797
798        let err = validate_answer(None, &json!({})).expect_err("no input");
799        assert!(matches!(err, ApiError::Internal(_)), "got {err:?}");
800    }
801
802    #[test]
803    fn human_input_validate_answer_resolves_defs_references() {
804        let schema = input_schema_for::<Nested>();
805        assert!(schema.get("$defs").is_some(), "schema: {schema}");
806        let input = json!({ HUMAN_INPUT_SCHEMA_KEY: schema });
807
808        let valid = validate_answer(Some(&input), &json!({"target": {"env": "prod"}}));
809        assert!(valid.is_ok(), "got {valid:?}");
810
811        let err = validate_answer(Some(&input), &json!({"target": {"env": 1}}))
812            .expect_err("wrong nested type");
813        match err {
814            ApiError::InvalidInput(errors) => assert_eq!(errors.len(), 1, "got {errors:?}"),
815            other => panic!("expected InvalidInput, got {other:?}"),
816        }
817    }
818}