Skip to main content

aft/bash_background/
mod.rs

1//! Background bash task management. Phase 0 stub; Phase 1 Track D fills in.
2
3pub mod buffer;
4pub mod persistence;
5pub mod process;
6pub mod registry;
7pub mod watchdog;
8
9use crate::context::AppContext;
10use crate::protocol::Response;
11use serde::{Deserialize, Serialize};
12use serde_json::json;
13use std::collections::HashMap;
14use std::path::PathBuf;
15use std::time::Duration;
16
17pub use registry::{BgCompletion, BgTaskRegistry};
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct BgTaskInfo {
21    pub task_id: String,
22    pub status: BgTaskStatus,
23    pub command: String,
24    pub started_at: u64,
25    pub duration_ms: Option<u64>,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
29#[serde(rename_all = "snake_case")]
30pub enum BgTaskStatus {
31    Starting,
32    Running,
33    Killing,
34    Completed,
35    Failed,
36    Killed,
37    TimedOut,
38}
39
40impl BgTaskStatus {
41    pub fn is_terminal(&self) -> bool {
42        matches!(
43            self,
44            BgTaskStatus::Completed
45                | BgTaskStatus::Failed
46                | BgTaskStatus::Killed
47                | BgTaskStatus::TimedOut
48        )
49    }
50}
51
52/// Spawn a bash command in the background. Returns a task_id immediately.
53pub fn spawn(
54    request_id: &str,
55    session_id: &str,
56    command: &str,
57    workdir: Option<PathBuf>,
58    env: Option<HashMap<String, String>>,
59    timeout_ms: Option<u64>,
60    ctx: &AppContext,
61) -> Response {
62    if !ctx.config().experimental_bash_background {
63        return Response::error(
64            request_id,
65            "feature_disabled",
66            "background bash is disabled; set `experimental.bash.background: true` in aft.jsonc",
67        );
68    }
69
70    let workdir = workdir.unwrap_or_else(|| {
71        ctx.config().project_root.clone().unwrap_or_else(|| {
72            std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
73        })
74    });
75    let storage_dir = storage_dir(ctx.config().storage_dir.as_deref());
76    let max_running = ctx.config().max_background_bash_tasks;
77    let timeout = timeout_ms.map(Duration::from_millis);
78
79    match ctx.bash_background().spawn(
80        command,
81        session_id.to_string(),
82        workdir,
83        env.unwrap_or_default(),
84        timeout,
85        storage_dir,
86        max_running,
87    ) {
88        Ok(task_id) => Response::success(
89            request_id,
90            json!({
91                "task_id": task_id,
92                "status": BgTaskStatus::Running,
93            }),
94        ),
95        Err(message) if message.contains("limit exceeded") => {
96            Response::error(request_id, "background_task_limit_exceeded", message)
97        }
98        Err(message) => Response::error(request_id, "execution_failed", message),
99    }
100}
101
102pub fn storage_dir(configured: Option<&std::path::Path>) -> PathBuf {
103    if let Some(dir) = configured {
104        return dir.to_path_buf();
105    }
106    if let Some(dir) = std::env::var_os("AFT_CACHE_DIR") {
107        return PathBuf::from(dir).join("aft");
108    }
109    // Fallback to the user's home directory. On Unix this is `$HOME`; on
110    // Windows `HOME` is typically unset, so fall back to `USERPROFILE`
111    // (which is always set in interactive sessions and in the env that
112    // OpenCode/Pi pass through to plugin processes). If both are missing
113    // (rare — embedded contexts, broken shells), fall back to a temp
114    // directory rather than `"."` — a relative path makes bg-bash wrapper
115    // commands like `move /Y .\.cache\aft\... ...` fail with "system
116    // cannot find the path specified" once the working directory shifts.
117    let home = std::env::var_os("HOME")
118        .or_else(|| std::env::var_os("USERPROFILE"))
119        .map(PathBuf::from)
120        .unwrap_or_else(std::env::temp_dir);
121    home.join(".cache").join("aft")
122}