rustvani 0.3.0

Voice AI framework for Rust — real-time speech pipelines with STT, LLM, TTS, and Dhara conversation flows
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
//! Cross-module integration tests for the agents subsystem:
//! task routing (Phase 2), ready-gating (Phase 3), bus edges (Phase 4),
//! and runner cascade (Phase 6).

use std::collections::HashSet;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use serde_json::json;

use crate::clock::system_clock;
use crate::frames::{Frame, FrameKind};
use crate::pipeline::{PipelineParams, PipelineTask};

use super::base::{Agent, BaseAgent, TaskHandler, TaskRequestCtx};
use super::bus::{AgentBus, BusMessage, BusPayload, LocalAgentBus, TaskStatus};
use super::edges::BusOutputEdge;
use super::runner::AgentRunner;

/// An empty pipeline (TaskSource → TaskSink) that runs until EndFrame.
fn idle_task() -> PipelineTask {
    PipelineTask::new(vec![], PipelineParams::default())
}

/// Spawn `runner.run()` and wait until all `names` are registered.
async fn start_and_wait(runner: &Arc<AgentRunner>, names: &[&str]) -> tokio::task::JoinHandle<()> {
    let r = runner.clone();
    let handle = tokio::spawn(async move {
        let _ = r.run().await;
    });
    let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
    'outer: loop {
        assert!(
            tokio::time::Instant::now() < deadline,
            "agents never became ready"
        );
        for name in names {
            if runner.registry().get(name).await.is_none() {
                tokio::time::sleep(Duration::from_millis(10)).await;
                continue 'outer;
            }
        }
        break;
    }
    handle
}

fn echo_handler() -> TaskHandler {
    Arc::new(|ctx: TaskRequestCtx| {
        Box::pin(async move {
            let payload = ctx.payload.clone();
            ctx.complete(TaskStatus::Completed, payload).await;
        })
    })
}

