koda-cli 0.4.0

A high-performance AI coding agent for macOS and Linux
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
//! `/agents` and `/cancel <id>` slash commands — runtime view of
//! **all** background tasks (sub-agents *and* shell processes).
//!
//! ## Overview
//!
//! `/agents` lists every currently-tracked background task — both
//! sub-agents from [`koda_core::child_agent::ChildAgentRegistry`]
//! (every `InvokeAgent` dispatch post-#1163) and background
//! shell processes from [`koda_core::tools::bg_process::BgRegistry`]
//! (spawned via `Bash { background: true }`). They share a single
//! table because from the user's perspective they're the same
//! concept: "stuff Koda kicked off in the background that I'd like
//! to see, wait on, or cancel."
//!
//! `/cancel <id>` accepts the same prefixed forms as the LLM-facing
//! `CancelTask` tool ([`parse_task_id`]):
//!
//! - `agent:N` — fire a bg sub-agent's cancel token
//! - `process:N` — SIGTERM a bg shell process
//! - `N` (bare numeric) — back-compat with the original #1042 UX,
//!   treated as `agent:N`
//!
//! Together they close #996: "the model launched background work
//! and I have no way to see what it's doing or stop it."
//!
//! ## Why one renderer instead of two slash commands
//!
//! We considered `/agents` + `/processes`, but Codex / Gemini / Claude
//! Code all converge on a single "background work" surface. Splitting
//! by spawn mechanism would push the user to remember which command
//! launched which task — exactly the friction the unified view fixes.
//! The `TYPE` column distinguishes the two when it matters (e.g.
//! "did `cargo test` finish?" vs "is the explore agent done?").
//!
//! Foreground sub-agents (the synchronous `/agent <name>` switch in
//! [`crate::tui_wizards::handle_list_agents`]) don't appear here —
//! they block the conversation and are visible inline.
//!
//! ## Display
//!
//! Status icons follow Codex's `multi_agents::status_summary_spans`
//! palette so users coming from that ecosystem find them familiar:
//!
//! | Status      | Glyph | Color      |
//! |-------------|-------|------------|
//! | `Pending`   | `◐`   | cyan       |
//! | `Running`   | `▶`   | cyan bold  |
//! | `Cancelled` | `⊗`   | dim        |
//! | `Completed` | `✓`   | green      |
//! | `Errored`   | `✗`   | red        |
//! | `Killed`    | `⊗`   | dim        |  (process-only)
//! | `Exited(c)` | `✓/✗` | green/red  |  (process-only; ✗ when c≠0)
//!
//! ## Out of scope (deferred)
//!
//! - The "completed lingers 30s" UX polish — deferred to a polish
//!   PR. Drained results still inject into the conversation, so the
//!   user isn't missing info, just visual confirmation.
//! - Status-bar pill — Layer 3 / PR #1044.
//! - Per-iter `iter` updates — Layer 4 / PR #1058 (landed).
//!
//! [`parse_task_id`]: koda_core::tools::task_id::parse_task_id

use crate::scroll_buffer::ScrollBuffer;
use crate::tui_output;
use koda_core::tools::task_id::TaskId;

