Skip to main content

greentic_runner_host/http/
agent_chat.rs

1//! `POST /agent/chat` — a loopback HTTP ingress that wraps `RunnerHost::handle_activity`
2//! so an external caller (the designer's runner sidecar) can send a chat turn to a
3//! loaded agentic-worker pack and receive the reply. Blocking JSON response (v1).
4
5use serde::{Deserialize, Serialize};
6
7use crate::activity::Activity;
8
9/// One chat turn for a loaded worker pack.
10#[derive(Debug, Deserialize)]
11#[serde(rename_all = "camelCase")]
12pub struct AgentChatRequest {
13    pub text: String,
14    #[serde(default)]
15    pub tenant: Option<String>,
16    #[serde(default)]
17    pub conversation_id: Option<String>,
18    #[serde(default)]
19    pub user_id: Option<String>,
20    #[serde(default)]
21    pub flow_id: Option<String>,
22    /// A card submit answering a `flow:` tool the worker parked on (the
23    /// previous turn ended with a `pending-card` frame / `pending_card`
24    /// field). Sent as this turn's activity payload, so the engine hands it to
25    /// the parked `dw.agent` as `AgentInput.resume_payload`. It must look like
26    /// a card submit — a non-blank `metadata.action` or submitted fields —
27    /// otherwise the engine reads it as a typed message and the agent cancels
28    /// the parked tool. Absent: an ordinary text turn.
29    #[serde(default, rename = "resume_payload", alias = "resumePayload")]
30    pub resume_payload: Option<serde_json::Map<String, serde_json::Value>>,
31}
32
33/// The payload of one chat turn: the text message, or — when the caller
34/// answers a parked `flow:` tool — the card submit, with `text` added only
35/// when the caller sent one and the submit carries none.
36pub(crate) fn turn_payload(
37    text: String,
38    resume_payload: Option<serde_json::Map<String, serde_json::Value>>,
39) -> serde_json::Value {
40    match resume_payload {
41        None => serde_json::json!({ "text": text }),
42        Some(mut submit) => {
43            if !text.trim().is_empty() {
44                submit
45                    .entry("text")
46                    .or_insert(serde_json::Value::String(text));
47            }
48            serde_json::Value::Object(submit)
49        }
50    }
51}
52
53/// The card a `dw.agent` of this turn parked on a `flow:` tool asks the user
54/// to answer: the `pending_presentation` of the node output whose
55/// `terminated_by` is `awaiting_tool_input`. `None` for any other turn.
56pub(crate) fn pending_card(
57    node_outputs: &std::collections::HashMap<String, serde_json::Value>,
58) -> Option<serde_json::Value> {
59    node_outputs
60        .values()
61        .find_map(crate::runner::engine::tool_presentation)
62        .cloned()
63}
64
65/// The agent's answer to a typed message that was handled as a side turn
66/// while a `flow:` tool stayed parked: the reply to show before the card.
67fn side_turn_reply(
68    node_outputs: &std::collections::HashMap<String, serde_json::Value>,
69) -> Option<String> {
70    node_outputs.values().find_map(|output| {
71        let is_side_turn = output.get("side_turn").and_then(|v| v.as_bool()) == Some(true);
72        let reply = output.get("reply").and_then(|v| v.as_str())?;
73        (is_side_turn && !reply.trim().is_empty()).then(|| reply.to_string())
74    })
75}
76
77/// One outbound reply line.
78#[derive(Debug, Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct ReplyView {
81    pub text: String,
82}
83
84/// The worker's reply turn.
85#[derive(Debug, Serialize)]
86#[serde(rename_all = "camelCase")]
87pub struct AgentChatResponse {
88    pub replies: Vec<ReplyView>,
89    /// The card a parked `flow:` tool asks the user to answer; send its
90    /// submit back as the next request's `resume_payload`.
91    #[serde(rename = "pending_card", skip_serializing_if = "Option::is_none")]
92    pub pending_card: Option<serde_json::Value>,
93}
94
95/// Extract a human-readable reply line from an outbound activity.
96///
97/// Priority order:
98/// 1. `payload["text"]` as a string
99/// 2. `payload["messages"][0]["text"]` as a string
100/// 3. Compact JSON rendering of the whole payload
101fn reply_text(activity: &Activity) -> String {
102    let payload = activity.payload();
103    if let Some(t) = payload.get("text").and_then(|v| v.as_str()) {
104        return t.to_string();
105    }
106    if let Some(t) = payload
107        .get("messages")
108        .and_then(|m| m.get(0))
109        .and_then(|m0| m0.get("text"))
110        .and_then(|v| v.as_str())
111    {
112        return t.to_string();
113    }
114    serde_json::to_string(payload).unwrap_or_default()
115}
116
117/// Map the runtime's outbound activities into the chat response, dropping empties.
118pub fn replies_to_response(activities: Vec<Activity>) -> AgentChatResponse {
119    let replies = activities
120        .iter()
121        .map(reply_text)
122        .filter(|t| !t.trim().is_empty())
123        .map(|text| ReplyView { text })
124        .collect();
125    AgentChatResponse {
126        replies,
127        pending_card: None,
128    }
129}
130
131/// Map a traced turn into the chat response. A turn that parked on a `flow:`
132/// tool carries the card as `pending_card` and no replies — its only outbound
133/// activity is the pending-flow envelope, which `reply_text` would render as a
134/// JSON blob rather than a line the user should read — except a side turn,
135/// whose answer is the one reply.
136pub fn trace_to_response(trace: crate::host::TurnTrace) -> AgentChatResponse {
137    match pending_card(&trace.node_outputs) {
138        Some(card) => AgentChatResponse {
139            replies: side_turn_reply(&trace.node_outputs)
140                .map(|text| vec![ReplyView { text }])
141                .unwrap_or_default(),
142            pending_card: Some(card),
143        },
144        None => replies_to_response(trace.replies),
145    }
146}
147
148use axum::http::StatusCode;
149use axum::response::IntoResponse;
150use axum::{Json, extract::State};
151
152use crate::host::RunnerHost;
153use crate::http::auth::AdminGuard;
154use crate::runner::ServerState;
155
156/// Default conversation/user identifiers so a caller that omits them still
157/// threads a single in-memory conversation across turns.
158const DEFAULT_CONVERSATION: &str = "test-chat";
159const DEFAULT_USER: &str = "test-chat-user";
160
161/// Extracted core logic — separated so tests can exercise tenant resolution
162/// and error mapping without needing the full axum extractor stack.
163async fn execute_chat(
164    host: &RunnerHost,
165    default_tenant: &str,
166    req: AgentChatRequest,
167) -> Result<AgentChatResponse, (StatusCode, serde_json::Value)> {
168    let tenant = req
169        .tenant
170        .as_deref()
171        .map(str::to_string)
172        .unwrap_or_else(|| default_tenant.to_string());
173
174    let mut activity = Activity::text("")
175        .with_payload(turn_payload(req.text, req.resume_payload))
176        .in_conversation(
177            req.conversation_id
178                .unwrap_or_else(|| DEFAULT_CONVERSATION.to_string()),
179        )
180        .from_user(req.user_id.unwrap_or_else(|| DEFAULT_USER.to_string()));
181    if let Some(flow) = req.flow_id {
182        activity = activity.with_flow(flow);
183    }
184
185    // Typed pre-check instead of matching on error text.
186    if host.active_packs().load_pack(&tenant).is_none() {
187        return Err(ChatError::TenantNotLoaded.into_response_parts());
188    }
189
190    match host.handle_activity_traced(&tenant, activity).await {
191        Ok(trace) => Ok(trace_to_response(trace)),
192        Err(e) => {
193            // Full chain goes to the log only; clients get a generic message.
194            tracing::error!(tenant = %tenant, error = %format!("{e:#}"), "agent chat turn failed");
195            Err(ChatError::Internal.into_response_parts())
196        }
197    }
198}
199
200/// Run `fut` on its own task and wait for it. If the caller's future is
201/// dropped (client disconnect, request timeout) the task keeps running to
202/// completion, so a turn is never cancelled between its work and its state
203/// save / lock release. A panic in `fut` comes back as a `JoinError`.
204pub(crate) async fn run_detached<T, F>(fut: F) -> Result<T, tokio::task::JoinError>
205where
206    F: std::future::Future<Output = T> + Send + 'static,
207    T: Send + 'static,
208{
209    tokio::spawn(fut).await
210}
211
212/// Failure modes of one chat turn, mapped to a status and a stable client body.
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214enum ChatError {
215    TenantNotLoaded,
216    Internal,
217}
218
219impl ChatError {
220    fn into_response_parts(self) -> (StatusCode, serde_json::Value) {
221        match self {
222            Self::TenantNotLoaded => (
223                StatusCode::NOT_FOUND,
224                serde_json::json!({ "error": "tenant_not_loaded", "message": "tenant not loaded" }),
225            ),
226            Self::Internal => (
227                StatusCode::INTERNAL_SERVER_ERROR,
228                serde_json::json!({ "error": "agent_chat_failed", "message": "agent chat failed" }),
229            ),
230        }
231    }
232}
233
234/// `POST /agent/chat` — loopback-only (AdminGuard). Sends one chat turn to
235/// the loaded worker pack and returns its reply.
236pub async fn agent_chat(
237    _guard: AdminGuard,
238    State(state): State<ServerState>,
239    Json(req): Json<AgentChatRequest>,
240) -> impl IntoResponse {
241    let host = state.host.clone();
242    let default_tenant = state.routing.default_tenant().to_string();
243    let outcome = run_detached(async move { execute_chat(&host, &default_tenant, req).await })
244        .await
245        .unwrap_or_else(|e| {
246            tracing::error!(error = %e, "agent chat turn task panicked or was cancelled");
247            Err(ChatError::Internal.into_response_parts())
248        });
249    match outcome {
250        Ok(response) => (StatusCode::OK, Json(response)).into_response(),
251        Err((code, body)) => (code, Json(body)).into_response(),
252    }
253}
254
255#[cfg(feature = "agentic-worker")]
256use axum::response::sse::{Event, KeepAlive, Sse};
257#[cfg(feature = "agentic-worker")]
258use futures::{Stream, StreamExt};
259#[cfg(feature = "agentic-worker")]
260use std::convert::Infallible;
261#[cfg(feature = "agentic-worker")]
262use std::sync::Arc;
263
264#[cfg(feature = "agentic-worker")]
265use crate::http::agent_stream::{SseForwardObserver, StreamFrame, StreamObserverRegistry};
266
267/// Extract the first non-empty reply line from a turn's outbound activities,
268/// using the same mapping `replies_to_response` uses for the non-streaming
269/// `/agent/chat` endpoint.
270#[cfg(feature = "agentic-worker")]
271fn first_nonempty_reply(activities: &[Activity]) -> Option<String> {
272    activities
273        .iter()
274        .map(reply_text)
275        .find(|t| !t.trim().is_empty())
276}
277
278/// RAII guard: removes this turn's entry from `stream_observers` on every
279/// exit path (Ok, Err, or a panic unwinding through the task). The registry
280/// is keyed only by `conversationId`, so a stale guard from an earlier turn
281/// must not evict a newer turn's observer — `Drop` only removes the entry
282/// when it is still THIS turn's observer (`Arc::ptr_eq`), so a guard whose
283/// entry was already replaced by a newer overlapping turn is a no-op.
284#[cfg(feature = "agentic-worker")]
285struct Cleanup {
286    registry: StreamObserverRegistry,
287    conversation_id: String,
288    observer: Arc<dyn greentic_aw_runtime::StepObserver>,
289}
290
291#[cfg(feature = "agentic-worker")]
292impl Cleanup {
293    /// The remove-if predicate, extracted so it can be exercised directly by
294    /// tests without needing a full `tokio::spawn` + `Drop` round-trip.
295    fn remove_stale(
296        registry: &StreamObserverRegistry,
297        conversation_id: &str,
298        observer: &Arc<dyn greentic_aw_runtime::StepObserver>,
299    ) {
300        registry.remove_if(conversation_id, |_k, stored| Arc::ptr_eq(stored, observer));
301    }
302}
303
304#[cfg(feature = "agentic-worker")]
305impl Drop for Cleanup {
306    fn drop(&mut self) {
307        Self::remove_stale(&self.registry, &self.conversation_id, &self.observer);
308    }
309}
310
311/// The frames a successfully completed stream turn ends with, in order.
312///
313/// - No-delta fallback: a single `TextChunk` synthesized from the assembled
314///   reply, only when the backend never streamed token deltas via the
315///   observer — a streaming backend already delivered its text incrementally,
316///   so emitting the reply again would double-print it. Skipped for a turn
317///   that parked on a `flow:` tool: its only reply is the pending-flow
318///   envelope, not text.
319/// - `PendingCard` when a `dw.agent` parked on a `flow:` tool.
320/// - The terminal `Done`, always.
321#[cfg(feature = "agentic-worker")]
322fn completed_turn_frames(trace: crate::host::TurnTrace, streamed: bool) -> Vec<StreamFrame> {
323    let mut frames = Vec::new();
324    match pending_card(&trace.node_outputs) {
325        Some(card) => {
326            // A side turn's answer has not reached the client unless it was
327            // streamed token by token.
328            if !streamed && let Some(text) = side_turn_reply(&trace.node_outputs) {
329                frames.push(StreamFrame::TextChunk { text });
330            }
331            frames.push(StreamFrame::PendingCard { card });
332        }
333        None => {
334            if !streamed && let Some(reply) = first_nonempty_reply(&trace.replies) {
335                frames.push(StreamFrame::TextChunk { text: reply });
336            }
337        }
338    }
339    frames.push(StreamFrame::Done);
340    frames
341}
342
343/// Build the ingress [`Activity`] for one `/agent/chat/stream` turn.
344///
345/// The session id is stamped with the `conversationId` on purpose. The SSE
346/// handler registers this turn's stream observer keyed by the raw
347/// `conversationId` (`stream_observers.insert(conversation_id, ..)`), while the
348/// `dw.agent` node looks that observer up by the node's `session_id` — which is
349/// the canonical ingress session hint. Leaving the session unset makes
350/// `IngressEnvelope::canonicalize` derive a 5-part
351/// `{tenant}:{provider}:{channel}:{conversation}:{user}` hint that never equals
352/// the bare `conversationId`, so the lookup misses, the turn runs with no
353/// observer, and it silently falls back to a single non-streamed reply (no
354/// token / tool / llm-call frames — the "no trace log" bug). Stamping the
355/// session keeps the hint bare so the registration and lookup keys agree.
356#[cfg(feature = "agentic-worker")]
357fn build_stream_turn_activity(
358    payload: serde_json::Value,
359    conversation_id: String,
360    user_id: Option<String>,
361    flow_id: Option<String>,
362) -> Activity {
363    let mut activity = Activity::text("")
364        .with_payload(payload)
365        .with_session(conversation_id.clone())
366        .in_conversation(conversation_id)
367        .from_user(user_id.unwrap_or_else(|| DEFAULT_USER.to_string()));
368    if let Some(flow) = flow_id {
369        activity = activity.with_flow(flow);
370    }
371    activity
372}
373
374/// Extractor-free core: registers a streaming observer under the
375/// conversation id, runs the turn on a background task, and returns a stream
376/// of frames. Mirrors `execute_chat`'s extractor-free split so tests can
377/// drive it without axum's extractor stack.
378///
379/// The `stream_observers` registry assumes at most one in-flight streaming
380/// turn per `conversationId`; a second overlapping turn on the same id
381/// replaces the first turn's registry entry (see `Cleanup` above for how the
382/// first turn's eventual cleanup avoids evicting the replacement).
383#[cfg(feature = "agentic-worker")]
384pub fn agent_chat_stream_core(
385    state: &ServerState,
386    req: AgentChatRequest,
387) -> impl Stream<Item = StreamFrame> + use<> {
388    let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel::<StreamFrame>();
389    let conversation_id = req
390        .conversation_id
391        .clone()
392        .unwrap_or_else(|| DEFAULT_CONVERSATION.to_string());
393
394    let observer = Arc::new(SseForwardObserver::new(frame_tx.clone()));
395    let observer_dyn: Arc<dyn greentic_aw_runtime::StepObserver> = observer.clone();
396    state
397        .stream_observers
398        .insert(conversation_id.clone(), observer_dyn.clone());
399
400    let host = state.host.clone();
401    let default_tenant = state.routing.default_tenant().to_string();
402    let registry: StreamObserverRegistry = state.stream_observers.clone();
403
404    let panic_tx = frame_tx.clone();
405    let turn = tokio::spawn(async move {
406        // See `Cleanup`'s doc comment for why this guard is ptr_eq-protected.
407        let _cleanup = Cleanup {
408            registry,
409            conversation_id: conversation_id.clone(),
410            observer: observer_dyn,
411        };
412
413        let tenant = req.tenant.unwrap_or(default_tenant);
414        let activity = build_stream_turn_activity(
415            turn_payload(req.text, req.resume_payload),
416            conversation_id,
417            req.user_id,
418            req.flow_id,
419        );
420
421        match host.handle_activity_traced(&tenant, activity).await {
422            Ok(trace) => {
423                for frame in completed_turn_frames(trace, observer.streamed()) {
424                    let _ = frame_tx.send(frame);
425                }
426            }
427            Err(e) => {
428                tracing::error!(error = %format!("{e:#}"), "agent chat stream turn failed");
429                let _ = frame_tx.send(StreamFrame::Error {
430                    message: "agent chat failed".to_string(),
431                });
432            }
433        }
434    });
435    // A panic inside the turn would otherwise close the stream with no
436    // terminal frame; surface it as an `Error` frame.
437    tokio::spawn(async move {
438        if let Err(e) = turn.await {
439            tracing::error!(error = %e, "agent chat stream turn task panicked");
440            let _ = panic_tx.send(StreamFrame::Error {
441                message: "agent chat failed".to_string(),
442            });
443        }
444    });
445
446    futures::stream::unfold(frame_rx, |mut rx| async move {
447        rx.recv().await.map(|frame| (frame, rx))
448    })
449}
450
451/// `POST /agent/chat/stream` — loopback-only (AdminGuard). SSE variant of
452/// `/agent/chat`: streams token/tool frames then a terminal `done`/`error`
453/// frame. Headers are sent as soon as the stream opens, so a turn that fails
454/// (e.g. unknown tenant) still returns 200 with an `error` frame rather than
455/// a 4xx/5xx status.
456#[cfg(feature = "agentic-worker")]
457pub async fn agent_chat_stream(
458    _guard: AdminGuard,
459    State(state): State<ServerState>,
460    Json(req): Json<AgentChatRequest>,
461) -> impl IntoResponse {
462    let stream = agent_chat_stream_core(&state, req).map(|frame| {
463        let data = serde_json::to_string(&frame).unwrap_or_else(|_| "null".into());
464        Ok::<Event, Infallible>(Event::default().event("frame").data(data))
465    });
466    Sse::new(stream).keep_alive(
467        KeepAlive::new()
468            .interval(std::time::Duration::from_secs(15))
469            .text("keepalive"),
470    )
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use crate::activity::Activity;
477    use serde_json::json;
478
479    fn reply_with(payload: serde_json::Value) -> Activity {
480        // Build an outbound-style activity carrying `payload`. Use the same
481        // constructor the runner uses for replies (Activity::from_output) —
482        // read activity.rs and match it; here we assert on the mapping only.
483        Activity::from_output(payload, "demo")
484    }
485
486    #[test]
487    fn maps_text_payload_to_reply() {
488        let out = replies_to_response(vec![reply_with(json!({"text": "hello there"}))]);
489        assert_eq!(out.replies.len(), 1);
490        assert_eq!(out.replies[0].text, "hello there");
491    }
492
493    #[test]
494    fn maps_nested_messages_text() {
495        let out = replies_to_response(vec![reply_with(
496            json!({"messages": [{"text": "nested hi"}]}),
497        )]);
498        assert_eq!(out.replies[0].text, "nested hi");
499    }
500
501    #[test]
502    fn skips_empty_and_keeps_order() {
503        let out = replies_to_response(vec![
504            reply_with(json!({"text": ""})),
505            reply_with(json!({"text": "second"})),
506        ]);
507        assert_eq!(out.replies.len(), 1);
508        assert_eq!(out.replies[0].text, "second");
509    }
510
511    #[test]
512    fn request_deserializes_camel_case() {
513        let r: AgentChatRequest = serde_json::from_value(json!({
514            "text": "hi", "conversationId": "c1", "userId": "u1"
515        }))
516        .unwrap();
517        assert_eq!(r.text, "hi");
518        assert_eq!(r.conversation_id.as_deref(), Some("c1"));
519        assert_eq!(r.user_id.as_deref(), Some("u1"));
520    }
521
522    /// Route wiring smoke-test: `execute_chat` against a host with no loaded
523    /// packs returns 404 with `error = "tenant_not_loaded"`, proving that
524    /// `handle_activity`'s "not loaded" error is correctly mapped by the handler
525    /// core.
526    #[tokio::test]
527    async fn agent_chat_unknown_tenant_maps_to_not_found() {
528        let host = crate::host::RunnerHost::for_test();
529        let req = AgentChatRequest {
530            text: "hello".into(),
531            tenant: Some("nope".into()),
532            conversation_id: None,
533            user_id: None,
534            flow_id: None,
535            resume_payload: None,
536        };
537        let err = execute_chat(&host, "test", req)
538            .await
539            .expect_err("unknown tenant should fail");
540        assert_eq!(err.0, StatusCode::NOT_FOUND);
541        assert_eq!(err.1["error"], "tenant_not_loaded");
542    }
543
544    #[tokio::test]
545    async fn run_detached_survives_dropped_caller() {
546        let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
547        let (go_tx, go_rx) = tokio::sync::oneshot::channel::<()>();
548        let caller = run_detached(async move {
549            let _ = go_rx.await;
550            let _ = done_tx.send(());
551        });
552        // Poll the caller briefly then drop it (simulates client disconnect).
553        let _ = tokio::time::timeout(std::time::Duration::from_millis(20), caller).await;
554        let _ = go_tx.send(());
555        let finished = tokio::time::timeout(std::time::Duration::from_secs(2), done_rx).await;
556        assert!(matches!(finished, Ok(Ok(()))), "task must outlive caller");
557    }
558
559    #[tokio::test]
560    async fn run_detached_reports_panics_as_join_error() {
561        let res = run_detached(async { panic!("boom") }).await;
562        assert!(res.is_err_and(|e| e.is_panic()));
563    }
564
565    #[test]
566    fn internal_chat_error_is_generic() {
567        let (code, body) = ChatError::Internal.into_response_parts();
568        assert_eq!(code, StatusCode::INTERNAL_SERVER_ERROR);
569        assert_eq!(body["message"], "agent chat failed");
570    }
571
572    /// With no loaded pack, the turn errors; the SSE core must still deliver a
573    /// single `error` frame (not panic / not silently swallow), and the
574    /// conversation's registry entry must be cleaned up afterwards (RAII guard).
575    #[cfg(feature = "agentic-worker")]
576    #[tokio::test]
577    async fn agent_chat_stream_unknown_tenant_emits_error_frame_not_500() {
578        let state = crate::runner::ServerState::for_test();
579        let req = AgentChatRequest {
580            text: "hi".into(),
581            tenant: Some("nope".into()),
582            conversation_id: Some("c1".into()),
583            user_id: None,
584            flow_id: None,
585            resume_payload: None,
586        };
587        let frames = drive_stream_to_vec(agent_chat_stream_core(&state, req)).await;
588        assert!(
589            matches!(frames.last(), Some(StreamFrame::Error { .. })),
590            "got {frames:?}"
591        );
592        // registry cleaned up after the turn
593        assert!(state.stream_observers.get("c1").is_none());
594    }
595
596    /// Regression for the silent "no trace" bug on `/agent/chat/stream`: the
597    /// SSE handler registers the turn's stream observer keyed by the raw
598    /// `conversationId` (`stream_observers.insert(conversation_id, ..)`), but the
599    /// dw.agent node looks it up by the canonical ingress session hint. When the
600    /// activity carries no explicit session, `canonicalize` derives a 5-part
601    /// `{tenant}:{provider}:{channel}:{conversation}:{user}` hint that never
602    /// equals the bare `conversationId`, the observer is never found, and the
603    /// turn silently falls back to a single non-streamed reply (no tool / token
604    /// frames). Stamping session = conversationId keeps the hint bare so the two
605    /// keys match.
606    #[cfg(feature = "agentic-worker")]
607    #[test]
608    fn stream_turn_activity_stamps_session_with_conversation_id() {
609        let activity = build_stream_turn_activity(
610            turn_payload("hi".into(), None),
611            "conv-uuid-1".into(),
612            None,
613            None,
614        );
615        assert_eq!(
616            activity.session_id(),
617            Some("conv-uuid-1"),
618            "stream turn must stamp session = conversationId so the canonical \
619             hint matches the observer registry key"
620        );
621        assert_eq!(activity.conversation(), Some("conv-uuid-1"));
622    }
623
624    #[cfg(feature = "agentic-worker")]
625    async fn drive_stream_to_vec(
626        stream: impl futures::Stream<Item = StreamFrame>,
627    ) -> Vec<StreamFrame> {
628        use futures::StreamExt;
629        stream.collect().await
630    }
631
632    /// Two overlapping turns on the same `conversationId`: the second
633    /// `insert` replaces the first turn's observer. The first turn's stale
634    /// `Cleanup` must not evict the second turn's observer (ptr_eq guard);
635    /// the second turn's own cleanup does remove it.
636    #[cfg(feature = "agentic-worker")]
637    #[test]
638    fn cleanup_remove_stale_does_not_evict_a_replaced_observer() {
639        let registry: StreamObserverRegistry = Arc::new(dashmap::DashMap::new());
640        let (tx_a, _rx_a) = tokio::sync::mpsc::unbounded_channel();
641        let (tx_b, _rx_b) = tokio::sync::mpsc::unbounded_channel();
642        let observer_a: Arc<dyn greentic_aw_runtime::StepObserver> =
643            Arc::new(SseForwardObserver::new(tx_a));
644        let observer_b: Arc<dyn greentic_aw_runtime::StepObserver> =
645            Arc::new(SseForwardObserver::new(tx_b));
646
647        registry.insert("c1".to_string(), observer_a.clone());
648        // A second overlapping turn on the same conversation id replaces A.
649        registry.insert("c1".to_string(), observer_b.clone());
650
651        // A's stale cleanup must not evict B's entry.
652        Cleanup::remove_stale(&registry, "c1", &observer_a);
653        assert!(
654            registry
655                .get("c1")
656                .is_some_and(|e| Arc::ptr_eq(e.value(), &observer_b)),
657            "stale cleanup for A must not evict B's observer"
658        );
659
660        // B's own cleanup removes its entry.
661        Cleanup::remove_stale(&registry, "c1", &observer_b);
662        assert!(registry.get("c1").is_none());
663    }
664
665    #[test]
666    fn request_carries_an_optional_resume_payload() {
667        let r: AgentChatRequest = serde_json::from_value(json!({
668            "text": "", "resume_payload": { "room": "101", "metadata": { "action": "submit" } }
669        }))
670        .unwrap();
671        let submit = r.resume_payload.expect("resume_payload parsed");
672        assert_eq!(submit["room"], "101");
673
674        let absent: AgentChatRequest = serde_json::from_value(json!({ "text": "hi" })).unwrap();
675        assert!(absent.resume_payload.is_none());
676    }
677
678    #[test]
679    fn turn_payload_is_the_text_or_the_submit() {
680        assert_eq!(turn_payload("hi".into(), None), json!({ "text": "hi" }));
681
682        let submit = json!({ "room": "101", "metadata": { "action": "submit" } });
683        let map = submit.as_object().cloned();
684        assert_eq!(
685            turn_payload(String::new(), map.clone()),
686            submit,
687            "an empty text adds nothing to the submit"
688        );
689        let with_text = turn_payload("done".into(), map);
690        assert_eq!(with_text["text"], "done");
691        assert_eq!(with_text["room"], "101");
692    }
693
694    fn parked_trace() -> crate::host::TurnTrace {
695        let mut node_outputs = std::collections::HashMap::new();
696        node_outputs.insert(
697            "agent".to_string(),
698            json!({
699                "reply": "",
700                "terminated_by": "awaiting_tool_input",
701                "pending_presentation": { "type": "AdaptiveCard", "body": [] }
702            }),
703        );
704        crate::host::TurnTrace {
705            replies: vec![reply_with(json!({ "status": "pending", "response": {} }))],
706            node_outputs,
707        }
708    }
709
710    #[test]
711    fn a_parked_flow_tool_surfaces_as_pending_card_and_no_replies() {
712        let response = trace_to_response(parked_trace());
713        assert!(
714            response.replies.is_empty(),
715            "the pending envelope is not a reply"
716        );
717        let body = serde_json::to_value(&response).unwrap();
718        assert_eq!(body["pending_card"]["type"], "AdaptiveCard");
719
720        let mut done = std::collections::HashMap::new();
721        done.insert(
722            "agent".to_string(),
723            json!({ "reply": "booked", "terminated_by": "final_reply" }),
724        );
725        let plain = trace_to_response(crate::host::TurnTrace {
726            replies: vec![reply_with(json!({ "text": "booked" }))],
727            node_outputs: done,
728        });
729        let body = serde_json::to_value(&plain).unwrap();
730        assert!(
731            body.get("pending_card").is_none(),
732            "omitted when None: {body}"
733        );
734        assert_eq!(body["replies"][0]["text"], "booked");
735    }
736
737    #[test]
738    fn a_side_turn_carries_its_reply_and_the_card() {
739        let mut outputs = std::collections::HashMap::new();
740        outputs.insert(
741            "agent".to_string(),
742            json!({
743                "reply": "the signature is in Settings",
744                "terminated_by": "awaiting_tool_input",
745                "side_turn": true,
746                "pending_presentation": { "type": "AdaptiveCard", "body": [] }
747            }),
748        );
749        let response = trace_to_response(crate::host::TurnTrace {
750            replies: vec![],
751            node_outputs: outputs,
752        });
753        let body = serde_json::to_value(&response).unwrap();
754        assert_eq!(body["replies"][0]["text"], "the signature is in Settings");
755        assert_eq!(body["pending_card"]["type"], "AdaptiveCard");
756    }
757
758    #[cfg(feature = "agentic-worker")]
759    #[test]
760    fn a_side_turn_that_was_not_streamed_sends_its_reply_before_the_card() {
761        let mut outputs = std::collections::HashMap::new();
762        outputs.insert(
763            "agent".to_string(),
764            json!({
765                "reply": "the signature is in Settings",
766                "terminated_by": "awaiting_tool_input",
767                "side_turn": true,
768                "pending_presentation": { "type": "AdaptiveCard", "body": [] }
769            }),
770        );
771        let trace = || crate::host::TurnTrace {
772            replies: vec![],
773            node_outputs: outputs.clone(),
774        };
775        let frames = completed_turn_frames(trace(), false);
776        assert!(
777            matches!(frames.as_slice(),
778                [StreamFrame::TextChunk { text }, StreamFrame::PendingCard { .. }, StreamFrame::Done]
779                    if text == "the signature is in Settings"),
780            "{frames:?}"
781        );
782        // Already streamed token by token: only the card follows.
783        let frames = completed_turn_frames(trace(), true);
784        assert!(
785            matches!(
786                frames.as_slice(),
787                [StreamFrame::PendingCard { .. }, StreamFrame::Done]
788            ),
789            "{frames:?}"
790        );
791    }
792
793    #[cfg(feature = "agentic-worker")]
794    #[test]
795    fn a_parked_flow_tool_streams_pending_card_then_done() {
796        let frames = completed_turn_frames(parked_trace(), false);
797        assert!(
798            matches!(
799                frames.as_slice(),
800                [StreamFrame::PendingCard { card }, StreamFrame::Done]
801                    if card["type"] == "AdaptiveCard"
802            ),
803            "got {frames:?}"
804        );
805
806        let plain = completed_turn_frames(
807            crate::host::TurnTrace {
808                replies: vec![reply_with(json!({ "text": "booked" }))],
809                node_outputs: std::collections::HashMap::new(),
810            },
811            false,
812        );
813        assert!(
814            matches!(
815                plain.as_slice(),
816                [StreamFrame::TextChunk { text }, StreamFrame::Done] if text == "booked"
817            ),
818            "got {plain:?}"
819        );
820    }
821}