#![cfg(feature = "subagents")]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
use std::sync::Arc;
use futures::StreamExt;
use graphrt_core::Workflow;
use graphrt_core::engine::{Engine, LinkedWorkflow, RunInput};
use graphrt_core::event::Event;
use graphrt_core::graph::Graph;
use graphrt_core::node::Registry;
use graphrt_core::nodes::workflow::check_call;
use graphrt_core::value::Value;
use indexmap::IndexMap;
use serde_json::{Value as Json, json};
fn graph(doc: Json) -> Arc<Graph> {
Arc::new(Graph::build(Workflow::from_value(doc).unwrap(), &Registry::with_builtins()).unwrap())
}
fn line() -> Arc<Graph> {
graph(json!({"graph": {
"nodes": [
{"id": "start", "type": "start", "variables": [
{"variable": "store", "type": "text", "required": true},
{"variable": "month", "type": "text", "required": true}
]},
{"id": "end", "type": "end", "outputs": [
{"variable": "store", "value_selector": ["start", "store"]},
{"variable": "month", "value_selector": ["start", "month"]},
{"variable": "region", "value_selector": ["sys", "region"]}
]}
],
"edges": [{"source": "start", "target": "end"}]
}}))
}
fn approve() -> Arc<Graph> {
graph(json!({"graph": {
"nodes": [
{"id": "start", "type": "start", "variables": [{"variable": "store", "type": "text", "required": true}]},
{"id": "check", "type": "human-input", "prompt": "Approve {{#start.store#}}?",
"form": {"fields": [{"variable": "note", "type": "text"}]}},
{"id": "end", "type": "end", "outputs": [
{"variable": "store", "value_selector": ["start", "store"]},
{"variable": "note", "value_selector": ["check", "note"]}
]}
],
"edges": [{"source": "start", "target": "check"}, {"source": "check", "handle": "submit", "target": "end"}]
}}))
}
fn again() -> Arc<Graph> {
graph(json!({"graph": {
"nodes": [
{"id": "start", "type": "start"},
{"id": "call", "type": "workflow", "workflow": "again"},
{"id": "end", "type": "end", "outputs": [{"variable": "x", "value_selector": ["call", "x"]}]}
],
"edges": [{"source": "start", "target": "call"}, {"source": "call", "target": "end"}]
}}))
}
fn report(child: &str, inputs: Json) -> Arc<Graph> {
graph(json!({"graph": {
"nodes": [
{"id": "start", "type": "start", "variables": [
{"variable": "stores", "type": "array[string]", "required": true},
{"variable": "month", "type": "text", "required": true}
]},
{"id": "each", "type": "iteration", "iterator_selector": ["start", "stores"],
"output_selector": ["call", "store"], "is_parallel": true, "parallel_nums": 3},
{"id": "each_start", "type": "iteration-start", "parent": "each"},
{"id": "call", "type": "workflow", "parent": "each", "workflow": child, "inputs": inputs},
{"id": "end", "type": "end", "outputs": [{"variable": "stores", "value_selector": ["each", "output"]}]}
],
"edges": [
{"source": "start", "target": "each"},
{"source": "each_start", "target": "call"},
{"source": "each", "target": "end"}
]
}}))
}
fn engine(parent: Arc<Graph>, linked: Vec<(&str, Arc<Graph>)>) -> Engine {
Engine::new(parent)
.with_linked(linked.into_iter().map(|(name, graph)| (name.to_owned(), LinkedWorkflow::new(graph))))
}
async fn events(engine: &Engine, input: RunInput) -> Vec<Event> {
engine.run(input).collect().await
}
fn stores() -> RunInput {
RunInput::new()
.input("stores", Value::array(["north", "south", "east"].map(Value::from)))
.input("month", "2026-10")
.sys("region", "west coast")
}
#[tokio::test]
async fn each_item_of_an_iteration_runs_the_workflow() {
let parent = report("line", json!({"store": "{{#each.item#}}", "month": "{{#start.month#}}"}));
let engine = engine(parent, vec![("line", line())]);
let events = events(&engine, stores()).await;
let Some(Event::RunSucceeded { outputs, .. }) = events.last() else { panic!("{:?}", events.last()) };
assert_eq!(outputs["stores"].to_json(), json!(["north", "south", "east"]));
let calls: Vec<Json> = events
.iter()
.filter_map(|event| match event {
Event::NodeSucceeded { node_id, outputs, .. } if node_id.as_ref() == "call" => {
Some(serde_json::to_value(outputs).unwrap())
}
_ => None,
})
.collect();
assert_eq!(calls.len(), 3);
assert!(calls.iter().all(|call| call["month"] == "2026-10" && call["region"] == "west coast"), "{calls:?}");
}
#[tokio::test]
async fn a_child_that_pauses_pauses_the_run_and_resumes_where_it_stopped() {
let parent = report("approve", json!({"store": "{{#each.item#}}"}));
let engine = engine(parent, vec![("approve", approve())]);
let input = RunInput::new().input("stores", Value::array([Value::from("north")])).input("month", "2026-10");
let events = events(&engine, input).await;
let Some(Event::RunPaused { reasons, snapshot }) = events.last() else { panic!("{:?}", events.last()) };
assert_eq!(reasons.len(), 1, "{reasons:?}");
let reason = &reasons[0];
assert_eq!(reason.kind, "human_input");
assert!(reason.frame.contains("call.approve[0]"), "{}", reason.frame);
let snapshot = graphrt_core::snapshot::Snapshot::from_json(&snapshot.to_json().unwrap()).unwrap();
let mut inputs = IndexMap::new();
let key = format!("{}/{}", reason.frame, reason.node_id.clone().unwrap());
inputs.insert(key, Value::from_json(json!({"action": "submit", "values": {"note": "looks right"}})));
let resumed = RunInput::new().resume(snapshot, inputs);
let events = self::events(&engine, resumed).await;
let Some(Event::RunSucceeded { .. }) = events.last() else { panic!("{:?}", events.last()) };
let note = events.iter().find_map(|event| match event {
Event::NodeSucceeded { node_id, outputs, .. } if node_id.as_ref() == "call" => outputs.get("note").cloned(),
_ => None,
});
assert_eq!(note, Some(Value::from("looks right")));
}
#[tokio::test]
async fn a_workflow_that_calls_itself_stops_at_the_depth_limit() {
let engine = engine(again(), vec![("again", again())]);
let events = events(&engine, RunInput::new()).await;
let Some(Event::RunFailed { error, error_type, .. }) = events.last() else { panic!("{:?}", events.last()) };
assert_eq!(error_type, "limit_exceeded", "{error}");
assert!(error.contains("depth"), "{error}");
}
#[tokio::test]
async fn an_unlinked_workflow_fails_the_node() {
let parent = report("missing", json!({}));
let engine = engine(parent, vec![("line", line())]);
let events = events(&engine, stores()).await;
let Some(Event::RunFailed { error, .. }) = events.last() else { panic!("{:?}", events.last()) };
assert!(error.contains("missing"), "{error}");
}
#[test]
fn a_call_is_checked_against_the_start_variables() {
let given = |names: &[&str]| names.iter().map(|name| (*name).to_owned()).collect::<Vec<_>>();
assert!(check_call(&line(), &given(&["store", "month"])).is_ok());
let missing = check_call(&line(), &given(&["store"])).unwrap_err();
assert!(missing.contains("`month`"), "{missing}");
let unknown = check_call(&line(), &given(&["store", "month", "year"])).unwrap_err();
assert!(unknown.contains("`year`") && unknown.contains("store, month"), "{unknown}");
}