| 1 | use std::collections::{BTreeSet, HashMap, HashSet}; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use codewhale_localization::{Locale, MessageId, tr}; |
| 5 | |
| 6 | use super::{HistoryCell, SubAgentCell, ToolCell, ToolStatus}; |
| 7 | use crate::tui::widgets::agent_card::AgentLifecycle; |
| 8 | |
| 9 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 10 | pub struct TurnFold { |
| 11 | pub key: usize, |
| 12 | pub members: Vec<usize>, |
| 13 | pub failed: usize, |
| 14 | pub files: usize, |
| 15 | pub added: Option<usize>, |
| 16 | pub deleted: Option<usize>, |
| 17 | pub duration: Option<Duration>, |
| 18 | } |
| 19 | |
| 20 | impl TurnFold { |
| 21 | #[must_use] |
| 22 | pub fn contains(&self, index: usize) -> bool { |
| 23 | self.members.binary_search(&index).is_ok() |
| 24 | } |
| 25 | |
| 26 | #[must_use] |
| 27 | pub fn host(&self) -> Option<usize> { |
| 28 | self.members.first().copied() |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Default, Clone, PartialEq, Eq)] |
| 33 | pub struct TurnFoldProjection { |
| 34 | pub turns: Vec<TurnFold>, |
| 35 | pub agents: Vec<usize>, |
| 36 | } |
| 37 | |
| 38 | impl TurnFoldProjection { |
| 39 | #[must_use] |
| 40 | pub fn turn_containing(&self, index: usize) -> Option<&TurnFold> { |
| 41 | self.turns.iter().find(|turn| turn.contains(index)) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[derive(Default)] |
| 46 | struct OpenTurn { |
| 47 | key: usize, |
| 48 | members: Vec<usize>, |
| 49 | agents: Vec<usize>, |
| 50 | failed: usize, |
| 51 | paths: BTreeSet<String>, |
| 52 | repeated_file: bool, |
| 53 | added: usize, |
| 54 | deleted: usize, |
| 55 | live: bool, |
| 56 | } |
| 57 | |
| 58 | pub(crate) fn superseded_todo_write_indices( |
| 59 | history: &[HistoryCell], |
| 60 | active_entries: &[HistoryCell], |
| 61 | ) -> HashSet<usize> { |
| 62 | let mut hidden = HashSet::new(); |
| 63 | let mut latest = None; |
| 64 | |
| 65 | for (index, cell) in history.iter().chain(active_entries).enumerate() { |
| 66 | let HistoryCell::Tool(ToolCell::Generic(tool)) = cell else { |
| 67 | continue; |
| 68 | }; |
| 69 | if tool.name != "todo_write" || tool.status != ToolStatus::Success { |
| 70 | continue; |
| 71 | } |
| 72 | |
| 73 | if let Some(previous) = latest.replace(index) { |
| 74 | hidden.insert(previous); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | if let Some(index) = latest { |
| 79 | let cell = history |
| 80 | .get(index) |
| 81 | .or_else(|| active_entries.get(index.saturating_sub(history.len()))); |
| 82 | if cell.is_some_and(todo_write_snapshot_is_empty) { |
| 83 | hidden.insert(index); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | hidden |
| 88 | } |
| 89 | |
| 90 | fn todo_write_snapshot_is_empty(cell: &HistoryCell) -> bool { |
| 91 | let HistoryCell::Tool(ToolCell::Generic(tool)) = cell else { |
| 92 | return false; |
| 93 | }; |
| 94 | let Some(output) = tool.output.as_deref() else { |
| 95 | return false; |
| 96 | }; |
| 97 | let Some(json_start) = output.find('{') else { |
| 98 | return false; |
| 99 | }; |
| 100 | let Ok(value) = serde_json::from_str::<serde_json::Value>(&output[json_start..]) else { |
| 101 | return false; |
| 102 | }; |
| 103 | value |
| 104 | .get("items") |
| 105 | .and_then(serde_json::Value::as_array) |
| 106 | .is_some_and(Vec::is_empty) |
| 107 | } |
| 108 | |
| 109 | fn infer_open_turn_user_index( |
| 110 | history: &[HistoryCell], |
| 111 | active_entries: &[HistoryCell], |
| 112 | echoed_queued_users: usize, |
| 113 | ) -> Option<usize> { |
| 114 | let total = history.len().saturating_add(active_entries.len()); |
| 115 | let users: Vec<usize> = (0..total) |
| 116 | .filter(|&idx| { |
| 117 | history |
| 118 | .get(idx) |
| 119 | .or_else(|| active_entries.get(idx - history.len())) |
| 120 | .is_some_and(|cell| matches!(cell, HistoryCell::User { .. })) |
| 121 | }) |
| 122 | .collect(); |
| 123 | if echoed_queued_users > 0 && users.len() > echoed_queued_users { |
| 124 | return Some(users[users.len() - 1 - echoed_queued_users]); |
| 125 | } |
| 126 | let &last_user = users.last()?; |
| 127 | if last_user + 1 == total && users.len() >= 2 { |
| 128 | let prev_user = users[users.len() - 2]; |
| 129 | let slice = (prev_user + 1)..last_user; |
| 130 | let has_work = slice.clone().any(|idx| { |
| 131 | history |
| 132 | .get(idx) |
| 133 | .is_some_and(|cell| !matches!(cell, HistoryCell::User { .. })) |
| 134 | }); |
| 135 | let has_assistant = slice.into_iter().any(|idx| { |
| 136 | history |
| 137 | .get(idx) |
| 138 | .is_some_and(|cell| matches!(cell, HistoryCell::Assistant { .. })) |
| 139 | }); |
| 140 | if has_work && !has_assistant { |
| 141 | return Some(prev_user); |
| 142 | } |
| 143 | } |
| 144 | Some(last_user) |
| 145 | } |
| 146 | |
| 147 | #[allow(clippy::too_many_arguments)] |
| 148 | #[must_use] |
| 149 | pub fn detect_turn_folds( |
| 150 | history: &[HistoryCell], |
| 151 | active_entries: &[HistoryCell], |
| 152 | open_tail: bool, |
| 153 | open_turn_user_index: Option<usize>, |
| 154 | echoed_queued_users: usize, |
| 155 | superseded_todos: &HashSet<usize>, |
| 156 | durations: &HashMap<usize, Duration>, |
| 157 | ) -> TurnFoldProjection { |
| 158 | let mut projection = TurnFoldProjection::default(); |
| 159 | let open_from = if !open_tail { |
| 160 | None |
| 161 | } else if open_turn_user_index.is_some() { |
| 162 | open_turn_user_index |
| 163 | } else { |
| 164 | infer_open_turn_user_index(history, active_entries, echoed_queued_users) |
| 165 | }; |
| 166 | let mut current: Option<OpenTurn> = None; |
| 167 | let total = history.len().saturating_add(active_entries.len()); |
| 168 | for index in 0..total { |
| 169 | let cell = history |
| 170 | .get(index) |
| 171 | .or_else(|| active_entries.get(index - history.len())); |
| 172 | let Some(cell) = cell else { continue }; |
| 173 | if matches!(cell, HistoryCell::User { .. }) { |
| 174 | if let Some(turn) = current.take() { |
| 175 | close_turn(turn, open_from, durations, &mut projection); |
| 176 | } |
| 177 | current = Some(OpenTurn { |
| 178 | key: index, |
| 179 | ..OpenTurn::default() |
| 180 | }); |
| 181 | continue; |
| 182 | } |
| 183 | let Some(turn) = current.as_mut() else { |
| 184 | continue; |
| 185 | }; |
| 186 | if superseded_todos.contains(&index) { |
| 187 | continue; |
| 188 | } |
| 189 | match cell { |
| 190 | HistoryCell::Tool(tool) if tool.is_running() => turn.live = true, |
| 191 | HistoryCell::Tool(tool) if tool.is_failed() => turn.failed += 1, |
| 192 | HistoryCell::Tool(tool) |
| 193 | if matches!( |
| 194 | tool.status(), |
| 195 | Some(ToolStatus::Warning | ToolStatus::Stopped) |
| 196 | ) => {} |
| 197 | HistoryCell::Tool(ToolCell::PatchSummary(patch)) => { |
| 198 | if let Some(receipt) = patch.receipt.as_ref() { |
| 199 | for file in &receipt.files { |
| 200 | if !turn.paths.insert(file.path.clone()) { |
| 201 | turn.repeated_file = true; |
| 202 | } |
| 203 | } |
| 204 | turn.added += receipt.added; |
| 205 | turn.deleted += receipt.deleted; |
| 206 | } |
| 207 | turn.members.push(index); |
| 208 | } |
| 209 | HistoryCell::Tool(tool) if tool.is_collapsible_guard() => {} |
| 210 | HistoryCell::Tool(_) => { |
| 211 | turn.members.push(index); |
| 212 | } |
| 213 | HistoryCell::SubAgent(agent) => { |
| 214 | if !sub_agent_settled(agent) { |
| 215 | turn.live = true; |
| 216 | } else if !sub_agent_attention(agent) { |
| 217 | turn.agents.push(index); |
| 218 | } |
| 219 | } |
| 220 | _ => {} |
| 221 | } |
| 222 | } |
| 223 | if let Some(turn) = current.take() { |
| 224 | close_turn(turn, open_from, durations, &mut projection); |
| 225 | } |
| 226 | projection |
| 227 | } |
| 228 | |
| 229 | fn close_turn( |
| 230 | turn: OpenTurn, |
| 231 | open_from: Option<usize>, |
| 232 | durations: &HashMap<usize, Duration>, |
| 233 | projection: &mut TurnFoldProjection, |
| 234 | ) { |
| 235 | if turn.live || open_from.is_some_and(|open| turn.key >= open) { |
| 236 | return; |
| 237 | } |
| 238 | projection.agents.extend(turn.agents); |
| 239 | if turn.members.is_empty() { |
| 240 | return; |
| 241 | } |
| 242 | projection.turns.push(TurnFold { |
| 243 | key: turn.key, |
| 244 | members: turn.members, |
| 245 | failed: turn.failed, |
| 246 | files: turn.paths.len(), |
| 247 | added: (!turn.repeated_file).then_some(turn.added), |
| 248 | deleted: (!turn.repeated_file).then_some(turn.deleted), |
| 249 | duration: durations.get(&turn.key).copied(), |
| 250 | }); |
| 251 | } |
| 252 | |
| 253 | fn sub_agent_settled(agent: &SubAgentCell) -> bool { |
| 254 | match agent { |
| 255 | SubAgentCell::Delegate(card) => card.status.is_terminal(), |
| 256 | SubAgentCell::Fanout(card) => card.aggregate_status_public().is_terminal(), |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | fn sub_agent_attention(agent: &SubAgentCell) -> bool { |
| 261 | let status = match agent { |
| 262 | SubAgentCell::Delegate(card) => card.status, |
| 263 | SubAgentCell::Fanout(card) => card.aggregate_status_public(), |
| 264 | }; |
| 265 | matches!(status, AgentLifecycle::Failed | AgentLifecycle::Interrupted) |
| 266 | } |
| 267 | |
| 268 | #[must_use] |
| 269 | pub fn turn_fold_headline(fold: &TurnFold, locale: Locale) -> String { |
| 270 | let steps = super::tool_run::counted( |
| 271 | fold.members.len(), |
| 272 | locale, |
| 273 | MessageId::TurnStepOne, |
| 274 | MessageId::TurnStepMany, |
| 275 | ); |
| 276 | let mut parts = Vec::new(); |
| 277 | if let Some(duration) = fold.duration.filter(|duration| duration.as_secs() > 0) { |
| 278 | parts.push(tr(locale, MessageId::TurnWorkedFor).replace( |
| 279 | "{duration}", |
| 280 | &codewhale_command_contract::elapsed::format_elapsed_secs(duration.as_secs()), |
| 281 | )); |
| 282 | } |
| 283 | parts.push(steps); |
| 284 | if fold.failed > 0 { |
| 285 | parts.push( |
| 286 | tr(locale, MessageId::WorkflowCountFailed).replace("{count}", &fold.failed.to_string()), |
| 287 | ); |
| 288 | } |
| 289 | super::tool_run::sentence_case_activity(parts.join(" \u{00B7} ")) |
| 290 | } |
| 291 | |
| 292 | #[must_use] |
| 293 | pub fn turn_fold_changes(fold: &TurnFold, locale: Locale) -> Option<String> { |
| 294 | turn_fold_changes_in(fold, locale, false) |
| 295 | } |
| 296 | |
| 297 | #[must_use] |
| 298 | pub fn turn_fold_changes_in(fold: &TurnFold, locale: Locale, ascii_safe: bool) -> Option<String> { |
| 299 | (fold.files > 0).then(|| { |
| 300 | let files = super::tool_run::counted( |
| 301 | fold.files, |
| 302 | locale, |
| 303 | MessageId::TurnFileChangedOne, |
| 304 | MessageId::BackgroundFilesChanged, |
| 305 | ); |
| 306 | match (fold.added, fold.deleted) { |
| 307 | (Some(added), Some(deleted)) => { |
| 308 | let minus = if ascii_safe { "-" } else { "\u{2212}" }; |
| 309 | format!("{files} +{added} {minus}{deleted}") |
| 310 | } |
| 311 | _ => files, |
| 312 | } |
| 313 | }) |
| 314 | } |
| 315 | |
| 316 | #[must_use] |
| 317 | pub fn turn_fold_diff(fold: &TurnFold, cells: impl Fn(usize) -> Option<HistoryCell>) -> String { |
| 318 | let mut diff = String::new(); |
| 319 | for &index in &fold.members { |
| 320 | if let Some(HistoryCell::Tool(ToolCell::PatchSummary(patch))) = cells(index) |
| 321 | && let Some(receipt) = patch.receipt.as_ref() |
| 322 | { |
| 323 | diff.push_str(&receipt.display_diff); |
| 324 | if !diff.ends_with('\n') { |
| 325 | diff.push('\n'); |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | diff |
| 330 | } |
| 331 | |
| 332 | #[cfg(test)] |
| 333 | mod tests { |
| 334 | use super::*; |
| 335 | use crate::tui::history::file_mutation::{ |
| 336 | FileMutationFile, FileMutationOutcome, FileMutationReceipt, |
| 337 | }; |
| 338 | use crate::tui::history::{PatchSummaryCell, ToolCell}; |
| 339 | |
| 340 | fn patch_cell(path: &str, added: usize, deleted: usize) -> HistoryCell { |
| 341 | HistoryCell::Tool(ToolCell::PatchSummary(PatchSummaryCell { |
| 342 | path: path.to_string(), |
| 343 | summary: String::new(), |
| 344 | status: ToolStatus::Success, |
| 345 | error: None, |
| 346 | receipt: Some(FileMutationReceipt { |
| 347 | exact_diff: String::new(), |
| 348 | display_diff: String::new(), |
| 349 | files: vec![FileMutationFile { |
| 350 | path: path.to_string(), |
| 351 | previous_path: None, |
| 352 | outcome: FileMutationOutcome::Updated, |
| 353 | }], |
| 354 | added, |
| 355 | deleted, |
| 356 | }), |
| 357 | })) |
| 358 | } |
| 359 | |
| 360 | #[test] |
| 361 | fn turn_fold_changes_uses_typographic_minus_and_ascii_fallback() { |
| 362 | let fold = TurnFold { |
| 363 | key: 0, |
| 364 | members: vec![1], |
| 365 | failed: 0, |
| 366 | files: 2, |
| 367 | added: Some(10), |
| 368 | deleted: Some(3), |
| 369 | duration: None, |
| 370 | }; |
| 371 | assert_eq!( |
| 372 | turn_fold_changes(&fold, Locale::En).as_deref(), |
| 373 | Some("2 files changed +10 \u{2212}3") |
| 374 | ); |
| 375 | assert_eq!( |
| 376 | turn_fold_changes_in(&fold, Locale::En, true).as_deref(), |
| 377 | Some("2 files changed +10 -3") |
| 378 | ); |
| 379 | } |
| 380 | |
| 381 | #[test] |
| 382 | fn repeated_edits_to_same_file_clear_ambiguous_line_counts() { |
| 383 | let history = vec![ |
| 384 | HistoryCell::User { |
| 385 | content: "edit".to_string(), |
| 386 | }, |
| 387 | patch_cell("src/a.rs", 5, 2), |
| 388 | patch_cell("src/a.rs", 3, 1), |
| 389 | ]; |
| 390 | let projection = detect_turn_folds( |
| 391 | &history, |
| 392 | &[], |
| 393 | false, |
| 394 | None, |
| 395 | 0, |
| 396 | &HashSet::new(), |
| 397 | &HashMap::new(), |
| 398 | ); |
| 399 | assert_eq!(projection.turns.len(), 1); |
| 400 | let fold = &projection.turns[0]; |
| 401 | assert_eq!(fold.files, 1); |
| 402 | assert_eq!(fold.added, None); |
| 403 | assert_eq!(fold.deleted, None); |
| 404 | assert_eq!( |
| 405 | turn_fold_changes(fold, Locale::En).as_deref(), |
| 406 | Some("1 file changed") |
| 407 | ); |
| 408 | } |
| 409 | } |
| 410 |