Skip to main content

lean_ctx/server/
background_shell.rs

1//! Explicit, in-process background jobs for `ctx_shell`.
2//!
3//! The MCP request may complete immediately, but the child keeps the exact
4//! timeout, allow-list, path-jail and process-group policy of foreground shell
5//! execution. Jobs intentionally live in the daemon: restarting it invalidates
6//! outstanding jobs rather than silently orphaning subprocesses.
7
8use std::collections::HashMap;
9use std::sync::{
10    Arc, LazyLock, Mutex,
11    atomic::{AtomicBool, Ordering},
12};
13use std::time::{Duration, Instant};
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum JobState {
17    Running { output: String },
18    Completed { output: String, exit_code: i32 },
19    Cancelled { output: String },
20}
21
22const MAX_RETAINED_COMPLETED_JOBS: usize = 64;
23const MAX_RETAINED_COMPLETED_BYTES: usize = 16 * 1024 * 1024;
24const COMPLETED_JOB_TTL: Duration = Duration::from_mins(5);
25
26struct Job {
27    cancel: Arc<AtomicBool>,
28    state: JobState,
29    finished_at: Option<Instant>,
30    // #1217: shared buffer the worker streams captured output into while the
31    // job runs, so `status` can report progress before the job completes.
32    live: Arc<Mutex<String>>,
33    // #1876: identical launches coalesce onto one entry, so several foreground
34    // calls can wait on it at once. Each reads its result from the entry, so it
35    // is removed only once the last waiter has read it, and never while a
36    // background caller (explicit or detached) may still poll it by id.
37    foreground_waiters: usize,
38    background_owned: bool,
39    telemetry_recorded: bool,
40}
41
42static JOBS: LazyLock<Mutex<HashMap<String, Job>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
43
44/// How often a foreground run reports progress to the MCP client (#1173).
45const TICK: Duration = Duration::from_secs(5);
46
47fn prune_finished_jobs(jobs: &mut HashMap<String, Job>, now: Instant) {
48    prune_finished_jobs_with_limits(
49        jobs,
50        now,
51        MAX_RETAINED_COMPLETED_JOBS,
52        MAX_RETAINED_COMPLETED_BYTES,
53    );
54}
55
56fn prune_finished_jobs_with_limits(
57    jobs: &mut HashMap<String, Job>,
58    now: Instant,
59    max_completed_jobs: usize,
60    max_completed_bytes: usize,
61) {
62    jobs.retain(|_, job| {
63        job.foreground_waiters > 0
64            || job
65                .finished_at
66                .is_none_or(|finished_at| now.duration_since(finished_at) < COMPLETED_JOB_TTL)
67    });
68
69    let mut completed: Vec<_> = jobs
70        .iter()
71        .filter(|(_, job)| job.foreground_waiters == 0)
72        .filter_map(|(id, job)| {
73            let finished_at = job.finished_at?;
74            let output_bytes = match &job.state {
75                JobState::Completed { output, .. } | JobState::Cancelled { output } => output.len(),
76                JobState::Running { .. } => 0,
77            };
78            Some((finished_at, id.clone(), output_bytes))
79        })
80        .collect();
81    completed.sort_unstable_by_key(|(finished_at, _, _)| *finished_at);
82
83    let mut retained_bytes = completed.iter().map(|(_, _, bytes)| bytes).sum::<usize>();
84    let mut retained_jobs = completed.len();
85    for (_, id, output_bytes) in completed {
86        if retained_jobs <= max_completed_jobs && retained_bytes <= max_completed_bytes {
87            break;
88        }
89        if retained_jobs == 1 {
90            break;
91        }
92        jobs.remove(&id);
93        retained_jobs -= 1;
94        retained_bytes = retained_bytes.saturating_sub(output_bytes);
95    }
96}
97
98pub fn start(
99    command: String,
100    cwd: String,
101    extra_env: std::collections::HashMap<String, String>,
102    timeout_ms: Option<u64>,
103) -> String {
104    start_inner(command, cwd, extra_env, timeout_ms, false)
105}
106
107fn start_inner(
108    command: String,
109    cwd: String,
110    extra_env: std::collections::HashMap<String, String>,
111    timeout_ms: Option<u64>,
112    foreground: bool,
113) -> String {
114    // IDs are content-addressed so tool responses stay deterministic (#498).
115    // An identical in-flight launch coalesces onto the same job instead of
116    // creating duplicate expensive builds/tests.
117    let mut env_entries: Vec<_> = extra_env.iter().collect();
118    env_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
119    let env_key = env_entries
120        .into_iter()
121        .map(|(key, value)| format!("{key}={value}"))
122        .collect::<Vec<_>>()
123        .join("\0");
124    let material = format!(
125        "{command}\0{cwd}\0{}\0{env_key}",
126        timeout_ms.unwrap_or_default()
127    );
128    let id = format!(
129        "shell_{}",
130        &blake3::hash(material.as_bytes()).to_hex()[..16]
131    );
132    let cancel = Arc::new(AtomicBool::new(false));
133    let worker_cancel = Arc::clone(&cancel);
134    let live = Arc::new(Mutex::new(String::new()));
135    let worker_live = Arc::clone(&live);
136    {
137        let mut jobs = JOBS
138            .lock()
139            .unwrap_or_else(std::sync::PoisonError::into_inner);
140        prune_finished_jobs(&mut jobs, Instant::now());
141        // A finished entry that a foreground waiter has not read yet is joined
142        // too (#1876): replacing it would hand that waiter's release to the new
143        // job, which then disappears under its own waiter.
144        if let Some(job) = jobs.get_mut(&id)
145            && (matches!(job.state, JobState::Running { .. }) || job.foreground_waiters > 0)
146        {
147            if foreground {
148                job.foreground_waiters += 1;
149            } else {
150                job.background_owned = true;
151            }
152            return id;
153        }
154        jobs.insert(
155            id.clone(),
156            Job {
157                cancel,
158                state: JobState::Running {
159                    output: String::new(),
160                },
161                finished_at: None,
162                live,
163                foreground_waiters: usize::from(foreground),
164                background_owned: !foreground,
165                telemetry_recorded: false,
166            },
167        );
168    }
169
170    let worker_id = id.clone();
171    std::thread::spawn(move || {
172        let (output, exit_code) = crate::server::execute::execute_command_with_env_cancellable(
173            &command,
174            &cwd,
175            &extra_env,
176            timeout_ms,
177            Some(&worker_cancel),
178            // #1113/#1173: bounded by output, not wall clock — a monitor loop
179            // emitting a line every 45s must survive. See `idle_keyed`.
180            true,
181            // #1217: stream captured output into the shared buffer as it arrives.
182            Some(&worker_live),
183        );
184        let mut jobs = JOBS
185            .lock()
186            .unwrap_or_else(std::sync::PoisonError::into_inner);
187        let Some(job) = jobs.get_mut(&worker_id) else {
188            return;
189        };
190        let cancelled = worker_cancel.load(Ordering::Acquire);
191        job.state = if cancelled {
192            JobState::Cancelled { output }
193        } else {
194            JobState::Completed { output, exit_code }
195        };
196        job.finished_at = Some(Instant::now());
197        // Only a background-owned job is counted here, so a failure nobody
198        // polls still reaches telemetry. A foreground run is classified once by
199        // the call pipeline, which knows that exit 1 with output (grep, diff,
200        // test) is not an error; counting it here as well filed every failing
201        // inline command twice, the second time as a LeanCTX-internal error.
202        if !cancelled && exit_code != 0 && job.background_owned {
203            let category = if exit_code == 124 {
204                crate::core::telemetry_v2::ErrorCategory::Timeout
205            } else {
206                crate::core::telemetry_v2::ErrorCategory::Command
207            };
208            if crate::core::telemetry_aggregate::record_error_category(category).is_ok() {
209                job.telemetry_recorded = true;
210            }
211        }
212        prune_finished_jobs(&mut jobs, Instant::now());
213    });
214    id
215}
216
217/// Outcome of a foreground run that is allowed to detach on a soft cap.
218pub enum ForegroundResult {
219    /// The command finished within the soft cap; output is returned inline.
220    /// Other coalesced foreground/background callers retain their result.
221    Finished { output: String, exit_code: i32 },
222    /// The command was still running at the soft cap and was left running as a
223    /// pollable background job (#1106).
224    Detached { job_id: String },
225}
226
227/// Run `command` as a managed background job but block up to `soft_cap` waiting
228/// for it to finish, so fast commands still return their output inline.
229///
230/// The MCP host aborts a tool call that stays in the foreground too long
231/// (~120s) and hands back a task id that `background_action=status` cannot
232/// resolve. By detaching *before* that deadline we always return a real
233/// `shell_*` job id the caller can poll or cancel (#1106).
234///
235/// `on_tick` is called roughly every `TICK` while the command is still
236/// running, so the caller can emit MCP progress notifications and a 3-minute
237/// build stops being indistinguishable from a hang (#1173).
238pub fn run_foreground_or_detach(
239    command: String,
240    cwd: String,
241    extra_env: std::collections::HashMap<String, String>,
242    timeout_ms: Option<u64>,
243    soft_cap: Duration,
244    on_tick: Option<&dyn Fn(Duration)>,
245    cancel: Option<&tokio_util::sync::CancellationToken>,
246) -> ForegroundResult {
247    let id = start_inner(command, cwd, extra_env, timeout_ms, true);
248    let started = Instant::now();
249    let deadline = started + soft_cap;
250    let mut next_tick = started + TICK;
251    loop {
252        match status(&id) {
253            Some(JobState::Completed { output, exit_code }) => {
254                release_foreground(&id, false);
255                return ForegroundResult::Finished { output, exit_code };
256            }
257            // A cancel can only be requested via background_action once the job
258            // is detached, so an inline wait realistically only sees Completed;
259            // handle Cancelled defensively with the timeout exit code.
260            Some(JobState::Cancelled { output }) => {
261                release_foreground(&id, false);
262                return ForegroundResult::Finished {
263                    output,
264                    exit_code: 130,
265                };
266            }
267            _ => {}
268        }
269        // #1781: when the host abandons the call, free this thread immediately.
270        // The foreground wait runs on the blocking pool — dispatch hands the
271        // handler to `spawn_blocking`, and that pool has
272        // `(workers * 4).clamp(8, 32)` slots. Without this check the loop spun
273        // on until `soft_cap` — five minutes for a `timeout_ms: 300_000` call —
274        // so a burst of abandoned commands could occupy every slot, after which
275        // subsequent tool calls queued behind them until the server restarted.
276        // Detaching rather than killing keeps the job alive under its id, which
277        // the caller already knows how to poll and cancel.
278        if cancel.is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
279            release_foreground(&id, true);
280            return ForegroundResult::Detached { job_id: id };
281        }
282        let now = Instant::now();
283        if now >= deadline {
284            release_foreground(&id, true);
285            return ForegroundResult::Detached { job_id: id };
286        }
287        if let Some(tick) = on_tick
288            && now >= next_tick
289        {
290            tick(started.elapsed());
291            next_tick = now + TICK;
292        }
293        std::thread::sleep(Duration::from_millis(50));
294    }
295}
296
297/// One foreground waiter is done with `id` (#1876). A detached waiter hands the
298/// id to its caller, so the entry becomes background-owned and stays pollable.
299/// Otherwise the entry is removed once no waiter and no background caller is
300/// left; a waiter that still polls it must not find it gone.
301fn release_foreground(id: &str, detached: bool) {
302    let mut jobs = JOBS
303        .lock()
304        .unwrap_or_else(std::sync::PoisonError::into_inner);
305    let Some(job) = jobs.get_mut(id) else {
306        return;
307    };
308    job.foreground_waiters = job.foreground_waiters.saturating_sub(1);
309    if detached {
310        job.background_owned = true;
311    } else if job.foreground_waiters == 0 && !job.background_owned {
312        jobs.remove(id);
313    }
314}
315
316#[cfg(test)]
317pub(crate) fn remove_for_test(id: &str) {
318    JOBS.lock()
319        .unwrap_or_else(std::sync::PoisonError::into_inner)
320        .remove(id);
321}
322
323/// Jobs whose command is still running. An idle MCP server with one of these
324/// is not idle: it holds the child and the output the agent will poll for.
325pub fn running_count() -> usize {
326    JOBS.lock()
327        .unwrap_or_else(std::sync::PoisonError::into_inner)
328        .values()
329        .filter(|job| matches!(job.state, JobState::Running { .. }))
330        .count()
331}
332
333pub fn status(id: &str) -> Option<JobState> {
334    let jobs = JOBS
335        .lock()
336        .unwrap_or_else(std::sync::PoisonError::into_inner);
337    let job = jobs.get(id)?;
338    Some(match &job.state {
339        // #1217: a running job's output lives in the shared buffer the worker
340        // streams into; surface the captured-so-far snapshot on each poll.
341        JobState::Running { .. } => JobState::Running {
342            output: job
343                .live
344                .lock()
345                .unwrap_or_else(std::sync::PoisonError::into_inner)
346                .clone(),
347        },
348        other => other.clone(),
349    })
350}
351
352/// Persist one aggregate for a terminal failed job, then mark that concrete
353/// retained job instance. A later execution may reuse the content-addressed ID,
354/// but replaces the `Job` and therefore starts with a fresh marker.
355pub fn record_error_telemetry_once(
356    id: &str,
357    category: crate::core::telemetry_v2::ErrorCategory,
358) -> Result<bool, String> {
359    let mut jobs = JOBS
360        .lock()
361        .unwrap_or_else(std::sync::PoisonError::into_inner);
362    let Some(job) = jobs.get_mut(id) else {
363        return Ok(false);
364    };
365    if job.telemetry_recorded
366        || !matches!(job.state, JobState::Completed { exit_code, .. } if exit_code != 0)
367    {
368        return Ok(false);
369    }
370    crate::core::telemetry_aggregate::record_error_category(category)?;
371    job.telemetry_recorded = true;
372    Ok(true)
373}
374
375pub fn cancel(id: &str) -> Option<JobState> {
376    let mut jobs = JOBS
377        .lock()
378        .unwrap_or_else(std::sync::PoisonError::into_inner);
379    let job = jobs.get_mut(id)?;
380    if matches!(job.state, JobState::Running { .. }) {
381        job.cancel.store(true, Ordering::Release);
382    }
383    Some(job.state.clone())
384}
385
386#[cfg(test)]
387mod tests {
388    use super::{
389        ForegroundResult, JobState, TICK, cancel, run_foreground_or_detach, start, status,
390    };
391    use std::time::Duration;
392
393    fn completed_job(exit_code: i32) -> super::Job {
394        super::Job {
395            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
396            state: JobState::Completed {
397                output: "opaque output".into(),
398                exit_code,
399            },
400            finished_at: Some(std::time::Instant::now()),
401            live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
402            foreground_waiters: 0,
403            background_owned: true,
404            telemetry_recorded: false,
405        }
406    }
407
408    #[test]
409    #[serial_test::serial]
410    fn failed_job_telemetry_is_once_per_execution_even_when_id_is_reused() {
411        let _iso = crate::core::data_dir::isolated_data_dir();
412        let id = "shell_same_content";
413        super::JOBS
414            .lock()
415            .unwrap_or_else(std::sync::PoisonError::into_inner)
416            .insert(id.into(), completed_job(2));
417
418        assert!(
419            super::record_error_telemetry_once(
420                id,
421                crate::core::telemetry_v2::ErrorCategory::Internal
422            )
423            .expect("record first execution")
424        );
425        assert!(
426            !super::record_error_telemetry_once(
427                id,
428                crate::core::telemetry_v2::ErrorCategory::Internal
429            )
430            .expect("deduplicate repeated poll")
431        );
432
433        super::JOBS
434            .lock()
435            .unwrap_or_else(std::sync::PoisonError::into_inner)
436            .insert(id.into(), completed_job(2));
437        assert!(
438            super::record_error_telemetry_once(
439                id,
440                crate::core::telemetry_v2::ErrorCategory::Internal
441            )
442            .expect("record replacement execution")
443        );
444
445        let batch = crate::core::telemetry_aggregate::preview_daily_batch().expect("preview");
446        let count = batch
447            .events
448            .iter()
449            .find_map(|envelope| match &envelope.event {
450                crate::core::telemetry_v2::TelemetryEventV2::ErrorCategoryAggregate(metrics)
451                    if metrics.category == crate::core::telemetry_v2::ErrorCategory::Internal =>
452                {
453                    Some(metrics.count)
454                }
455                _ => None,
456            });
457        assert_eq!(count, Some(2));
458        super::remove_for_test(id);
459    }
460
461    fn queued_error_count(category: crate::core::telemetry_v2::ErrorCategory) -> Option<u64> {
462        // A preview fails fast while another test's send holds the state lock;
463        // that is transient, so wait it out instead of failing this test.
464        let mut attempt = 0;
465        let batch = loop {
466            match crate::core::telemetry_aggregate::preview_daily_batch() {
467                Ok(batch) => break batch,
468                Err(_) if attempt < 100 => {
469                    attempt += 1;
470                    std::thread::sleep(Duration::from_millis(20));
471                }
472                Err(error) => panic!("preview: {error}"),
473            }
474        };
475        batch
476            .events
477            .iter()
478            .find_map(|envelope| match &envelope.event {
479                crate::core::telemetry_v2::TelemetryEventV2::ErrorCategoryAggregate(metrics)
480                    if metrics.category == category =>
481                {
482                    Some(metrics.count)
483                }
484                _ => None,
485            })
486    }
487
488    /// A failing inline command is classified once, by the call pipeline; the
489    /// worker counts only background-owned jobs, and as a failed command, never
490    /// as a LeanCTX-internal error.
491    #[test]
492    #[serial_test::serial]
493    #[cfg_attr(windows, ignore)]
494    fn worker_counts_only_background_failures_and_as_commands() {
495        use crate::core::telemetry_v2::ErrorCategory;
496        let _iso = crate::core::data_dir::isolated_data_dir();
497
498        let result = run_foreground_or_detach(
499            "exit 3".to_string(),
500            ".".to_string(),
501            std::collections::HashMap::default(),
502            Some(10_000),
503            Duration::from_secs(10),
504            None,
505            None,
506        );
507        assert!(matches!(
508            result,
509            ForegroundResult::Finished { exit_code: 3, .. }
510        ));
511        assert_eq!(queued_error_count(ErrorCategory::Command), None);
512        assert_eq!(queued_error_count(ErrorCategory::Internal), None);
513
514        let id = start(
515            "exit 4".to_string(),
516            ".".to_string(),
517            std::collections::HashMap::default(),
518            Some(10_000),
519        );
520        for _ in 0..200 {
521            if matches!(status(&id), Some(JobState::Completed { .. })) {
522                break;
523            }
524            std::thread::sleep(Duration::from_millis(25));
525        }
526        assert!(matches!(
527            status(&id),
528            Some(JobState::Completed { exit_code: 4, .. })
529        ));
530        assert_eq!(queued_error_count(ErrorCategory::Command), Some(1));
531        assert_eq!(queued_error_count(ErrorCategory::Internal), None);
532        super::remove_for_test(&id);
533    }
534
535    #[test]
536    fn completed_job_retention_is_bounded() {
537        let now = std::time::Instant::now();
538        let mut jobs = std::collections::HashMap::new();
539        for index in 0..=super::MAX_RETAINED_COMPLETED_JOBS {
540            jobs.insert(
541                format!("job_{index}"),
542                super::Job {
543                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
544                    state: JobState::Completed {
545                        output: "x".repeat(1024),
546                        exit_code: 0,
547                    },
548                    finished_at: Some(
549                        now.checked_sub(Duration::from_secs((index + 1) as u64))
550                            .unwrap(),
551                    ),
552                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
553                    foreground_waiters: 0,
554                    background_owned: true,
555                    telemetry_recorded: false,
556                },
557            );
558        }
559        jobs.insert(
560            "expired".to_string(),
561            super::Job {
562                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
563                state: JobState::Completed {
564                    output: "expired".to_string(),
565                    exit_code: 0,
566                },
567                finished_at: Some(
568                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
569                        .unwrap(),
570                ),
571                live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
572                foreground_waiters: 0,
573                background_owned: true,
574                telemetry_recorded: false,
575            },
576        );
577
578        super::prune_finished_jobs(&mut jobs, now);
579
580        assert_eq!(jobs.len(), super::MAX_RETAINED_COMPLETED_JOBS);
581        assert!(!jobs.contains_key("expired"));
582        assert!(!jobs.contains_key(&format!("job_{}", super::MAX_RETAINED_COMPLETED_JOBS)));
583    }
584
585    #[test]
586    fn completed_job_output_bytes_are_bounded() {
587        let now = std::time::Instant::now();
588        let mut jobs = std::collections::HashMap::new();
589        for index in 0..3 {
590            jobs.insert(
591                format!("job_{index}"),
592                super::Job {
593                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
594                    state: JobState::Completed {
595                        output: "x".repeat(8),
596                        exit_code: 0,
597                    },
598                    finished_at: Some(
599                        now.checked_sub(Duration::from_secs((3 - index) as u64))
600                            .unwrap(),
601                    ),
602                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
603                    foreground_waiters: 0,
604                    background_owned: true,
605                    telemetry_recorded: false,
606                },
607            );
608        }
609
610        super::prune_finished_jobs_with_limits(&mut jobs, now, 10, 16);
611
612        assert_eq!(jobs.len(), 2);
613        assert!(!jobs.contains_key("job_0"));
614    }
615
616    #[test]
617    #[cfg_attr(windows, ignore)]
618    fn foreground_run_finishing_within_cap_returns_inline() {
619        let result = run_foreground_or_detach(
620            "printf FG_OK".to_string(),
621            ".".to_string(),
622            std::collections::HashMap::default(),
623            Some(10_000),
624            Duration::from_secs(10),
625            None,
626            None,
627        );
628        match result {
629            ForegroundResult::Finished { output, exit_code } => {
630                assert_eq!(exit_code, 0);
631                assert!(output.contains("FG_OK"));
632            }
633            ForegroundResult::Detached { .. } => panic!("fast command should not detach"),
634        }
635    }
636
637    #[test]
638    #[cfg_attr(windows, ignore)]
639    fn foreground_run_exceeding_cap_detaches_to_pollable_job() {
640        let result = run_foreground_or_detach(
641            "sleep 5; printf SLOW_OK".to_string(),
642            ".".to_string(),
643            std::collections::HashMap::default(),
644            Some(10_000),
645            Duration::from_millis(100),
646            None,
647            None,
648        );
649        let ForegroundResult::Detached { job_id } = result else {
650            panic!("slow command should detach");
651        };
652        assert!(job_id.starts_with("shell_"));
653        // The returned id must resolve via status — the core #1106 guarantee.
654        assert!(status(&job_id).is_some());
655        cancel(&job_id);
656    }
657
658    /// #1173: a `timeout_ms` far beyond the soft cap must NOT keep the command
659    /// in the foreground. Raising the cap past the MCP host's ~120s abort is
660    /// what stranded results behind an unresolvable task id; the caller must
661    /// still get a real `shell_*` job id at the cap.
662    #[test]
663    #[cfg_attr(windows, ignore)]
664    fn large_timeout_ms_still_detaches_at_the_soft_cap() {
665        let result = run_foreground_or_detach(
666            "sleep 5; printf NEVER_INLINE".to_string(),
667            ".".to_string(),
668            std::collections::HashMap::default(),
669            Some(600_000),
670            Duration::from_millis(100),
671            None,
672            None,
673        );
674        let ForegroundResult::Detached { job_id } = result else {
675            panic!("timeout_ms must not extend the foreground wait");
676        };
677        assert!(status(&job_id).is_some());
678        cancel(&job_id);
679    }
680
681    /// #1173: a foreground run reports progress while it waits, so a slow
682    /// command is distinguishable from a hang. Deliberately slower than the
683    /// other tests here — it has to outlive one real [`TICK`].
684    #[test]
685    #[cfg_attr(windows, ignore)]
686    fn foreground_run_reports_progress_while_waiting() {
687        let ticks = std::sync::atomic::AtomicUsize::new(0);
688        let tick = |elapsed: Duration| {
689            assert!(elapsed >= TICK, "tick must report real elapsed time");
690            ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
691        };
692        let result = run_foreground_or_detach(
693            "sleep 30".to_string(),
694            ".".to_string(),
695            std::collections::HashMap::default(),
696            Some(60_000),
697            TICK + Duration::from_millis(500),
698            Some(&tick),
699            None,
700        );
701        let ForegroundResult::Detached { job_id } = result else {
702            panic!("slow command should detach");
703        };
704        cancel(&job_id);
705        assert!(
706            ticks.load(std::sync::atomic::Ordering::Relaxed) >= 1,
707            "no progress reported during a {}s+ foreground wait",
708            TICK.as_secs()
709        );
710    }
711
712    /// #1781: a client-side cancellation must free the waiting thread long
713    /// before the soft cap. The assertion is on *elapsed time*, not just on the
714    /// `Detached` shape — detaching at the cap returns the same variant, so the
715    /// shape alone would pass even with the check removed.
716    #[test]
717    #[cfg_attr(windows, ignore)]
718    fn cancelled_token_detaches_without_waiting_for_the_soft_cap() {
719        let token = tokio_util::sync::CancellationToken::new();
720        token.cancel();
721        let started = std::time::Instant::now();
722        let result = run_foreground_or_detach(
723            // Distinct from the progress test's `sleep 30`: identical commands
724            // coalesce onto one job (#1876), so a shared one would be cancelled
725            // under the other test's feet.
726            "sleep 31".to_string(),
727            ".".to_string(),
728            std::collections::HashMap::default(),
729            Some(60_000),
730            Duration::from_mins(1),
731            None,
732            Some(&token),
733        );
734        let elapsed = started.elapsed();
735        let ForegroundResult::Detached { job_id } = result else {
736            panic!("a cancelled request must detach instead of waiting it out");
737        };
738        cancel(&job_id);
739        assert!(
740            elapsed < Duration::from_secs(5),
741            "cancelled wait took {elapsed:?} against a one-minute cap — token not observed"
742        );
743    }
744
745    #[test]
746    #[cfg_attr(windows, ignore)]
747    fn background_job_runs_past_request_and_can_be_observed() {
748        let id = start(
749            "sleep 0.1; printf BG_JOB_OK".to_string(),
750            ".".to_string(),
751            std::collections::HashMap::default(),
752            Some(10_000),
753        );
754        assert!(matches!(status(&id), Some(JobState::Running { .. })));
755        for _ in 0..40 {
756            if let Some(JobState::Completed { output, exit_code }) = status(&id) {
757                assert_eq!(exit_code, 0);
758                assert!(output.contains("BG_JOB_OK"));
759                return;
760            }
761            std::thread::sleep(Duration::from_millis(25));
762        }
763        panic!("background job did not complete");
764    }
765
766    #[test]
767    #[cfg_attr(windows, ignore)]
768    fn cancelling_background_job_returns_cancelled_state() {
769        let id = start(
770            "sleep 5".to_string(),
771            ".".to_string(),
772            std::collections::HashMap::default(),
773            Some(10_000),
774        );
775        assert!(matches!(cancel(&id), Some(JobState::Running { .. })));
776        for _ in 0..40 {
777            if let Some(JobState::Cancelled { output }) = status(&id) {
778                assert!(output.contains("[cancelled: command stopped on request]"));
779                return;
780            }
781            std::thread::sleep(Duration::from_millis(25));
782        }
783        panic!("background job was not cancelled");
784    }
785
786    /// #1217: a still-running job's `status` must surface the captured-so-far
787    /// output, not a bare "running" with no signal of progress.
788    #[test]
789    #[cfg_attr(windows, ignore)]
790    fn running_background_job_status_streams_partial_output() {
791        let id = start(
792            "printf EARLY_LINE; sleep 5".to_string(),
793            ".".to_string(),
794            std::collections::HashMap::default(),
795            Some(10_000),
796        );
797        let mut saw_partial = false;
798        for _ in 0..80 {
799            if let Some(JobState::Running { output }) = status(&id)
800                && output.contains("EARLY_LINE")
801            {
802                saw_partial = true;
803                break;
804            }
805            std::thread::sleep(Duration::from_millis(25));
806        }
807        cancel(&id);
808        assert!(
809            saw_partial,
810            "status never surfaced the running job's early output"
811        );
812    }
813
814    /// #1876: identical foreground calls coalesce onto one job. The first to
815    /// see it finish used to remove the shared entry, so every other caller
816    /// polled a missing id until the host timed out. Each must get the output.
817    #[test]
818    #[cfg_attr(windows, ignore)]
819    fn identical_concurrent_foreground_calls_all_observe_completion() {
820        const CALLERS: usize = 3;
821        let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
822        let handles: Vec<_> = (0..CALLERS)
823            .map(|_| {
824                let barrier = std::sync::Arc::clone(&barrier);
825                std::thread::spawn(move || {
826                    barrier.wait();
827                    run_foreground_or_detach(
828                        "sleep 0.2; printf GH1876_ALL_OK".to_string(),
829                        ".".to_string(),
830                        std::collections::HashMap::default(),
831                        Some(10_000),
832                        Duration::from_secs(10),
833                        None,
834                        None,
835                    )
836                })
837            })
838            .collect();
839        for handle in handles {
840            match handle.join().expect("foreground caller panicked") {
841                ForegroundResult::Finished { output, exit_code } => {
842                    assert_eq!(exit_code, 0);
843                    assert!(output.contains("GH1876_ALL_OK"), "got: {output}");
844                }
845                ForegroundResult::Detached { job_id } => {
846                    cancel(&job_id);
847                    panic!("a coalesced caller lost the shared job and detached");
848                }
849            }
850        }
851    }
852
853    /// #1876: a foreground call that joins an explicit background job must
854    /// not remove the entry the background caller still polls by id.
855    #[test]
856    #[cfg_attr(windows, ignore)]
857    fn foreground_join_keeps_a_background_job_pollable() {
858        let command = "sleep 0.2; printf GH1876_BG_OK".to_string();
859        let id = start(
860            command.clone(),
861            ".".to_string(),
862            std::collections::HashMap::default(),
863            Some(10_000),
864        );
865        let result = run_foreground_or_detach(
866            command,
867            ".".to_string(),
868            std::collections::HashMap::default(),
869            Some(10_000),
870            Duration::from_secs(10),
871            None,
872            None,
873        );
874        assert!(matches!(result, ForegroundResult::Finished { .. }));
875        match status(&id) {
876            Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_BG_OK")),
877            other => panic!("background job vanished after a foreground join: {other:?}"),
878        }
879        super::remove_for_test(&id);
880    }
881
882    /// #1876: a call that arrives after the job finished but before its waiter
883    /// read the result must join that entry. Replacing it let the first
884    /// waiter's release delete the second caller's job.
885    #[test]
886    #[cfg_attr(windows, ignore)]
887    fn a_caller_joins_a_finished_entry_its_waiter_has_not_read() {
888        let launch = || {
889            super::start_inner(
890                "printf GH1876_WINDOW".to_string(),
891                ".".to_string(),
892                std::collections::HashMap::default(),
893                Some(10_000),
894                true,
895            )
896        };
897        let id = launch();
898        let deadline = std::time::Instant::now() + Duration::from_secs(10);
899        while !matches!(status(&id), Some(JobState::Completed { .. })) {
900            assert!(std::time::Instant::now() < deadline, "job never completed");
901            std::thread::sleep(Duration::from_millis(10));
902        }
903
904        assert_eq!(launch(), id);
905        super::release_foreground(&id, false);
906        match status(&id) {
907            Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_WINDOW")),
908            other => panic!("the joined caller lost its result: {other:?}"),
909        }
910        super::release_foreground(&id, false);
911        assert!(status(&id).is_none(), "the last waiter removes the entry");
912    }
913
914    /// #1876: fast identical commands finish inside one poll interval, which
915    /// is where callers used to replace an unread entry.
916    #[test]
917    #[cfg_attr(windows, ignore)]
918    fn fast_identical_concurrent_foreground_calls_all_return() {
919        const CALLERS: usize = 8;
920        for _ in 0..5 {
921            let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
922            let handles: Vec<_> = (0..CALLERS)
923                .map(|_| {
924                    let barrier = std::sync::Arc::clone(&barrier);
925                    std::thread::spawn(move || {
926                        barrier.wait();
927                        run_foreground_or_detach(
928                            "printf GH1876_FAST".to_string(),
929                            ".".to_string(),
930                            std::collections::HashMap::default(),
931                            Some(10_000),
932                            Duration::from_secs(5),
933                            None,
934                            None,
935                        )
936                    })
937                })
938                .collect();
939            for handle in handles {
940                match handle.join().expect("foreground caller panicked") {
941                    ForegroundResult::Finished { output, .. } => {
942                        assert!(output.contains("GH1876_FAST"), "got: {output}");
943                    }
944                    ForegroundResult::Detached { job_id } => {
945                        cancel(&job_id);
946                        panic!("a fast identical caller lost its job and detached");
947                    }
948                }
949            }
950        }
951    }
952
953    #[test]
954    fn pruning_keeps_finished_jobs_that_a_waiter_has_not_read() {
955        let now = std::time::Instant::now();
956        let mut jobs = std::collections::HashMap::new();
957        jobs.insert(
958            "waited".to_string(),
959            super::Job {
960                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
961                state: JobState::Completed {
962                    output: "x".repeat(64),
963                    exit_code: 0,
964                },
965                finished_at: Some(
966                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
967                        .unwrap(),
968                ),
969                live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
970                foreground_waiters: 1,
971                background_owned: false,
972                telemetry_recorded: false,
973            },
974        );
975
976        super::prune_finished_jobs_with_limits(&mut jobs, now, 0, 0);
977
978        assert!(jobs.contains_key("waited"));
979    }
980}