/// Render `/cancel <id>`. Routes to the right registry based on the
/// parsed [`TaskId`]:
///
/// - [`TaskId::Agent`] → [`ChildAgentRegistry::cancel`]
/// - [`TaskId::Process`] → [`BgRegistry::kill`] (sends SIGTERM)
///
/// Both registries' cancel paths are idempotent (PR #1041's
/// `cancel_is_idempotent_while_pending` for agents; SIGTERM-on-already-
/// dead is a no-op for processes), so re-issuing on a still-running
/// cancelled task is harmless.
///
/// `task_id == None` means the user typed `/cancel` with no arg or
/// an arg that didn't parse — we report the usage error here rather
/// than at the parser layer (see `ReplAction::CancelBackgroundTask`'s
/// docstring for the rationale).
///
/// [`ChildAgentRegistry::cancel`]: koda_core::child_agent::ChildAgentRegistry::cancel
/// [`BgRegistry::kill`]: koda_core::tools::bg_process::BgRegistry::kill
pub(crate) fn handle_cancel_background_task(
    buffer: &mut ScrollBuffer,
    bg_agents: &koda_core::child_agent::ChildAgentRegistry,
    bg_processes: &koda_core::tools::bg_process::BgRegistry,
    child_activity: &mut crate::child_activity::ChildActivityTracker,
    task_id: Option<TaskId>,
) {
    let Some(id) = task_id else {
        tui_output::warn_msg(
            buffer,
            "Usage: /cancel <agent:id|process:id>  (ids are visible in the live bg-activity overlay)".into(),
        );
        return;
    };

    match id {
        TaskId::Agent(n) => {
            if bg_agents.cancel(n) {
                // Flip the overlay icon to red immediately so the user
                // sees their cancel landed (#1210). The registry status
                // doesn't transition to Cancelled until the inference
                // loop next checks the token — could be a few hundred
                // ms — and that lag without feedback feels broken.
                child_activity.mark_cancelling(n);
                tui_output::ok_msg(
                    buffer,
                    format!("Cancellation requested for agent:{n}. Result will inject shortly."),
                );
            } else {
                tui_output::warn_msg(
                    buffer,
                    format!(
                        "No background sub-agent with id agent:{n}. Check the bg-activity overlay for active task ids."
                    ),
                );
            }
        }
        TaskId::Process(n) => {
            if bg_processes.kill(n) {
                tui_output::ok_msg(
                    buffer,
                    format!("SIGTERM sent to process:{n}. It should exit shortly."),
                );
            } else {
                tui_output::warn_msg(
                    buffer,
                    format!(
                        "No background process with id process:{n}. Check the bg-activity overlay for active task ids."
                    ),
                );
            }
        }
    }
}

/// Cancel every active background agent and SIGTERM every running
/// background process. Used by the global Ctrl+C path so users have
/// a single keystroke to stop *all* background work — see issue #1200.
///
/// Counts only entries that are still running/pending; already-finished
/// snapshots are skipped so we don't spam "Cancelled 0" messages when
/// the registries are full of completed (not-yet-reaped) entries.
///
/// Returns `(agents_cancelled, processes_killed)` so callers can decide
/// whether to emit a "nothing to do" message or fall through to
/// alternate Ctrl+C behaviour (e.g. textarea clear at idle).
pub(crate) fn cancel_all_bg_work(
    buffer: &mut ScrollBuffer,
    bg_agents: &koda_core::child_agent::ChildAgentRegistry,
    bg_processes: &koda_core::tools::bg_process::BgRegistry,
    child_activity: &mut crate::child_activity::ChildActivityTracker,
) -> (usize, usize) {
    use koda_core::child_agent::AgentStatus;

    // Collect ids first so we don't hold the registry lock across
    // `.cancel()` (which itself takes the lock). Snapshot is cheap
    // — copies are bounded by the small number of bg tasks.
    let agent_ids: Vec<u32> = bg_agents
        .snapshot()
        .into_iter()
        .filter(|s| matches!(s.status, AgentStatus::Pending | AgentStatus::Running { .. }))
        .map(|s| s.task_id)
        .collect();
    let proc_ids: Vec<u32> = bg_processes
        .snapshot()
        .into_iter()
        .filter(|s| {
            matches!(
                s.status,
                koda_core::tools::bg_process::BgProcessStatus::Running
            )
        })
        .map(|s| s.pid)
        .collect();

    let agents_cancelled = agent_ids
        .iter()
        .filter(|id| {
            let cancelled = bg_agents.cancel(**id);
            if cancelled {
                // Flip the overlay icon red right away so the user gets
                // immediate feedback (#1210); the registry status
                // transition to Cancelled lags by an inference
                // iteration.
                child_activity.mark_cancelling(**id);
            }
            cancelled
        })
        .count();
    let processes_killed = proc_ids
        .iter()
        .filter(|pid| bg_processes.kill(**pid))
        .count();

    if agents_cancelled + processes_killed > 0 {
        let parts: Vec<String> = [
            (agents_cancelled > 0).then(|| format!("{agents_cancelled} agent(s)")),
            (processes_killed > 0).then(|| format!("{processes_killed} process(es)")),
        ]
        .into_iter()
        .flatten()
        .collect();
        tui_output::warn_msg(
            buffer,
            format!("\u{26d4} Cancelled {} background work", parts.join(" + ")),
        );
    }

    (agents_cancelled, processes_killed)
}

