greentic-runner-host 1.2.0

Host runtime shim for Greentic runner: config, pack loading, activity handling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! `POST /agent/chat` — a loopback HTTP ingress that wraps `RunnerHost::handle_activity`
//! so an external caller (the designer's runner sidecar) can send a chat turn to a
//! loaded agentic-worker pack and receive the reply. Blocking JSON response (v1).

use serde::{Deserialize, Serialize};

use crate::activity::Activity;

/// One chat turn for a loaded worker pack.
#[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>,
    /// A card submit answering a `flow:` tool the worker parked on (the
    /// previous turn ended with a `pending-card` frame / `pending_card`
    /// field). Sent as this turn's activity payload, so the engine hands it to
    /// the parked `dw.agent` as `AgentInput.resume_payload`. It must look like
    /// a card submit — a non-blank `metadata.action` or submitted fields —
    /// otherwise the engine reads it as a typed message and the agent cancels
    /// the parked tool. Absent: an ordinary text turn.
    #[serde(default, rename = "resume_payload", alias = "resumePayload")]
    pub resume_payload: Option<serde_json::Map<String, serde_json::Value>>,
}

/// The payload of one chat turn: the text message, or — when the caller
/// answers a parked `flow:` tool — the card submit, with `text` added only
/// when the caller sent one and the submit carries none.
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)
        }
    }
}

/// The card a `dw.agent` of this turn parked on a `flow:` tool asks the user
/// to answer: the `pending_presentation` of the node output whose
/// `terminated_by` is `awaiting_tool_input`. `None` for any other turn.
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()
}

/// The agent's answer to a typed message that was handled as a side turn
/// while a `flow:` tool stayed parked: the reply to show before the card.
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())
    })
}

/// One outbound reply line.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplyView {
    pub text: String,
}

/// The worker's reply turn.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentChatResponse {
    pub replies: Vec<ReplyView>,
    /// The card a parked `flow:` tool asks the user to answer; send its
    /// submit back as the next request's `resume_payload`.
    #[serde(rename = "pending_card", skip_serializing_if = "Option::is_none")]
    pub pending_card: Option<serde_json::Value>,
}

/// Extract a human-readable reply line from an outbound activity.
///
/// Priority order:
/// 1. `payload["text"]` as a string
/// 2. `payload["messages"][0]["text"]` as a string
/// 3. Compact JSON rendering of the whole payload
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()
}

/// Map the runtime's outbound activities into the chat response, dropping empties.
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,
    }
}

/// Map a traced turn into the chat response. A turn that parked on a `flow:`
/// tool carries the card as `pending_card` and no replies — its only outbound
/// activity is the pending-flow envelope, which `reply_text` would render as a
/// JSON blob rather than a line the user should read — except a side turn,
/// whose answer is the one reply.
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;

/// Default conversation/user identifiers so a caller that omits them still
/// threads a single in-memory conversation across turns.
const DEFAULT_CONVERSATION: &str = "test-chat";
const DEFAULT_USER: &str = "test-chat-user";

/// Extracted core logic — separated so tests can exercise tenant resolution
/// and error mapping without needing the full axum extractor stack.
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:#}");
            // handle_activity returns "tenant <name> not loaded" when the tenant
            // isn't present in ActivePacks. Surface that as 404.
            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 })))
        }
    }
}

/// `POST /agent/chat` — loopback-only (AdminGuard). Sends one chat turn to
/// the loaded worker pack and returns its reply.
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};

/// Extract the first non-empty reply line from a turn's outbound activities,
/// using the same mapping `replies_to_response` uses for the non-streaming
/// `/agent/chat` endpoint.
#[cfg(feature = "agentic-worker")]
fn first_nonempty_reply(activities: &[Activity]) -> Option<String> {
    activities
        .iter()
        .map(reply_text)
        .find(|t| !t.trim().is_empty())
}

/// RAII guard: removes this turn's entry from `stream_observers` on every
/// exit path (Ok, Err, or a panic unwinding through the task). The registry
/// is keyed only by `conversationId`, so a stale guard from an earlier turn
/// must not evict a newer turn's observer — `Drop` only removes the entry
/// when it is still THIS turn's observer (`Arc::ptr_eq`), so a guard whose
/// entry was already replaced by a newer overlapping turn is a no-op.
#[cfg(feature = "agentic-worker")]
struct Cleanup {
    registry: StreamObserverRegistry,
    conversation_id: String,
    observer: Arc<dyn greentic_aw_runtime::StepObserver>,
}

#[cfg(feature = "agentic-worker")]
impl Cleanup {
    /// The remove-if predicate, extracted so it can be exercised directly by
    /// tests without needing a full `tokio::spawn` + `Drop` round-trip.
    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);
    }
}

