| 1 | use super::*; |
| 2 | |
| 3 | fn tool_use(id: &str, name: &str, input: Value) -> ContentBlock { |
| 4 | ContentBlock::ToolUse { |
| 5 | id: id.to_string(), |
| 6 | name: name.to_string(), |
| 7 | input, |
| 8 | execution_id: None, |
| 9 | caller: None, |
| 10 | thought_signature: None, |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | fn tool_result(id: &str, content: &str, is_error: bool) -> ContentBlock { |
| 15 | ContentBlock::ToolResult { |
| 16 | tool_use_id: id.to_string(), |
| 17 | content: content.to_string(), |
| 18 | execution_id: None, |
| 19 | is_error: is_error.then_some(true), |
| 20 | content_blocks: None, |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | fn assistant(blocks: Vec<ContentBlock>) -> Message { |
| 25 | Message { |
| 26 | role: Role::Assistant, |
| 27 | content: blocks, |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | fn user(blocks: Vec<ContentBlock>) -> Message { |
| 32 | Message { |
| 33 | role: Role::User, |
| 34 | content: blocks, |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | fn manager_with_running_child( |
| 39 | root: &std::path::Path, |
| 40 | name: &str, |
| 41 | ) -> (SharedSubAgentManager, String) { |
| 42 | let mut inner = SubAgentManager::new(root.to_path_buf(), 4); |
| 43 | let agent_id = insert_running_agent(&mut inner, name); |
| 44 | inner.register_worker_for_session( |
| 45 | make_worker_spec(&agent_id, root.to_path_buf()), |
| 46 | "workspace", |
| 47 | None, |
| 48 | ); |
| 49 | (Arc::new(RwLock::new(inner)), agent_id) |
| 50 | } |
| 51 | |
| 52 | async fn peek( |
| 53 | manager: SharedSubAgentManager, |
| 54 | root: &std::path::Path, |
| 55 | agent_id: &str, |
| 56 | ) -> (ToolResult, Value) { |
| 57 | let context = ToolContext::new(root.to_path_buf()); |
| 58 | let result = inspect_agent_from_input( |
| 59 | &json!({"action": "peek", "agent_id": agent_id}), |
| 60 | manager, |
| 61 | &context, |
| 62 | true, |
| 63 | None, |
| 64 | ) |
| 65 | .await |
| 66 | .expect("peek never fails on transcript problems"); |
| 67 | let payload: Value = serde_json::from_str(&result.content).expect("peek json"); |
| 68 | (result, payload) |
| 69 | } |
| 70 | |
| 71 | #[tokio::test] |
| 72 | async fn peek_recent_activity_lists_tool_calls_with_previews_and_work_summary() { |
| 73 | let dir = tempdir().unwrap(); |
| 74 | let (manager, agent_id) = manager_with_running_child(dir.path(), "peek_activity_pairs"); |
| 75 | let long_output = "x".repeat(900); |
| 76 | let messages = vec![ |
| 77 | text_message("user", "fix the parser"), |
| 78 | assistant(vec![ |
| 79 | ContentBlock::Text { |
| 80 | text: "Looking around first.".into(), |
| 81 | cache_control: None, |
| 82 | }, |
| 83 | tool_use( |
| 84 | "c1", |
| 85 | "exec_shell", |
| 86 | json!({"command": "rg -n parse_header src"}), |
| 87 | ), |
| 88 | tool_use("c2", "read_file", json!({"path": "src/parser.rs"})), |
| 89 | ]), |
| 90 | user(vec![ |
| 91 | tool_result("c1", "src/parser.rs:12: fn parse_header", false), |
| 92 | tool_result("c2", &long_output, false), |
| 93 | ]), |
| 94 | assistant(vec![tool_use( |
| 95 | "c3", |
| 96 | "edit_file", |
| 97 | json!({"path": "src/parser.rs", "old": "a", "new": "b"}), |
| 98 | )]), |
| 99 | user(vec![tool_result("c3", "old text not found", true)]), |
| 100 | assistant(vec![ |
| 101 | tool_use( |
| 102 | "c4", |
| 103 | "write_file", |
| 104 | json!({"path": "src/new.rs", "content": "fn x() {}"}), |
| 105 | ), |
| 106 | tool_use("c5", "exec_shell", json!({"command": "cargo test parser"})), |
| 107 | ]), |
| 108 | user(vec![tool_result("c4", "wrote 9 bytes", false)]), |
| 109 | assistant(vec![ContentBlock::Text { |
| 110 | text: "Parser fixed; running tests now.".into(), |
| 111 | cache_control: None, |
| 112 | }]), |
| 113 | ]; |
| 114 | write_subagent_transcript_artifact_for_test(dir.path(), &agent_id, &messages) |
| 115 | .expect("write transcript"); |
| 116 | |
| 117 | let (result, payload) = peek(manager, dir.path(), &agent_id).await; |
| 118 | assert!(result.content.len() <= lifecycle::COMPACT_STATUS_BYTES); |
| 119 | assert!( |
| 120 | payload.get("recent_activity_unavailable").is_none(), |
| 121 | "{payload}" |
| 122 | ); |
| 123 | let activity = payload["recent_activity"] |
| 124 | .as_array() |
| 125 | .expect("activity array"); |
| 126 | let tools: Vec<&str> = activity |
| 127 | .iter() |
| 128 | .map(|e| e["tool"].as_str().unwrap()) |
| 129 | .collect(); |
| 130 | assert_eq!( |
| 131 | tools, |
| 132 | [ |
| 133 | "exec_shell", |
| 134 | "read_file", |
| 135 | "edit_file", |
| 136 | "write_file", |
| 137 | "exec_shell" |
| 138 | ] |
| 139 | ); |
| 140 | assert_eq!(activity[0]["input_preview"], "rg -n parse_header src"); |
| 141 | assert_eq!( |
| 142 | activity[0]["result_preview"], |
| 143 | "src/parser.rs:12: fn parse_header" |
| 144 | ); |
| 145 | assert_eq!(activity[0]["is_error"], false); |
| 146 | assert_eq!(activity[1]["input_preview"], r#"{"path":"src/parser.rs"}"#); |
| 147 | let long_preview = activity[1]["result_preview"].as_str().unwrap(); |
| 148 | assert!(long_preview.len() <= 200 && long_preview.ends_with("...")); |
| 149 | assert_eq!(activity[2]["is_error"], true); |
| 150 | assert_eq!(activity[2]["result_preview"], "old text not found"); |
| 151 | assert_eq!(activity[4]["input_preview"], "cargo test parser"); |
| 152 | assert_eq!(activity[4]["pending"], true); |
| 153 | assert!(activity[4]["result_preview"].is_null()); |
| 154 | assert_eq!( |
| 155 | payload["last_assistant_text"], |
| 156 | "Parser fixed; running tests now." |
| 157 | ); |
| 158 | let summary = &payload["work_summary"]; |
| 159 | assert_eq!(summary["tool_calls_total"], 5); |
| 160 | assert_eq!(summary["edit_calls"], 2); |
| 161 | assert_eq!(summary["tool_counts"]["exec_shell"], 2); |
| 162 | assert_eq!(summary["tool_counts"]["read_file"], 1); |
| 163 | assert_eq!(summary["tool_counts"]["edit_file"], 1); |
| 164 | assert_eq!(summary["tool_counts"]["write_file"], 1); |
| 165 | assert!(summary["last_activity_at"].is_string(), "{summary}"); |
| 166 | assert!(payload["recent_events"].is_array()); |
| 167 | } |
| 168 | |
| 169 | #[tokio::test] |
| 170 | async fn peek_recent_activity_keeps_only_the_newest_calls_within_the_byte_budget() { |
| 171 | let dir = tempdir().unwrap(); |
| 172 | let (manager, agent_id) = manager_with_running_child(dir.path(), "peek_activity_budget"); |
| 173 | { |
| 174 | let mut guard = manager.write().await; |
| 175 | let record = guard.worker_records.get_mut(&agent_id).unwrap(); |
| 176 | for i in 0..8_u64 { |
| 177 | record.events.push_back(AgentWorkerEvent { |
| 178 | seq: 100 + i, |
| 179 | worker_id: agent_id.clone(), |
| 180 | status: AgentWorkerStatus::RunningTool, |
| 181 | timestamp_ms: 1_700_000_000_000 + i, |
| 182 | message: Some("\"quoted\" ".repeat(40)), |
| 183 | step: Some(3), |
| 184 | tool_name: Some("grep_files".into()), |
| 185 | }); |
| 186 | } |
| 187 | } |
| 188 | let quoted = "\"\\".repeat(200); |
| 189 | let mut messages = vec![text_message("user", "search everything")]; |
| 190 | for i in 0..40 { |
| 191 | let id = format!("call-{i:02}"); |
| 192 | messages.push(assistant(vec![tool_use( |
| 193 | &id, |
| 194 | &format!("tool_{}_{}", i, "n".repeat(50)), |
| 195 | json!({"pattern": quoted, "index": i}), |
| 196 | )])); |
| 197 | messages.push(user(vec![tool_result(&id, "ed, false)])); |
| 198 | } |
| 199 | write_subagent_transcript_artifact_for_test(dir.path(), &agent_id, &messages) |
| 200 | .expect("write transcript"); |
| 201 | |
| 202 | let (result, payload) = peek(manager, dir.path(), &agent_id).await; |
| 203 | assert!( |
| 204 | result.content.len() <= lifecycle::COMPACT_STATUS_BYTES, |
| 205 | "peek is {} bytes", |
| 206 | result.content.len() |
| 207 | ); |
| 208 | let activity = payload["recent_activity"].as_array().expect("activity"); |
| 209 | let omitted = payload["recent_activity_omitted"] |
| 210 | .as_u64() |
| 211 | .expect("truncation is reported"); |
| 212 | assert!(omitted > 0); |
| 213 | assert!(payload["recent_activity_truncated"].is_string()); |
| 214 | assert_eq!( |
| 215 | activity.len() as u64 + omitted, |
| 216 | lifecycle::PEEK_RECENT_ACTIVITY_LIMIT as u64 |
| 217 | ); |
| 218 | let last = activity.last().expect("newest call kept"); |
| 219 | assert!( |
| 220 | last["tool"].as_str().unwrap().starts_with("tool_39_"), |
| 221 | "{last}" |
| 222 | ); |
| 223 | assert_eq!(payload["work_summary"]["tool_calls_total"], 40); |
| 224 | } |
| 225 | |
| 226 | #[tokio::test] |
| 227 | async fn peek_reports_missing_and_corrupt_transcripts_without_failing() { |
| 228 | let dir = tempdir().unwrap(); |
| 229 | let (manager, agent_id) = manager_with_running_child(dir.path(), "peek_activity_missing"); |
| 230 | let (_, payload) = peek(Arc::clone(&manager), dir.path(), &agent_id).await; |
| 231 | assert_eq!(payload["action"], "peek"); |
| 232 | assert_eq!(payload["recent_activity"], json!([])); |
| 233 | let reason = payload["recent_activity_unavailable"].as_str().unwrap(); |
| 234 | assert!(reason.starts_with("transcript_missing"), "{reason}"); |
| 235 | |
| 236 | let path = write_subagent_transcript_artifact_for_test( |
| 237 | dir.path(), |
| 238 | &agent_id, |
| 239 | &[text_message("user", "hello")], |
| 240 | ) |
| 241 | .expect("write transcript"); |
| 242 | std::fs::write(&path, "{not json\n").expect("corrupt transcript"); |
| 243 | let (_, payload) = peek(manager, dir.path(), &agent_id).await; |
| 244 | assert_eq!(payload["recent_activity"], json!([])); |
| 245 | let reason = payload["recent_activity_unavailable"].as_str().unwrap(); |
| 246 | assert!(reason.starts_with("transcript_unreadable"), "{reason}"); |
| 247 | assert!(payload.get("work_summary").is_none()); |
| 248 | } |
| 249 | |
| 250 | #[cfg(unix)] |
| 251 | #[tokio::test] |
| 252 | async fn peek_refuses_a_symlinked_transcript() { |
| 253 | use std::os::unix::fs::symlink; |
| 254 | |
| 255 | let dir = tempdir().unwrap(); |
| 256 | let (manager, agent_id) = manager_with_running_child(dir.path(), "peek_activity_symlink"); |
| 257 | let decoy = vec![ |
| 258 | text_message("user", "decoy"), |
| 259 | assistant(vec![tool_use( |
| 260 | "d1", |
| 261 | "exec_shell", |
| 262 | json!({"command": "leak"}), |
| 263 | )]), |
| 264 | ]; |
| 265 | let outside_root = tempdir().unwrap(); |
| 266 | let outside = |
| 267 | write_subagent_transcript_artifact_for_test(outside_root.path(), &agent_id, &decoy) |
| 268 | .expect("outside transcript"); |
| 269 | let path = write_subagent_transcript_artifact_for_test( |
| 270 | dir.path(), |
| 271 | &agent_id, |
| 272 | &[text_message("user", "real")], |
| 273 | ) |
| 274 | .expect("write transcript"); |
| 275 | std::fs::remove_file(&path).expect("remove transcript"); |
| 276 | symlink(&outside, &path).expect("symlink transcript"); |
| 277 | |
| 278 | let (_, payload) = peek(manager, dir.path(), &agent_id).await; |
| 279 | assert_eq!(payload["recent_activity"], json!([])); |
| 280 | let reason = payload["recent_activity_unavailable"].as_str().unwrap(); |
| 281 | assert!(reason.contains("must not traverse symlinks"), "{reason}"); |
| 282 | } |
| 283 |