1use std::collections::HashMap;
32use std::sync::Arc;
33use std::time::Duration;
34
35use tokio::time::interval;
36
37use crate::backend::blockcontroller::{get_block_controller_status, STATUS_RUNNING};
38use crate::backend::storage::filestore::FileStore;
39use crate::backend::storage::store::Store;
40use crate::backend::transcript::source::TranscriptSource;
41use crate::backend::mps::Broker;
42use crate::backend::work_facts::overlap_notes::{NewEdit, NewPr};
43
44use super::get_global_handler;
45
46const SWEEP_INTERVAL_SECS: u64 = 3;
49
50const MAX_READ_BYTES: i64 = 4 * 1024 * 1024;
55
56const MAX_TODOS: usize = 24;
60
61const MAX_OPEN_TOOLS: usize = 32;
65
66pub const EVENT_AGENT_PROGRESS: &str = "agent:progress";
67
68const REPUBLISH_EVERY_TICKS: u64 = 5;
78
79const TODO_TOOL_NAMES: &[&str] = &["TodoWrite", "TaskCreate", "TaskUpdate"];
94
95#[path = "progress_codex_plan.rs"]
96pub mod codex_plan;
97use codex_plan::codex_plan;
98
99fn is_todo_tool(name: &str) -> bool {
100 TODO_TOOL_NAMES.contains(&name) || name.contains("Todo")
101}
102
103const FILE_EDIT_TOOL_NAMES: &[&str] = &["Edit", "Write", "MultiEdit", "NotebookEdit"];
107
108fn is_shell_tool(name: &str) -> bool {
111 let lower = name.to_ascii_lowercase();
112 lower.contains("bash") || lower.ends_with("shell") || lower.ends_with("terminal")
113}
114
115#[cfg(test)]
120fn is_pr_create(command: &str) -> bool {
121 pr_create(command).is_some()
122}
123
124fn pr_create(command: &str) -> Option<NewPrCommand> {
129 let clean = |w: &str| w.trim_matches(|c| matches!(c, '"' | '\'' | '(' | ')' | ';')).to_string();
130 let raw: Vec<&str> = command.split_whitespace().collect();
131 for (i, first) in raw.iter().enumerate() {
132 let word = clean(first);
133 let program = word.rsplit(['/', '\\']).next().unwrap_or(&word);
134 let program = program.trim_end_matches(".cmd").trim_end_matches(".exe");
135 if !matches!(program, "gh" | "gh-agent") {
136 continue;
137 }
138 let mut rest: Vec<String> = Vec::new();
139 for w in &raw[i + 1..] {
140 if matches!(*w, "&&" | "||" | "|" | ";") {
141 break;
142 }
143 rest.push(clean(w));
144 if w.ends_with(';') {
145 break;
146 }
147 }
148 let (mut k, mut words) = (0, Vec::new());
150 while k < rest.len() && words.len() < 2 {
151 match rest[k].as_str() {
152 "-R" | "--repo" => k += 2,
153 w if w.starts_with('-') => k += 1,
154 w => {
155 words.push(w.to_string());
156 k += 1;
157 }
158 }
159 }
160 if words != ["pr", "create"] {
161 continue;
162 }
163 let mut pr = NewPrCommand::default();
164 while k < rest.len() {
165 let w = rest[k].as_str();
166 let next = || rest.get(k + 1).cloned();
167 match w {
168 "-H" | "--head" => {
169 pr.head = next();
170 k += 2;
171 continue;
172 }
173 "-B" | "--base" => {
174 pr.base = next();
175 k += 2;
176 continue;
177 }
178 _ => {}
179 }
180 if let Some(v) = w.strip_prefix("--head=") {
181 pr.head = Some(v.to_string());
182 } else if let Some(v) = w.strip_prefix("--base=") {
183 pr.base = Some(v.to_string());
184 }
185 k += 1;
186 }
187 return Some(pr);
188 }
189 None
190}
191
192#[derive(Debug, Clone, Default, PartialEq, Eq)]
194struct NewPrCommand {
195 head: Option<String>,
196 base: Option<String>,
197}
198
199const MAX_NEW_PRS: usize = 4;
201
202pub const MAX_RECENT_FILES: usize = 50;
204
205#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
207pub struct RecentFile {
208 pub path: String,
210 pub tool: String,
211 pub ts_ms: u64,
216}
217
218fn line_timestamp(v: &serde_json::Value) -> Option<u64> {
221 let ts = v.get("timestamp")?;
222 if let Some(n) = ts.as_u64() {
223 return Some(n);
224 }
225 chrono::DateTime::parse_from_rfc3339(ts.as_str()?)
226 .ok()
227 .and_then(|dt| u64::try_from(dt.timestamp_millis()).ok())
228}
229
230#[derive(Debug, Clone, Default)]
233pub struct WatchedWork {
234 pub progress: AgentProgress,
235 pub recent_files: Vec<RecentFile>,
236}
237
238fn snapshot() -> &'static parking_lot::RwLock<HashMap<String, WatchedWork>> {
240 static SNAPSHOT: std::sync::LazyLock<parking_lot::RwLock<HashMap<String, WatchedWork>>> =
241 std::sync::LazyLock::new(Default::default);
242 &SNAPSHOT
243}
244
245pub fn watched_work(block_id: &str) -> Option<WatchedWork> {
248 snapshot().read().get(block_id).cloned()
249}
250
251fn note_recent_file(files: &mut Vec<RecentFile>, path: &str, tool: &str, ts_ms: u64) {
254 files.retain(|f| f.path != path);
255 files.insert(0, RecentFile { path: path.to_string(), tool: tool.to_string(), ts_ms });
256 files.truncate(MAX_RECENT_FILES);
257}
258
259#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
261#[ts(export, export_to = "../../../frontend/types/rpc/")]
262pub struct TodoItem {
263 pub text: String,
264 pub status: String,
269}
270
271#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
273pub struct AgentProgress {
274 pub todos: Vec<TodoItem>,
275 pub todos_truncated: usize,
278 pub todos_partial: bool,
283 pub current_tool: Option<String>,
286}
287
288impl AgentProgress {
289 fn is_empty(&self) -> bool {
291 self.todos.is_empty() && self.current_tool.is_none()
292 }
293}
294
295#[derive(Debug, Default)]
297struct BlockState {
298 next_offset: i64,
300 tasks: Vec<(String, TodoItem)>,
304 list: Option<Vec<TodoItem>>,
307 open: Vec<(String, String)>,
309 partial: bool,
311 recent_files: Vec<RecentFile>,
313 new_edits: Vec<RecentFile>,
316 new_prs: Vec<NewPrCommand>,
319 seen: bool,
321 global: bool,
324}
325
326impl BlockState {
327 fn progress(&self) -> AgentProgress {
328 let mut todos = self
329 .list
330 .clone()
331 .unwrap_or_else(|| self.tasks.iter().map(|(_, i)| i.clone()).collect());
332 let todos_truncated = todos.len().saturating_sub(MAX_TODOS);
333 todos.truncate(MAX_TODOS);
334 AgentProgress {
335 todos,
336 todos_truncated,
337 todos_partial: self.partial && self.list.is_none(),
340 current_tool: self.open.first().map(|(_, name)| name.clone()),
341 }
342 }
343}
344
345fn apply_lines(state: &mut BlockState, lines: &[&str], live_now_ms: Option<u64>) {
357 for line in lines {
358 let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
359 continue;
360 };
361
362 for id in tool_result_ids(&v) {
365 state.open.retain(|(open_id, _)| *open_id != id);
366 }
367
368 if v.get("type").and_then(|t| t.as_str()) == Some("item.started") {
371 let item = v.get("item");
372 let is_command = item.and_then(|i| i.get("type")).and_then(|t| t.as_str()) == Some("command_execution");
373 let command = item.and_then(|i| i.get("command")).and_then(|c| c.as_str());
374 if let Some(pr) = command.filter(|_| is_command).and_then(pr_create) {
375 if live_now_ms.is_some() && state.new_prs.len() < MAX_NEW_PRS {
376 state.new_prs.push(pr);
377 }
378 }
379 }
380
381 if let Some(items) = codex_plan(&v) {
385 state.list = Some(items);
386 state.tasks.clear();
387 continue;
388 }
389
390 for frame in tool_frames(&v) {
391 if frame.get("type").and_then(|t| t.as_str()) != Some("tool_use") {
392 continue;
393 }
394 let Some(name) = frame_tool_name(frame) else { continue };
395 if let Some(id) = frame_tool_id(frame) {
396 state.open.push((id.to_string(), name.to_string()));
397 if state.open.len() > MAX_OPEN_TOOLS {
400 state.open.remove(0);
401 }
402 }
403
404 if is_shell_tool(name) {
405 let opens = frame_input(frame).and_then(|i| first_string(i, &["command", "cmd"])).and_then(|c| pr_create(&c));
406 if let Some(pr) = opens {
407 if live_now_ms.is_some() && state.new_prs.len() < MAX_NEW_PRS {
408 state.new_prs.push(pr);
409 }
410 }
411 continue;
412 }
413
414 if FILE_EDIT_TOOL_NAMES.contains(&name) {
415 if let Some(path) = frame_input(frame)
416 .and_then(|i| first_string(i, &["file_path", "notebook_path"]))
417 {
418 if let Some(ts) = line_timestamp(&v).or(live_now_ms) {
419 note_recent_file(&mut state.recent_files, &path, name, ts);
420 if live_now_ms.is_some() && state.new_edits.len() < MAX_RECENT_FILES {
423 state.new_edits.push(RecentFile { path, tool: name.to_string(), ts_ms: ts });
424 }
425 }
426 }
427 continue;
428 }
429
430 if !is_todo_tool(name) {
431 continue;
432 }
433 let Some(input) = frame_input(frame) else { continue };
434
435 if let Some(items) = parse_todo_array(input) {
436 state.list = Some(items);
437 state.tasks.clear();
438 continue;
439 }
440 if state.list.is_none() {
444 merge_single_task(&mut state.tasks, input, name);
445 }
446 }
447 }
448}
449
450fn tool_frames(v: &serde_json::Value) -> Vec<&serde_json::Value> {
462 let mut frames: Vec<&serde_json::Value> = v
463 .get("message")
464 .and_then(|m| m.get("content"))
465 .or_else(|| v.get("content"))
466 .and_then(|c| c.as_array())
467 .map(|a| a.iter().collect())
468 .unwrap_or_default();
469 if matches!(v.get("type").and_then(|t| t.as_str()), Some("tool_use") | Some("tool_result")) {
472 frames.push(v);
473 }
474 frames
475}
476
477fn frame_tool_name(frame: &serde_json::Value) -> Option<&str> {
480 frame
481 .get("name")
482 .or_else(|| frame.get("tool_name"))
483 .and_then(|n| n.as_str())
484}
485
486fn frame_tool_id(frame: &serde_json::Value) -> Option<&str> {
488 frame
489 .get("id")
490 .or_else(|| frame.get("tool_id"))
491 .and_then(|i| i.as_str())
492}
493
494fn frame_input(frame: &serde_json::Value) -> Option<&serde_json::Value> {
496 frame.get("input").or_else(|| frame.get("parameters"))
497}
498
499fn tool_result_ids(v: &serde_json::Value) -> Vec<String> {
500 let mut ids = Vec::new();
501 if let Some(id) = v.get("tool_use_id").and_then(|i| i.as_str()) {
502 ids.push(id.to_string());
503 }
504 for frame in tool_frames(v) {
505 if frame.get("type").and_then(|t| t.as_str()) != Some("tool_result") {
506 continue;
507 }
508 if let Some(id) = frame
511 .get("tool_use_id")
512 .or_else(|| frame.get("tool_id"))
513 .and_then(|i| i.as_str())
514 {
515 ids.push(id.to_string());
516 }
517 }
518 ids
519}
520
521fn parse_todo_array(input: &serde_json::Value) -> Option<Vec<TodoItem>> {
523 let arr = input
524 .get("todos")
525 .or_else(|| input.get("items"))
526 .and_then(|t| t.as_array())?;
527 Some(arr.iter().filter_map(parse_todo_entry).collect())
530}
531
532fn parse_todo_entry(entry: &serde_json::Value) -> Option<TodoItem> {
533 let text = first_string(entry, &["content", "title", "text", "step", "activeForm", "description"])?;
534 let status = first_string(entry, &["status", "state"]).unwrap_or_else(|| "pending".to_string());
535 Some(TodoItem { text, status })
536}
537
538fn is_create_call(tool_name: &str) -> bool {
557 tool_name.contains("Create") || tool_name.contains("Add") || tool_name.contains("New")
558}
559
560fn merge_single_task(items: &mut Vec<(String, TodoItem)>, input: &serde_json::Value, tool_name: &str) {
561 let text = first_string(input, &["content", "title", "text", "activeForm", "description"]);
562 let status = first_string(input, &["status", "state"]);
563 let id = first_string(input, &["task_id", "taskId", "id"]);
564
565 if id.is_none() && is_create_call(tool_name) {
567 let Some(text) = text else { return };
568 items.push((
569 format!("{}#{}", text, items.len()),
572 TodoItem { text, status: status.unwrap_or_else(|| "pending".to_string()) },
573 ));
574 return;
575 }
576
577 let existing = match &id {
582 Some(id) => items.iter_mut().find(|(k, _)| k == id),
583 None => match &text {
584 Some(text) => items.iter_mut().find(|(_, item)| item.text == *text),
585 None => None,
586 },
587 };
588 if let Some(slot) = existing {
589 if let Some(text) = text {
590 slot.1.text = text;
591 }
592 if let Some(status) = status {
593 slot.1.status = status;
594 }
595 return;
596 }
597
598 let Some(key) = id.or_else(|| text.clone()) else {
599 return;
601 };
602
603 let Some(text) = text else { return };
606 items.push((key, TodoItem { text, status: status.unwrap_or_else(|| "pending".to_string()) }));
607}
608
609fn first_string(v: &serde_json::Value, keys: &[&str]) -> Option<String> {
610 keys.iter()
611 .find_map(|k| v.get(*k).and_then(|s| s.as_str()))
612 .map(|s| s.trim().to_string())
613 .filter(|s| !s.is_empty())
614}
615
616fn consume_new_output(source: &TranscriptSource<'_>, state: &mut BlockState) -> bool {
622 let size = match source.stat() {
623 Some((size, _)) => size,
624 None => 0,
625 };
626 if state.seen && state.global != source.global {
629 *state = BlockState::default();
630 }
631 state.global = source.global;
632 let first_sight = !state.seen;
636 state.seen = true;
637 if size <= 0 {
638 return false;
639 }
640
641 if size < state.next_offset {
645 *state = BlockState { seen: true, global: source.global, ..BlockState::default() };
646 }
647
648 if state.next_offset == 0 && size > MAX_READ_BYTES {
649 state.next_offset = size - MAX_READ_BYTES;
653 state.partial = true;
654 }
655
656 let available = size - state.next_offset;
657 if available <= 0 {
658 return false;
659 }
660 let want = available.min(MAX_READ_BYTES);
661 let Some(bytes) = source.read_range(state.next_offset, want) else {
662 return false;
663 };
664 if bytes.is_empty() {
665 return false;
666 }
667
668 let consumed = match bytes.iter().rposition(|b| *b == b'\n') {
672 Some(idx) => idx + 1,
673 None if want == MAX_READ_BYTES => bytes.len(),
676 None => return false,
677 };
678 state.next_offset += consumed as i64;
679
680 let text = String::from_utf8_lossy(&bytes[..consumed]);
681 let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
682 if lines.is_empty() {
683 return false;
684 }
685 let live_now_ms = (!first_sight).then(agentmux_common::time::now_ms_u64);
686 apply_lines(state, &lines, live_now_ms);
687 true
688}
689
690struct SweepOutcome {
693 agent_id: String,
694 block_id: String,
695 progress: AgentProgress,
696}
697
698type Swept = (HashMap<String, BlockState>, Vec<SweepOutcome>, (Vec<NewEdit>, Vec<NewPr>));
701
702fn sweep_blocking(
711 filestore: &FileStore,
712 mstore: &Store,
713 agents: Vec<(String, String)>,
714 mut states: HashMap<String, BlockState>,
715 last_published: &HashMap<String, AgentProgress>,
716 force_republish: bool,
717) -> Swept {
718 let mut out = Vec::new();
719 let mut edits = Vec::new();
720 let mut prs = Vec::new();
721
722 for (agent_id, block_id) in agents {
723 let Some(status) = get_block_controller_status(&block_id) else { continue };
726 if status.shellprocstatus != STATUS_RUNNING || !status.is_agent_pane {
727 continue;
728 }
729
730 let state = states.entry(block_id.clone()).or_default();
731 let source = TranscriptSource::resolve(filestore, mstore, &block_id);
733 let had_new = consume_new_output(&source, state);
734 edits.extend(state.new_edits.drain(..).map(|f| NewEdit {
735 agent_id: agent_id.clone(),
736 block_id: block_id.clone(),
737 path: f.path,
738 }));
739 prs.extend(state.new_prs.drain(..).map(|p| NewPr {
740 agent_id: agent_id.clone(),
741 block_id: block_id.clone(),
742 head: p.head,
743 base: p.base,
744 }));
745 let progress = state.progress();
746
747 if !had_new && !last_published.contains_key(&block_id) {
750 continue;
751 }
752 if progress.is_empty() && !last_published.contains_key(&block_id) {
753 continue;
754 }
755 if !force_republish && last_published.get(&block_id) == Some(&progress) {
756 continue;
757 }
758 out.push(SweepOutcome { agent_id, block_id, progress });
759 }
760
761 (states, out, (edits, prs))
762}
763
764pub async fn run_agent_progress_loop(filestore: Arc<FileStore>, mstore: Arc<Store>, broker: Arc<Broker>) {
766 let mut ticker = interval(Duration::from_secs(SWEEP_INTERVAL_SECS));
767 let mut tick: u64 = 0;
768 let mut states: HashMap<String, BlockState> = HashMap::new();
769 let mut last_published: HashMap<String, AgentProgress> = HashMap::new();
772
773 loop {
774 ticker.tick().await;
775 tick += 1;
776 let force_republish = tick % REPUBLISH_EVERY_TICKS == 0;
777
778 let agents: Vec<(String, String)> = get_global_handler()
779 .list_agents()
780 .into_iter()
781 .map(|a| (a.agent_id, a.block_id))
782 .collect();
783 let registered: std::collections::HashSet<String> =
784 agents.iter().map(|(_, block_id)| block_id.clone()).collect();
785 states.retain(|block_id, _| registered.contains(block_id));
788 last_published.retain(|block_id, _| registered.contains(block_id));
789
790 let fs = filestore.clone();
791 let ms = mstore.clone();
792 let published = last_published.clone();
793 let taken = std::mem::take(&mut states);
794 let joined = tokio::task::spawn_blocking(move || {
795 sweep_blocking(&fs, &ms, agents, taken, &published, force_republish)
796 })
797 .await;
798
799 let (returned_states, outcomes, (edits, prs)) = match joined {
805 Ok(v) => v,
806 Err(e) => {
807 tracing::error!(error = %e, "progress sweep task failed; state reset for next tick");
808 continue;
809 }
810 };
811 states = returned_states;
812 crate::backend::work_facts::overlap_notes::on_new_edits(edits);
814 crate::backend::kanban::on_new_prs(&prs);
815 crate::backend::work_facts::overlap_notes::on_new_prs(prs);
816 *snapshot().write() = states
817 .iter()
818 .map(|(block_id, s)| {
819 (block_id.clone(), WatchedWork { progress: s.progress(), recent_files: s.recent_files.clone() })
820 })
821 .collect();
822
823 for SweepOutcome { agent_id, block_id, progress } in outcomes {
824 last_published.insert(block_id.clone(), progress.clone());
825
826 let ts = agentmux_common::time::now_ms_u64();
827
828 let event = crate::backend::mps_events::AgentProgressEvent {
829 agent_id,
830 block_id: block_id.clone(),
831 todos: progress.todos,
832 todos_truncated: progress.todos_truncated,
833 todos_partial: progress.todos_partial,
834 current_tool: progress.current_tool,
835 ts,
836 };
837 broker.publish_event::<crate::backend::mps_events::AgentProgress>(&event, vec![format!("block:{}", block_id)], 1);
841 }
842 }
843}
844
845#[cfg(test)]
846mod tests {
847 use super::*;
848
849 fn todo_write(id: &str, todos: &str) -> String {
850 format!(
851 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"TodoWrite","input":{{"todos":{todos}}}}}]}}}}"#
852 )
853 }
854
855 fn task_call(id: &str, tool: &str, tid: &str, title: &str, status: &str) -> String {
856 format!(
857 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"{tool}","input":{{"task_id":"{tid}","title":"{title}","status":"{status}"}}}}]}}}}"#
858 )
859 }
860
861 fn tool_use(id: &str, name: &str) -> String {
862 format!(
863 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"{name}","input":{{}}}}]}}}}"#
864 )
865 }
866
867 fn tool_result(id: &str) -> String {
868 format!(
869 r#"{{"type":"user","message":{{"content":[{{"type":"tool_result","tool_use_id":"{id}"}}]}}}}"#
870 )
871 }
872
873 fn feed(state: &mut BlockState, lines: &[String]) {
875 feed_at(state, lines, 1_000);
876 }
877
878 fn feed_at(state: &mut BlockState, lines: &[String], now_ms: u64) {
879 let refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
880 apply_lines(state, &refs, Some(now_ms));
881 }
882
883 fn consume(fs: &FileStore, block: &str, st: &mut BlockState) -> bool {
885 consume_new_output(&TranscriptSource::own(fs, block), st)
886 }
887
888 fn output_store(block: &str, text: &str) -> FileStore {
889 use crate::backend::storage::filestore::{FileMeta, FileOpts};
890 let fs = FileStore::open_in_memory().unwrap();
891 fs.make_file(block, "output", FileMeta::default(), FileOpts::default()).unwrap();
892 fs.append_data(block, "output", text.as_bytes()).unwrap();
893 fs
894 }
895
896 #[test]
900 fn a_first_sight_backlog_does_not_read_as_just_edited() {
901 let block = "b-backlog";
902 let stamped = r#"{"type":"assistant","timestamp":"2026-10-01T10:00:00Z","message":{"content":[{"type":"tool_use","id":"s1","name":"Edit","input":{"file_path":"/r/stamped.rs"}}]}}"#;
903 let backlog = format!("{}
904{}
905", edit_call("e1", "Edit", "file_path", "/r/old.rs"), stamped);
906 let fs = output_store(block, &backlog);
907 let mut st = BlockState::default();
908 assert!(consume(&fs, block, &mut st));
909 let got: Vec<(&str, u64)> = st.recent_files.iter().map(|f| (f.path.as_str(), f.ts_ms)).collect();
910 assert_eq!(got, vec![("/r/stamped.rs", 1_790_848_800_000)], "the untimed backlog edit is not recorded");
911 assert!(st.new_edits.is_empty(), "backlog edits are never checked for overlap");
912
913 let before = agentmux_common::time::now_ms_u64();
914 fs.append_data(block, "output", format!("{}
915", edit_call("e2", "Write", "file_path", "/r/new.rs")).as_bytes())
916 .unwrap();
917 assert!(consume(&fs, block, &mut st));
918 assert_eq!(st.recent_files[0].path, "/r/new.rs");
919 assert!(st.recent_files[0].ts_ms >= before, "a live edit takes the read time");
920 let live: Vec<&str> = st.new_edits.iter().map(|f| f.path.as_str()).collect();
921 assert_eq!(live, vec!["/r/new.rs"], "a live edit is handed to the overlap check");
922 }
923
924 #[test]
926 fn a_block_first_seen_empty_records_its_first_edits() {
927 let block = "b-empty";
928 let fs = FileStore::open_in_memory().unwrap();
929 let mut st = BlockState::default();
930 assert!(!consume(&fs, block, &mut st));
931 let fs = output_store(block, &format!("{}
932", edit_call("e1", "Edit", "file_path", "/r/a.rs")));
933 assert!(consume(&fs, block, &mut st));
934 assert_eq!(st.recent_files.len(), 1);
935 }
936
937 #[test]
940 fn progress_is_read_from_the_agents_zone() {
941 let zone = "agent:progress-global:current";
942 let global = output_store(zone, "");
943 let mut st = BlockState::default();
944 let source = TranscriptSource { fs: &global, zone: zone.to_string(), global: true, own: None };
945 assert!(!consume_new_output(&source, &mut st), "an empty zone has nothing");
946 global
947 .append_data(zone, "output", format!("{}\n", edit_call("e1", "Edit", "file_path", "/r/zone.rs")).as_bytes())
948 .unwrap();
949 assert!(consume_new_output(&source, &mut st));
950 assert_eq!(st.recent_files.len(), 1);
951 assert_eq!(st.recent_files[0].path, "/r/zone.rs");
952 assert!(st.global);
953 }
954
955 #[test]
959 fn a_change_of_source_starts_the_cursor_over() {
960 let block = "b-flip";
961 let own = output_store(block, &format!("{}\n{}\n", edit_call("e1", "Edit", "file_path", "/r/own1.rs"), edit_call("e2", "Edit", "file_path", "/r/own2.rs")));
962 let mut st = BlockState::default();
963 assert!(consume(&own, block, &mut st));
964 let offset_in_own = st.next_offset;
965 assert!(offset_in_own > 0 && !st.global);
966
967 let zone = "agent:progress-flip:current";
968 let global = output_store(zone, &format!("{}\n", edit_call("g1", "Edit", "file_path", "/r/zone1.rs")));
969 let source = TranscriptSource { fs: &global, zone: zone.to_string(), global: true, own: None };
970 assert!(consume_new_output(&source, &mut st));
974 assert!(st.global);
975 assert!(st.recent_files.is_empty(), "{:?}", st.recent_files.iter().map(|f| &f.path).collect::<Vec<_>>());
976 assert_eq!(st.next_offset, global.stat(zone, "output").unwrap().unwrap().size);
977 global
979 .append_data(zone, "output", format!("{}\n", edit_call("g2", "Edit", "file_path", "/r/zone2.rs")).as_bytes())
980 .unwrap();
981 assert!(consume_new_output(&source, &mut st));
982 let paths: Vec<&str> = st.recent_files.iter().map(|f| f.path.as_str()).collect();
983 assert_eq!(paths, vec!["/r/zone2.rs"]);
984 }
985
986 fn edit_call(id: &str, tool: &str, key: &str, path: &str) -> String {
987 format!(
988 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"{tool}","input":{{"{key}":"{path}","old_string":"a","new_string":"b"}}}}]}}}}"#
989 )
990 }
991
992 #[test]
995 fn edit_tools_fill_recent_files_newest_first() {
996 let mut st = BlockState::default();
997 feed_at(
998 &mut st,
999 &[
1000 edit_call("e1", "Edit", "file_path", "C:/r/a.rs"),
1001 tool_result("e1"),
1002 edit_call("e2", "Write", "file_path", "C:/r/b.rs"),
1003 edit_call("e3", "MultiEdit", "file_path", "C:/r/c.rs"),
1004 ],
1005 10,
1006 );
1007 feed_at(&mut st, &[edit_call("e4", "NotebookEdit", "notebook_path", "C:/r/n.ipynb")], 20);
1008 let got: Vec<(&str, &str, u64)> =
1009 st.recent_files.iter().map(|f| (f.path.as_str(), f.tool.as_str(), f.ts_ms)).collect();
1010 assert_eq!(
1011 got,
1012 vec![
1013 ("C:/r/n.ipynb", "NotebookEdit", 20),
1014 ("C:/r/c.rs", "MultiEdit", 10),
1015 ("C:/r/b.rs", "Write", 10),
1016 ("C:/r/a.rs", "Edit", 10),
1017 ]
1018 );
1019 assert!(st.progress().todos.is_empty());
1021 assert_eq!(st.progress().current_tool.as_deref(), Some("Write"));
1022 }
1023
1024 #[test]
1025 fn editing_a_file_again_moves_it_to_the_front_without_duplicating_it() {
1026 let mut st = BlockState::default();
1027 feed_at(&mut st, &[edit_call("e1", "Edit", "file_path", "/r/a.rs")], 1);
1028 feed_at(&mut st, &[edit_call("e2", "Edit", "file_path", "/r/b.rs")], 2);
1029 feed_at(&mut st, &[edit_call("e3", "Write", "file_path", "/r/a.rs")], 3);
1030 let got: Vec<(&str, u64)> = st.recent_files.iter().map(|f| (f.path.as_str(), f.ts_ms)).collect();
1031 assert_eq!(got, vec![("/r/a.rs", 3), ("/r/b.rs", 2)]);
1032 assert_eq!(st.recent_files[0].tool, "Write");
1033 }
1034
1035 #[test]
1036 fn recent_files_stay_bounded() {
1037 let mut st = BlockState::default();
1038 let calls: Vec<String> = (0..MAX_RECENT_FILES + 7)
1039 .map(|i| edit_call(&format!("e{i}"), "Edit", "file_path", &format!("/r/f{i}.rs")))
1040 .collect();
1041 feed(&mut st, &calls);
1042 assert_eq!(st.recent_files.len(), MAX_RECENT_FILES);
1043 assert_eq!(st.recent_files[0].path, format!("/r/f{}.rs", MAX_RECENT_FILES + 6));
1044 }
1045
1046 #[test]
1047 fn reads_and_other_tools_add_no_recent_files() {
1048 let mut st = BlockState::default();
1049 feed(
1050 &mut st,
1051 &[
1052 edit_call("r1", "Read", "file_path", "/r/a.rs"),
1053 edit_call("g1", "Grep", "file_path", "/r/b.rs"),
1054 edit_call("w1", "Edit", "old_string", "no path"),
1055 ],
1056 );
1057 assert!(st.recent_files.is_empty());
1058 }
1059
1060 fn run(lines: &[String]) -> AgentProgress {
1061 let mut st = BlockState::default();
1062 feed(&mut st, lines);
1063 st.progress()
1064 }
1065
1066 #[test]
1067 fn extracts_a_todowrite_checklist() {
1068 let p = run(&[todo_write(
1069 "t1",
1070 r#"[{"content":"Fix the bug","status":"in_progress"},{"content":"Write tests","status":"pending"}]"#,
1071 )]);
1072 assert_eq!(
1073 p.todos,
1074 vec![
1075 TodoItem { text: "Fix the bug".into(), status: "in_progress".into() },
1076 TodoItem { text: "Write tests".into(), status: "pending".into() },
1077 ]
1078 );
1079 }
1080
1081 #[test]
1082 fn the_latest_full_list_supersedes_earlier_ones() {
1083 let p = run(&[
1084 todo_write("t1", r#"[{"content":"A","status":"pending"}, {"content":"B","status":"pending"}]"#),
1085 todo_write("t2", r#"[{"content":"A","status":"completed"}]"#),
1086 ]);
1087 assert_eq!(p.todos, vec![TodoItem { text: "A".into(), status: "completed".into() }]);
1088 }
1089
1090 #[test]
1091 fn task_style_calls_accumulate_and_update_in_place() {
1092 let p = run(&[
1093 task_call("c1", "TaskCreate", "k1", "First", "pending"),
1094 task_call("c2", "TaskCreate", "k2", "Second", "pending"),
1095 task_call("u1", "TaskUpdate", "k1", "First", "completed"),
1096 ]);
1097 assert_eq!(
1098 p.todos,
1099 vec![
1100 TodoItem { text: "First".into(), status: "completed".into() },
1101 TodoItem { text: "Second".into(), status: "pending".into() },
1102 ],
1103 "an update revises its own row and preserves creation order",
1104 );
1105 }
1106
1107 #[test]
1112 fn a_task_created_in_an_earlier_tick_survives_later_unrelated_output() {
1113 let mut st = BlockState::default();
1114 feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Long-lived task", "pending")]);
1115
1116 let noise: Vec<String> = (0..50).map(|i| tool_use(&format!("n{i}"), "Read")).collect();
1118 feed(&mut st, &noise);
1119
1120 assert_eq!(
1121 st.progress().todos,
1122 vec![TodoItem { text: "Long-lived task".into(), status: "pending".into() }],
1123 "the task is still open and must still be listed",
1124 );
1125 }
1126
1127 #[test]
1128 fn an_update_arriving_a_tick_later_still_finds_its_row() {
1129 let mut st = BlockState::default();
1130 feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Task", "pending")]);
1131 feed(&mut st, &[tool_use("n1", "Bash"), tool_result("n1")]);
1132 feed(&mut st, &[task_call("u1", "TaskUpdate", "k1", "Task", "completed")]);
1133
1134 assert_eq!(st.progress().todos, vec![TodoItem { text: "Task".into(), status: "completed".into() }]);
1135 }
1136
1137 #[test]
1138 fn current_tool_is_the_outstanding_tool_use() {
1139 let p = run(&[tool_use("a", "Read"), tool_result("a"), tool_use("b", "Bash")]);
1140 assert_eq!(p.current_tool.as_deref(), Some("Bash"));
1141 }
1142
1143 #[test]
1144 fn no_current_tool_once_every_call_has_returned() {
1145 let p = run(&[tool_use("a", "Read"), tool_result("a")]);
1146 assert_eq!(p.current_tool, None);
1147 }
1148
1149 #[test]
1152 fn a_result_in_a_later_tick_clears_the_call_from_an_earlier_one() {
1153 let mut st = BlockState::default();
1154 feed(&mut st, &[tool_use("a", "Bash")]);
1155 assert_eq!(st.progress().current_tool.as_deref(), Some("Bash"));
1156 feed(&mut st, &[tool_result("a")]);
1157 assert_eq!(st.progress().current_tool, None);
1158 }
1159
1160 #[test]
1161 fn an_explicitly_cleared_checklist_reads_as_empty() {
1162 let p = run(&[
1163 todo_write("t1", r#"[{"content":"A","status":"pending"}]"#),
1164 todo_write("t2", "[]"),
1165 ]);
1166 assert!(p.todos.is_empty());
1167 }
1168
1169 #[test]
1170 fn truncates_a_pathological_list_and_reports_how_many_were_dropped() {
1171 let entries: Vec<String> = (0..MAX_TODOS + 5)
1172 .map(|i| format!(r#"{{"content":"item {i}","status":"pending"}}"#))
1173 .collect();
1174 let p = run(&[todo_write("t1", &format!("[{}]", entries.join(",")))]);
1175 assert_eq!(p.todos.len(), MAX_TODOS);
1176 assert_eq!(p.todos_truncated, 5);
1177 }
1178
1179 #[test]
1182 fn a_tail_seeded_block_reports_its_checklist_as_partial() {
1183 let mut st = BlockState { partial: true, ..Default::default() };
1184 feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Only what we saw", "pending")]);
1185 let p = st.progress();
1186 assert!(p.todos_partial, "item-at-a-time rows may be missing earlier entries");
1187 assert_eq!(p.todos_truncated, 0, "nothing was dropped by the cap");
1188 }
1189
1190 #[test]
1193 fn a_full_list_call_clears_the_partial_flag() {
1194 let mut st = BlockState { partial: true, ..Default::default() };
1195 feed(&mut st, &[todo_write("t1", r#"[{"content":"Whole list","status":"pending"}]"#)]);
1196 assert!(!st.progress().todos_partial);
1197 }
1198
1199 #[test]
1200 fn ignores_malformed_lines_instead_of_giving_up_on_the_whole_batch() {
1201 let p = run(&[
1202 "not json at all".to_string(),
1203 String::new(),
1204 todo_write("t1", r#"[{"content":"Survives","status":"pending"}]"#),
1205 ]);
1206 assert_eq!(p.todos.len(), 1);
1207 }
1208
1209 #[test]
1210 fn a_non_todo_tool_never_contributes_checklist_rows() {
1211 let p = run(&[tool_use("a", "Read"), tool_use("b", "Bash")]);
1212 assert!(p.todos.is_empty());
1213 }
1214
1215 #[test]
1216 fn recognizes_todo_tools_by_name_across_provider_vocabularies() {
1217 assert!(is_todo_tool("TodoWrite"));
1218 assert!(is_todo_tool("TaskCreate"));
1219 assert!(is_todo_tool("TaskUpdate"));
1220 assert!(is_todo_tool("mcp__planner__TodoSync"));
1222 assert!(!is_todo_tool("Read"));
1223 assert!(!is_todo_tool("Task"), "the subagent-spawning Task tool is not a checklist");
1224 }
1225
1226 #[test]
1230 fn read_style_task_tools_are_not_claimed_as_supported() {
1231 assert!(
1232 !TODO_TOOL_NAMES.contains(&"TaskList"),
1233 "TaskList's tasks live in its tool_result, not its input",
1234 );
1235 assert!(parse_todo_array(&serde_json::json!({})).is_none());
1239 }
1240
1241 #[test]
1242 fn the_open_tool_list_stays_bounded_when_results_go_missing() {
1243 let mut st = BlockState::default();
1244 let calls: Vec<String> = (0..MAX_OPEN_TOOLS + 20)
1245 .map(|i| tool_use(&format!("t{i}"), "Read"))
1246 .collect();
1247 feed(&mut st, &calls);
1248 assert_eq!(st.open.len(), MAX_OPEN_TOOLS);
1249 }
1250
1251 #[test]
1255 fn a_status_only_update_moves_the_row_without_resending_its_text() {
1256 let mut st = BlockState::default();
1257 feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Ship it", "pending")]);
1258 feed(
1259 &mut st,
1260 &[format!(
1261 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"task_id":"k1","status":"completed"}}}}]}}}}"#
1262 )],
1263 );
1264 assert_eq!(
1265 st.progress().todos,
1266 vec![TodoItem { text: "Ship it".into(), status: "completed".into() }],
1267 "text is preserved from the create, status taken from the update",
1268 );
1269 }
1270
1271 #[test]
1273 fn a_text_only_update_preserves_the_existing_status() {
1274 let mut st = BlockState::default();
1275 feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Old wording", "in_progress")]);
1276 feed(
1277 &mut st,
1278 &[format!(
1279 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"task_id":"k1","title":"New wording"}}}}]}}}}"#
1280 )],
1281 );
1282 assert_eq!(
1283 st.progress().todos,
1284 vec![TodoItem { text: "New wording".into(), status: "in_progress".into() }],
1285 );
1286 }
1287
1288 #[test]
1291 fn a_status_only_update_for_an_unknown_task_creates_no_row() {
1292 let mut st = BlockState::default();
1293 feed(
1294 &mut st,
1295 &[format!(
1296 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"task_id":"ghost","status":"completed"}}}}]}}}}"#
1297 )],
1298 );
1299 assert!(st.progress().todos.is_empty());
1300 }
1301
1302 #[test]
1306 fn parses_provider_native_top_level_tool_frames() {
1307 let mut st = BlockState::default();
1308 feed(
1309 &mut st,
1310 &[r#"{"type":"tool_use","tool_name":"Bash","tool_id":"g1","parameters":{}}"#.to_string()],
1311 );
1312 assert_eq!(st.progress().current_tool.as_deref(), Some("Bash"));
1313
1314 feed(
1315 &mut st,
1316 &[r#"{"type":"tool_result","tool_id":"g1","status":"success"}"#.to_string()],
1317 );
1318 assert_eq!(st.progress().current_tool, None, "a tool_id result clears its call");
1319 }
1320
1321 #[test]
1322 fn parses_a_todo_checklist_from_a_top_level_frame() {
1323 let mut st = BlockState::default();
1324 feed(
1325 &mut st,
1326 &[r#"{"type":"tool_use","tool_name":"TodoWrite","tool_id":"g2","parameters":{"todos":[{"content":"From Gemini","status":"pending"}]}}"#.to_string()],
1327 );
1328 assert_eq!(
1329 st.progress().todos,
1330 vec![TodoItem { text: "From Gemini".into(), status: "pending".into() }],
1331 );
1332 }
1333
1334 #[test]
1336 fn a_plain_line_is_not_treated_as_a_tool_frame() {
1337 let mut st = BlockState::default();
1338 feed(&mut st, &[r#"{"type":"system","subtype":"init","name":"TodoWrite"}"#.to_string()]);
1339 assert!(st.progress().todos.is_empty());
1340 assert_eq!(st.progress().current_tool, None);
1341 }
1342
1343 #[test]
1348 fn two_idless_creates_with_the_same_title_stay_two_rows() {
1349 let idless_create = |id: &str, title: &str| {
1350 format!(
1351 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"TaskCreate","input":{{"title":"{title}","status":"pending"}}}}]}}}}"#
1352 )
1353 };
1354 let p = run(&[idless_create("c1", "Retry the flaky step"), idless_create("c2", "Retry the flaky step")]);
1355 assert_eq!(p.todos.len(), 2, "two distinct tasks must not collapse into one row");
1356 assert!(p.todos.iter().all(|t| t.text == "Retry the flaky step"));
1357 }
1358
1359 #[test]
1362 fn an_idless_update_still_matches_its_row_by_text() {
1363 let mut st = BlockState::default();
1364 feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Ship it", "pending")]);
1365 feed(
1366 &mut st,
1367 &[format!(
1368 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"title":"Ship it","status":"completed"}}}}]}}}}"#
1369 )],
1370 );
1371 assert_eq!(
1372 st.progress().todos,
1373 vec![TodoItem { text: "Ship it".into(), status: "completed".into() }],
1374 );
1375 }
1376
1377 #[test]
1380 fn ids_take_precedence_over_text_for_identity() {
1381 let p = run(&[
1382 task_call("c1", "TaskCreate", "k1", "Same title", "pending"),
1383 task_call("c2", "TaskCreate", "k2", "Same title", "pending"),
1384 task_call("u1", "TaskUpdate", "k2", "Same title", "completed"),
1385 ]);
1386 assert_eq!(
1387 p.todos,
1388 vec![
1389 TodoItem { text: "Same title".into(), status: "pending".into() },
1390 TodoItem { text: "Same title".into(), status: "completed".into() },
1391 ],
1392 );
1393 }
1394
1395 #[test]
1396 fn create_style_tool_names_are_recognized() {
1397 assert!(is_create_call("TaskCreate"));
1398 assert!(is_create_call("TodoAdd"));
1399 assert!(!is_create_call("TaskUpdate"));
1400 assert!(!is_create_call("TodoWrite"), "a whole-list write never reaches the single-item path");
1401 }
1402
1403 #[test]
1404 fn empty_progress_is_recognized_so_idle_agents_publish_nothing() {
1405 assert!(AgentProgress::default().is_empty());
1406 let p = run(&[tool_use("a", "Read")]);
1407 assert!(!p.is_empty(), "an in-flight tool is worth publishing on its own");
1408 }
1409
1410 #[test]
1411 fn a_pr_create_is_recognized_in_any_shell_command() {
1412 assert!(is_pr_create("gh-agent pr create --title x --body y"));
1413 assert!(is_pr_create("cd /w/agentmux && gh pr create --fill"));
1414 assert!(is_pr_create("/usr/local/bin/gh-agent pr create -t x"));
1415 assert!(is_pr_create("C:\\npm\\gh-agent.cmd pr create -t x"));
1416 assert!(!is_pr_create("gh-agent pr view 12"));
1417 assert!(!is_pr_create("echo gh pr list; grep create"));
1418 assert!(!is_pr_create("git commit -m 'gh-agent pr: create'"));
1419 assert!(is_shell_tool("Bash") && is_shell_tool("mcp__agentmux__Terminal") && !is_shell_tool("Edit"));
1420 assert!(is_pr_create("pwsh.exe -NoProfile -Command 'gh-agent pr create -t x'"));
1421 }
1422
1423 #[test]
1426 fn a_pr_create_with_flags_and_its_head_and_base() {
1427 assert!(is_pr_create("gh --repo owner/repo pr create -t x"));
1428 assert!(is_pr_create("gh pr -R owner/repo create -t x"));
1429 assert!(!is_pr_create("gh --repo pr view create"), "the value of --repo is not a word");
1430 assert!(!is_pr_create("gh pr view 1 && echo create"));
1431 let pr = |c: &str| pr_create(c).unwrap();
1432 assert_eq!(pr("gh-agent pr create -H agenty/x -B release"), NewPrCommand {
1433 head: Some("agenty/x".into()),
1434 base: Some("release".into())
1435 });
1436 assert_eq!(pr("gh pr create --head=me:feature --title t").head.as_deref(), Some("me:feature"));
1437 assert_eq!(pr("gh pr create -t x && git push --base y"), NewPrCommand::default(), "flags of the next command are not its");
1438 }
1439
1440 #[test]
1443 fn a_codex_pr_create_is_handed_to_the_overlap_note() {
1444 let started = r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"pwsh.exe -NoProfile -Command 'gh-agent pr create -t x'","aggregated_output":"","exit_code":null,"status":"in_progress"}}"#;
1445 let completed = started.replace("item.started", "item.completed");
1446 let mut st = BlockState::default();
1447 apply_lines(&mut st, &[started, completed.as_str()], Some(1_000));
1448 assert_eq!(st.new_prs.len(), 1, "the start counts, its completion does not");
1449 }
1450
1451 #[test]
1452 fn only_a_live_pr_create_is_handed_to_the_overlap_note() {
1453 let line = |cmd: &str| format!(
1454 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"p1","name":"Bash","input":{{"command":"{cmd}"}}}}]}}}}"#
1455 );
1456 let mut backlog = BlockState::default();
1457 apply_lines(&mut backlog, &[line("gh-agent pr create -t x").as_str()], None);
1458 assert!(backlog.new_prs.is_empty(), "backlog is history");
1459 let mut live = BlockState::default();
1460 apply_lines(&mut live, &[line("gh-agent pr create -t x").as_str(), line("ls").as_str()], Some(1_000));
1461 assert_eq!(live.new_prs, vec![NewPrCommand::default()]);
1462 assert_eq!(live.open.len(), 2, "both calls still count as in flight");
1463 }
1464}