/// The frames a successfully completed stream turn ends with, in order.
///
/// - No-delta fallback: a single `TextChunk` synthesized from the assembled
///   reply, only when the backend never streamed token deltas via the
///   observer — a streaming backend already delivered its text incrementally,
///   so emitting the reply again would double-print it. Skipped for a turn
///   that parked on a `flow:` tool: its only reply is the pending-flow
///   envelope, not text.
/// - `PendingCard` when a `dw.agent` parked on a `flow:` tool.
/// - The terminal `Done`, always.
#[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) => {
            // A side turn's answer has not reached the client unless it was
            // streamed token by token.
            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
}

/// Build the ingress [`Activity`] for one `/agent/chat/stream` turn.
///
/// The session id is stamped with the `conversationId` on purpose. The SSE
/// handler registers this turn's stream observer keyed by the raw
/// `conversationId` (`stream_observers.insert(conversation_id, ..)`), while the
/// `dw.agent` node looks that observer up by the node's `session_id` — which is
/// the canonical ingress session hint. Leaving the session unset makes
/// `IngressEnvelope::canonicalize` derive a 5-part
/// `{tenant}:{provider}:{channel}:{conversation}:{user}` hint that never equals
/// the bare `conversationId`, so the lookup misses, the turn runs with no
/// observer, and it silently falls back to a single non-streamed reply (no
/// token / tool / llm-call frames — the "no trace log" bug). Stamping the
/// session keeps the hint bare so the registration and lookup keys agree.
#[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
}

/// Extractor-free core: registers a streaming observer under the
/// conversation id, runs the turn on a background task, and returns a stream
/// of frames. Mirrors `execute_chat`'s extractor-free split so tests can
/// drive it without axum's extractor stack.
///
/// The `stream_observers` registry assumes at most one in-flight streaming
/// turn per `conversationId`; a second overlapping turn on the same id
/// replaces the first turn's registry entry (see `Cleanup` above for how the
/// first turn's eventual cleanup avoids evicting the replacement).
#[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 {
        // See `Cleanup`'s doc comment for why this guard is ptr_eq-protected.
        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))
    })
}

/// `POST /agent/chat/stream` — loopback-only (AdminGuard). SSE variant of
/// `/agent/chat`: streams token/tool frames then a terminal `done`/`error`
/// frame. Headers are sent as soon as the stream opens, so a turn that fails
/// (e.g. unknown tenant) still returns 200 with an `error` frame rather than
/// a 4xx/5xx status.
#[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 {
        // Build an outbound-style activity carrying `payload`. Use the same
        // constructor the runner uses for replies (Activity::from_output) —
        // read activity.rs and match it; here we assert on the mapping only.
        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"));
    }

    /// Route wiring smoke-test: `execute_chat` against a host with no loaded
    /// packs returns 404 with `error = "tenant_not_loaded"`, proving that
    /// `handle_activity`'s "not loaded" error is correctly mapped by the handler
    /// core.
    #[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");
    }

    /// With no loaded pack, the turn errors; the SSE core must still deliver a
    /// single `error` frame (not panic / not silently swallow), and the
    /// conversation's registry entry must be cleaned up afterwards (RAII guard).
    #[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:?}"
        );
        // registry cleaned up after the turn
        assert!(state.stream_observers.get("c1").is_none());
    }

    /// Regression for the silent "no trace" bug on `/agent/chat/stream`: the
    /// SSE handler registers the turn's stream observer keyed by the raw
    /// `conversationId` (`stream_observers.insert(conversation_id, ..)`), but the
    /// dw.agent node looks it up by the canonical ingress session hint. When the
    /// activity carries no explicit session, `canonicalize` derives a 5-part
    /// `{tenant}:{provider}:{channel}:{conversation}:{user}` hint that never
    /// equals the bare `conversationId`, the observer is never found, and the
    /// turn silently falls back to a single non-streamed reply (no tool / token
    /// frames). Stamping session = conversationId keeps the hint bare so the two
    /// keys match.
    #[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
    }

    /// Two overlapping turns on the same `conversationId`: the second
    /// `insert` replaces the first turn's observer. The first turn's stale
    /// `Cleanup` must not evict the second turn's observer (ptr_eq guard);
    /// the second turn's own cleanup does remove it.
    #[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());
        // A second overlapping turn on the same conversation id replaces A.
        registry.insert("c1".to_string(), observer_b.clone());

        // A's stale cleanup must not evict B's entry.
        Cleanup::remove_stale(&registry, "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"
        );

        // B's own cleanup removes its entry.
        Cleanup::remove_stale(&registry, "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:?}"
        );
        // Already streamed token by token: only the card follows.
        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:?}"
        );
    }
}