1use 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
27pub const DIR: &str = "tasks";
29
30pub const BG: &str = "/bg";
32
33pub const TASKS: &str = "/tasks";
35
36const PROMPT_CHARS: usize = 60;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum State {
47 Starting,
49 Running,
51 Done,
53 Failed,
55 Stopped,
57 Waiting,
59 Died,
61}
62
63impl State {
64 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 pub fn alive_only(self) -> bool {
82 matches!(self, State::Starting | State::Running)
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct Task {
89 pub session: String,
92 pub pid: u32,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub pid_since: Option<u64>,
98 pub started_ms: u64,
100 pub updated_ms: u64,
102 pub prompt: String,
104 pub state: State,
105 pub last: String,
107 #[serde(default, skip_serializing_if = "String::is_empty")]
109 pub detail: String,
110}
111
112impl Task {
113 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 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 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 pub fn headline(&self) -> String {
154 format!(
155 "{} · {}",
156 self.state_now().word(),
157 ago_words(self.updated_ms)
158 )
159 }
160
161 pub fn settled(&self) -> bool {
163 !self.state_now().alive_only()
164 }
165
166 pub fn died(&self) -> bool {
168 self.state_now() == State::Died
169 }
170}
171
172fn 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#[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#[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#[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#[cfg(unix)]
230fn pid_live(pid: u32, since: Option<u64>) -> bool {
231 if pid == 0 {
232 return false;
233 }
234 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 pid != 0
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct Registry {
260 dir: PathBuf,
261}
262
263impl Registry {
264 pub fn new(state_dir: impl AsRef<Path>) -> Registry {
267 Registry {
268 dir: state_dir.as_ref().join(DIR),
269 }
270 }
271
272 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 pub fn path(&self, id: &str) -> PathBuf {
286 self.dir.join(format!("{id}.json"))
287 }
288
289 pub fn log_path(&self, id: &str) -> PathBuf {
292 self.dir.join(format!("{id}.log"))
293 }
294
295 pub fn is_empty(&self) -> bool {
297 self.list().is_empty()
298 }
299
300 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 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 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 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 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 if !detail.is_empty() {
369 task.last = detail.to_string();
370 }
371 task.updated_ms = now_ms();
372 self.write(&task)
373 }
374
375 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 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
434pub 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
447pub 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
458pub 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#[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 pub fn event(&self, event: &AgentEvent) {
503 if let Some(line) = describe_event(event) {
504 self.say(&line);
505 }
506 }
507
508 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 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 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 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 #[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 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 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 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 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}