use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use crate::runtime::AgentEvent;
use crate::session::{ago_words, now_ms, validate_id};
pub const DIR: &str = "tasks";
pub const BG: &str = "/bg";
pub const TASKS: &str = "/tasks";
const PROMPT_CHARS: usize = 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
Starting,
Running,
Done,
Failed,
Stopped,
Waiting,
Died,
}
impl State {
pub fn word(self) -> &'static str {
match self {
State::Starting => "starting",
State::Running => "running",
State::Done => "done",
State::Failed => "failed",
State::Stopped => "stopped",
State::Waiting => "waiting",
State::Died => "died",
}
}
pub fn alive_only(self) -> bool {
matches!(self, State::Starting | State::Running)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Task {
pub session: String,
pub pid: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pid_since: Option<u64>,
pub started_ms: u64,
pub updated_ms: u64,
pub prompt: String,
pub state: State,
pub last: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub detail: String,
}
impl Task {
pub fn spawned(session: &str, pid: u32, prompt: &str) -> Task {
let now = now_ms();
Task {
session: session.to_string(),
pid,
pid_since: pid_since(pid),
started_ms: now,
updated_ms: now,
prompt: clip_words(prompt, PROMPT_CHARS),
state: State::Starting,
last: "starting".to_string(),
detail: String::new(),
}
}
pub fn begun(session: &str, prompt: &str) -> Task {
let mut task = Task::spawned(session, std::process::id(), prompt);
task.state = State::Running;
task.last = "thinking".to_string();
task
}
pub fn state_now(&self) -> State {
if self.state.alive_only() && !pid_live(self.pid, self.pid_since) {
return State::Died;
}
self.state
}
pub fn headline(&self) -> String {
format!(
"{} · {}",
self.state_now().word(),
ago_words(self.updated_ms)
)
}
pub fn settled(&self) -> bool {
!self.state_now().alive_only()
}
pub fn died(&self) -> bool {
self.state_now() == State::Died
}
}
fn clip_words(text: &str, max: usize) -> String {
let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.chars().count() <= max {
return flat;
}
let mut out: String = flat.chars().take(max).collect();
if let Some(at) = out.rfind(' ') {
out.truncate(at);
}
out.push('…');
out
}
#[cfg(target_os = "linux")]
fn proc_stat(pid: u32) -> Option<(char, u64)> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let mut fields = stat.rsplit_once(')')?.1.split_whitespace();
let state = fields.next()?.chars().next()?;
let since = fields.nth(18)?.parse().ok()?;
Some((state, since))
}
#[cfg(target_os = "linux")]
fn pid_since(pid: u32) -> Option<u64> {
proc_stat(pid).map(|(_, since)| since)
}
#[cfg(not(target_os = "linux"))]
fn pid_since(_pid: u32) -> Option<u64> {
None
}
#[cfg(target_os = "linux")]
fn uncollected(pid: u32) -> bool {
matches!(proc_stat(pid), Some(('Z', _)))
}
#[cfg(not(target_os = "linux"))]
fn uncollected(_pid: u32) -> bool {
false
}
#[cfg(unix)]
fn pid_live(pid: u32, since: Option<u64>) -> bool {
if pid == 0 {
return false;
}
if unsafe { libc::kill(pid as libc::pid_t, 0) } != 0 {
let err = std::io::Error::last_os_error().raw_os_error();
if err != Some(libc::EPERM) {
return false;
}
}
if uncollected(pid) {
return false;
}
match (since, pid_since(pid)) {
(Some(wanted), Some(found)) => wanted == found,
_ => true,
}
}
#[cfg(not(unix))]
fn pid_live(pid: u32, _since: Option<u64>) -> bool {
pid != 0
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Registry {
dir: PathBuf,
}
impl Registry {
pub fn new(state_dir: impl AsRef<Path>) -> Registry {
Registry {
dir: state_dir.as_ref().join(DIR),
}
}
pub fn none() -> Registry {
Registry {
dir: PathBuf::new(),
}
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn path(&self, id: &str) -> PathBuf {
self.dir.join(format!("{id}.json"))
}
pub fn log_path(&self, id: &str) -> PathBuf {
self.dir.join(format!("{id}.log"))
}
pub fn is_empty(&self) -> bool {
self.list().is_empty()
}
pub fn write(&self, task: &Task) -> std::io::Result<()> {
validate_id(&task.session).map_err(|e| std::io::Error::other(e.to_string()))?;
std::fs::create_dir_all(&self.dir)?;
let path = self.path(&task.session);
let tmp = self.dir.join(format!(".{}.json.tmp", task.session));
let body = serde_json::to_string_pretty(task).map_err(std::io::Error::other)?;
std::fs::write(&tmp, body + "\n")?;
std::fs::rename(&tmp, &path)
}
pub fn load(&self, id: &str) -> Option<Task> {
validate_id(id).ok()?;
let text = std::fs::read_to_string(self.path(id)).ok()?;
serde_json::from_str(&text).ok()
}
pub fn list(&self) -> Vec<Task> {
let Ok(entries) = std::fs::read_dir(&self.dir) else {
return Vec::new();
};
let mut tasks: Vec<Task> = entries
.flatten()
.filter(|e| {
e.path()
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.ends_with(".json") && !n.starts_with('.'))
})
.filter_map(|e| std::fs::read_to_string(e.path()).ok())
.filter_map(|text| serde_json::from_str::<Task>(&text).ok())
.collect();
tasks.sort_by(|a, b| {
b.updated_ms
.cmp(&a.updated_ms)
.then_with(|| a.session.cmp(&b.session))
});
tasks
}
pub fn touch(&self, id: &str, last: &str) -> std::io::Result<()> {
let Some(mut task) = self.load(id) else {
return Ok(());
};
if task.state != State::Running || task.last == last {
return Ok(());
}
task.last = last.to_string();
task.updated_ms = now_ms();
self.write(&task)
}
pub fn finish(&self, id: &str, state: State, detail: &str) -> std::io::Result<()> {
let Some(mut task) = self.load(id) else {
return Ok(());
};
task.state = state;
task.detail = detail.to_string();
if !detail.is_empty() {
task.last = detail.to_string();
}
task.updated_ms = now_ms();
self.write(&task)
}
pub fn report(&self) -> String {
let tasks = self.list();
if tasks.is_empty() {
return "no background tasks — `/bg <prompt>` starts one".to_string();
}
let id_width = tasks
.iter()
.map(|t| t.session.len())
.max()
.unwrap_or(0)
.max("id".len());
let state_width = tasks
.iter()
.map(|t| t.state_now().word().len())
.max()
.unwrap_or(0)
.max("state".len());
let mut lines = vec![format!(
"{:<id_width$} {:<state_width$} {:<7} {}",
"id", "state", "age", "last"
)];
for t in &tasks {
let state = t.state_now();
let age = ago_words(t.updated_ms);
let age = age.strip_suffix(" ago").map(str::to_string).unwrap_or(age);
let last = if t.detail.is_empty() {
t.last.clone()
} else {
format!("{} ({})", t.last, t.detail)
};
lines.push(format!(
"{:<id_width$} {:<state_width$} {:<7} {}",
t.session,
state.word(),
age,
clip_words(&last, 70)
));
let under = if t.settled() {
t.prompt.clone()
} else {
format!("pid {} · {}", t.pid, t.prompt)
};
lines.push(format!(
"{:<id_width$} {:<state_width$} {:<7} {}",
"",
"",
"",
clip_words(&under, 70)
));
}
lines.join("\n")
}
}
pub fn bg_prompt(line: &str) -> Option<&str> {
let rest = line.trim_start().strip_prefix(BG)?;
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return None;
}
Some(rest.trim())
}
pub fn bg_refusal(surface: &str) -> String {
format!(
"`{BG}` starts a task that outlives the prompt, and {surface} has no prompt to return to — \
the line was not run. Run it from `eclipse`, or send the question as a prompt."
)
}
pub fn describe_event(event: &AgentEvent) -> Option<String> {
match event {
AgentEvent::ToolCall { name, .. } => Some(format!("tool {name}")),
AgentEvent::ToolResult { name, is_error, .. } => Some(if *is_error {
format!("tool {name} failed")
} else {
format!("tool {name} ok")
}),
AgentEvent::Message(_) => Some("replied".to_string()),
_ => None,
}
}
#[derive(Debug, Clone)]
pub struct Tracker {
registry: Registry,
id: String,
wrote: std::sync::Arc<Mutex<String>>,
}
impl Tracker {
pub fn new(registry: Registry, id: impl Into<String>) -> Tracker {
Tracker {
registry,
id: id.into(),
wrote: std::sync::Arc::new(Mutex::new(String::new())),
}
}
pub fn id(&self) -> &str {
&self.id
}
pub fn event(&self, event: &AgentEvent) {
if let Some(line) = describe_event(event) {
self.say(&line);
}
}
pub fn say(&self, line: &str) {
let mut wrote = match self.wrote.lock() {
Ok(w) => w,
Err(e) => e.into_inner(),
};
if *wrote == line {
return;
}
if self.registry.touch(&self.id, line).is_ok() {
*wrote = line.to_string();
}
}
pub fn finish(&self, state: State, detail: &str) {
let _ = self.registry.finish(&self.id, state, detail);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::message::Message;
fn scratch() -> (tempfile::TempDir, Registry) {
let dir = tempfile::tempdir().expect("a scratch directory");
let registry = Registry::new(dir.path());
(dir, registry)
}
fn task(id: &str, state: State) -> Task {
let mut t = Task::spawned(id, std::process::id(), "count the files");
t.state = state;
t
}
#[test]
fn an_entry_is_written_read_and_listed_newest_first() {
let (_dir, registry) = scratch();
assert!(registry.list().is_empty());
assert!(registry.is_empty());
let mut older = task("100-1-0", State::Done);
older.updated_ms = 1_000;
older.last = "replied".into();
let mut newer = task("200-2-0", State::Running);
newer.updated_ms = 2_000;
newer.last = "tool shell".into();
registry.write(&older).unwrap();
registry.write(&newer).unwrap();
let listed = registry.list();
assert_eq!(
listed
.iter()
.map(|t| t.session.as_str())
.collect::<Vec<_>>(),
["200-2-0", "100-1-0"],
"newest activity first"
);
assert_eq!(registry.load("100-1-0"), Some(older));
assert_eq!(registry.load("nope"), None);
assert!(!registry.is_empty());
}
#[test]
fn a_running_entry_whose_process_is_gone_is_died_not_running() {
let (_dir, registry) = scratch();
let mut child = std::process::Command::new("true").spawn().expect("spawn");
let pid = child.id();
child.wait().expect("reap");
assert!(
pid_since(pid).is_none(),
"the process is gone: nothing to read"
);
let mut entry = Task::spawned("300-3-0", pid, "a question");
entry.state = State::Running;
registry.write(&entry).unwrap();
assert_eq!(
registry.load("300-3-0").unwrap().state_now(),
State::Died,
"a pid that is gone cannot be running"
);
assert!(registry.list()[0].died());
assert!(registry.list()[0].settled());
let done = task("400-4-0", State::Done);
registry.write(&done).unwrap();
assert_eq!(registry.load("400-4-0").unwrap().state_now(), State::Done);
}
#[test]
fn a_recycled_pid_with_a_different_start_time_is_not_the_same_task() {
let (_dir, registry) = scratch();
let mut entry = task("500-5-0", State::Running);
entry.pid = std::process::id();
entry.pid_since = pid_since(std::process::id()).map(|ticks| ticks.wrapping_add(1));
registry.write(&entry).unwrap();
assert_eq!(
registry.load("500-5-0").unwrap().state_now(),
State::Died,
"same number, different process"
);
let mut ours = task("600-6-0", State::Running);
ours.pid = std::process::id();
ours.pid_since = pid_since(std::process::id());
registry.write(&ours).unwrap();
assert_eq!(
registry.load("600-6-0").unwrap().state_now(),
State::Running,
"the live process is the one this entry names"
);
}
#[test]
fn a_tracker_writes_each_distinct_line_once_and_finishes_with_a_reason() {
let (_dir, registry) = scratch();
let entry = Task::begun("700-7-0", "do the thing");
registry.write(&entry).unwrap();
let tracker = Tracker::new(registry.clone(), "700-7-0");
tracker.event(&AgentEvent::ToolCall {
call_id: "c1".into(),
name: "shell".into(),
arguments: "{}".into(),
});
assert_eq!(registry.load("700-7-0").unwrap().last, "tool shell");
tracker.event(&AgentEvent::ToolResult {
call_id: "c1".into(),
name: "shell".into(),
output: "ok".into(),
is_error: true,
});
assert_eq!(
registry.load("700-7-0").unwrap().last,
"tool shell failed",
"a failed tool says so"
);
tracker.event(&AgentEvent::Message("the answer".into()));
assert_eq!(registry.load("700-7-0").unwrap().last, "replied");
tracker.event(&AgentEvent::Delta("half".into()));
assert_eq!(registry.load("700-7-0").unwrap().last, "replied");
tracker.finish(State::Failed, "the model refused the shape");
let ended = registry.load("700-7-0").unwrap();
assert_eq!(ended.state, State::Failed);
assert_eq!(ended.detail, "the model refused the shape");
assert_eq!(ended.last, "the model refused the shape");
let clean = Task::begun("701-7-1", "do the thing");
registry.write(&clean).unwrap();
Tracker::new(registry.clone(), "701-7-1").finish(State::Done, "");
let finished = registry.load("701-7-1").unwrap();
assert_eq!(finished.state, State::Done);
assert_eq!(finished.last, "thinking", "what it was doing when it ended");
assert!(finished.detail.is_empty());
}
#[test]
fn the_report_names_the_state_the_age_and_what_it_last_did() {
let (_dir, registry) = scratch();
assert_eq!(
registry.report(),
"no background tasks — `/bg <prompt>` starts one"
);
let mut running = Task::begun("800-8-0", "summarise every issue");
running.last = "tool search_files".into();
registry.write(&running).unwrap();
let report = registry.report();
assert!(report.starts_with("id"), "{report}");
assert!(report.contains("800-8-0"), "{report}");
assert!(report.contains("running"), "{report}");
assert!(report.contains("tool search_files"), "{report}");
assert!(report.contains("summarise every issue"), "{report}");
assert!(
report.contains(&format!("pid {}", std::process::id())),
"a live task prints the pid that stops it: {report}"
);
assert!(
report.contains("just now") || report.contains("now"),
"{report}"
);
}
#[test]
fn a_bg_line_is_the_word_and_the_question_behind_it() {
assert_eq!(bg_prompt("/bg count the files"), Some("count the files"));
assert_eq!(bg_prompt(" /bg two spaces "), Some("two spaces"));
assert_eq!(bg_prompt("/bg"), Some(""));
assert_eq!(bg_prompt("/bgfoo"), None, "a prefix is not the word");
assert_eq!(bg_prompt("what does /bg do?"), None, "not at the start");
assert_eq!(bg_prompt("hello"), None);
}
#[test]
fn the_refusal_says_where_it_does_work() {
let said = bg_refusal("`eclipse run`");
assert!(said.contains("/bg"), "{said}");
assert!(said.contains("eclipse run"), "{said}");
assert!(said.contains("from `eclipse`"), "{said}");
}
#[test]
fn a_long_prompt_is_cut_on_a_word_boundary() {
let long = "one two three four five six seven eight nine ten";
let cut = clip_words(long, 20);
assert!(cut.chars().count() <= 21, "{cut}");
assert!(cut.ends_with('…'), "{cut}");
assert!(!cut.contains(" "), "{cut}");
assert_eq!(clip_words("short", 20), "short");
assert_eq!(clip_words("a\n b", 20), "a b");
}
#[test]
fn the_two_live_states_are_the_only_ones_that_need_a_pid() {
let live: Vec<State> = [State::Starting, State::Running]
.into_iter()
.filter(|s| s.alive_only())
.collect();
assert_eq!(live.len(), 2);
for state in [
State::Done,
State::Failed,
State::Stopped,
State::Waiting,
State::Died,
] {
assert!(!state.alive_only(), "{state:?}");
}
}
#[test]
fn an_id_with_a_slash_in_it_is_refused() {
let (_dir, registry) = scratch();
let mut bad = task("../escape", State::Running);
bad.session = "../escape".into();
assert!(registry.write(&bad).is_err());
assert!(registry.load("../escape").is_none());
}
#[test]
fn a_file_that_does_not_parse_is_skipped_rather_than_reported() {
let (dir, registry) = scratch();
std::fs::create_dir_all(registry.dir()).unwrap();
std::fs::write(registry.dir().join("broken.json"), "{ not json").unwrap();
std::fs::write(registry.dir().join(".900.json.tmp"), "{}").unwrap();
registry.write(&task("901-9-0", State::Done)).unwrap();
let listed = registry.list();
assert_eq!(listed.len(), 1, "only the real entry: {listed:?}");
assert_eq!(listed[0].session, "901-9-0");
assert!(dir.path().exists());
}
#[test]
fn touching_an_entry_that_is_already_finished_changes_nothing() {
let (_dir, registry) = scratch();
let mut finished = task("902-9-0", State::Done);
finished.last = "replied".into();
finished.updated_ms = 5_000;
registry.write(&finished).unwrap();
registry.touch("902-9-0", "tool shell").unwrap();
let after = registry.load("902-9-0").unwrap();
assert_eq!(
after.last, "replied",
"a finished task does not start again"
);
assert_eq!(after.updated_ms, 5_000);
}
#[test]
fn a_message_event_carries_no_prompt_text_into_the_registry() {
let line = describe_event(&AgentEvent::Message("the secret is hunter2".into()));
assert_eq!(line.as_deref(), Some("replied"));
let _ = Message::user("x");
}
}