/// Snapshot count of *active* bg work (running agents + tracked
/// processes). Used by the idle Ctrl+C path to decide whether to
/// cancel bg work or fall back to the textarea-clear behaviour.
pub(crate) fn active_bg_count(
    bg_agents: &koda_core::child_agent::ChildAgentRegistry,
    bg_processes: &koda_core::tools::bg_process::BgRegistry,
) -> usize {
    use koda_core::child_agent::AgentStatus;
    use koda_core::tools::bg_process::BgProcessStatus;
    let active_agents = bg_agents
        .snapshot()
        .into_iter()
        .filter(|s| matches!(s.status, AgentStatus::Pending | AgentStatus::Running { .. }))
        .count();
    let active_procs = bg_processes
        .snapshot()
        .into_iter()
        .filter(|s| matches!(s.status, BgProcessStatus::Running))
        .count();
    active_agents + active_procs
}

#[cfg(test)]
mod tests {
    use super::*;
    use koda_core::child_agent::{AgentStatus, BgPayload, ChildAgentRegistry};
    use koda_core::tools::bg_process::BgRegistry;
    use tokio::sync::{oneshot, watch};
    use tokio_util::sync::CancellationToken;

    /// Concatenate every line in the buffer into one searchable
    /// string. Style/color is stripped — we only assert content here.
    fn buffer_text(buffer: &ScrollBuffer) -> String {
        buffer
            .all_lines()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Build a registered bg-agent entry using only `ChildAgentRegistry`'s
    /// **public** API. We can't use the in-crate `register_test*`
    /// helpers because they're `#[cfg(test)]`-gated to `koda-core`
    /// itself — those gates make them invisible to other crates'
    /// test builds.
    ///
    /// Returns `(task_id, result_sender, status_sender, cancel_observer)`
    /// so tests can drive the entry through any state. The
    /// `JoinHandle` we attach is a noop spawn — enough to satisfy
    /// `AbortOnDropHandle` without burning a tokio worker on real work.
    fn register_entry(
        reg: &ChildAgentRegistry,
        agent_name: &str,
        prompt: &str,
    ) -> (
        u32,
        oneshot::Sender<Result<BgPayload, BgPayload>>,
        watch::Sender<AgentStatus>,
        CancellationToken,
    ) {
        let parent = CancellationToken::new();
        // Phase A1 of #996 added a `spawner: Option<u32>` to both
        // reserve() and attach(). The TUI test harness only ever
        // exercises the top-level path, so `None` is the right value.
        let r = reg.reserve(&parent, None, true);
        let task_id = r.task_id;
        let tx = r.tx;
        let status_tx = r.status_tx;
        let observer = r.cancel.clone();
        let noop = tokio::spawn(async {});
        reg.attach(
            task_id,
            agent_name,
            prompt,
            r.rx,
            r.cancel,
            r.status_rx,
            None,
            true,
            None,
            noop,
        );
        (task_id, tx, status_tx, observer)
    }

    /// Spawn a real child process for tests that need a live PID in
    /// the [`BgRegistry`]. We use `sleep` because it's universally
    /// available, exits cleanly on SIGTERM, and lets us observe
    /// kill / reap state without timing flakiness.
    ///
    /// `BgRegistry::insert` takes a `tokio::process::Child` (not the
    /// std variant) because the LLM-tool path needs async waits.
    /// Returns the OS pid — also the id we register under, since
    /// `BgRegistry::insert` doesn't allocate its own ids.
    fn spawn_sleep_in_registry(reg: &BgRegistry) -> u32 {
        let mut cmd = tokio::process::Command::new("sleep");
        cmd.arg("60");
        let child = cmd.spawn().expect("spawn sleep");
        let pid = child.id().expect("sleep should have a pid before exit");
        reg.insert(pid, "sleep 60".to_string(), child, None);
        pid
    }

    // ── handle_cancel_background_task ──────────────────────────────────────────────

    /// Happy path for an agent: known `agent:N` → cancel fires,
    /// success message surfaces, and the underlying token observed
    /// the cancel.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_known_agent_id_reports_success_and_fires_token() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();
        let (task_id, _tx, _status_tx, observer) = register_entry(&reg, "explore", "x");

        handle_cancel_background_task(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
            Some(TaskId::Agent(task_id)),
        );

        let text = buffer_text(&buf);
        assert!(
            text.contains(&format!("agent:{task_id}")),
            "success message should mention the prefixed id, got: {text}"
        );
        assert!(
            observer.is_cancelled(),
            "the cancel token should have been fired"
        );
    }