/// Phase 2 test 1: dispatch → named handler → complete → await_completion.
#[tokio::test]
async fn task_round_trip() {
    let a = Arc::new(BaseAgent::new("a", idle_task(), None, true));
    let b = Arc::new(BaseAgent::new("b", idle_task(), None, true).on_task("echo", echo_handler()));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    let ctx = a.task_ctx().unwrap();
    let handle = ctx
        .dispatch("a", "b", Some("echo".into()), Some(json!({"x": 42})))
        .await
        .unwrap();
    let result = handle
        .await_completion(Some(Duration::from_secs(2)))
        .await
        .unwrap();

    assert_eq!(result.status, TaskStatus::Completed);
    assert_eq!(result.response, Some(json!({"x": 42})));

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 2 test 2: StreamStart + 3×StreamData + StreamEnd then Response —
/// stream_updates yields 5 updates and the result.
#[tokio::test]
async fn task_streaming() {
    let streamer: TaskHandler = Arc::new(|ctx: TaskRequestCtx| {
        Box::pin(async move {
            ctx.stream_start(Some(json!("start"))).await;
            for i in 0..3 {
                ctx.stream_data(Some(json!(i))).await;
            }
            ctx.stream_end(Some(json!("end"))).await;
            ctx.complete(TaskStatus::Completed, Some(json!("done")))
                .await;
        })
    });

    let a = Arc::new(BaseAgent::new("a", idle_task(), None, true));
    let b = Arc::new(BaseAgent::new("b", idle_task(), None, true).on_task("stream", streamer));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    let ctx = a.task_ctx().unwrap();
    let handle = ctx
        .dispatch("a", "b", Some("stream".into()), None)
        .await
        .unwrap();
    let (updates, result) = handle
        .stream_updates(Some(Duration::from_secs(2)))
        .await
        .unwrap();

    assert_eq!(updates.len(), 5, "expected 5 stream updates: {updates:?}");
    assert_eq!(result.status, TaskStatus::Completed);
    assert_eq!(result.response, Some(json!("done")));

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 2 test 3: TaskCancel aborts the handler and the requester
/// receives a terminal Cancelled response.
#[tokio::test]
async fn task_cancel() {
    let sleepy: TaskHandler = Arc::new(|ctx: TaskRequestCtx| {
        Box::pin(async move {
            tokio::time::sleep(Duration::from_secs(30)).await;
            ctx.complete(TaskStatus::Completed, None).await;
        })
    });

    let a = Arc::new(BaseAgent::new("a", idle_task(), None, true));
    let b = Arc::new(BaseAgent::new("b", idle_task(), None, true).on_task("sleep", sleepy));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    let ctx = a.task_ctx().unwrap();
    let handle = ctx
        .dispatch("a", "b", Some("sleep".into()), None)
        .await
        .unwrap();
    let task_id = handle.task_id.clone();

    // Give B a moment to start the handler, then cancel.
    tokio::time::sleep(Duration::from_millis(100)).await;
    ctx.cancel_task("a", "b", task_id, Some("changed my mind".into()))
        .await;

    let result = handle
        .await_completion(Some(Duration::from_secs(2)))
        .await
        .unwrap();
    assert_eq!(result.status, TaskStatus::Cancelled);

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 2 test 4: dispatch with an unknown handler name resolves Failed
/// instead of hanging.
#[tokio::test]
async fn task_no_handler_fails_fast() {
    let a = Arc::new(BaseAgent::new("a", idle_task(), None, true));
    let b = Arc::new(BaseAgent::new("b", idle_task(), None, true));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    let ctx = a.task_ctx().unwrap();
    let handle = ctx
        .dispatch("a", "b", Some("nonexistent".into()), None)
        .await
        .unwrap();
    let result = handle
        .await_completion(Some(Duration::from_secs(2)))
        .await
        .unwrap();
    assert_eq!(result.status, TaskStatus::Failed);

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 2 test 5: B ends while a job is active — A's pending handle
/// resolves (Cancelled or error) within 1s instead of hanging.
#[tokio::test]
async fn task_resolves_when_executor_dies() {
    let sleepy: TaskHandler = Arc::new(|ctx: TaskRequestCtx| {
        Box::pin(async move {
            tokio::time::sleep(Duration::from_secs(30)).await;
            ctx.complete(TaskStatus::Completed, None).await;
        })
    });

    let a = Arc::new(BaseAgent::new("a", idle_task(), None, true));
    let b = Arc::new(BaseAgent::new("b", idle_task(), None, true).on_task("sleep", sleepy));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b.clone()).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    let ctx = a.task_ctx().unwrap();
    let handle = ctx
        .dispatch("a", "b", Some("sleep".into()), None)
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_millis(100)).await;

    // End B directly while the job is in flight.
    b.end(Some("shutting down".into())).await.unwrap();

    let result = tokio::time::timeout(
        Duration::from_secs(1),
        handle.await_completion(Some(Duration::from_secs(1))),
    )
    .await
    .expect("handle did not resolve within 1s");
    // A closed-channel error is also acceptable.
    if let Ok(r) = result {
        assert_eq!(r.status, TaskStatus::Cancelled);
    }

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 3: dispatch to a target that is not ready yet waits (no polling)
/// and proceeds once the target announces readiness.
#[tokio::test]
async fn dispatch_waits_for_target_ready() {
    let a = Arc::new(BaseAgent::new("a", idle_task(), None, true));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus.clone(), system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    let run = start_and_wait(&runner, &["a"]).await;

    // Dispatch to "late" before it exists. Spawn the dispatch, then bring
    // the agent up by registering it manually after a delay.
    let ctx = a.task_ctx().unwrap();
    let registry = runner.registry().clone();
    let register = tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(200)).await;
        registry
            .register(super::registry::AgentInfo {
                name: "late".into(),
                runner: "r".into(),
                parent: None,
                active: true,
                bridged: false,
                started_at: None,
            })
            .await;
    });

    let started = tokio::time::Instant::now();
    let handle = ctx
        .dispatch_with("a", "late", None, None, Some(Duration::from_secs(5)))
        .await
        .expect("dispatch should succeed once the target registers");
    assert!(
        started.elapsed() >= Duration::from_millis(150),
        "dispatch returned before the target was ready"
    );
    drop(handle);
    register.await.unwrap();

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 3: dispatch to a target that never becomes ready errors after the
/// ready timeout instead of silently dropping the request.
#[tokio::test]
async fn dispatch_times_out_when_target_never_ready() {
    let a = Arc::new(BaseAgent::new("a", idle_task(), None, true));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    let run = start_and_wait(&runner, &["a"]).await;

    let ctx = a.task_ctx().unwrap();
    let result = ctx
        .dispatch_with("a", "ghost", None, None, Some(Duration::from_millis(200)))
        .await;
    assert!(result.is_err(), "dispatch to a missing agent should error");

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

// ---------------------------------------------------------------------------
// Phase 6 — runner parent/child cascade
// ---------------------------------------------------------------------------

/// Ending the runner stops the child before the parent's pipeline
/// finishes, and the runner exits within the timeout.
#[tokio::test]
async fn end_cascades_child_before_parent() {
    let finish_order: Arc<std::sync::Mutex<Vec<&'static str>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));

    let parent_task = idle_task();
    let order = finish_order.clone();
    parent_task.add_on_pipeline_finished(move |_f, _r| {
        let order = order.clone();
        Box::pin(async move {
            order.lock().unwrap().push("parent");
        })
    });

    let child_task = idle_task();
    let order = finish_order.clone();
    child_task.add_on_pipeline_finished(move |_f, _r| {
        let order = order.clone();
        Box::pin(async move {
            order.lock().unwrap().push("child");
        })
    });

    let parent = Arc::new(BaseAgent::new("parent", parent_task, None, true));
    let child = Arc::new(BaseAgent::new("child", child_task, None, true).with_parent("parent"));

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(parent).await.unwrap();
    runner.add_agent(child).await.unwrap();
    let run = start_and_wait(&runner, &["parent", "child"]).await;

    runner.end(None).await;
    tokio::time::timeout(Duration::from_secs(8), run)
        .await
        .expect("runner did not exit within timeout")
        .unwrap();

    let order = finish_order.lock().unwrap().clone();
    assert_eq!(
        order,
        vec!["child", "parent"],
        "child must finish before the parent's pipeline"
    );
}

// ---------------------------------------------------------------------------
// Phase 4 — bus edge processors
// ---------------------------------------------------------------------------

/// Build a bridged agent whose pipeline is `[BusOutputEdge]`, counting
/// frames of `count_kind` that reach the pipeline's downstream boundary.
fn bridged_agent(
    name: &str,
    peers: Vec<String>,
    exclude: HashSet<FrameKind>,
    count_kind: FrameKind,
) -> (Arc<BaseAgent>, Arc<AtomicUsize>) {
    let edge = BusOutputEdge::with_exclude(name, peers.clone(), exclude);
    let task = PipelineTask::new(vec![edge.to_processor()], PipelineParams::default());

    let mut filter = HashSet::new();
    filter.insert(count_kind);
    task.set_downstream_filter(filter);

    let count = Arc::new(AtomicUsize::new(0));
    let count_cb = count.clone();
    task.add_on_frame_reached_downstream(move |_frame| {
        let count = count_cb.clone();
        Box::pin(async move {
            count.fetch_add(1, Ordering::SeqCst);
        })
    });

    let agent = Arc::new(BaseAgent::new(name, task, Some(peers), true).with_output_edge(edge));
    (agent, count)
}

/// Phase 4 test 1: two pipelines bridged via output edges — a frame pushed
/// into A arrives in B's pipeline, and a frame published by B targeted at
/// A arrives at A's head. Mutual exclusions break the re-publish loop.
#[tokio::test]
async fn bridged_pipelines_exchange_frames() {
    // A publishes to b, never re-publishes Transcription (B's output kind).
    let (a, a_transcripts) = bridged_agent(
        "a",
        vec!["b".into()],
        HashSet::from([FrameKind::Transcription]),
        FrameKind::Transcription,
    );
    // B publishes to a, never re-publishes LLMText (A's output kind).
    let (b, b_texts) = bridged_agent(
        "b",
        vec!["a".into()],
        HashSet::from([FrameKind::LLMText]),
        FrameKind::LLMText,
    );

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b.clone()).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    // A → B: text frame pushed into A's pipeline reaches B's processor.
    a.pipeline()
        .push_frame(
            Frame::llm_text("hello b".into()),
            crate::frames::FrameDirection::Downstream,
        )
        .await
        .unwrap();

    // B → A: transcription pushed into B's pipeline reaches A's head.
    b.pipeline()
        .push_frame(
            Frame::transcription(crate::frames::TranscriptionData::new(
                "hello a", "user", "now",
            )),
            crate::frames::FrameDirection::Downstream,
        )
        .await
        .unwrap();

    let ok = async {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
        while tokio::time::Instant::now() < deadline {
            if b_texts.load(Ordering::SeqCst) >= 1 && a_transcripts.load(Ordering::SeqCst) >= 1 {
                return true;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        false
    }
    .await;
    assert!(
        ok,
        "bridge failed: b_texts={}, a_transcripts={}",
        b_texts.load(Ordering::SeqCst),
        a_transcripts.load(Ordering::SeqCst)
    );

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 4 test 2: deactivating A keeps frames flowing inside A's pipeline
/// but publishes nothing; reactivating resumes the flow.
#[tokio::test]
async fn edge_activation_gating() {
    // A counts its own LLMText locally to prove local flow continues.
    let (a, a_local) = bridged_agent("a", vec!["b".into()], HashSet::new(), FrameKind::LLMText);
    let (b, b_texts) = bridged_agent(
        "b",
        vec![],
        HashSet::from([FrameKind::LLMText]),
        FrameKind::LLMText,
    );

    let bus: Arc<dyn AgentBus> = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus.clone(), system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b.clone()).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    // Deactivate A, push a frame: local flow continues, nothing reaches B.
    bus.send(BusMessage::new(
        "r",
        Some("a".into()),
        BusPayload::Deactivate,
    ))
    .await;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    while a.active() && tokio::time::Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert!(!a.active(), "Deactivate never took effect");

    a.pipeline()
        .push_frame(
            Frame::llm_text("while inactive".into()),
            crate::frames::FrameDirection::Downstream,
        )
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_millis(200)).await;
    assert_eq!(a_local.load(Ordering::SeqCst), 1, "local flow stalled");
    assert_eq!(
        b_texts.load(Ordering::SeqCst),
        0,
        "published while inactive"
    );

    // Reactivate and push again: flow to B resumes.
    bus.send(BusMessage::new(
        "r",
        Some("a".into()),
        BusPayload::Activate { args: None },
    ))
    .await;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    while !a.active() && tokio::time::Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    a.pipeline()
        .push_frame(
            Frame::llm_text("while active".into()),
            crate::frames::FrameDirection::Downstream,
        )
        .await
        .unwrap();
    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    while b_texts.load(Ordering::SeqCst) == 0 && tokio::time::Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert_eq!(b_texts.load(Ordering::SeqCst), 1, "flow did not resume");
    assert_eq!(a_local.load(Ordering::SeqCst), 2);

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 4 test 3: excluded frame kinds are forwarded locally but never
/// published.
#[tokio::test]
async fn edge_exclusion() {
    let (a, a_local) = bridged_agent(
        "a",
        vec!["b".into()],
        HashSet::from([FrameKind::LLMText]),
        FrameKind::LLMText,
    );
    let (b, b_texts) = bridged_agent("b", vec![], HashSet::new(), FrameKind::LLMText);

    let bus = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus, system_clock()));
    runner.add_agent(a.clone()).await.unwrap();
    runner.add_agent(b.clone()).await.unwrap();
    let run = start_and_wait(&runner, &["a", "b"]).await;

    a.pipeline()
        .push_frame(
            Frame::llm_text("excluded".into()),
            crate::frames::FrameDirection::Downstream,
        )
        .await
        .unwrap();

    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    while a_local.load(Ordering::SeqCst) == 0 && tokio::time::Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert_eq!(a_local.load(Ordering::SeqCst), 1, "local forward failed");
    tokio::time::sleep(Duration::from_millis(200)).await;
    assert_eq!(
        b_texts.load(Ordering::SeqCst),
        0,
        "excluded frame published"
    );

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}

/// Phase 2 test 6: bridged peer filter — frames from a listed source are
/// injected, frames from others are ignored.
#[tokio::test]
async fn bridged_peer_filter() {
    let task = idle_task();
    let mut filter = HashSet::new();
    filter.insert(FrameKind::LLMText);
    task.set_downstream_filter(filter);

    let received = Arc::new(AtomicUsize::new(0));
    let received_cb = received.clone();
    task.add_on_frame_reached_downstream(move |_frame| {
        let received = received_cb.clone();
        Box::pin(async move {
            received.fetch_add(1, Ordering::SeqCst);
        })
    });

    let agent = Arc::new(BaseAgent::new(
        "listener",
        task,
        Some(vec!["voice".to_string()]),
        true,
    ));

    let bus: Arc<dyn AgentBus> = Arc::new(LocalAgentBus::new());
    let runner = Arc::new(AgentRunner::new("r", bus.clone(), system_clock()));
    runner.add_agent(agent.clone()).await.unwrap();
    let run = start_and_wait(&runner, &["listener"]).await;

    // Frame from "voice" — accepted.
    bus.send(BusMessage::new(
        "voice",
        Some("listener".into()),
        BusPayload::Frame {
            frame: Frame::llm_text("hello".into()),
            direction: crate::frames::FrameDirection::Downstream,
        },
    ))
    .await;
    // Frame from "other" — ignored.
    bus.send(BusMessage::new(
        "other",
        Some("listener".into()),
        BusPayload::Frame {
            frame: Frame::llm_text("spam".into()),
            direction: crate::frames::FrameDirection::Downstream,
        },
    ))
    .await;

    tokio::time::sleep(Duration::from_millis(300)).await;
    assert_eq!(
        received.load(Ordering::SeqCst),
        1,
        "only the frame from 'voice' should be injected"
    );

    runner.end(None).await;
    let _ = tokio::time::timeout(Duration::from_secs(5), run).await;
}