| 1 | //! Task-panel and shell projection: task-panel refresh, shell live-output |
| 2 | //! reconciliation, detached-job projection, and RLM task entries |
| 3 | //! (docs/architecture/TUI_MODULARIZATION.md slice 5). Pure projection — no dispatch here. |
| 4 | |
| 5 | use super::*; |
| 6 | use crate::tui::automation_panel::AutomationScan; |
| 7 | use crate::tui::background_finished::{FinishedOutcome, FinishedWork, MAX_FINISHED_SHELLS}; |
| 8 | use codewhale_localization::{Locale, MessageId, tr}; |
| 9 | |
| 10 | pub(super) async fn refresh_active_task_panel(app: &mut App) -> LiveRefresh { |
| 11 | let Some(task_manager) = app.task_manager() else { |
| 12 | return LiveRefresh::Unchanged; |
| 13 | }; |
| 14 | let task_manager = &task_manager; |
| 15 | let namespace_changed = app.task_panel_session_id != app.current_session_id; |
| 16 | if namespace_changed { |
| 17 | app.task_panel.clear(); |
| 18 | app.task_panel_session_id = app.current_session_id.clone(); |
| 19 | app.task_panel_unavailable = false; |
| 20 | } |
| 21 | let tasks = match app.current_session_id.as_deref() { |
| 22 | Some(session_id) => match task_manager |
| 23 | .list_tasks_for_owner(None, None, session_id) |
| 24 | .await |
| 25 | { |
| 26 | Ok(tasks) => tasks, |
| 27 | Err(error) => { |
| 28 | let changed = namespace_changed || !app.task_panel_unavailable; |
| 29 | if !app.task_panel_unavailable { |
| 30 | app.push_status_toast( |
| 31 | codewhale_localization::tr( |
| 32 | app.ui_locale, |
| 33 | codewhale_localization::MessageId::TaskInventoryUnavailable, |
| 34 | ) |
| 35 | .to_string(), |
| 36 | crate::tui::app::StatusToastLevel::Warning, |
| 37 | Some(8_000), |
| 38 | ); |
| 39 | tracing::warn!(%error, "Task inventory unavailable; preserving scoped snapshot"); |
| 40 | } |
| 41 | app.task_panel_unavailable = true; |
| 42 | return if changed { |
| 43 | LiveRefresh::Changed |
| 44 | } else { |
| 45 | LiveRefresh::Unchanged |
| 46 | }; |
| 47 | } |
| 48 | }, |
| 49 | None => Vec::new(), |
| 50 | }; |
| 51 | let was_unavailable = std::mem::replace(&mut app.task_panel_unavailable, false); |
| 52 | // #6565: a durable task that failed or was cancelled is as much news as |
| 53 | // one that completed; each lands in the batched notice by its summary. |
| 54 | let newly_finished_tasks = tasks |
| 55 | .iter() |
| 56 | .filter_map(|task| { |
| 57 | let (outcome, word) = match task.status { |
| 58 | TaskStatus::Completed => (FinishedOutcome::Done, MessageId::BackgroundOutcomeDone), |
| 59 | TaskStatus::Failed => (FinishedOutcome::Failed, MessageId::BackgroundOutcomeFailed), |
| 60 | TaskStatus::Canceled => ( |
| 61 | FinishedOutcome::Stopped, |
| 62 | MessageId::BackgroundOutcomeCancelled, |
| 63 | ), |
| 64 | TaskStatus::Queued | TaskStatus::Running => return None, |
| 65 | }; |
| 66 | // Restored history is not a new completion. A task that finishes |
| 67 | // between polls still counts, without ever needing a live row. |
| 68 | if !task.ended_at.is_some_and(|at| at >= app.session_started_at) |
| 69 | || !app.notified_task_ids.insert(task.id.clone()) |
| 70 | { |
| 71 | return None; |
| 72 | } |
| 73 | let word = tr(app.ui_locale, word); |
| 74 | let summary = match task.duration_ms { |
| 75 | Some(ms) => format!( |
| 76 | "{word} · {}", |
| 77 | codewhale_engine::agent_roster::format_duration(ms) |
| 78 | ), |
| 79 | None => word.to_string(), |
| 80 | }; |
| 81 | let summary = match task.error.as_deref().map(str::trim) { |
| 82 | Some(error) if !error.is_empty() && outcome != FinishedOutcome::Done => { |
| 83 | format!("{summary} · {}", bound_agent_activity_text(error)) |
| 84 | } |
| 85 | _ => summary, |
| 86 | }; |
| 87 | Some( |
| 88 | FinishedWork::task( |
| 89 | &task.prompt_summary, |
| 90 | outcome, |
| 91 | summary, |
| 92 | std::time::Duration::from_millis(task.duration_ms.unwrap_or_default()), |
| 93 | ) |
| 94 | .in_turn(app.is_loading), |
| 95 | ) |
| 96 | }) |
| 97 | .collect::<Vec<_>>(); |
| 98 | let durable_background_completed = newly_finished_tasks |
| 99 | .iter() |
| 100 | .any(|task| task.outcome == FinishedOutcome::Done); |
| 101 | app.background_finished.extend(newly_finished_tasks); |
| 102 | let mut lifecycle_changed = false; |
| 103 | if let (Some(work), Some(session_id)) = ( |
| 104 | app.runtime_services.work.as_ref(), |
| 105 | app.current_session_id.as_deref(), |
| 106 | ) { |
| 107 | for task in &tasks { |
| 108 | if !task.execution_binding_known { |
| 109 | continue; |
| 110 | } |
| 111 | let external = format!("task:{}", task.id); |
| 112 | if !work.has_operation_binding(Some(session_id), &external) { |
| 113 | continue; |
| 114 | } |
| 115 | match work.reconcile_operation( |
| 116 | session_id, |
| 117 | task_owner_snapshot( |
| 118 | &task.id, |
| 119 | task.status, |
| 120 | task.lifecycle_seq, |
| 121 | task.created_at, |
| 122 | task.started_at, |
| 123 | task.ended_at, |
| 124 | ), |
| 125 | ) { |
| 126 | Ok(changed) => lifecycle_changed |= changed, |
| 127 | Err(err) => { |
| 128 | tracing::warn!(task_id = %task.id, error = %err, "failed to reconcile durable task lifecycle"); |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | if lifecycle_changed && let Err(err) = persist_pending_work_checkpoint(app).await { |
| 134 | tracing::warn!(error = %err, "durable task lifecycle checkpoint remains pending"); |
| 135 | } |
| 136 | let session_started_at = app.session_started_at; |
| 137 | let mut entries: Vec<TaskPanelEntry> = |
| 138 | select_work_sidebar_tasks(tasks, session_started_at, app.current_session_id.as_deref()) |
| 139 | .into_iter() |
| 140 | .map(|summary| { |
| 141 | let unverified = !summary.execution_binding_known |
| 142 | && matches!(summary.status, TaskStatus::Queued | TaskStatus::Running); |
| 143 | let mut entry = task_summary_to_panel_entry(summary); |
| 144 | if unverified { |
| 145 | entry.stale = true; |
| 146 | entry.role = Some( |
| 147 | codewhale_localization::tr( |
| 148 | app.ui_locale, |
| 149 | codewhale_localization::MessageId::TaskOwnershipUnverified, |
| 150 | ) |
| 151 | .to_string(), |
| 152 | ); |
| 153 | } |
| 154 | entry |
| 155 | }) |
| 156 | .collect(); |
| 157 | |
| 158 | entries.extend(active_rlm_task_entries(app)); |
| 159 | |
| 160 | // #3804: this is a render-only read of shell jobs and must not block the |
| 161 | // async UI loop on the shell manager's std::sync Mutex. Use try_lock; on |
| 162 | // contention, fail closed (no shell rows this frame) rather than show a |
| 163 | // snapshot that may belong to a replaced session. Shell ownership, |
| 164 | // cancellation, approval state, and output capture never depend on this |
| 165 | // refresh succeeding. |
| 166 | let jobs = match app.runtime_services.shell_manager.as_ref() { |
| 167 | Some(shell_mgr) => match shell_mgr.try_lock() { |
| 168 | Ok(mut mgr) => Some( |
| 169 | mgr.list_jobs_for_session(app.current_session_id.as_deref().unwrap_or_default()), |
| 170 | ), |
| 171 | Err(_) => None, |
| 172 | }, |
| 173 | None => None, |
| 174 | }; |
| 175 | let jobs = jobs.unwrap_or_default(); |
| 176 | let shell_background_completed = project_shell_jobs(app, &mut entries, &jobs); |
| 177 | |
| 178 | // Report whether anything visible changed so the idle tick can skip the |
| 179 | // redraw: an unconditional 2.5 s repaint kept the app from ever going |
| 180 | // quiescent (#3757). |
| 181 | let refresh = fold_task_panel( |
| 182 | app, |
| 183 | entries, |
| 184 | namespace_changed || was_unavailable || lifecycle_changed || shell_background_completed, |
| 185 | ); |
| 186 | let tip_shown = (durable_background_completed || shell_background_completed) |
| 187 | && app.maybe_show_behavioral_tip( |
| 188 | crate::tui::behavioral_tips::BehavioralTip::BackgroundJobReceipt, |
| 189 | ); |
| 190 | if tip_shown { |
| 191 | LiveRefresh::Changed |
| 192 | } else { |
| 193 | refresh |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | pub(super) fn fold_task_panel( |
| 198 | app: &mut App, |
| 199 | entries: Vec<TaskPanelEntry>, |
| 200 | changed: bool, |
| 201 | ) -> LiveRefresh { |
| 202 | let refresh = if changed || !task_rows_differ_only_in_elapsed(&app.task_panel, &entries) { |
| 203 | LiveRefresh::Changed |
| 204 | } else if app.task_panel != entries { |
| 205 | LiveRefresh::ElapsedOnly |
| 206 | } else { |
| 207 | LiveRefresh::Unchanged |
| 208 | }; |
| 209 | app.task_panel = entries; |
| 210 | refresh |
| 211 | } |
| 212 | |
| 213 | fn task_rows_differ_only_in_elapsed(before: &[TaskPanelEntry], after: &[TaskPanelEntry]) -> bool { |
| 214 | before.len() == after.len() |
| 215 | && before.iter().zip(after).all(|(old, new)| { |
| 216 | TaskPanelEntry { |
| 217 | duration_ms: new.duration_ms, |
| 218 | elapsed_since_output_ms: new.elapsed_since_output_ms, |
| 219 | ..old.clone() |
| 220 | } == *new |
| 221 | }) |
| 222 | } |
| 223 | |
| 224 | /// Fold one session-scoped snapshot. An empty snapshot may be a lock miss; |
| 225 | /// neither completion deduplication nor retained IDs depend on visible rows. |
| 226 | pub(super) fn project_shell_jobs( |
| 227 | app: &mut App, |
| 228 | entries: &mut Vec<TaskPanelEntry>, |
| 229 | jobs: &[codewhale_engine::tools::shell::ShellJobSnapshot], |
| 230 | ) -> bool { |
| 231 | // #6565: every terminal status is a completion a person should hear |
| 232 | // about (a failed, killed or timed-out shell used to vanish silently), |
| 233 | // and a finished shell stays listed, muted, with how it ended. |
| 234 | let finished_now = newly_terminal(&mut app.notified_shell_ids, jobs, app.session_started_at); |
| 235 | for job in &finished_now { |
| 236 | let retained = app |
| 237 | .finished_shell_ids |
| 238 | .entry(app.current_session_id.clone().unwrap_or_default()) |
| 239 | .or_default(); |
| 240 | retained.push_back(job.id.clone()); |
| 241 | while retained.len() > MAX_FINISHED_SHELLS { |
| 242 | retained.pop_front(); |
| 243 | } |
| 244 | let label = FinishedWork::shell_display_label(&job.command, job.description.as_deref()); |
| 245 | let (outcome, summary) = shell_outcome(app.ui_locale, job); |
| 246 | let toast = format!("shell · {label} · {summary}"); |
| 247 | let level = if outcome == FinishedOutcome::Done { |
| 248 | crate::tui::app::StatusToastLevel::Info |
| 249 | } else { |
| 250 | crate::tui::app::StatusToastLevel::Warning |
| 251 | }; |
| 252 | app.push_status_toast(bound_agent_activity_text(&toast), level, Some(6_000)); |
| 253 | let parent_busy = app.is_loading; |
| 254 | app.background_finished.push( |
| 255 | FinishedWork::shell( |
| 256 | &job.command, |
| 257 | job.description.as_deref(), |
| 258 | outcome, |
| 259 | summary, |
| 260 | std::time::Duration::from_millis(job.elapsed_ms), |
| 261 | ) |
| 262 | .in_turn(parent_busy), |
| 263 | ); |
| 264 | } |
| 265 | let finished_order = app |
| 266 | .finished_shell_ids |
| 267 | .get(app.current_session_id.as_deref().unwrap_or_default()) |
| 268 | .into_iter() |
| 269 | .flatten() |
| 270 | .cloned() |
| 271 | .collect::<Vec<_>>(); |
| 272 | let shell_entry = |job: &codewhale_engine::tools::shell::ShellJobSnapshot| { |
| 273 | let label = FinishedWork::shell_display_label(&job.command, job.description.as_deref()); |
| 274 | TaskPanelEntry { |
| 275 | id: job.id.clone(), |
| 276 | status: shell_status_token(&job.status).to_string(), |
| 277 | prompt_summary: format!("shell: {label}"), |
| 278 | duration_ms: Some(job.elapsed_ms), |
| 279 | kind: TaskPanelEntryKind::Shell, |
| 280 | stale: job.stale, |
| 281 | elapsed_since_output_ms: job.elapsed_since_output_ms, |
| 282 | owner_agent_id: job.owner_agent_id.clone(), |
| 283 | owner_agent_name: job.owner_agent_name.clone(), |
| 284 | current_tool: None, |
| 285 | role: None, |
| 286 | files_touched: 0, |
| 287 | exit_code: job.exit_code, |
| 288 | } |
| 289 | }; |
| 290 | // Only shells that really run in the background are jobs. A foreground |
| 291 | // Bash wait is already the live tool card in the transcript; listing it |
| 292 | // here too counted one command as a `1 shell` footer chip, a `Shells 1` |
| 293 | // row and the tool card at once. A wait that outlives its foreground |
| 294 | // budget (or Ctrl+B) flips `background`, and the shell then appears here. |
| 295 | entries.extend( |
| 296 | jobs.iter() |
| 297 | .filter(|job| { |
| 298 | job.background |
| 299 | && matches!( |
| 300 | job.status, |
| 301 | codewhale_engine::tools::shell::ShellStatus::Running |
| 302 | ) |
| 303 | }) |
| 304 | .map(shell_entry), |
| 305 | ); |
| 306 | // Finished shells in the order they finished, so the list is stable and |
| 307 | // an idle tick with nothing new changes nothing (#3757). |
| 308 | entries.extend( |
| 309 | finished_order |
| 310 | .iter() |
| 311 | .filter_map(|id| jobs.iter().find(|job| &job.id == id)) |
| 312 | .filter(|job| { |
| 313 | job.background |
| 314 | && !matches!( |
| 315 | job.status, |
| 316 | codewhale_engine::tools::shell::ShellStatus::Running |
| 317 | ) |
| 318 | }) |
| 319 | .map(shell_entry), |
| 320 | ); |
| 321 | !finished_now.is_empty() |
| 322 | } |
| 323 | |
| 324 | /// The wire token a shell status shows as in the task panel. |
| 325 | pub(crate) fn shell_status_token( |
| 326 | status: &codewhale_engine::tools::shell::ShellStatus, |
| 327 | ) -> &'static str { |
| 328 | use codewhale_engine::tools::shell::ShellStatus; |
| 329 | match status { |
| 330 | ShellStatus::Running => "running", |
| 331 | ShellStatus::Completed => "completed", |
| 332 | ShellStatus::Failed => "failed", |
| 333 | ShellStatus::Killed => "killed", |
| 334 | ShellStatus::TimedOut => "timed_out", |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | /// How a finished shell ended, in the words its row and notice use: |
| 339 | /// `exit 0 · 12s`, `failed · exit 2`, `killed`, `timed out`. |
| 340 | pub(crate) fn shell_outcome( |
| 341 | locale: Locale, |
| 342 | job: &codewhale_engine::tools::shell::ShellJobSnapshot, |
| 343 | ) -> (FinishedOutcome, String) { |
| 344 | use codewhale_engine::tools::shell::ShellStatus; |
| 345 | let exit = job |
| 346 | .exit_code |
| 347 | .map(|code| tr(locale, MessageId::BackgroundExitCode).replace("{code}", &code.to_string())); |
| 348 | let took = codewhale_engine::agent_roster::format_duration(job.elapsed_ms); |
| 349 | match job.status { |
| 350 | ShellStatus::Completed | ShellStatus::Running => ( |
| 351 | FinishedOutcome::Done, |
| 352 | format!( |
| 353 | "{} · {took}", |
| 354 | exit.unwrap_or_else(|| tr(locale, MessageId::BackgroundOutcomeDone).into_owned()) |
| 355 | ), |
| 356 | ), |
| 357 | ShellStatus::Failed => ( |
| 358 | FinishedOutcome::Failed, |
| 359 | match exit { |
| 360 | Some(exit) => format!( |
| 361 | "{} · {exit}", |
| 362 | tr(locale, MessageId::BackgroundOutcomeFailed) |
| 363 | ), |
| 364 | None => tr(locale, MessageId::BackgroundOutcomeFailed).into_owned(), |
| 365 | }, |
| 366 | ), |
| 367 | ShellStatus::Killed => ( |
| 368 | FinishedOutcome::Stopped, |
| 369 | tr(locale, MessageId::BackgroundOutcomeKilled).into_owned(), |
| 370 | ), |
| 371 | ShellStatus::TimedOut => ( |
| 372 | FinishedOutcome::Stopped, |
| 373 | tr(locale, MessageId::BackgroundOutcomeTimedOut).into_owned(), |
| 374 | ), |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | /// Every fresh background completion once, even when never observed running. |
| 379 | /// A missed lock, session switch or evicted row never resets this ledger. |
| 380 | /// The session-start cutoff suppresses restored history after a TUI restart. |
| 381 | /// Finish time is the manager's first terminal observation, not OS exit time; |
| 382 | /// legacy snapshots without it are history, never new completion receipts. |
| 383 | pub(super) fn newly_terminal<'a>( |
| 384 | notified_ids: &mut HashSet<String>, |
| 385 | jobs: &'a [codewhale_engine::tools::shell::ShellJobSnapshot], |
| 386 | session_started_at: chrono::DateTime<chrono::Utc>, |
| 387 | ) -> Vec<&'a codewhale_engine::tools::shell::ShellJobSnapshot> { |
| 388 | jobs.iter() |
| 389 | .filter(|job| job.background && job.finished_at.is_some_and(|at| at >= session_started_at)) |
| 390 | .filter(|job| { |
| 391 | !matches!( |
| 392 | job.status, |
| 393 | codewhale_engine::tools::shell::ShellStatus::Running |
| 394 | ) |
| 395 | }) |
| 396 | .filter(|job| notified_ids.insert(job.id.clone())) |
| 397 | .collect() |
| 398 | } |
| 399 | |
| 400 | /// Newest runs scanned per automation when refreshing the automation |
| 401 | /// projection. Live runs sit at the head of the newest-first listing, and a |
| 402 | /// failure once seen is held unacknowledged by the projection until the |
| 403 | /// operator engages the automation surface, so the band never needs a full |
| 404 | /// run-history scan on the render cadence. |
| 405 | const AUTOMATION_PANEL_RUN_SCAN: usize = 25; |
| 406 | |
| 407 | /// Refresh the activity band's scheduled-work projection |
| 408 | /// (AUTOMATION-VISIBILITY-SPEC §2.1) from the durable automation store. |
| 409 | /// |
| 410 | /// The store is files on disk — every definition plus up to |
| 411 | /// `AUTOMATION_PANEL_RUN_SCAN` run files per definition — so the scan never |
| 412 | /// runs on the async UI loop: it is taken on a blocking thread, and this |
| 413 | /// tick folds whatever scan has finished, then starts the next one. At most |
| 414 | /// one scan is in flight; a slow disk costs the band latency, never the |
| 415 | /// frame. Returns whether the visible state changed, so the idle tick can |
| 416 | /// skip the redraw (#3757). |
| 417 | /// |
| 418 | /// `start_next` says whether the next scan may begin once a finished one is |
| 419 | /// folded. The caller passes [`automation_scan_is_due`], so a quiet session |
| 420 | /// with nothing scheduled does not re-read the store every 2.5 s (#6728); a |
| 421 | /// scan already in flight is still folded on every tick. |
| 422 | pub(super) async fn refresh_automation_panel(app: &mut App, start_next: bool) -> bool { |
| 423 | let mut changed = false; |
| 424 | if let Some(scan) = app.automation_scan.take() { |
| 425 | if scan.is_finished() { |
| 426 | match scan.await { |
| 427 | Ok(scan) => changed = fold_automation_scan(app, &scan), |
| 428 | Err(err) => { |
| 429 | tracing::warn!(error = %err, "automation panel scan task failed"); |
| 430 | } |
| 431 | } |
| 432 | } else { |
| 433 | app.automation_scan = Some(scan); |
| 434 | return false; |
| 435 | } |
| 436 | } |
| 437 | if start_next { |
| 438 | app.automation_scan = start_automation_scan(app, false); |
| 439 | } |
| 440 | changed |
| 441 | } |
| 442 | |
| 443 | /// The 2.5 s cadence the activity band is scanned at whenever it has |
| 444 | /// something to show or the user is around. |
| 445 | pub(super) const AUTOMATION_SCAN_BUSY_INTERVAL: std::time::Duration = |
| 446 | std::time::Duration::from_millis(2_500); |
| 447 | |
| 448 | /// The cadence for a quiet session whose band shows nothing: a new |
| 449 | /// automation created from outside this process lights the band within this |
| 450 | /// long. Anything created from inside it (a command, a tool call, a click) is |
| 451 | /// input or an engine event, which restores the busy cadence at once. |
| 452 | pub(super) const AUTOMATION_SCAN_QUIET_INTERVAL: std::time::Duration = |
| 453 | std::time::Duration::from_secs(15); |
| 454 | |
| 455 | /// How long to wait between automation scans. Pure: busy unless the UI is |
| 456 | /// quiet *and* the band has nothing to track *and* no automation surface is |
| 457 | /// open. A scan already in flight does not matter here: it is folded on every |
| 458 | /// 2.5 s tick whatever this says, and only the *start* of the next one waits. |
| 459 | pub(super) fn automation_scan_interval(app: &App, ui_quiet: bool) -> std::time::Duration { |
| 460 | let panel = &app.automation_panel; |
| 461 | let band_tracks_something = panel.active_automations > 0 |
| 462 | || panel.live_runs > 0 |
| 463 | || !panel.live_run_owners().is_empty() |
| 464 | || panel.has_unacknowledged_failure(); |
| 465 | let surface_open = app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::Automations); |
| 466 | if ui_quiet && !band_tracks_something && !surface_open { |
| 467 | AUTOMATION_SCAN_QUIET_INTERVAL |
| 468 | } else { |
| 469 | AUTOMATION_SCAN_BUSY_INTERVAL |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | /// Whether the next automation scan may start, `since_last_scan` after the |
| 474 | /// previous one. |
| 475 | pub(super) fn automation_scan_is_due( |
| 476 | app: &App, |
| 477 | ui_quiet: bool, |
| 478 | since_last_scan: std::time::Duration, |
| 479 | ) -> bool { |
| 480 | since_last_scan >= automation_scan_interval(app, ui_quiet) |
| 481 | } |
| 482 | |
| 483 | /// Startup variant: take one scan and wait for it, so the first frame |
| 484 | /// already carries the band count (the task panel gets the same courtesy). |
| 485 | /// The startup pass is FULL — every run file — so a long-running task that |
| 486 | /// already sits behind more than a window of newer runs is visible from the |
| 487 | /// first frame. The manager lock is retried briefly: the scheduler tick |
| 488 | /// holds it only while persisting, and giving up here would blank the band |
| 489 | /// on a contended startup. |
| 490 | pub(super) async fn refresh_automation_panel_blocking(app: &mut App) -> bool { |
| 491 | let scan = 'retry: { |
| 492 | for _ in 0..STARTUP_SCAN_LOCK_RETRIES { |
| 493 | if let Some(scan) = start_automation_scan(app, true) { |
| 494 | break 'retry Some(scan); |
| 495 | } |
| 496 | tokio::time::sleep(STARTUP_SCAN_LOCK_RETRY_DELAY).await; |
| 497 | } |
| 498 | None |
| 499 | }; |
| 500 | let Some(scan) = scan else { |
| 501 | return false; |
| 502 | }; |
| 503 | match scan.await { |
| 504 | Ok(scan) => fold_automation_scan(app, &scan), |
| 505 | Err(err) => { |
| 506 | tracing::warn!(error = %err, "automation panel scan task failed"); |
| 507 | false |
| 508 | } |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | /// Startup lock-retry budget: the scheduler's persist phase is short; ten |
| 513 | /// 50 ms attempts covers it without parking startup on a stuck lock. |
| 514 | const STARTUP_SCAN_LOCK_RETRIES: usize = 10; |
| 515 | const STARTUP_SCAN_LOCK_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(50); |
| 516 | |
| 517 | /// Start one store scan on a blocking thread. The manager is cloned out |
| 518 | /// from under its tokio Mutex (`try_lock`, same rule as the shell snapshot: |
| 519 | /// the scheduler tick holds that lock while persisting, and the UI loop |
| 520 | /// must not park behind it; on contention the next tick retries) so the |
| 521 | /// scan holds no lock while it reads — the store's writes are atomic |
| 522 | /// renames, so a concurrent read sees a whole file either way. |
| 523 | /// |
| 524 | /// `full` reads every run file (startup only). The cadence scan reads the |
| 525 | /// newest `AUTOMATION_PANEL_RUN_SCAN` runs per automation PLUS the runs |
| 526 | /// this session already watched go live, wherever they sit in history — a |
| 527 | /// frequent automation can stack newer runs behind a long-running task, |
| 528 | /// and neither the live count nor the settle receipt may depend on the |
| 529 | /// task staying inside the newest window. |
| 530 | fn start_automation_scan(app: &App, full: bool) -> Option<tokio::task::JoinHandle<AutomationScan>> { |
| 531 | let automations = app.runtime_services.automations.as_ref()?; |
| 532 | let manager = automations.try_lock().ok()?.clone(); |
| 533 | let live_owners = app.automation_panel.live_run_owners(); |
| 534 | Some(tokio::task::spawn_blocking(move || { |
| 535 | let execution_scope = manager.execution_scope().map(str::to_string); |
| 536 | let records = match manager.list_automations() { |
| 537 | Ok(records) => records, |
| 538 | Err(err) => { |
| 539 | tracing::warn!(error = %err, "automation panel refresh could not list automations"); |
| 540 | return AutomationScan::default(); |
| 541 | } |
| 542 | }; |
| 543 | let mut runs = Vec::new(); |
| 544 | for record in &records { |
| 545 | let limit = if full { |
| 546 | None |
| 547 | } else { |
| 548 | Some(AUTOMATION_PANEL_RUN_SCAN) |
| 549 | }; |
| 550 | match manager.list_runs(&record.id, limit) { |
| 551 | Ok(recent) => runs.extend(recent), |
| 552 | Err(err) => { |
| 553 | tracing::warn!(automation_id = %record.id, error = %err, "automation panel refresh could not list runs"); |
| 554 | } |
| 555 | } |
| 556 | if !full { |
| 557 | let wanted: std::collections::BTreeSet<String> = live_owners |
| 558 | .iter() |
| 559 | .filter(|(_, owner)| owner.as_str() == record.id.as_str()) |
| 560 | .map(|(run_id, _)| run_id.clone()) |
| 561 | .collect(); |
| 562 | if !wanted.is_empty() { |
| 563 | match manager.get_runs_by_ids(&record.id, &wanted) { |
| 564 | Ok(found) => runs.extend(found), |
| 565 | Err(err) => { |
| 566 | tracing::warn!(automation_id = %record.id, error = %err, "automation panel refresh could not re-read live runs"); |
| 567 | } |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | } |
| 572 | // A re-read live run may also sit inside the newest window; the |
| 573 | // fold counts by id, so dedupe before handing the scan over. |
| 574 | let mut seen = std::collections::BTreeSet::new(); |
| 575 | runs.retain(|run| seen.insert(run.id.clone())); |
| 576 | AutomationScan { |
| 577 | records, |
| 578 | runs, |
| 579 | execution_scope, |
| 580 | } |
| 581 | })) |
| 582 | } |
| 583 | |
| 584 | /// Fold a finished scan into the projection and post the typed receipt |
| 585 | /// (spec §2.2) for every run this session watched go live and settle — the |
| 586 | /// transcript learns about background work from the same scan that |
| 587 | /// repaints the band. |
| 588 | fn fold_automation_scan(app: &mut App, scan: &AutomationScan) -> bool { |
| 589 | let session_started_at = app.session_started_at; |
| 590 | let delta = app.automation_panel.fold_scan_in_scope( |
| 591 | &scan.records, |
| 592 | &scan.runs, |
| 593 | session_started_at, |
| 594 | scan.execution_scope.as_deref(), |
| 595 | ); |
| 596 | let locale = app.ui_locale; |
| 597 | for run in &delta.settled { |
| 598 | app.add_message(crate::tui::automation_routing::settled_run_receipt( |
| 599 | locale, run, |
| 600 | )); |
| 601 | } |
| 602 | delta.changed || !delta.settled.is_empty() |
| 603 | } |
| 604 | |
| 605 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 606 | pub(super) enum LiveRefresh { |
| 607 | Unchanged, |
| 608 | ElapsedOnly, |
| 609 | Changed, |
| 610 | } |
| 611 | |
| 612 | pub(super) fn refresh_shell_exec_live_output(app: &mut App) -> LiveRefresh { |
| 613 | let Some(shell_mgr) = app.runtime_services.shell_manager.as_ref().cloned() else { |
| 614 | return LiveRefresh::Unchanged; |
| 615 | }; |
| 616 | // #3804: render-only read — try_lock so a contended shell Mutex can never |
| 617 | // block the async UI loop; skip this frame's live-output update on |
| 618 | // contention (the next refresh picks it up). |
| 619 | let jobs = { |
| 620 | let Ok(mut mgr) = shell_mgr.try_lock() else { |
| 621 | return LiveRefresh::Unchanged; |
| 622 | }; |
| 623 | mgr.list_jobs_for_session(app.current_session_id.as_deref().unwrap_or_default()) |
| 624 | .into_iter() |
| 625 | .map(|job| (job.id.clone(), job)) |
| 626 | .collect::<std::collections::HashMap<_, _>>() |
| 627 | }; |
| 628 | apply_shell_job_snapshots(app, &jobs) |
| 629 | } |
| 630 | |
| 631 | pub(super) fn apply_shell_job_snapshots( |
| 632 | app: &mut App, |
| 633 | jobs: &std::collections::HashMap<String, ShellJobSnapshot>, |
| 634 | ) -> LiveRefresh { |
| 635 | let mut refresh = LiveRefresh::Unchanged; |
| 636 | for index in 0..app.virtual_cell_count() { |
| 637 | let Some(ShellExecLiveUpdate { |
| 638 | task_id, |
| 639 | status: next_status, |
| 640 | output: next_live, |
| 641 | duration_ms: next_duration, |
| 642 | finalized, |
| 643 | stale_elapsed_since_output_ms, |
| 644 | }) = shell_exec_live_update(app, index, jobs) |
| 645 | else { |
| 646 | continue; |
| 647 | }; |
| 648 | let Some(HistoryCell::Tool(ToolCell::Exec(exec))) = app.cell_at_virtual_index_mut(index) |
| 649 | else { |
| 650 | continue; |
| 651 | }; |
| 652 | if exec.output.is_some() || exec.shell_task_id.as_deref() != Some(task_id.as_str()) { |
| 653 | continue; |
| 654 | } |
| 655 | let elapsed_only = |
| 656 | !finalized && exec.status == next_status && exec.live_output == next_live; |
| 657 | exec.status = next_status; |
| 658 | exec.duration_ms = Some(next_duration); |
| 659 | exec.stale_elapsed_since_output_ms = stale_elapsed_since_output_ms; |
| 660 | if finalized { |
| 661 | exec.output = next_live; |
| 662 | exec.output_summary = exec |
| 663 | .output |
| 664 | .as_deref() |
| 665 | .map(codewhale_app_server::exec_agent::summarize_tool_output); |
| 666 | exec.live_output = None; |
| 667 | exec.stale_elapsed_since_output_ms = None; |
| 668 | } else { |
| 669 | exec.live_output = next_live; |
| 670 | } |
| 671 | refresh = if elapsed_only { |
| 672 | refresh.max(LiveRefresh::ElapsedOnly) |
| 673 | } else { |
| 674 | LiveRefresh::Changed |
| 675 | }; |
| 676 | } |
| 677 | refresh |
| 678 | } |
| 679 | |
| 680 | pub(super) struct ShellExecLiveUpdate { |
| 681 | pub(super) task_id: String, |
| 682 | pub(super) status: ToolStatus, |
| 683 | pub(super) output: Option<String>, |
| 684 | pub(super) duration_ms: u64, |
| 685 | pub(super) finalized: bool, |
| 686 | pub(super) stale_elapsed_since_output_ms: Option<u64>, |
| 687 | } |
| 688 | |
| 689 | pub(super) fn shell_exec_live_update( |
| 690 | app: &App, |
| 691 | index: usize, |
| 692 | jobs: &std::collections::HashMap<String, ShellJobSnapshot>, |
| 693 | ) -> Option<ShellExecLiveUpdate> { |
| 694 | let HistoryCell::Tool(ToolCell::Exec(exec)) = app.cell_at_virtual_index(index)? else { |
| 695 | return None; |
| 696 | }; |
| 697 | if exec.output.is_some() { |
| 698 | return None; |
| 699 | } |
| 700 | let task_id = exec.shell_task_id.as_deref()?; |
| 701 | let Some(job) = jobs.get(task_id) else { |
| 702 | return Some(ShellExecLiveUpdate { |
| 703 | task_id: task_id.to_string(), |
| 704 | status: ToolStatus::Stopped, |
| 705 | output: detached_shell_job_output(task_id, exec), |
| 706 | duration_ms: exec.duration_ms.unwrap_or_default(), |
| 707 | finalized: true, |
| 708 | stale_elapsed_since_output_ms: None, |
| 709 | }); |
| 710 | }; |
| 711 | let next_status = shell_job_tool_status(&job.status); |
| 712 | let next_live = shell_job_live_output(job).or_else(|| exec.live_output.clone()); |
| 713 | let finalized = !matches!(job.status, ShellStatus::Running); |
| 714 | let quiet_after_ms = |
| 715 | u64::try_from(codewhale_engine::tools::shell::QUIET_NO_OUTPUT_AFTER.as_millis()) |
| 716 | .unwrap_or(u64::MAX); |
| 717 | let stale_elapsed_since_output_ms = if matches!(job.status, ShellStatus::Running) { |
| 718 | job.elapsed_since_output_ms |
| 719 | .filter(|elapsed| *elapsed >= quiet_after_ms) |
| 720 | } else { |
| 721 | None |
| 722 | }; |
| 723 | if exec.status == next_status |
| 724 | && exec.live_output == next_live |
| 725 | && exec.duration_ms == Some(job.elapsed_ms) |
| 726 | && exec.stale_elapsed_since_output_ms == stale_elapsed_since_output_ms |
| 727 | { |
| 728 | return None; |
| 729 | } |
| 730 | Some(ShellExecLiveUpdate { |
| 731 | task_id: task_id.to_string(), |
| 732 | status: next_status, |
| 733 | output: next_live, |
| 734 | duration_ms: job.elapsed_ms, |
| 735 | finalized, |
| 736 | stale_elapsed_since_output_ms, |
| 737 | }) |
| 738 | } |
| 739 | |
| 740 | pub(super) fn detached_shell_job_output(task_id: &str, exec: &ExecCell) -> Option<String> { |
| 741 | let mut output = exec.live_output.clone().unwrap_or_default(); |
| 742 | if !output.trim().is_empty() { |
| 743 | output.push_str("\n\n"); |
| 744 | } |
| 745 | output.push_str(&format!( |
| 746 | "Shell job `{task_id}` is no longer attached to this TUI session." |
| 747 | )); |
| 748 | Some(output) |
| 749 | } |
| 750 | |
| 751 | pub(super) fn shell_job_tool_status(status: &ShellStatus) -> ToolStatus { |
| 752 | match status { |
| 753 | ShellStatus::Running => ToolStatus::Running, |
| 754 | ShellStatus::Completed => ToolStatus::Success, |
| 755 | ShellStatus::Killed => ToolStatus::Stopped, |
| 756 | ShellStatus::Failed | ShellStatus::TimedOut => ToolStatus::Failed, |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | pub(super) fn shell_job_live_output(job: &ShellJobSnapshot) -> Option<String> { |
| 761 | match (job.stdout_tail.is_empty(), job.stderr_tail.is_empty()) { |
| 762 | (true, true) => None, |
| 763 | (false, true) => Some(job.stdout_tail.clone()), |
| 764 | (true, false) => Some(format!("STDERR:\n{}", job.stderr_tail)), |
| 765 | (false, false) => Some(format!( |
| 766 | "{}\n\nSTDERR:\n{}", |
| 767 | job.stdout_tail, job.stderr_tail |
| 768 | )), |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | pub(super) fn active_rlm_task_entries(app: &App) -> Vec<TaskPanelEntry> { |
| 773 | let Some(active) = app.active_cell.as_ref() else { |
| 774 | return Vec::new(); |
| 775 | }; |
| 776 | let duration_ms = app |
| 777 | .turn_started_at |
| 778 | .map(|started| u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)); |
| 779 | active |
| 780 | .entries() |
| 781 | .iter() |
| 782 | .enumerate() |
| 783 | .filter_map(|(idx, entry)| { |
| 784 | let HistoryCell::Tool(ToolCell::Generic(generic)) = entry else { |
| 785 | return None; |
| 786 | }; |
| 787 | if !matches!( |
| 788 | generic.name.as_str(), |
| 789 | "rlm_open" | "rlm_eval" | "rlm_configure" | "rlm_close" | "rlm" |
| 790 | ) || !generic.status.is_active() |
| 791 | { |
| 792 | return None; |
| 793 | } |
| 794 | let summary = generic |
| 795 | .input_summary |
| 796 | .as_deref() |
| 797 | .filter(|summary| !summary.trim().is_empty()) |
| 798 | .unwrap_or("running chunked analysis"); |
| 799 | Some(TaskPanelEntry { |
| 800 | exit_code: None, |
| 801 | id: format!("rlm-{}", idx + 1), |
| 802 | status: "running".to_string(), |
| 803 | prompt_summary: format!("RLM: {summary}"), |
| 804 | duration_ms, |
| 805 | kind: TaskPanelEntryKind::Background, |
| 806 | stale: false, |
| 807 | elapsed_since_output_ms: None, |
| 808 | owner_agent_id: None, |
| 809 | owner_agent_name: None, |
| 810 | current_tool: None, |
| 811 | role: None, |
| 812 | files_touched: 0, |
| 813 | }) |
| 814 | }) |
| 815 | .collect() |
| 816 | } |
| 817 | |
| 818 | #[cfg(test)] |
| 819 | mod automation_scan_gate_tests { |
| 820 | use super::*; |
| 821 | use std::time::Duration; |
| 822 | |
| 823 | fn app() -> App { |
| 824 | crate::tui::test_support::test_app_with_options(crate::tui::app::TuiOptions { |
| 825 | skip_onboarding: true, |
| 826 | ..crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")) |
| 827 | }) |
| 828 | } |
| 829 | |
| 830 | #[test] |
| 831 | fn a_quiet_session_with_nothing_scheduled_rescans_on_the_long_interval() { |
| 832 | let app = app(); |
| 833 | assert_eq!( |
| 834 | automation_scan_interval(&app, true), |
| 835 | AUTOMATION_SCAN_QUIET_INTERVAL |
| 836 | ); |
| 837 | assert!(!automation_scan_is_due(&app, true, Duration::from_secs(14))); |
| 838 | assert!(automation_scan_is_due(&app, true, Duration::from_secs(15))); |
| 839 | } |
| 840 | |
| 841 | #[test] |
| 842 | fn a_session_in_use_keeps_the_busy_cadence() { |
| 843 | let app = app(); |
| 844 | assert_eq!( |
| 845 | automation_scan_interval(&app, false), |
| 846 | AUTOMATION_SCAN_BUSY_INTERVAL |
| 847 | ); |
| 848 | assert!(!automation_scan_is_due( |
| 849 | &app, |
| 850 | false, |
| 851 | Duration::from_millis(2_499) |
| 852 | )); |
| 853 | assert!(automation_scan_is_due( |
| 854 | &app, |
| 855 | false, |
| 856 | Duration::from_millis(2_500) |
| 857 | )); |
| 858 | } |
| 859 | |
| 860 | #[test] |
| 861 | fn scheduled_work_in_the_band_keeps_the_busy_cadence_even_when_quiet() { |
| 862 | let mut app = app(); |
| 863 | app.automation_panel.active_automations = 1; |
| 864 | assert_eq!( |
| 865 | automation_scan_interval(&app, true), |
| 866 | AUTOMATION_SCAN_BUSY_INTERVAL, |
| 867 | "an active automation can start a run at any moment" |
| 868 | ); |
| 869 | |
| 870 | let mut app = self::app(); |
| 871 | app.automation_panel.live_runs = 1; |
| 872 | assert_eq!( |
| 873 | automation_scan_interval(&app, true), |
| 874 | AUTOMATION_SCAN_BUSY_INTERVAL, |
| 875 | "a live run settles into a receipt the scan produces" |
| 876 | ); |
| 877 | } |
| 878 | |
| 879 | #[test] |
| 880 | fn a_finished_scan_is_folded_without_starting_the_next_one() { |
| 881 | let rt = tokio::runtime::Builder::new_current_thread() |
| 882 | .enable_all() |
| 883 | .build() |
| 884 | .expect("runtime"); |
| 885 | let mut app = app(); |
| 886 | rt.block_on(async { |
| 887 | let scan = |
| 888 | tokio::spawn(async { crate::tui::automation_panel::AutomationScan::default() }); |
| 889 | while !scan.is_finished() { |
| 890 | tokio::task::yield_now().await; |
| 891 | } |
| 892 | app.automation_scan = Some(scan); |
| 893 | // Not due: the scan is folded and nothing replaces it, so a |
| 894 | // quiet session does not chain scan after scan. |
| 895 | let changed = refresh_automation_panel(&mut app, false).await; |
| 896 | assert!(!changed, "an empty store changes nothing visible"); |
| 897 | }); |
| 898 | assert!(app.automation_scan.is_none()); |
| 899 | } |
| 900 | } |
| 901 |