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    /// One entry, as stored.
313    pub fn load(&self, id: &str) -> Option<Task> {
314        validate_id(id).ok()?;
315        let text = std::fs::read_to_string(self.path(id)).ok()?;
316        serde_json::from_str(&text).ok()
317    }
318
319    /// Every entry, newest activity first. A file that does not parse is skipped rather than
320    /// reported: it is a half-written temp file at worst, and `/tasks` is not a JSON validator.
321    pub fn list(&self) -> Vec<Task> {
322        let Ok(entries) = std::fs::read_dir(&self.dir) else {
323            return Vec::new();
324        };
325        let mut tasks: Vec<Task> = entries
326            .flatten()
327            .filter(|e| {
328                e.path()
329                    .file_name()
330                    .and_then(|n| n.to_str())
331                    .is_some_and(|n| n.ends_with(".json") && !n.starts_with('.'))
332            })
333            .filter_map(|e| std::fs::read_to_string(e.path()).ok())
334            .filter_map(|text| serde_json::from_str::<Task>(&text).ok())
335            .collect();
336        tasks.sort_by(|a, b| {
337            b.updated_ms
338                .cmp(&a.updated_ms)
339                .then_with(|| a.session.cmp(&b.session))
340        });
341        tasks
342    }
343
344    /// What the last turn did, for the row. A no-op when nothing changed, so a long run does not
345    /// rewrite the same line for every event it emits.
346    pub fn touch(&self, id: &str, last: &str) -> std::io::Result<()> {
347        let Some(mut task) = self.load(id) else {
348            return Ok(());
349        };
350        if task.state != State::Running || task.last == last {
351            return Ok(());
352        }
353        task.last = last.to_string();
354        task.updated_ms = now_ms();
355        self.write(&task)
356    }
357
358    /// How it ended. The one line a killed task never gets to write, which is why the pid is
359    /// read instead of believed.
360    pub fn finish(&self, id: &str, state: State, detail: &str) -> std::io::Result<()> {
361        let Some(mut task) = self.load(id) else {
362            return Ok(());
363        };
364        task.state = state;
365        task.detail = detail.to_string();
366        // An empty detail means the run simply ended: `last` keeps what it actually did
367        // (`replied`), because a row that says `done` beside `done` says it twice.
368        if !detail.is_empty() {
369            task.last = detail.to_string();
370        }
371        task.updated_ms = now_ms();
372        self.write(&task)
373    }
374
375    /// The rows `/tasks` prints: a header, then one line per task, or one line saying there are
376    /// none. Shared by both front ends so the REPL and the interface cannot disagree about what a
377    /// task is called.
378    pub fn report(&self) -> String {
379        let tasks = self.list();
380        if tasks.is_empty() {
381            return "no background tasks — `/bg <prompt>` starts one".to_string();
382        }
383        let id_width = tasks
384            .iter()
385            .map(|t| t.session.len())
386            .max()
387            .unwrap_or(0)
388            .max("id".len());
389        let state_width = tasks
390            .iter()
391            .map(|t| t.state_now().word().len())
392            .max()
393            .unwrap_or(0)
394            .max("state".len());
395        let mut lines = vec![format!(
396            "{:<id_width$}  {:<state_width$}  {:<7}  {}",
397            "id", "state", "age", "last"
398        )];
399        for t in &tasks {
400            let state = t.state_now();
401            let age = ago_words(t.updated_ms);
402            let age = age.strip_suffix(" ago").map(str::to_string).unwrap_or(age);
403            let last = if t.detail.is_empty() {
404                t.last.clone()
405            } else {
406                format!("{} ({})", t.last, t.detail)
407            };
408            lines.push(format!(
409                "{:<id_width$}  {:<state_width$}  {:<7}  {}",
410                t.session,
411                state.word(),
412                age,
413                clip_words(&last, 70)
414            ));
415            // The pid is printed while it means something: it is the handle for stopping a run
416            // (`kill <pid>`), and once the task is finished the number may belong to anything.
417            let under = if t.settled() {
418                t.prompt.clone()
419            } else {
420                format!("pid {} · {}", t.pid, t.prompt)
421            };
422            lines.push(format!(
423                "{:<id_width$}  {:<state_width$}  {:<7}  {}",
424                "",
425                "",
426                "",
427                clip_words(&under, 70)
428            ));
429        }
430        lines.join("\n")
431    }
432}
433
434/// The prompt behind a `/bg` line, or `None` when the line is not one.
435///
436/// `/bg` is a word, not a prefix: `/bgfoo` is a prompt for the model, the same way `fix!` is.
437/// An empty answer is still `Some("")` — "you typed the word and nothing else" is a usage error
438/// the caller can say out loud, not a question to send.
439pub fn bg_prompt(line: &str) -> Option<&str> {
440    let rest = line.trim_start().strip_prefix(BG)?;
441    if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
442        return None;
443    }
444    Some(rest.trim())
445}
446
447/// Why `/bg` is not a thing on `surface`.
448///
449/// The registry is a directory and the return-to-the-composer is a keyboard; a headless caller has
450/// neither, and a scheduled job that spawns background jobs is a fork bomb with a schedule.
451pub fn bg_refusal(surface: &str) -> String {
452    format!(
453        "`{BG}` starts a task that outlives the prompt, and {surface} has no prompt to return to — \
454         the line was not run. Run it from `eclipse`, or send the question as a prompt."
455    )
456}
457
458/// The one place a child turns an [`AgentEvent`] into the row's `last` line.
459///
460/// It lives here rather than in the loop because two things need the same words: the child writing
461/// its own registry entry, and nothing else — but a second copy of this mapping would drift from
462/// the states the list shows.
463pub fn describe_event(event: &AgentEvent) -> Option<String> {
464    match event {
465        AgentEvent::ToolCall { name, .. } => Some(format!("tool {name}")),
466        AgentEvent::ToolResult { name, is_error, .. } => Some(if *is_error {
467            format!("tool {name} failed")
468        } else {
469            format!("tool {name} ok")
470        }),
471        AgentEvent::Message(_) => Some("replied".to_string()),
472        _ => None,
473    }
474}
475
476/// A task's entry, kept up to date by the process doing the work.
477///
478/// Cheap to clone (a path and an id) and safe to share: the last written line is compared under a
479/// lock so a turn that emits twenty events writes the file once.
480#[derive(Debug, Clone)]
481pub struct Tracker {
482    registry: Registry,
483    id: String,
484    wrote: std::sync::Arc<Mutex<String>>,
485}
486
487impl Tracker {
488    pub fn new(registry: Registry, id: impl Into<String>) -> Tracker {
489        Tracker {
490            registry,
491            id: id.into(),
492            wrote: std::sync::Arc::new(Mutex::new(String::new())),
493        }
494    }
495
496    pub fn id(&self) -> &str {
497        &self.id
498    }
499
500    /// Follow one event, if it says something a row can carry. Errors are nobody's business here:
501    /// a registry that cannot be written must not stop the run it is describing.
502    pub fn event(&self, event: &AgentEvent) {
503        if let Some(line) = describe_event(event) {
504            self.say(&line);
505        }
506    }
507
508    /// Write `last`, once per distinct line.
509    pub fn say(&self, line: &str) {
510        let mut wrote = match self.wrote.lock() {
511            Ok(w) => w,
512            Err(e) => e.into_inner(),
513        };
514        if *wrote == line {
515            return;
516        }
517        if self.registry.touch(&self.id, line).is_ok() {
518            *wrote = line.to_string();
519        }
520    }
521
522    /// How it ended. Always written when the process got this far.
523    pub fn finish(&self, state: State, detail: &str) {
524        let _ = self.registry.finish(&self.id, state, detail);
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531    use crate::message::Message;
532
533    fn scratch() -> (tempfile::TempDir, Registry) {
534        let dir = tempfile::tempdir().expect("a scratch directory");
535        let registry = Registry::new(dir.path());
536        (dir, registry)
537    }
538
539    fn task(id: &str, state: State) -> Task {
540        let mut t = Task::spawned(id, std::process::id(), "count the files");
541        t.state = state;
542        t
543    }
544
545    #[test]
546    fn an_entry_is_written_read_and_listed_newest_first() {
547        let (_dir, registry) = scratch();
548        assert!(registry.list().is_empty());
549        assert!(registry.is_empty());
550
551        let mut older = task("100-1-0", State::Done);
552        older.updated_ms = 1_000;
553        older.last = "replied".into();
554        let mut newer = task("200-2-0", State::Running);
555        newer.updated_ms = 2_000;
556        newer.last = "tool shell".into();
557        registry.write(&older).unwrap();
558        registry.write(&newer).unwrap();
559
560        let listed = registry.list();
561        assert_eq!(
562            listed
563                .iter()
564                .map(|t| t.session.as_str())
565                .collect::<Vec<_>>(),
566            ["200-2-0", "100-1-0"],
567            "newest activity first"
568        );
569        assert_eq!(registry.load("100-1-0"), Some(older));
570        assert_eq!(registry.load("nope"), None);
571        assert!(!registry.is_empty());
572    }
573
574    #[test]
575    fn a_running_entry_whose_process_is_gone_is_died_not_running() {
576        let (_dir, registry) = scratch();
577        // A pid that has certainly exited: a child of this test, waited for.
578        let mut child = std::process::Command::new("true").spawn().expect("spawn");
579        let pid = child.id();
580        child.wait().expect("reap");
581        assert!(
582            pid_since(pid).is_none(),
583            "the process is gone: nothing to read"
584        );
585
586        let mut entry = Task::spawned("300-3-0", pid, "a question");
587        entry.state = State::Running;
588        registry.write(&entry).unwrap();
589        assert_eq!(
590            registry.load("300-3-0").unwrap().state_now(),
591            State::Died,
592            "a pid that is gone cannot be running"
593        );
594        assert!(registry.list()[0].died());
595        assert!(registry.list()[0].settled());
596
597        // A finished entry stays finished: there is no process left to ask about.
598        let done = task("400-4-0", State::Done);
599        registry.write(&done).unwrap();
600        assert_eq!(registry.load("400-4-0").unwrap().state_now(), State::Done);
601    }
602
603    /// The pid is paired with the kernel's start time, so a recycled pid cannot resurrect an old
604    /// entry. Simulated by writing a start time that is not the live process's.
605    #[test]
606    fn a_recycled_pid_with_a_different_start_time_is_not_the_same_task() {
607        let (_dir, registry) = scratch();
608        let mut entry = task("500-5-0", State::Running);
609        entry.pid = std::process::id();
610        entry.pid_since = pid_since(std::process::id()).map(|ticks| ticks.wrapping_add(1));
611        registry.write(&entry).unwrap();
612        assert_eq!(
613            registry.load("500-5-0").unwrap().state_now(),
614            State::Died,
615            "same number, different process"
616        );
617
618        let mut ours = task("600-6-0", State::Running);
619        ours.pid = std::process::id();
620        ours.pid_since = pid_since(std::process::id());
621        registry.write(&ours).unwrap();
622        assert_eq!(
623            registry.load("600-6-0").unwrap().state_now(),
624            State::Running,
625            "the live process is the one this entry names"
626        );
627    }
628
629    #[test]
630    fn a_tracker_writes_each_distinct_line_once_and_finishes_with_a_reason() {
631        let (_dir, registry) = scratch();
632        let entry = Task::begun("700-7-0", "do the thing");
633        registry.write(&entry).unwrap();
634        let tracker = Tracker::new(registry.clone(), "700-7-0");
635
636        tracker.event(&AgentEvent::ToolCall {
637            call_id: "c1".into(),
638            name: "shell".into(),
639            arguments: "{}".into(),
640        });
641        assert_eq!(registry.load("700-7-0").unwrap().last, "tool shell");
642        tracker.event(&AgentEvent::ToolResult {
643            call_id: "c1".into(),
644            name: "shell".into(),
645            output: "ok".into(),
646            is_error: true,
647        });
648        assert_eq!(
649            registry.load("700-7-0").unwrap().last,
650            "tool shell failed",
651            "a failed tool says so"
652        );
653        tracker.event(&AgentEvent::Message("the answer".into()));
654        assert_eq!(registry.load("700-7-0").unwrap().last, "replied");
655        // Nothing to say about this one: the row keeps what it had.
656        tracker.event(&AgentEvent::Delta("half".into()));
657        assert_eq!(registry.load("700-7-0").unwrap().last, "replied");
658
659        tracker.finish(State::Failed, "the model refused the shape");
660        let ended = registry.load("700-7-0").unwrap();
661        assert_eq!(ended.state, State::Failed);
662        assert_eq!(ended.detail, "the model refused the shape");
663        assert_eq!(ended.last, "the model refused the shape");
664
665        // A clean finish keeps what the run last *did*: the row already says `done`, and
666        // `done` beside `done` is the same word twice.
667        let clean = Task::begun("701-7-1", "do the thing");
668        registry.write(&clean).unwrap();
669        Tracker::new(registry.clone(), "701-7-1").finish(State::Done, "");
670        let finished = registry.load("701-7-1").unwrap();
671        assert_eq!(finished.state, State::Done);
672        assert_eq!(finished.last, "thinking", "what it was doing when it ended");
673        assert!(finished.detail.is_empty());
674    }
675
676    #[test]
677    fn the_report_names_the_state_the_age_and_what_it_last_did() {
678        let (_dir, registry) = scratch();
679        assert_eq!(
680            registry.report(),
681            "no background tasks — `/bg <prompt>` starts one"
682        );
683
684        let mut running = Task::begun("800-8-0", "summarise every issue");
685        running.last = "tool search_files".into();
686        registry.write(&running).unwrap();
687        let report = registry.report();
688        assert!(report.starts_with("id"), "{report}");
689        assert!(report.contains("800-8-0"), "{report}");
690        assert!(report.contains("running"), "{report}");
691        assert!(report.contains("tool search_files"), "{report}");
692        assert!(report.contains("summarise every issue"), "{report}");
693        assert!(
694            report.contains(&format!("pid {}", std::process::id())),
695            "a live task prints the pid that stops it: {report}"
696        );
697        assert!(
698            report.contains("just now") || report.contains("now"),
699            "{report}"
700        );
701    }
702
703    #[test]
704    fn a_bg_line_is_the_word_and_the_question_behind_it() {
705        assert_eq!(bg_prompt("/bg count the files"), Some("count the files"));
706        assert_eq!(bg_prompt("  /bg   two  spaces "), Some("two  spaces"));
707        assert_eq!(bg_prompt("/bg"), Some(""));
708        assert_eq!(bg_prompt("/bgfoo"), None, "a prefix is not the word");
709        assert_eq!(bg_prompt("what does /bg do?"), None, "not at the start");
710        assert_eq!(bg_prompt("hello"), None);
711    }
712
713    #[test]
714    fn the_refusal_says_where_it_does_work() {
715        let said = bg_refusal("`eclipse run`");
716        assert!(said.contains("/bg"), "{said}");
717        assert!(said.contains("eclipse run"), "{said}");
718        assert!(said.contains("from `eclipse`"), "{said}");
719    }
720
721    #[test]
722    fn a_long_prompt_is_cut_on_a_word_boundary() {
723        let long = "one two three four five six seven eight nine ten";
724        let cut = clip_words(long, 20);
725        assert!(cut.chars().count() <= 21, "{cut}");
726        assert!(cut.ends_with('…'), "{cut}");
727        assert!(!cut.contains("  "), "{cut}");
728        assert_eq!(clip_words("short", 20), "short");
729        // Whitespace in the prompt is flattened: a row is one line.
730        assert_eq!(clip_words("a\n  b", 20), "a b");
731    }
732
733    #[test]
734    fn the_two_live_states_are_the_only_ones_that_need_a_pid() {
735        let live: Vec<State> = [State::Starting, State::Running]
736            .into_iter()
737            .filter(|s| s.alive_only())
738            .collect();
739        assert_eq!(live.len(), 2);
740        for state in [
741            State::Done,
742            State::Failed,
743            State::Stopped,
744            State::Waiting,
745            State::Died,
746        ] {
747            assert!(!state.alive_only(), "{state:?}");
748        }
749    }
750
751    #[test]
752    fn an_id_with_a_slash_in_it_is_refused() {
753        let (_dir, registry) = scratch();
754        let mut bad = task("../escape", State::Running);
755        bad.session = "../escape".into();
756        assert!(registry.write(&bad).is_err());
757        assert!(registry.load("../escape").is_none());
758    }
759
760    #[test]
761    fn a_file_that_does_not_parse_is_skipped_rather_than_reported() {
762        let (dir, registry) = scratch();
763        std::fs::create_dir_all(registry.dir()).unwrap();
764        std::fs::write(registry.dir().join("broken.json"), "{ not json").unwrap();
765        std::fs::write(registry.dir().join(".900.json.tmp"), "{}").unwrap();
766        registry.write(&task("901-9-0", State::Done)).unwrap();
767        let listed = registry.list();
768        assert_eq!(listed.len(), 1, "only the real entry: {listed:?}");
769        assert_eq!(listed[0].session, "901-9-0");
770        assert!(dir.path().exists());
771    }
772
773    #[test]
774    fn touching_an_entry_that_is_already_finished_changes_nothing() {
775        let (_dir, registry) = scratch();
776        let mut finished = task("902-9-0", State::Done);
777        finished.last = "replied".into();
778        finished.updated_ms = 5_000;
779        registry.write(&finished).unwrap();
780        registry.touch("902-9-0", "tool shell").unwrap();
781        let after = registry.load("902-9-0").unwrap();
782        assert_eq!(
783            after.last, "replied",
784            "a finished task does not start again"
785        );
786        assert_eq!(after.updated_ms, 5_000);
787    }
788
789    #[test]
790    fn a_message_event_carries_no_prompt_text_into_the_registry() {
791        // The row says what kind of thing happened, never what was said: the prompt is in the
792        // session, and a registry that copies answers is a second place to leak them.
793        let line = describe_event(&AgentEvent::Message("the secret is hunter2".into()));
794        assert_eq!(line.as_deref(), Some("replied"));
795        let _ = Message::user("x");
796    }
797}