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}
34
35static JOBS: LazyLock<Mutex<HashMap<String, Job>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
36
37/// How often a foreground run reports progress to the MCP client (#1173).
38const TICK: Duration = Duration::from_secs(5);
39
40fn prune_finished_jobs(jobs: &mut HashMap<String, Job>, now: Instant) {
41    prune_finished_jobs_with_limits(
42        jobs,
43        now,
44        MAX_RETAINED_COMPLETED_JOBS,
45        MAX_RETAINED_COMPLETED_BYTES,
46    );
47}
48
49fn prune_finished_jobs_with_limits(
50    jobs: &mut HashMap<String, Job>,
51    now: Instant,
52    max_completed_jobs: usize,
53    max_completed_bytes: usize,
54) {
55    jobs.retain(|_, job| {
56        job.finished_at
57            .is_none_or(|finished_at| now.duration_since(finished_at) < COMPLETED_JOB_TTL)
58    });
59
60    let mut completed: Vec<_> = jobs
61        .iter()
62        .filter_map(|(id, job)| {
63            let finished_at = job.finished_at?;
64            let output_bytes = match &job.state {
65                JobState::Completed { output, .. } | JobState::Cancelled { output } => output.len(),
66                JobState::Running { .. } => 0,
67            };
68            Some((finished_at, id.clone(), output_bytes))
69        })
70        .collect();
71    completed.sort_unstable_by_key(|(finished_at, _, _)| *finished_at);
72
73    let mut retained_bytes = completed.iter().map(|(_, _, bytes)| bytes).sum::<usize>();
74    let mut retained_jobs = completed.len();
75    for (_, id, output_bytes) in completed {
76        if retained_jobs <= max_completed_jobs && retained_bytes <= max_completed_bytes {
77            break;
78        }
79        if retained_jobs == 1 {
80            break;
81        }
82        jobs.remove(&id);
83        retained_jobs -= 1;
84        retained_bytes = retained_bytes.saturating_sub(output_bytes);
85    }
86}
87
88pub fn start(
89    command: String,
90    cwd: String,
91    extra_env: std::collections::HashMap<String, String>,
92    timeout_ms: Option<u64>,
93) -> String {
94    // IDs are content-addressed so tool responses stay deterministic (#498).
95    // An identical in-flight launch coalesces onto the same job instead of
96    // creating duplicate expensive builds/tests.
97    let mut env_entries: Vec<_> = extra_env.iter().collect();
98    env_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
99    let env_key = env_entries
100        .into_iter()
101        .map(|(key, value)| format!("{key}={value}"))
102        .collect::<Vec<_>>()
103        .join("\0");
104    let material = format!(
105        "{command}\0{cwd}\0{}\0{env_key}",
106        timeout_ms.unwrap_or_default()
107    );
108    let id = format!(
109        "shell_{}",
110        &blake3::hash(material.as_bytes()).to_hex()[..16]
111    );
112    let cancel = Arc::new(AtomicBool::new(false));
113    let worker_cancel = Arc::clone(&cancel);
114    let live = Arc::new(Mutex::new(String::new()));
115    let worker_live = Arc::clone(&live);
116    {
117        let mut jobs = JOBS
118            .lock()
119            .unwrap_or_else(std::sync::PoisonError::into_inner);
120        prune_finished_jobs(&mut jobs, Instant::now());
121        if matches!(
122            jobs.get(&id).map(|job| &job.state),
123            Some(JobState::Running { .. })
124        ) {
125            return id;
126        }
127        jobs.insert(
128            id.clone(),
129            Job {
130                cancel,
131                state: JobState::Running {
132                    output: String::new(),
133                },
134                finished_at: None,
135                live,
136            },
137        );
138    }
139
140    let worker_id = id.clone();
141    std::thread::spawn(move || {
142        let (output, exit_code) = crate::server::execute::execute_command_with_env_cancellable(
143            &command,
144            &cwd,
145            &extra_env,
146            timeout_ms,
147            Some(&worker_cancel),
148            // #1113/#1173: bounded by output, not wall clock — a monitor loop
149            // emitting a line every 45s must survive. See `idle_keyed`.
150            true,
151            // #1217: stream captured output into the shared buffer as it arrives.
152            Some(&worker_live),
153        );
154        let mut jobs = JOBS
155            .lock()
156            .unwrap_or_else(std::sync::PoisonError::into_inner);
157        let Some(job) = jobs.get_mut(&worker_id) else {
158            return;
159        };
160        job.state = if worker_cancel.load(Ordering::Acquire) {
161            JobState::Cancelled { output }
162        } else {
163            JobState::Completed { output, exit_code }
164        };
165        job.finished_at = Some(Instant::now());
166        prune_finished_jobs(&mut jobs, Instant::now());
167    });
168    id
169}
170
171/// Outcome of a foreground run that is allowed to detach on a soft cap.
172pub enum ForegroundResult {
173    /// The command finished within the soft cap; output is returned inline and
174    /// the job has been removed from the registry.
175    Finished { output: String, exit_code: i32 },
176    /// The command was still running at the soft cap and was left running as a
177    /// pollable background job (#1106).
178    Detached { job_id: String },
179}
180
181/// Run `command` as a managed background job but block up to `soft_cap` waiting
182/// for it to finish, so fast commands still return their output inline.
183///
184/// The MCP host aborts a tool call that stays in the foreground too long
185/// (~120s) and hands back a task id that `background_action=status` cannot
186/// resolve. By detaching *before* that deadline we always return a real
187/// `shell_*` job id the caller can poll or cancel (#1106).
188///
189/// `on_tick` is called roughly every `TICK` while the command is still
190/// running, so the caller can emit MCP progress notifications and a 3-minute
191/// build stops being indistinguishable from a hang (#1173).
192pub fn run_foreground_or_detach(
193    command: String,
194    cwd: String,
195    extra_env: std::collections::HashMap<String, String>,
196    timeout_ms: Option<u64>,
197    soft_cap: Duration,
198    on_tick: Option<&dyn Fn(Duration)>,
199    cancel: Option<&tokio_util::sync::CancellationToken>,
200) -> ForegroundResult {
201    let id = start(command, cwd, extra_env, timeout_ms);
202    let started = Instant::now();
203    let deadline = started + soft_cap;
204    let mut next_tick = started + TICK;
205    loop {
206        match status(&id) {
207            Some(JobState::Completed { output, exit_code }) => {
208                remove(&id);
209                return ForegroundResult::Finished { output, exit_code };
210            }
211            // A cancel can only be requested via background_action once the job
212            // is detached, so an inline wait realistically only sees Completed;
213            // handle Cancelled defensively with the timeout exit code.
214            Some(JobState::Cancelled { output }) => {
215                remove(&id);
216                return ForegroundResult::Finished {
217                    output,
218                    exit_code: 130,
219                };
220            }
221            _ => {}
222        }
223        // #1781: when the host abandons the call, free this thread immediately.
224        // The foreground wait runs on the blocking pool — dispatch hands the
225        // handler to `spawn_blocking`, and that pool has
226        // `(workers * 4).clamp(8, 32)` slots. Without this check the loop spun
227        // on until `soft_cap` — five minutes for a `timeout_ms: 300_000` call —
228        // so a burst of abandoned commands could occupy every slot, after which
229        // subsequent tool calls queued behind them until the server restarted.
230        // Detaching rather than killing keeps the job alive under its id, which
231        // the caller already knows how to poll and cancel.
232        if cancel.is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
233            return ForegroundResult::Detached { job_id: id };
234        }
235        let now = Instant::now();
236        if now >= deadline {
237            return ForegroundResult::Detached { job_id: id };
238        }
239        if let Some(tick) = on_tick
240            && now >= next_tick
241        {
242            tick(started.elapsed());
243            next_tick = now + TICK;
244        }
245        std::thread::sleep(Duration::from_millis(50));
246    }
247}
248
249/// Drop a finished job from the registry so inline foreground runs do not
250/// accumulate completed entries.
251fn remove(id: &str) {
252    JOBS.lock()
253        .unwrap_or_else(std::sync::PoisonError::into_inner)
254        .remove(id);
255}
256
257#[cfg(all(test, not(windows)))]
258pub(crate) fn remove_for_test(id: &str) {
259    remove(id);
260}
261
262pub fn status(id: &str) -> Option<JobState> {
263    let jobs = JOBS
264        .lock()
265        .unwrap_or_else(std::sync::PoisonError::into_inner);
266    let job = jobs.get(id)?;
267    Some(match &job.state {
268        // #1217: a running job's output lives in the shared buffer the worker
269        // streams into; surface the captured-so-far snapshot on each poll.
270        JobState::Running { .. } => JobState::Running {
271            output: job
272                .live
273                .lock()
274                .unwrap_or_else(std::sync::PoisonError::into_inner)
275                .clone(),
276        },
277        other => other.clone(),
278    })
279}
280
281pub fn cancel(id: &str) -> Option<JobState> {
282    let mut jobs = JOBS
283        .lock()
284        .unwrap_or_else(std::sync::PoisonError::into_inner);
285    let job = jobs.get_mut(id)?;
286    if matches!(job.state, JobState::Running { .. }) {
287        job.cancel.store(true, Ordering::Release);
288    }
289    Some(job.state.clone())
290}
291
292#[cfg(test)]
293mod tests {
294    use super::{
295        ForegroundResult, JobState, TICK, cancel, run_foreground_or_detach, start, status,
296    };
297    use std::time::Duration;
298
299    #[test]
300    fn completed_job_retention_is_bounded() {
301        let now = std::time::Instant::now();
302        let mut jobs = std::collections::HashMap::new();
303        for index in 0..=super::MAX_RETAINED_COMPLETED_JOBS {
304            jobs.insert(
305                format!("job_{index}"),
306                super::Job {
307                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
308                    state: JobState::Completed {
309                        output: "x".repeat(1024),
310                        exit_code: 0,
311                    },
312                    finished_at: Some(
313                        now.checked_sub(Duration::from_secs((index + 1) as u64))
314                            .unwrap(),
315                    ),
316                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
317                },
318            );
319        }
320        jobs.insert(
321            "expired".to_string(),
322            super::Job {
323                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
324                state: JobState::Completed {
325                    output: "expired".to_string(),
326                    exit_code: 0,
327                },
328                finished_at: Some(
329                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
330                        .unwrap(),
331                ),
332                live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
333            },
334        );
335
336        super::prune_finished_jobs(&mut jobs, now);
337
338        assert_eq!(jobs.len(), super::MAX_RETAINED_COMPLETED_JOBS);
339        assert!(!jobs.contains_key("expired"));
340        assert!(!jobs.contains_key(&format!("job_{}", super::MAX_RETAINED_COMPLETED_JOBS)));
341    }
342
343    #[test]
344    fn completed_job_output_bytes_are_bounded() {
345        let now = std::time::Instant::now();
346        let mut jobs = std::collections::HashMap::new();
347        for index in 0..3 {
348            jobs.insert(
349                format!("job_{index}"),
350                super::Job {
351                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
352                    state: JobState::Completed {
353                        output: "x".repeat(8),
354                        exit_code: 0,
355                    },
356                    finished_at: Some(
357                        now.checked_sub(Duration::from_secs((3 - index) as u64))
358                            .unwrap(),
359                    ),
360                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
361                },
362            );
363        }
364
365        super::prune_finished_jobs_with_limits(&mut jobs, now, 10, 16);
366
367        assert_eq!(jobs.len(), 2);
368        assert!(!jobs.contains_key("job_0"));
369    }
370
371    #[test]
372    #[cfg_attr(windows, ignore)]
373    fn foreground_run_finishing_within_cap_returns_inline() {
374        let result = run_foreground_or_detach(
375            "printf FG_OK".to_string(),
376            ".".to_string(),
377            std::collections::HashMap::default(),
378            Some(10_000),
379            Duration::from_secs(10),
380            None,
381            None,
382        );
383        match result {
384            ForegroundResult::Finished { output, exit_code } => {
385                assert_eq!(exit_code, 0);
386                assert!(output.contains("FG_OK"));
387            }
388            ForegroundResult::Detached { .. } => panic!("fast command should not detach"),
389        }
390    }
391
392    #[test]
393    #[cfg_attr(windows, ignore)]
394    fn foreground_run_exceeding_cap_detaches_to_pollable_job() {
395        let result = run_foreground_or_detach(
396            "sleep 5; printf SLOW_OK".to_string(),
397            ".".to_string(),
398            std::collections::HashMap::default(),
399            Some(10_000),
400            Duration::from_millis(100),
401            None,
402            None,
403        );
404        let ForegroundResult::Detached { job_id } = result else {
405            panic!("slow command should detach");
406        };
407        assert!(job_id.starts_with("shell_"));
408        // The returned id must resolve via status — the core #1106 guarantee.
409        assert!(status(&job_id).is_some());
410        cancel(&job_id);
411    }
412
413    /// #1173: a `timeout_ms` far beyond the soft cap must NOT keep the command
414    /// in the foreground. Raising the cap past the MCP host's ~120s abort is
415    /// what stranded results behind an unresolvable task id; the caller must
416    /// still get a real `shell_*` job id at the cap.
417    #[test]
418    #[cfg_attr(windows, ignore)]
419    fn large_timeout_ms_still_detaches_at_the_soft_cap() {
420        let result = run_foreground_or_detach(
421            "sleep 5; printf NEVER_INLINE".to_string(),
422            ".".to_string(),
423            std::collections::HashMap::default(),
424            Some(600_000),
425            Duration::from_millis(100),
426            None,
427            None,
428        );
429        let ForegroundResult::Detached { job_id } = result else {
430            panic!("timeout_ms must not extend the foreground wait");
431        };
432        assert!(status(&job_id).is_some());
433        cancel(&job_id);
434    }
435
436    /// #1173: a foreground run reports progress while it waits, so a slow
437    /// command is distinguishable from a hang. Deliberately slower than the
438    /// other tests here — it has to outlive one real [`TICK`].
439    #[test]
440    #[cfg_attr(windows, ignore)]
441    fn foreground_run_reports_progress_while_waiting() {
442        let ticks = std::sync::atomic::AtomicUsize::new(0);
443        let tick = |elapsed: Duration| {
444            assert!(elapsed >= TICK, "tick must report real elapsed time");
445            ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
446        };
447        let result = run_foreground_or_detach(
448            "sleep 30".to_string(),
449            ".".to_string(),
450            std::collections::HashMap::default(),
451            Some(60_000),
452            TICK + Duration::from_millis(500),
453            Some(&tick),
454            None,
455        );
456        let ForegroundResult::Detached { job_id } = result else {
457            panic!("slow command should detach");
458        };
459        cancel(&job_id);
460        assert!(
461            ticks.load(std::sync::atomic::Ordering::Relaxed) >= 1,
462            "no progress reported during a {}s+ foreground wait",
463            TICK.as_secs()
464        );
465    }
466
467    /// #1781: a client-side cancellation must free the waiting thread long
468    /// before the soft cap. The assertion is on *elapsed time*, not just on the
469    /// `Detached` shape — detaching at the cap returns the same variant, so the
470    /// shape alone would pass even with the check removed.
471    #[test]
472    #[cfg_attr(windows, ignore)]
473    fn cancelled_token_detaches_without_waiting_for_the_soft_cap() {
474        let token = tokio_util::sync::CancellationToken::new();
475        token.cancel();
476        let started = std::time::Instant::now();
477        let result = run_foreground_or_detach(
478            "sleep 30".to_string(),
479            ".".to_string(),
480            std::collections::HashMap::default(),
481            Some(60_000),
482            Duration::from_mins(1),
483            None,
484            Some(&token),
485        );
486        let elapsed = started.elapsed();
487        let ForegroundResult::Detached { job_id } = result else {
488            panic!("a cancelled request must detach instead of waiting it out");
489        };
490        cancel(&job_id);
491        assert!(
492            elapsed < Duration::from_secs(5),
493            "cancelled wait took {elapsed:?} against a one-minute cap — token not observed"
494        );
495    }
496
497    #[test]
498    #[cfg_attr(windows, ignore)]
499    fn background_job_runs_past_request_and_can_be_observed() {
500        let id = start(
501            "sleep 0.1; printf BG_JOB_OK".to_string(),
502            ".".to_string(),
503            std::collections::HashMap::default(),
504            Some(10_000),
505        );
506        assert!(matches!(status(&id), Some(JobState::Running { .. })));
507        for _ in 0..40 {
508            if let Some(JobState::Completed { output, exit_code }) = status(&id) {
509                assert_eq!(exit_code, 0);
510                assert!(output.contains("BG_JOB_OK"));
511                return;
512            }
513            std::thread::sleep(Duration::from_millis(25));
514        }
515        panic!("background job did not complete");
516    }
517
518    #[test]
519    #[cfg_attr(windows, ignore)]
520    fn cancelling_background_job_returns_cancelled_state() {
521        let id = start(
522            "sleep 5".to_string(),
523            ".".to_string(),
524            std::collections::HashMap::default(),
525            Some(10_000),
526        );
527        assert!(matches!(cancel(&id), Some(JobState::Running { .. })));
528        for _ in 0..40 {
529            if let Some(JobState::Cancelled { output }) = status(&id) {
530                assert!(output.contains("[cancelled: command stopped on request]"));
531                return;
532            }
533            std::thread::sleep(Duration::from_millis(25));
534        }
535        panic!("background job was not cancelled");
536    }
537
538    /// #1217: a still-running job's `status` must surface the captured-so-far
539    /// output, not a bare "running" with no signal of progress.
540    #[test]
541    #[cfg_attr(windows, ignore)]
542    fn running_background_job_status_streams_partial_output() {
543        let id = start(
544            "printf EARLY_LINE; sleep 5".to_string(),
545            ".".to_string(),
546            std::collections::HashMap::default(),
547            Some(10_000),
548        );
549        let mut saw_partial = false;
550        for _ in 0..80 {
551            if let Some(JobState::Running { output }) = status(&id)
552                && output.contains("EARLY_LINE")
553            {
554                saw_partial = true;
555                break;
556            }
557            std::thread::sleep(Duration::from_millis(25));
558        }
559        cancel(&id);
560        assert!(
561            saw_partial,
562            "status never surfaced the running job's early output"
563        );
564    }
565}