use serde::{Deserialize, Serialize};
use crate::activity::Activity;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentChatRequest {
pub text: String,
#[serde(default)]
pub tenant: Option<String>,
#[serde(default)]
pub conversation_id: Option<String>,
#[serde(default)]
pub user_id: Option<String>,
#[serde(default)]
pub flow_id: Option<String>,
#[serde(default, rename = "resume_payload", alias = "resumePayload")]
pub resume_payload: Option<serde_json::Map<String, serde_json::Value>>,
}
pub(crate) fn turn_payload(
text: String,
resume_payload: Option<serde_json::Map<String, serde_json::Value>>,
) -> serde_json::Value {
match resume_payload {
None => serde_json::json!({ "text": text }),
Some(mut submit) => {
if !text.trim().is_empty() {
submit
.entry("text")
.or_insert(serde_json::Value::String(text));
}
serde_json::Value::Object(submit)
}
}
}
pub(crate) fn pending_card(
node_outputs: &std::collections::HashMap<String, serde_json::Value>,
) -> Option<serde_json::Value> {
node_outputs
.values()
.find_map(crate::runner::engine::tool_presentation)
.cloned()
}
fn side_turn_reply(
node_outputs: &std::collections::HashMap<String, serde_json::Value>,
) -> Option<String> {
node_outputs.values().find_map(|output| {
let is_side_turn = output.get("side_turn").and_then(|v| v.as_bool()) == Some(true);
let reply = output.get("reply").and_then(|v| v.as_str())?;
(is_side_turn && !reply.trim().is_empty()).then(|| reply.to_string())
})
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplyView {
pub text: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentChatResponse {
pub replies: Vec<ReplyView>,
#[serde(rename = "pending_card", skip_serializing_if = "Option::is_none")]
pub pending_card: Option<serde_json::Value>,
}
fn reply_text(activity: &Activity) -> String {
let payload = activity.payload();
if let Some(t) = payload.get("text").and_then(|v| v.as_str()) {
return t.to_string();
}
if let Some(t) = payload
.get("messages")
.and_then(|m| m.get(0))
.and_then(|m0| m0.get("text"))
.and_then(|v| v.as_str())
{
return t.to_string();
}
serde_json::to_string(payload).unwrap_or_default()
}
pub fn replies_to_response(activities: Vec<Activity>) -> AgentChatResponse {
let replies = activities
.iter()
.map(reply_text)
.filter(|t| !t.trim().is_empty())
.map(|text| ReplyView { text })
.collect();
AgentChatResponse {
replies,
pending_card: None,
}
}
pub fn trace_to_response(trace: crate::host::TurnTrace) -> AgentChatResponse {
match pending_card(&trace.node_outputs) {
Some(card) => AgentChatResponse {
replies: side_turn_reply(&trace.node_outputs)
.map(|text| vec![ReplyView { text }])
.unwrap_or_default(),
pending_card: Some(card),
},
None => replies_to_response(trace.replies),
}
}
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::{Json, extract::State};
use crate::host::RunnerHost;
use crate::http::auth::AdminGuard;
use crate::runner::ServerState;
const DEFAULT_CONVERSATION: &str = "test-chat";
const DEFAULT_USER: &str = "test-chat-user";
async fn execute_chat(
host: &RunnerHost,
default_tenant: &str,
req: AgentChatRequest,
) -> Result<AgentChatResponse, (StatusCode, serde_json::Value)> {
let tenant = req
.tenant
.as_deref()
.map(str::to_string)
.unwrap_or_else(|| default_tenant.to_string());
let mut activity = Activity::text("")
.with_payload(turn_payload(req.text, req.resume_payload))
.in_conversation(
req.conversation_id
.unwrap_or_else(|| DEFAULT_CONVERSATION.to_string()),
)
.from_user(req.user_id.unwrap_or_else(|| DEFAULT_USER.to_string()));
if let Some(flow) = req.flow_id {
activity = activity.with_flow(flow);
}
match host.handle_activity_traced(&tenant, activity).await {
Ok(trace) => Ok(trace_to_response(trace)),
Err(e) => {
let msg = format!("{e:#}");
let (code, error) = if msg.contains("not loaded") {
(StatusCode::NOT_FOUND, "tenant_not_loaded")
} else {
(StatusCode::INTERNAL_SERVER_ERROR, "agent_chat_failed")
};
Err((code, serde_json::json!({ "error": error, "message": msg })))
}
}
}
pub async fn agent_chat(
_guard: AdminGuard,
State(state): State<ServerState>,
Json(req): Json<AgentChatRequest>,
) -> impl IntoResponse {
match execute_chat(&state.host, state.routing.default_tenant(), req).await {
Ok(response) => (StatusCode::OK, Json(response)).into_response(),
Err((code, body)) => (code, Json(body)).into_response(),
}
}
#[cfg(feature = "agentic-worker")]
use axum::response::sse::{Event, KeepAlive, Sse};
#[cfg(feature = "agentic-worker")]
use futures::{Stream, StreamExt};
#[cfg(feature = "agentic-worker")]
use std::convert::Infallible;
#[cfg(feature = "agentic-worker")]
use std::sync::Arc;
#[cfg(feature = "agentic-worker")]
use crate::http::agent_stream::{SseForwardObserver, StreamFrame, StreamObserverRegistry};
#[cfg(feature = "agentic-worker")]
fn first_nonempty_reply(activities: &[Activity]) -> Option<String> {
activities
.iter()
.map(reply_text)
.find(|t| !t.trim().is_empty())
}
#[cfg(feature = "agentic-worker")]
struct Cleanup {
registry: StreamObserverRegistry,
conversation_id: String,
observer: Arc<dyn greentic_aw_runtime::StepObserver>,
}
#[cfg(feature = "agentic-worker")]
impl Cleanup {
fn remove_stale(
registry: &StreamObserverRegistry,
conversation_id: &str,
observer: &Arc<dyn greentic_aw_runtime::StepObserver>,
) {
registry.remove_if(conversation_id, |_k, stored| Arc::ptr_eq(stored, observer));
}
}
#[cfg(feature = "agentic-worker")]
impl Drop for Cleanup {
fn drop(&mut self) {
Self::remove_stale(&self.registry, &self.conversation_id, &self.observer);
}
}
#[cfg(feature = "agentic-worker")]
fn completed_turn_frames(trace: crate::host::TurnTrace, streamed: bool) -> Vec<StreamFrame> {
let mut frames = Vec::new();
match pending_card(&trace.node_outputs) {
Some(card) => {
if !streamed && let Some(text) = side_turn_reply(&trace.node_outputs) {
frames.push(StreamFrame::TextChunk { text });
}
frames.push(StreamFrame::PendingCard { card });
}
None => {
if !streamed && let Some(reply) = first_nonempty_reply(&trace.replies) {
frames.push(StreamFrame::TextChunk { text: reply });
}
}
}
frames.push(StreamFrame::Done);
frames
}
#[cfg(feature = "agentic-worker")]
fn build_stream_turn_activity(
payload: serde_json::Value,
conversation_id: String,
user_id: Option<String>,
flow_id: Option<String>,
) -> Activity {
let mut activity = Activity::text("")
.with_payload(payload)
.with_session(conversation_id.clone())
.in_conversation(conversation_id)
.from_user(user_id.unwrap_or_else(|| DEFAULT_USER.to_string()));
if let Some(flow) = flow_id {
activity = activity.with_flow(flow);
}
activity
}
#[cfg(feature = "agentic-worker")]
pub fn agent_chat_stream_core(
state: &ServerState,
req: AgentChatRequest,
) -> impl Stream<Item = StreamFrame> + use<> {
let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel::<StreamFrame>();
let conversation_id = req
.conversation_id
.clone()
.unwrap_or_else(|| DEFAULT_CONVERSATION.to_string());
let observer = Arc::new(SseForwardObserver::new(frame_tx.clone()));
let observer_dyn: Arc<dyn greentic_aw_runtime::StepObserver> = observer.clone();
state
.stream_observers
.insert(conversation_id.clone(), observer_dyn.clone());
let host = state.host.clone();
let default_tenant = state.routing.default_tenant().to_string();
let registry: StreamObserverRegistry = state.stream_observers.clone();
tokio::spawn(async move {
let _cleanup = Cleanup {
registry,
conversation_id: conversation_id.clone(),
observer: observer_dyn,
};
let tenant = req.tenant.unwrap_or(default_tenant);
let activity = build_stream_turn_activity(
turn_payload(req.text, req.resume_payload),
conversation_id,
req.user_id,
req.flow_id,
);
match host.handle_activity_traced(&tenant, activity).await {
Ok(trace) => {
for frame in completed_turn_frames(trace, observer.streamed()) {
let _ = frame_tx.send(frame);
}
}
Err(e) => {
let _ = frame_tx.send(StreamFrame::Error {
message: format!("{e:#}"),
});
}
}
});
futures::stream::unfold(frame_rx, |mut rx| async move {
rx.recv().await.map(|frame| (frame, rx))
})
}
#[cfg(feature = "agentic-worker")]
pub async fn agent_chat_stream(
_guard: AdminGuard,
State(state): State<ServerState>,
Json(req): Json<AgentChatRequest>,
) -> impl IntoResponse {
let stream = agent_chat_stream_core(&state, req).map(|frame| {
let data = serde_json::to_string(&frame).unwrap_or_else(|_| "null".into());
Ok::<Event, Infallible>(Event::default().event("frame").data(data))
});
Sse::new(stream).keep_alive(
KeepAlive::new()
.interval(std::time::Duration::from_secs(15))
.text("keepalive"),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::activity::Activity;
use serde_json::json;
fn reply_with(payload: serde_json::Value) -> Activity {
Activity::from_output(payload, "demo")
}
#[test]
fn maps_text_payload_to_reply() {
let out = replies_to_response(vec![reply_with(json!({"text": "hello there"}))]);
assert_eq!(out.replies.len(), 1);
assert_eq!(out.replies[0].text, "hello there");
}
#[test]
fn maps_nested_messages_text() {
let out = replies_to_response(vec![reply_with(
json!({"messages": [{"text": "nested hi"}]}),
)]);
assert_eq!(out.replies[0].text, "nested hi");
}
#[test]
fn skips_empty_and_keeps_order() {
let out = replies_to_response(vec![
reply_with(json!({"text": ""})),
reply_with(json!({"text": "second"})),
]);
assert_eq!(out.replies.len(), 1);
assert_eq!(out.replies[0].text, "second");
}
#[test]
fn request_deserializes_camel_case() {
let r: AgentChatRequest = serde_json::from_value(json!({
"text": "hi", "conversationId": "c1", "userId": "u1"
}))
.unwrap();
assert_eq!(r.text, "hi");
assert_eq!(r.conversation_id.as_deref(), Some("c1"));
assert_eq!(r.user_id.as_deref(), Some("u1"));
}
#[tokio::test]
async fn agent_chat_unknown_tenant_maps_to_not_found() {
let host = crate::host::RunnerHost::for_test();
let req = AgentChatRequest {
text: "hello".into(),
tenant: Some("nope".into()),
conversation_id: None,
user_id: None,
flow_id: None,
resume_payload: None,
};
let err = execute_chat(&host, "test", req)
.await
.expect_err("unknown tenant should fail");
assert_eq!(err.0, StatusCode::NOT_FOUND);
assert_eq!(err.1["error"], "tenant_not_loaded");
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn agent_chat_stream_unknown_tenant_emits_error_frame_not_500() {
let state = crate::runner::ServerState::for_test();
let req = AgentChatRequest {
text: "hi".into(),
tenant: Some("nope".into()),
conversation_id: Some("c1".into()),
user_id: None,
flow_id: None,
resume_payload: None,
};
let frames = drive_stream_to_vec(agent_chat_stream_core(&state, req)).await;
assert!(
matches!(frames.last(), Some(StreamFrame::Error { .. })),
"got {frames:?}"
);
assert!(state.stream_observers.get("c1").is_none());
}
#[cfg(feature = "agentic-worker")]
#[test]
fn stream_turn_activity_stamps_session_with_conversation_id() {
let activity = build_stream_turn_activity(
turn_payload("hi".into(), None),
"conv-uuid-1".into(),
None,
None,
);
assert_eq!(
activity.session_id(),
Some("conv-uuid-1"),
"stream turn must stamp session = conversationId so the canonical \
hint matches the observer registry key"
);
assert_eq!(activity.conversation(), Some("conv-uuid-1"));
}
#[cfg(feature = "agentic-worker")]
async fn drive_stream_to_vec(
stream: impl futures::Stream<Item = StreamFrame>,
) -> Vec<StreamFrame> {
use futures::StreamExt;
stream.collect().await
}
#[cfg(feature = "agentic-worker")]
#[test]
fn cleanup_remove_stale_does_not_evict_a_replaced_observer() {
let registry: StreamObserverRegistry = Arc::new(dashmap::DashMap::new());
let (tx_a, _rx_a) = tokio::sync::mpsc::unbounded_channel();
let (tx_b, _rx_b) = tokio::sync::mpsc::unbounded_channel();
let observer_a: Arc<dyn greentic_aw_runtime::StepObserver> =
Arc::new(SseForwardObserver::new(tx_a));
let observer_b: Arc<dyn greentic_aw_runtime::StepObserver> =
Arc::new(SseForwardObserver::new(tx_b));
registry.insert("c1".to_string(), observer_a.clone());
registry.insert("c1".to_string(), observer_b.clone());
Cleanup::remove_stale(®istry, "c1", &observer_a);
assert!(
registry
.get("c1")
.is_some_and(|e| Arc::ptr_eq(e.value(), &observer_b)),
"stale cleanup for A must not evict B's observer"
);
Cleanup::remove_stale(®istry, "c1", &observer_b);
assert!(registry.get("c1").is_none());
}
#[test]
fn request_carries_an_optional_resume_payload() {
let r: AgentChatRequest = serde_json::from_value(json!({
"text": "", "resume_payload": { "room": "101", "metadata": { "action": "submit" } }
}))
.unwrap();
let submit = r.resume_payload.expect("resume_payload parsed");
assert_eq!(submit["room"], "101");
let absent: AgentChatRequest = serde_json::from_value(json!({ "text": "hi" })).unwrap();
assert!(absent.resume_payload.is_none());
}
#[test]
fn turn_payload_is_the_text_or_the_submit() {
assert_eq!(turn_payload("hi".into(), None), json!({ "text": "hi" }));
let submit = json!({ "room": "101", "metadata": { "action": "submit" } });
let map = submit.as_object().cloned();
assert_eq!(
turn_payload(String::new(), map.clone()),
submit,
"an empty text adds nothing to the submit"
);
let with_text = turn_payload("done".into(), map);
assert_eq!(with_text["text"], "done");
assert_eq!(with_text["room"], "101");
}
fn parked_trace() -> crate::host::TurnTrace {
let mut node_outputs = std::collections::HashMap::new();
node_outputs.insert(
"agent".to_string(),
json!({
"reply": "",
"terminated_by": "awaiting_tool_input",
"pending_presentation": { "type": "AdaptiveCard", "body": [] }
}),
);
crate::host::TurnTrace {
replies: vec![reply_with(json!({ "status": "pending", "response": {} }))],
node_outputs,
}
}
#[test]
fn a_parked_flow_tool_surfaces_as_pending_card_and_no_replies() {
let response = trace_to_response(parked_trace());
assert!(
response.replies.is_empty(),
"the pending envelope is not a reply"
);
let body = serde_json::to_value(&response).unwrap();
assert_eq!(body["pending_card"]["type"], "AdaptiveCard");
let mut done = std::collections::HashMap::new();
done.insert(
"agent".to_string(),
json!({ "reply": "booked", "terminated_by": "final_reply" }),
);
let plain = trace_to_response(crate::host::TurnTrace {
replies: vec![reply_with(json!({ "text": "booked" }))],
node_outputs: done,
});
let body = serde_json::to_value(&plain).unwrap();
assert!(
body.get("pending_card").is_none(),
"omitted when None: {body}"
);
assert_eq!(body["replies"][0]["text"], "booked");
}
#[test]
fn a_side_turn_carries_its_reply_and_the_card() {
let mut outputs = std::collections::HashMap::new();
outputs.insert(
"agent".to_string(),
json!({
"reply": "the signature is in Settings",
"terminated_by": "awaiting_tool_input",
"side_turn": true,
"pending_presentation": { "type": "AdaptiveCard", "body": [] }
}),
);
let response = trace_to_response(crate::host::TurnTrace {
replies: vec![],
node_outputs: outputs,
});
let body = serde_json::to_value(&response).unwrap();
assert_eq!(body["replies"][0]["text"], "the signature is in Settings");
assert_eq!(body["pending_card"]["type"], "AdaptiveCard");
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_side_turn_that_was_not_streamed_sends_its_reply_before_the_card() {
let mut outputs = std::collections::HashMap::new();
outputs.insert(
"agent".to_string(),
json!({
"reply": "the signature is in Settings",
"terminated_by": "awaiting_tool_input",
"side_turn": true,
"pending_presentation": { "type": "AdaptiveCard", "body": [] }
}),
);
let trace = || crate::host::TurnTrace {
replies: vec![],
node_outputs: outputs.clone(),
};
let frames = completed_turn_frames(trace(), false);
assert!(
matches!(frames.as_slice(),
[StreamFrame::TextChunk { text }, StreamFrame::PendingCard { .. }, StreamFrame::Done]
if text == "the signature is in Settings"),
"{frames:?}"
);
let frames = completed_turn_frames(trace(), true);
assert!(
matches!(
frames.as_slice(),
[StreamFrame::PendingCard { .. }, StreamFrame::Done]
),
"{frames:?}"
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_parked_flow_tool_streams_pending_card_then_done() {
let frames = completed_turn_frames(parked_trace(), false);
assert!(
matches!(
frames.as_slice(),
[StreamFrame::PendingCard { card }, StreamFrame::Done]
if card["type"] == "AdaptiveCard"
),
"got {frames:?}"
);
let plain = completed_turn_frames(
crate::host::TurnTrace {
replies: vec![reply_with(json!({ "text": "booked" }))],
node_outputs: std::collections::HashMap::new(),
},
false,
);
assert!(
matches!(
plain.as_slice(),
[StreamFrame::TextChunk { text }, StreamFrame::Done] if text == "booked"
),
"got {plain:?}"
);
}
}