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) -> ForegroundResult {
200    let id = start(command, cwd, extra_env, timeout_ms);
201    let started = Instant::now();
202    let deadline = started + soft_cap;
203    let mut next_tick = started + TICK;
204    loop {
205        match status(&id) {
206            Some(JobState::Completed { output, exit_code }) => {
207                remove(&id);
208                return ForegroundResult::Finished { output, exit_code };
209            }
210            // A cancel can only be requested via background_action once the job
211            // is detached, so an inline wait realistically only sees Completed;
212            // handle Cancelled defensively with the timeout exit code.
213            Some(JobState::Cancelled { output }) => {
214                remove(&id);
215                return ForegroundResult::Finished {
216                    output,
217                    exit_code: 130,
218                };
219            }
220            _ => {}
221        }
222        let now = Instant::now();
223        if now >= deadline {
224            return ForegroundResult::Detached { job_id: id };
225        }
226        if let Some(tick) = on_tick
227            && now >= next_tick
228        {
229            tick(started.elapsed());
230            next_tick = now + TICK;
231        }
232        std::thread::sleep(Duration::from_millis(50));
233    }
234}
235
236/// Drop a finished job from the registry so inline foreground runs do not
237/// accumulate completed entries.
238fn remove(id: &str) {
239    JOBS.lock()
240        .unwrap_or_else(std::sync::PoisonError::into_inner)
241        .remove(id);
242}
243
244#[cfg(all(test, not(windows)))]
245pub(crate) fn remove_for_test(id: &str) {
246    remove(id);
247}
248
249pub fn status(id: &str) -> Option<JobState> {
250    let jobs = JOBS
251        .lock()
252        .unwrap_or_else(std::sync::PoisonError::into_inner);
253    let job = jobs.get(id)?;
254    Some(match &job.state {
255        // #1217: a running job's output lives in the shared buffer the worker
256        // streams into; surface the captured-so-far snapshot on each poll.
257        JobState::Running { .. } => JobState::Running {
258            output: job
259                .live
260                .lock()
261                .unwrap_or_else(std::sync::PoisonError::into_inner)
262                .clone(),
263        },
264        other => other.clone(),
265    })
266}
267
268pub fn cancel(id: &str) -> Option<JobState> {
269    let mut jobs = JOBS
270        .lock()
271        .unwrap_or_else(std::sync::PoisonError::into_inner);
272    let job = jobs.get_mut(id)?;
273    if matches!(job.state, JobState::Running { .. }) {
274        job.cancel.store(true, Ordering::Release);
275    }
276    Some(job.state.clone())
277}
278
279#[cfg(test)]
280mod tests {
281    use super::{
282        ForegroundResult, JobState, TICK, cancel, run_foreground_or_detach, start, status,
283    };
284    use std::time::Duration;
285
286    #[test]
287    fn completed_job_retention_is_bounded() {
288        let now = std::time::Instant::now();
289        let mut jobs = std::collections::HashMap::new();
290        for index in 0..=super::MAX_RETAINED_COMPLETED_JOBS {
291            jobs.insert(
292                format!("job_{index}"),
293                super::Job {
294                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
295                    state: JobState::Completed {
296                        output: "x".repeat(1024),
297                        exit_code: 0,
298                    },
299                    finished_at: Some(
300                        now.checked_sub(Duration::from_secs((index + 1) as u64))
301                            .unwrap(),
302                    ),
303                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
304                },
305            );
306        }
307        jobs.insert(
308            "expired".to_string(),
309            super::Job {
310                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
311                state: JobState::Completed {
312                    output: "expired".to_string(),
313                    exit_code: 0,
314                },
315                finished_at: Some(
316                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
317                        .unwrap(),
318                ),
319                live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
320            },
321        );
322
323        super::prune_finished_jobs(&mut jobs, now);
324
325        assert_eq!(jobs.len(), super::MAX_RETAINED_COMPLETED_JOBS);
326        assert!(!jobs.contains_key("expired"));
327        assert!(!jobs.contains_key(&format!("job_{}", super::MAX_RETAINED_COMPLETED_JOBS)));
328    }
329
330    #[test]
331    fn completed_job_output_bytes_are_bounded() {
332        let now = std::time::Instant::now();
333        let mut jobs = std::collections::HashMap::new();
334        for index in 0..3 {
335            jobs.insert(
336                format!("job_{index}"),
337                super::Job {
338                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
339                    state: JobState::Completed {
340                        output: "x".repeat(8),
341                        exit_code: 0,
342                    },
343                    finished_at: Some(
344                        now.checked_sub(Duration::from_secs((3 - index) as u64))
345                            .unwrap(),
346                    ),
347                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
348                },
349            );
350        }
351
352        super::prune_finished_jobs_with_limits(&mut jobs, now, 10, 16);
353
354        assert_eq!(jobs.len(), 2);
355        assert!(!jobs.contains_key("job_0"));
356    }
357
358    #[test]
359    #[cfg_attr(windows, ignore)]
360    fn foreground_run_finishing_within_cap_returns_inline() {
361        let result = run_foreground_or_detach(
362            "printf FG_OK".to_string(),
363            ".".to_string(),
364            std::collections::HashMap::default(),
365            Some(10_000),
366            Duration::from_secs(10),
367            None,
368        );
369        match result {
370            ForegroundResult::Finished { output, exit_code } => {
371                assert_eq!(exit_code, 0);
372                assert!(output.contains("FG_OK"));
373            }
374            ForegroundResult::Detached { .. } => panic!("fast command should not detach"),
375        }
376    }
377
378    #[test]
379    #[cfg_attr(windows, ignore)]
380    fn foreground_run_exceeding_cap_detaches_to_pollable_job() {
381        let result = run_foreground_or_detach(
382            "sleep 5; printf SLOW_OK".to_string(),
383            ".".to_string(),
384            std::collections::HashMap::default(),
385            Some(10_000),
386            Duration::from_millis(100),
387            None,
388        );
389        let ForegroundResult::Detached { job_id } = result else {
390            panic!("slow command should detach");
391        };
392        assert!(job_id.starts_with("shell_"));
393        // The returned id must resolve via status — the core #1106 guarantee.
394        assert!(status(&job_id).is_some());
395        cancel(&job_id);
396    }
397
398    /// #1173: a `timeout_ms` far beyond the soft cap must NOT keep the command
399    /// in the foreground. Raising the cap past the MCP host's ~120s abort is
400    /// what stranded results behind an unresolvable task id; the caller must
401    /// still get a real `shell_*` job id at the cap.
402    #[test]
403    #[cfg_attr(windows, ignore)]
404    fn large_timeout_ms_still_detaches_at_the_soft_cap() {
405        let result = run_foreground_or_detach(
406            "sleep 5; printf NEVER_INLINE".to_string(),
407            ".".to_string(),
408            std::collections::HashMap::default(),
409            Some(600_000),
410            Duration::from_millis(100),
411            None,
412        );
413        let ForegroundResult::Detached { job_id } = result else {
414            panic!("timeout_ms must not extend the foreground wait");
415        };
416        assert!(status(&job_id).is_some());
417        cancel(&job_id);
418    }
419
420    /// #1173: a foreground run reports progress while it waits, so a slow
421    /// command is distinguishable from a hang. Deliberately slower than the
422    /// other tests here — it has to outlive one real [`TICK`].
423    #[test]
424    #[cfg_attr(windows, ignore)]
425    fn foreground_run_reports_progress_while_waiting() {
426        let ticks = std::sync::atomic::AtomicUsize::new(0);
427        let tick = |elapsed: Duration| {
428            assert!(elapsed >= TICK, "tick must report real elapsed time");
429            ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
430        };
431        let result = run_foreground_or_detach(
432            "sleep 30".to_string(),
433            ".".to_string(),
434            std::collections::HashMap::default(),
435            Some(60_000),
436            TICK + Duration::from_millis(500),
437            Some(&tick),
438        );
439        let ForegroundResult::Detached { job_id } = result else {
440            panic!("slow command should detach");
441        };
442        cancel(&job_id);
443        assert!(
444            ticks.load(std::sync::atomic::Ordering::Relaxed) >= 1,
445            "no progress reported during a {}s+ foreground wait",
446            TICK.as_secs()
447        );
448    }
449
450    #[test]
451    #[cfg_attr(windows, ignore)]
452    fn background_job_runs_past_request_and_can_be_observed() {
453        let id = start(
454            "sleep 0.1; printf BG_JOB_OK".to_string(),
455            ".".to_string(),
456            std::collections::HashMap::default(),
457            Some(10_000),
458        );
459        assert!(matches!(status(&id), Some(JobState::Running { .. })));
460        for _ in 0..40 {
461            if let Some(JobState::Completed { output, exit_code }) = status(&id) {
462                assert_eq!(exit_code, 0);
463                assert!(output.contains("BG_JOB_OK"));
464                return;
465            }
466            std::thread::sleep(Duration::from_millis(25));
467        }
468        panic!("background job did not complete");
469    }
470
471    #[test]
472    #[cfg_attr(windows, ignore)]
473    fn cancelling_background_job_returns_cancelled_state() {
474        let id = start(
475            "sleep 5".to_string(),
476            ".".to_string(),
477            std::collections::HashMap::default(),
478            Some(10_000),
479        );
480        assert!(matches!(cancel(&id), Some(JobState::Running { .. })));
481        for _ in 0..40 {
482            if let Some(JobState::Cancelled { output }) = status(&id) {
483                assert!(output.contains("[cancelled: command stopped on request]"));
484                return;
485            }
486            std::thread::sleep(Duration::from_millis(25));
487        }
488        panic!("background job was not cancelled");
489    }
490
491    /// #1217: a still-running job's `status` must surface the captured-so-far
492    /// output, not a bare "running" with no signal of progress.
493    #[test]
494    #[cfg_attr(windows, ignore)]
495    fn running_background_job_status_streams_partial_output() {
496        let id = start(
497            "printf EARLY_LINE; sleep 5".to_string(),
498            ".".to_string(),
499            std::collections::HashMap::default(),
500            Some(10_000),
501        );
502        let mut saw_partial = false;
503        for _ in 0..80 {
504            if let Some(JobState::Running { output }) = status(&id)
505                && output.contains("EARLY_LINE")
506            {
507                saw_partial = true;
508                break;
509            }
510            std::thread::sleep(Duration::from_millis(25));
511        }
512        cancel(&id);
513        assert!(
514            saw_partial,
515            "status never surfaced the running job's early output"
516        );
517    }
518}