Skip to main content

eclipse_core/
tasks.rs

1//! Background tasks: a run that outlives the prompt (#225).
2//!
3//! `/bg <prompt>` starts the same run `eclipse run` would — same workspace, same config, same
4//! profile, same tool policy — in a detached process with its own session id, and returns to the
5//! composer at once. Two verbs read one registry: `/tasks` lists it, and `eclipse doctor` looks at
6//! it for entries whose process is gone.
7//!
8//! **The registry is one directory**: `<state>/tasks/`, one `<session>.json` per task, written by
9//! the parent when it spawns (state `starting`, with the child's pid) and by the child at start and
10//! after each turn. Beside it sits `<session>.log` — the child's own stdout and stderr, which is
11//! where a failure explains itself without the registry having to guess.
12//!
13//! **The state is read through the pid, not trusted from the file.** A process that was killed
14//! writes no final line, so a file that says `running` beside a pid that is gone is `died`: the
15//! honest answer, and the one that stops a stale entry from claiming to be alive all day. The pid
16//! is paired with the kernel's start time for that process so a recycled pid cannot make an old
17//! entry look alive again.
18
19use std::path::{Path, PathBuf};
20use std::sync::Mutex;
21
22use serde::{Deserialize, Serialize};
23
24use crate::runtime::AgentEvent;
25use crate::session::{ago_words, now_ms, validate_id};
26
27/// The directory, under the state directory, that holds the registry.
28pub const DIR: &str = "tasks";
29
30/// The word that starts a background run.
31pub const BG: &str = "/bg";
32
33/// The word that lists them.
34pub const TASKS: &str = "/tasks";
35
36/// How much of a prompt a row carries. The whole prompt is in the file and in the session; a list
37/// is for telling two rows apart, not for reading a paragraph.
38const PROMPT_CHARS: usize = 60;
39
40/// Where a task is.
41///
42/// `Starting` and `Running` are the two that are only true while a process is alive; everything
43/// else is what the child wrote on its way out, and stays.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum State {
47    /// Spawned, and the child has not written its first line yet.
48    Starting,
49    /// The child is working.
50    Running,
51    /// The turn finished.
52    Done,
53    /// The run stopped with an error, or its process ended without saying why.
54    Failed,
55    /// Stopped on purpose — a signal, or a `Ctrl-C` in a terminal the person still had.
56    Stopped,
57    /// The run parked on an approval nobody was there to answer.
58    Waiting,
59    /// The file says it is running and the process is gone. Never written: always derived.
60    Died,
61}
62
63impl State {
64    /// The word the list and `/tasks` print.
65    pub fn word(self) -> &'static str {
66        match self {
67            State::Starting => "starting",
68            State::Running => "running",
69            State::Done => "done",
70            State::Failed => "failed",
71            State::Stopped => "stopped",
72            State::Waiting => "waiting",
73            State::Died => "died",
74        }
75    }
76
77    /// Whether the state is true only while a process is alive.
78    ///
79    /// This is the whole of the pid rule: a task in one of these two states has to have a live
80    /// process behind it, and one that does not is [`State::Died`].
81    pub fn alive_only(self) -> bool {
82        matches!(self, State::Starting | State::Running)
83    }
84}
85
86/// One background run.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct Task {
89    /// The task is identified by the session it runs in: one run, one transcript, and
90    /// `eclipse --plain -s <id>` opens it without a second id to remember.
91    pub session: String,
92    /// The process doing the work. Read through, never trusted: see [`Task::state_now`].
93    pub pid: u32,
94    /// The kernel's start time for that pid, in clock ticks since boot. With the pid this is
95    /// what makes "the same process" a question with an answer.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub pid_since: Option<u64>,
98    /// When the task was spawned.
99    pub started_ms: u64,
100    /// The last write: when it started, what it last did, or how it ended.
101    pub updated_ms: u64,
102    /// The question it was given, cut to something a row can hold.
103    pub prompt: String,
104    pub state: State,
105    /// The last thing it did, in one line: `tool shell`, `replied`, `turn 3 · 4.1K tok`.
106    pub last: String,
107    /// Why it ended, when ending needs a reason.
108    #[serde(default, skip_serializing_if = "String::is_empty")]
109    pub detail: String,
110}
111
112impl Task {
113    /// The entry the parent writes the moment the child is spawned.
114    ///
115    /// Written by the parent, not the child, so `/tasks` straight after `/bg` already has a row:
116    /// a run that is invisible for its first hundred milliseconds is a run someone will ask
117    /// twice about.
118    pub fn spawned(session: &str, pid: u32, prompt: &str) -> Task {
119        let now = now_ms();
120        Task {
121            session: session.to_string(),
122            pid,
123            pid_since: pid_since(pid),
124            started_ms: now,
125            updated_ms: now,
126            prompt: clip_words(prompt, PROMPT_CHARS),
127            state: State::Starting,
128            last: "starting".to_string(),
129            detail: String::new(),
130        }
131    }
132
133    /// The entry the child writes for itself once it is running.
134    pub fn begun(session: &str, prompt: &str) -> Task {
135        let mut task = Task::spawned(session, std::process::id(), prompt);
136        task.state = State::Running;
137        task.last = "thinking".to_string();
138        task
139    }
140
141    /// The state this entry is honestly in *now*.
142    ///
143    /// A stored `running` whose process is gone is [`State::Died`]. Everything else is what the
144    /// child wrote, because a finished task has no process left to ask.
145    pub fn state_now(&self) -> State {
146        if self.state.alive_only() && !pid_live(self.pid, self.pid_since) {
147            return State::Died;
148        }
149        self.state
150    }
151
152    /// `running · 2m ago`, or `died · 6h ago` — the two words a row is read for.
153    pub fn headline(&self) -> String {
154        format!(
155            "{} · {}",
156            self.state_now().word(),
157            ago_words(self.updated_ms)
158        )
159    }
160
161    /// Whether this entry is finished in any sense, including died.
162    pub fn settled(&self) -> bool {
163        !self.state_now().alive_only()
164    }
165
166    /// A died entry: its process is gone and no final line was written.
167    pub fn died(&self) -> bool {
168        self.state_now() == State::Died
169    }
170}
171
172/// Cut `text` to `max` characters on a word boundary, with an ellipsis: a row, not a paragraph.
173fn clip_words(text: &str, max: usize) -> String {
174    let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
175    if flat.chars().count() <= max {
176        return flat;
177    }
178    let mut out: String = flat.chars().take(max).collect();
179    if let Some(at) = out.rfind(' ') {
180        out.truncate(at);
181    }
182    out.push('…');
183    out
184}
185
186/// `/proc/<pid>/stat`, as (the process state, the kernel's start time in clock ticks since boot).
187///
188/// The comm field can hold spaces and parentheses, so the split starts after the *last* `)`.
189/// Field 3 is the state and field 22 is the start time, which is index 0 and 19 after that split.
190#[cfg(target_os = "linux")]
191fn proc_stat(pid: u32) -> Option<(char, u64)> {
192    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
193    let mut fields = stat.rsplit_once(')')?.1.split_whitespace();
194    let state = fields.next()?.chars().next()?;
195    let since = fields.nth(18)?.parse().ok()?;
196    Some((state, since))
197}
198
199/// The kernel's start time for `pid`. `None` when there is no `/proc` to read, or the process is
200/// already gone.
201#[cfg(target_os = "linux")]
202fn pid_since(pid: u32) -> Option<u64> {
203    proc_stat(pid).map(|(_, since)| since)
204}
205
206#[cfg(not(target_os = "linux"))]
207fn pid_since(_pid: u32) -> Option<u64> {
208    None
209}
210
211/// Whether the process has exited but not been reaped yet. A zombie still answers `kill(pid, 0)`
212/// and is not running, so a task whose process is a zombie is `died`, not `running`.
213#[cfg(target_os = "linux")]
214fn uncollected(pid: u32) -> bool {
215    matches!(proc_stat(pid), Some(('Z', _)))
216}
217
218#[cfg(not(target_os = "linux"))]
219fn uncollected(_pid: u32) -> bool {
220    false
221}
222
223/// Whether `pid` is that same process, still running.
224///
225/// A signal of 0 sends nothing and only tests for the process. `EPERM` means it exists and belongs
226/// to somebody else, which is still alive. When both start times are known they have to agree: a
227/// recycled pid with a different start time is a different process, and an entry that says
228/// `running` about it would be the stale claim this whole module is written to avoid.
229#[cfg(unix)]
230fn pid_live(pid: u32, since: Option<u64>) -> bool {
231    if pid == 0 {
232        return false;
233    }
234    // SAFETY: signal 0 is a permission and existence probe; it delivers nothing.
235    if unsafe { libc::kill(pid as libc::pid_t, 0) } != 0 {
236        let err = std::io::Error::last_os_error().raw_os_error();
237        if err != Some(libc::EPERM) {
238            return false;
239        }
240    }
241    if uncollected(pid) {
242        return false;
243    }
244    match (since, pid_since(pid)) {
245        (Some(wanted), Some(found)) => wanted == found,
246        _ => true,
247    }
248}
249
250#[cfg(not(unix))]
251fn pid_live(pid: u32, _since: Option<u64>) -> bool {
252    // There is no portable probe here, and pretending a process is gone is worse than a row that
253    // waits for `/tasks` to say `died`: the file the child writes on the way out is the fallback.
254    pid != 0
255}
256
257/// The registry: one directory, one file per task.
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct Registry {
260    dir: PathBuf,
261}
262
263impl Registry {
264    /// `state_dir` is the state directory itself (`~/.eclipse/state`), not the `tasks/` inside it:
265    /// the caller already knows where its state lives, and this module owns the subdirectory name.
266    pub fn new(state_dir: impl AsRef<Path>) -> Registry {
267        Registry {
268            dir: state_dir.as_ref().join(DIR),
269        }
270    }
271
272    /// A registry that has never written anything, for a surface that must not care where the
273    /// state directory is (`/tasks` before the first `/bg`).
274    pub fn none() -> Registry {
275        Registry {
276            dir: PathBuf::new(),
277        }
278    }
279
280    pub fn dir(&self) -> &Path {
281        &self.dir
282    }
283
284    /// `<id>.json`.
285    pub fn path(&self, id: &str) -> PathBuf {
286        self.dir.join(format!("{id}.json"))
287    }
288
289    /// `<id>.log`: what the child printed. Kept beside the entry because a failure that only ever
290    /// existed on a terminal that is gone is a failure nobody can read.
291    pub fn log_path(&self, id: &str) -> PathBuf {
292        self.dir.join(format!("{id}.log"))
293    }
294
295    /// Whether anything has ever been registered. `/tasks` says one line and stops when not.
296    pub fn is_empty(&self) -> bool {
297        self.list().is_empty()
298    }
299
300    /// Write an entry. Atomic (a sibling `.tmp` then a rename), because `/tasks` may be reading
301    /// while a child is writing and half a JSON document is not a state.
302    pub fn write(&self, task: &Task) -> std::io::Result<()> {
303        validate_id(&task.session).map_err(|e| std::io::Error::other(e.to_string()))?;
304        std::fs::create_dir_all(&self.dir)?;
305        let path = self.path(&task.session);
306        let tmp = self.dir.join(format!(".{}.json.tmp", task.session));
307        let body = serde_json::to_string_pretty(task).map_err(std::io::Error::other)?;
308        std::fs::write(&tmp, body + "\n")?;
309        std::fs::rename(&tmp, &path)
310    }
311
312    /// Register a task the child has not announced yet, and only then. The child writes `running`
313    /// the moment it starts, which can be before this process gets its entry on disk; a plain
314    /// `write` would put `starting` back over a live task (`#585`).
315    pub fn write_new(&self, task: &Task) -> std::io::Result<()> {
316        if self.load(&task.session).is_some() {
317            return Ok(());
318        }
319        self.write(task)
320    }
321
322    /// One entry, as stored.
323    pub fn load(&self, id: &str) -> Option<Task> {
324        validate_id(id).ok()?;
325        let text = std::fs::read_to_string(self.path(id)).ok()?;
326        serde_json::from_str(&text).ok()
327    }
328
329    /// Every entry, newest activity first. A file that does not parse is skipped rather than
330    /// reported: it is a half-written temp file at worst, and `/tasks` is not a JSON validator.
331    pub fn list(&self) -> Vec<Task> {
332        let Ok(entries) = std::fs::read_dir(&self.dir) else {
333            return Vec::new();
334        };
335        let mut tasks: Vec<Task> = entries
336            .flatten()
337            .filter(|e| {
338                e.path()
339                    .file_name()
340                    .and_then(|n| n.to_str())
341                    .is_some_and(|n| n.ends_with(".json") && !n.starts_with('.'))
342            })
343            .filter_map(|e| std::fs::read_to_string(e.path()).ok())
344            .filter_map(|text| serde_json::from_str::<Task>(&text).ok())
345            .collect();
346        tasks.sort_by(|a, b| {
347            b.updated_ms
348                .cmp(&a.updated_ms)
349                .then_with(|| a.session.cmp(&b.session))
350        });
351        tasks
352    }
353
354    /// What the last turn did, for the row. A no-op when nothing changed, so a long run does not
355    /// rewrite the same line for every event it emits.
356    pub fn touch(&self, id: &str, last: &str) -> std::io::Result<()> {
357        let Some(mut task) = self.load(id) else {
358            return Ok(());
359        };
360        if task.state != State::Running || task.last == last {
361            return Ok(());
362        }
363        task.last = last.to_string();
364        task.updated_ms = now_ms();
365        self.write(&task)
366    }
367
368    /// How it ended. The one line a killed task never gets to write, which is why the pid is
369    /// read instead of believed.
370    pub fn finish(&self, id: &str, state: State, detail: &str) -> std::io::Result<()> {
371        let Some(mut task) = self.load(id) else {
372            return Ok(());
373        };
374        task.state = state;
375        task.detail = detail.to_string();
376        // An empty detail means the run simply ended: `last` keeps what it actually did
377        // (`replied`), because a row that says `done` beside `done` says it twice.
378        if !detail.is_empty() {
379            task.last = detail.to_string();
380        }
381        task.updated_ms = now_ms();
382        self.write(&task)
383    }
384
385    /// The rows `/tasks` prints: a header, then one line per task, or one line saying there are
386    /// none. Shared by both front ends so the REPL and the interface cannot disagree about what a
387    /// task is called.
388    pub fn report(&self) -> String {
389        let tasks = self.list();
390        if tasks.is_empty() {
391            return "no background tasks — `/bg <prompt>` starts one".to_string();
392        }
393        let id_width = tasks
394            .iter()
395            .map(|t| t.session.len())
396            .max()
397            .unwrap_or(0)
398            .max("id".len());
399        let state_width = tasks
400            .iter()
401            .map(|t| t.state_now().word().len())
402            .max()
403            .unwrap_or(0)
404            .max("state".len());
405        let mut lines = vec![format!(
406            "{:<id_width$}  {:<state_width$}  {:<7}  {}",
407            "id", "state", "age", "last"
408        )];
409        for t in &tasks {
410            let state = t.state_now();
411            let age = ago_words(t.updated_ms);
412            let age = age.strip_suffix(" ago").map(str::to_string).unwrap_or(age);
413            let last = if t.detail.is_empty() {
414                t.last.clone()
415            } else {
416                format!("{} ({})", t.last, t.detail)
417            };
418            lines.push(format!(
419                "{:<id_width$}  {:<state_width$}  {:<7}  {}",
420                t.session,
421                state.word(),
422                age,
423                clip_words(&last, 70)
424            ));
425            // The pid is printed while it means something: it is the handle for stopping a run
426            // (`kill <pid>`), and once the task is finished the number may belong to anything.
427            let under = if t.settled() {
428                t.prompt.clone()
429            } else {
430                format!("pid {} · {}", t.pid, t.prompt)
431            };
432            lines.push(format!(
433                "{:<id_width$}  {:<state_width$}  {:<7}  {}",
434                "",
435                "",
436                "",
437                clip_words(&under, 70)
438            ));
439        }
440        lines.join("\n")
441    }
442}
443
444/// The prompt behind a `/bg` line, or `None` when the line is not one.
445///
446/// `/bg` is a word, not a prefix: `/bgfoo` is a prompt for the model, the same way `fix!` is.
447/// An empty answer is still `Some("")` — "you typed the word and nothing else" is a usage error
448/// the caller can say out loud, not a question to send.
449pub fn bg_prompt(line: &str) -> Option<&str> {
450    let rest = line.trim_start().strip_prefix(BG)?;
451    if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
452        return None;
453    }
454    Some(rest.trim())
455}
456
457/// Why `/bg` is not a thing on `surface`.
458///
459/// The registry is a directory and the return-to-the-composer is a keyboard; a headless caller has
460/// neither, and a scheduled job that spawns background jobs is a fork bomb with a schedule.
461pub fn bg_refusal(surface: &str) -> String {
462    format!(
463        "`{BG}` starts a task that outlives the prompt, and {surface} has no prompt to return to — \
464         the line was not run. Run it from `eclipse`, or send the question as a prompt."
465    )
466}
467
468/// The one place a child turns an [`AgentEvent`] into the row's `last` line.
469///
470/// It lives here rather than in the loop because two things need the same words: the child writing
471/// its own registry entry, and nothing else — but a second copy of this mapping would drift from
472/// the states the list shows.
473pub fn describe_event(event: &AgentEvent) -> Option<String> {
474    match event {
475        AgentEvent::ToolCall { name, .. } => Some(format!("tool {name}")),
476        AgentEvent::ToolResult { name, is_error, .. } => Some(if *is_error {
477            format!("tool {name} failed")
478        } else {
479            format!("tool {name} ok")
480        }),
481        AgentEvent::Message(_) => Some("replied".to_string()),
482        _ => None,
483    }
484}
485
486/// A task's entry, kept up to date by the process doing the work.
487///
488/// Cheap to clone (a path and an id) and safe to share: the last written line is compared under a
489/// lock so a turn that emits twenty events writes the file once.
490#[derive(Debug, Clone)]
491pub struct Tracker {
492    registry: Registry,
493    id: String,
494    wrote: std::sync::Arc<Mutex<String>>,
495}
496
497impl Tracker {
498    pub fn new(registry: Registry, id: impl Into<String>) -> Tracker {
499        Tracker {
500            registry,
501            id: id.into(),
502            wrote: std::sync::Arc::new(Mutex::new(String::new())),
503        }
504    }
505
506    pub fn id(&self) -> &str {
507        &self.id
508    }
509
510    /// Follow one event, if it says something a row can carry. Errors are nobody's business here:
511    /// a registry that cannot be written must not stop the run it is describing.
512    pub fn event(&self, event: &AgentEvent) {
513        if let Some(line) = describe_event(event) {
514            self.say(&line);
515        }
516    }
517
518    /// Write `last`, once per distinct line.
519    pub fn say(&self, line: &str) {
520        let mut wrote = match self.wrote.lock() {
521            Ok(w) => w,
522            Err(e) => e.into_inner(),
523        };
524        if *wrote == line {
525            return;
526        }
527        if self.registry.touch(&self.id, line).is_ok() {
528            *wrote = line.to_string();
529        }
530    }
531
532    /// How it ended. Always written when the process got this far.
533    pub fn finish(&self, state: State, detail: &str) {
534        let _ = self.registry.finish(&self.id, state, detail);
535    }
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541    use crate::message::Message;
542
543    fn scratch() -> (tempfile::TempDir, Registry) {
544        let dir = tempfile::tempdir().expect("a scratch directory");
545        let registry = Registry::new(dir.path());
546        (dir, registry)
547    }
548
549    fn task(id: &str, state: State) -> Task {
550        let mut t = Task::spawned(id, std::process::id(), "count the files");
551        t.state = state;
552        t
553    }
554
555    #[test]
556    fn an_entry_is_written_read_and_listed_newest_first() {
557        let (_dir, registry) = scratch();
558        assert!(registry.list().is_empty());
559        assert!(registry.is_empty());
560
561        let mut older = task("100-1-0", State::Done);
562        older.updated_ms = 1_000;
563        older.last = "replied".into();
564        let mut newer = task("200-2-0", State::Running);
565        newer.updated_ms = 2_000;
566        newer.last = "tool shell".into();
567        registry.write(&older).unwrap();
568        registry.write(&newer).unwrap();
569
570        let listed = registry.list();
571        assert_eq!(
572            listed
573                .iter()
574                .map(|t| t.session.as_str())
575                .collect::<Vec<_>>(),
576            ["200-2-0", "100-1-0"],
577            "newest activity first"
578        );
579        assert_eq!(registry.load("100-1-0"), Some(older));
580        assert_eq!(registry.load("nope"), None);
581        assert!(!registry.is_empty());
582    }
583
584    #[test]
585    fn a_running_entry_whose_process_is_gone_is_died_not_running() {
586        let (_dir, registry) = scratch();
587        // A pid that has certainly exited: a child of this test, waited for.
588        let mut child = std::process::Command::new("true").spawn().expect("spawn");
589        let pid = child.id();
590        child.wait().expect("reap");
591        assert!(
592            pid_since(pid).is_none(),
593            "the process is gone: nothing to read"
594        );
595
596        let mut entry = Task::spawned("300-3-0", pid, "a question");
597        entry.state = State::Running;
598        registry.write(&entry).unwrap();
599        assert_eq!(
600            registry.load("300-3-0").unwrap().state_now(),
601            State::Died,
602            "a pid that is gone cannot be running"
603        );
604        assert!(registry.list()[0].died());
605        assert!(registry.list()[0].settled());
606
607        // A finished entry stays finished: there is no process left to ask about.
608        let done = task("400-4-0", State::Done);
609        registry.write(&done).unwrap();
610        assert_eq!(registry.load("400-4-0").unwrap().state_now(), State::Done);
611    }
612
613    /// The pid is paired with the kernel's start time, so a recycled pid cannot resurrect an old
614    /// entry. Simulated by writing a start time that is not the live process's.
615    #[test]
616    fn a_recycled_pid_with_a_different_start_time_is_not_the_same_task() {
617        let (_dir, registry) = scratch();
618        let mut entry = task("500-5-0", State::Running);
619        entry.pid = std::process::id();
620        entry.pid_since = pid_since(std::process::id()).map(|ticks| ticks.wrapping_add(1));
621        registry.write(&entry).unwrap();
622        assert_eq!(
623            registry.load("500-5-0").unwrap().state_now(),
624            State::Died,
625            "same number, different process"
626        );
627
628        let mut ours = task("600-6-0", State::Running);
629        ours.pid = std::process::id();
630        ours.pid_since = pid_since(std::process::id());
631        registry.write(&ours).unwrap();
632        assert_eq!(
633            registry.load("600-6-0").unwrap().state_now(),
634            State::Running,
635            "the live process is the one this entry names"
636        );
637    }
638
639    #[test]
640    fn a_tracker_writes_each_distinct_line_once_and_finishes_with_a_reason() {
641        let (_dir, registry) = scratch();
642        let entry = Task::begun("700-7-0", "do the thing");
643        registry.write(&entry).unwrap();
644        let tracker = Tracker::new(registry.clone(), "700-7-0");
645
646        tracker.event(&AgentEvent::ToolCall {
647            call_id: "c1".into(),
648            name: "shell".into(),
649            arguments: "{}".into(),
650        });
651        assert_eq!(registry.load("700-7-0").unwrap().last, "tool shell");
652        tracker.event(&AgentEvent::ToolResult {
653            call_id: "c1".into(),
654            name: "shell".into(),
655            output: "ok".into(),
656            is_error: true,
657        });
658        assert_eq!(
659            registry.load("700-7-0").unwrap().last,
660            "tool shell failed",
661            "a failed tool says so"
662        );
663        tracker.event(&AgentEvent::Message("the answer".into()));
664        assert_eq!(registry.load("700-7-0").unwrap().last, "replied");
665        // Nothing to say about this one: the row keeps what it had.
666        tracker.event(&AgentEvent::Delta("half".into()));
667        assert_eq!(registry.load("700-7-0").unwrap().last, "replied");
668
669        tracker.finish(State::Failed, "the model refused the shape");
670        let ended = registry.load("700-7-0").unwrap();
671        assert_eq!(ended.state, State::Failed);
672        assert_eq!(ended.detail, "the model refused the shape");
673        assert_eq!(ended.last, "the model refused the shape");
674
675        // A clean finish keeps what the run last *did*: the row already says `done`, and
676        // `done` beside `done` is the same word twice.
677        let clean = Task::begun("701-7-1", "do the thing");
678        registry.write(&clean).unwrap();
679        Tracker::new(registry.clone(), "701-7-1").finish(State::Done, "");
680        let finished = registry.load("701-7-1").unwrap();
681        assert_eq!(finished.state, State::Done);
682        assert_eq!(finished.last, "thinking", "what it was doing when it ended");
683        assert!(finished.detail.is_empty());
684    }
685
686    #[test]
687    fn the_report_names_the_state_the_age_and_what_it_last_did() {
688        let (_dir, registry) = scratch();
689        assert_eq!(
690            registry.report(),
691            "no background tasks — `/bg <prompt>` starts one"
692        );
693
694        let mut running = Task::begun("800-8-0", "summarise every issue");
695        running.last = "tool search_files".into();
696        registry.write(&running).unwrap();
697        let report = registry.report();
698        assert!(report.starts_with("id"), "{report}");
699        assert!(report.contains("800-8-0"), "{report}");
700        assert!(report.contains("running"), "{report}");
701        assert!(report.contains("tool search_files"), "{report}");
702        assert!(report.contains("summarise every issue"), "{report}");
703        assert!(
704            report.contains(&format!("pid {}", std::process::id())),
705            "a live task prints the pid that stops it: {report}"
706        );
707        assert!(
708            report.contains("just now") || report.contains("now"),
709            "{report}"
710        );
711    }
712
713    #[test]
714    fn a_bg_line_is_the_word_and_the_question_behind_it() {
715        assert_eq!(bg_prompt("/bg count the files"), Some("count the files"));
716        assert_eq!(bg_prompt("  /bg   two  spaces "), Some("two  spaces"));
717        assert_eq!(bg_prompt("/bg"), Some(""));
718        assert_eq!(bg_prompt("/bgfoo"), None, "a prefix is not the word");
719        assert_eq!(bg_prompt("what does /bg do?"), None, "not at the start");
720        assert_eq!(bg_prompt("hello"), None);
721    }
722
723    #[test]
724    fn the_refusal_says_where_it_does_work() {
725        let said = bg_refusal("`eclipse run`");
726        assert!(said.contains("/bg"), "{said}");
727        assert!(said.contains("eclipse run"), "{said}");
728        assert!(said.contains("from `eclipse`"), "{said}");
729    }
730
731    #[test]
732    fn a_long_prompt_is_cut_on_a_word_boundary() {
733        let long = "one two three four five six seven eight nine ten";
734        let cut = clip_words(long, 20);
735        assert!(cut.chars().count() <= 21, "{cut}");
736        assert!(cut.ends_with('…'), "{cut}");
737        assert!(!cut.contains("  "), "{cut}");
738        assert_eq!(clip_words("short", 20), "short");
739        // Whitespace in the prompt is flattened: a row is one line.
740        assert_eq!(clip_words("a\n  b", 20), "a b");
741    }
742
743    #[test]
744    fn the_two_live_states_are_the_only_ones_that_need_a_pid() {
745        let live: Vec<State> = [State::Starting, State::Running]
746            .into_iter()
747            .filter(|s| s.alive_only())
748            .collect();
749        assert_eq!(live.len(), 2);
750        for state in [
751            State::Done,
752            State::Failed,
753            State::Stopped,
754            State::Waiting,
755            State::Died,
756        ] {
757            assert!(!state.alive_only(), "{state:?}");
758        }
759    }
760
761    #[test]
762    fn an_id_with_a_slash_in_it_is_refused() {
763        let (_dir, registry) = scratch();
764        let mut bad = task("../escape", State::Running);
765        bad.session = "../escape".into();
766        assert!(registry.write(&bad).is_err());
767        assert!(registry.load("../escape").is_none());
768    }
769
770    #[test]
771    fn a_file_that_does_not_parse_is_skipped_rather_than_reported() {
772        let (dir, registry) = scratch();
773        std::fs::create_dir_all(registry.dir()).unwrap();
774        std::fs::write(registry.dir().join("broken.json"), "{ not json").unwrap();
775        std::fs::write(registry.dir().join(".900.json.tmp"), "{}").unwrap();
776        registry.write(&task("901-9-0", State::Done)).unwrap();
777        let listed = registry.list();
778        assert_eq!(listed.len(), 1, "only the real entry: {listed:?}");
779        assert_eq!(listed[0].session, "901-9-0");
780        assert!(dir.path().exists());
781    }
782
783    #[test]
784    fn touching_an_entry_that_is_already_finished_changes_nothing() {
785        let (_dir, registry) = scratch();
786        let mut finished = task("902-9-0", State::Done);
787        finished.last = "replied".into();
788        finished.updated_ms = 5_000;
789        registry.write(&finished).unwrap();
790        registry.touch("902-9-0", "tool shell").unwrap();
791        let after = registry.load("902-9-0").unwrap();
792        assert_eq!(
793            after.last, "replied",
794            "a finished task does not start again"
795        );
796        assert_eq!(after.updated_ms, 5_000);
797    }
798
799    #[test]
800    fn a_message_event_carries_no_prompt_text_into_the_registry() {
801        // The row says what kind of thing happened, never what was said: the prompt is in the
802        // session, and a registry that copies answers is a second place to leak them.
803        let line = describe_event(&AgentEvent::Message("the secret is hunter2".into()));
804        assert_eq!(line.as_deref(), Some("replied"));
805        let _ = Message::user("x");
806    }
807}