    /// Happy path for a process: known `process:N` → SIGTERM fires
    /// and the registry transitions the entry into `Killed`. The
    /// child eventually exits but we don't wait on it here — the
    /// reaper handles that.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_known_process_id_kills_and_reports_success() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();
        let pid = spawn_sleep_in_registry(&procs);

        handle_cancel_background_task(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
            Some(TaskId::Process(pid)),
        );

        let text = buffer_text(&buf);
        assert!(
            text.contains(&format!("process:{pid}")),
            "success message should mention the prefixed id, got: {text}"
        );
        assert!(
            text.to_lowercase().contains("sigterm") || text.to_lowercase().contains("exit"),
            "expected SIGTERM acknowledgement, got: {text}"
        );
    }

    /// Unknown agent id → warn, don't crash. The user should learn
    /// the correct id (or that the task already finished) without us
    /// throwing or silently no-oping.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_unknown_agent_id_reports_helpful_error() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();
        handle_cancel_background_task(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
            Some(TaskId::Agent(999)),
        );
        let text = buffer_text(&buf);
        assert!(
            text.contains("agent:999") && text.contains("bg-activity overlay"),
            "warn should name the missing prefixed id and point to the bg-activity overlay, got: {text}"
        );
    }

    /// Unknown process id → warn, don't crash. Same shape as the
    /// agent equivalent so users get a consistent error story.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_unknown_process_id_reports_helpful_error() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();
        handle_cancel_background_task(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
            Some(TaskId::Process(999_999)),
        );
        let text = buffer_text(&buf);
        assert!(
            text.contains("process:999999") && text.contains("bg-activity overlay"),
            "warn should name the missing prefixed id and point to the bg-activity overlay, got: {text}"
        );
    }

    /// `None` id (user typed `/cancel` with no arg or unparseable
    /// arg) renders Usage — not a panic, and not a misleading "task
    /// 0 not found." The Usage line must mention both prefix forms
    /// so the user learns the new syntax.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_none_id_renders_usage_with_both_prefixes() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();
        handle_cancel_background_task(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
            None,
        );
        let text = buffer_text(&buf);
        assert!(
            text.contains("Usage:") && text.contains("agent:") && text.contains("process:"),
            "None id should render a Usage: line with both prefixes, got: {text}"
        );
    }

    // ── cancel_all_bg_work / active_bg_count (#1200) ─────────────────

    /// Empty registries: `cancel_all_bg_work` returns (0, 0) and
    /// emits no message. The buffer must stay clean so the idle
    /// Ctrl+C path can fall through to its textarea-clear behaviour
    /// without leaving a phantom "cancelled 0" line in scrollback.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_all_bg_work_empty_is_silent() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();
        let (a, p) = cancel_all_bg_work(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
        );
        assert_eq!((a, p), (0, 0));
        assert!(
            buffer_text(&buf).is_empty(),
            "empty registries must not emit a status line"
        );
    }

    /// Multiple running agents are all cancelled in one call and
    /// each `ChildAgentReservation::cancel` token observes the cascade.
    /// This is the in-process equivalent of "user hit Ctrl+C and
    /// every bg agent should die".
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_all_bg_work_cancels_every_running_agent() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();

        let (_id1, _tx1, status1, observer1) = register_entry(&reg, "explore", "prompt 1");
        let (_id2, _tx2, status2, observer2) = register_entry(&reg, "task", "prompt 2");
        // Bring them out of Pending so they show up as Running in
        // the snapshot filter.
        status1.send(AgentStatus::Running { iter: 1 }).unwrap();
        status2.send(AgentStatus::Running { iter: 1 }).unwrap();

        let (a, p) = cancel_all_bg_work(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
        );
        assert_eq!((a, p), (2, 0));
        assert!(observer1.is_cancelled(), "agent 1 should observe cascade");
        assert!(observer2.is_cancelled(), "agent 2 should observe cascade");
        let text = buffer_text(&buf);
        assert!(
            text.contains("Cancelled") && text.contains("2 agent(s)"),
            "summary line should report agent count, got: {text}"
        );
    }

    /// Mixed registries: agents + processes get cancelled and the
    /// summary line names both kinds. We use a real `sleep 60`
    /// child so `BgRegistry::kill` exercises its real SIGTERM path,
    /// not a stubbed one.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_all_bg_work_handles_agents_and_processes() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();

        let (_id, _tx, status, observer) = register_entry(&reg, "explore", "hi");
        status.send(AgentStatus::Running { iter: 1 }).unwrap();
        let _pid = spawn_sleep_in_registry(&procs);

        let (a, p) = cancel_all_bg_work(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
        );
        assert_eq!((a, p), (1, 1));
        assert!(observer.is_cancelled());
        let text = buffer_text(&buf);
        assert!(
            text.contains("1 agent(s)") && text.contains("1 process(es)"),
            "summary should mention both kinds, got: {text}"
        );
    }

    /// Already-completed agents are skipped — we don't want Ctrl+C
    /// to spam "cancelled" for entries that finished naturally and
    /// just haven't been reaped yet.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cancel_all_bg_work_skips_completed_entries() {
        let mut buf = ScrollBuffer::new(64);
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();

        let (_id, tx, status, observer) = register_entry(&reg, "explore", "hi");
        // Drive to Completed terminal state.
        status
            .send(AgentStatus::Completed {
                summary: "done".to_string(),
            })
            .unwrap();
        // Send a result so the entry looks fully resolved.
        let _ = tx.send(Ok(("done".to_string(), vec![])));

        let (a, p) = cancel_all_bg_work(
            &mut buf,
            &reg,
            &procs,
            &mut crate::child_activity::ChildActivityTracker::default(),
        );
        assert_eq!((a, p), (0, 0));
        assert!(
            !observer.is_cancelled(),
            "completed entries must not have their cancel token fired"
        );
        assert!(buffer_text(&buf).is_empty());
    }

    /// `active_bg_count` matches what the idle Ctrl+C handler will
    /// see when deciding whether to cancel bg work or fall through
    /// to the textarea-clear path. Counts must exclude completed
    /// entries (same filter as `cancel_all_bg_work`).
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn active_bg_count_excludes_completed() {
        let reg = ChildAgentRegistry::new();
        let procs = BgRegistry::new();
        assert_eq!(active_bg_count(&reg, &procs), 0);

        let (_id1, _tx1, s1, _obs1) = register_entry(&reg, "a", "p1");
        s1.send(AgentStatus::Running { iter: 1 }).unwrap();
        let (_id2, tx2, s2, _obs2) = register_entry(&reg, "b", "p2");
        s2.send(AgentStatus::Completed {
            summary: "x".to_string(),
        })
        .unwrap();
        let _ = tx2.send(Ok(("x".to_string(), vec![])));

        assert_eq!(
            active_bg_count(&reg, &procs),
            1,
            "only the running agent should count"
        );
    }
}