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 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 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 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 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 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 if !detail.is_empty() {
379 task.last = detail.to_string();
380 }
381 task.updated_ms = now_ms();
382 self.write(&task)
383 }
384
385 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 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
444pub 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
457pub 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
468pub 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#[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 pub fn event(&self, event: &AgentEvent) {
513 if let Some(line) = describe_event(event) {
514 self.say(&line);
515 }
516 }
517
518 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 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 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 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 #[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 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 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 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 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}