| 1 | //! Background shell job-center helpers for slash commands and pagers. |
| 2 | //! |
| 3 | //! Known limitations: the Bash Job pager (opened from `/jobs`, Alt+V or a |
| 4 | //! work-dock shell row) follows a running job by re-reading it on the event |
| 5 | //! loop's 2.5 s refresh (a bounded read that never consumes the model's |
| 6 | //! output cursor), so new output lands up to 2.5 s late. Shells run by |
| 7 | //! delegated agents show in `/jobs` and the dock with their Owner, not in the |
| 8 | //! agent's detail. Named PTY sessions (`tools/terminal_session.rs`) are not |
| 9 | //! listed here or in `/jobs`; they live in the terminal dock (#6912). |
| 10 | |
| 11 | use crate::tui::app::App; |
| 12 | use crate::tui::history::{HistoryCell, ToolCell}; |
| 13 | use crate::tui::pager::PagerView; |
| 14 | use crate::tui::views::{CommandPaletteAction, ViewEvent}; |
| 15 | use codewhale_engine::tools::shell::{ShellJobDetail, ShellJobSnapshot, ShellResult, ShellStatus}; |
| 16 | use codewhale_localization::MessageId; |
| 17 | |
| 18 | fn status_label(status: &ShellStatus, stale: bool) -> &'static str { |
| 19 | if stale { |
| 20 | return "stale"; |
| 21 | } |
| 22 | match status { |
| 23 | ShellStatus::Running => "running", |
| 24 | ShellStatus::Completed => "complete", |
| 25 | ShellStatus::Failed => "failed", |
| 26 | ShellStatus::Killed => "killed", |
| 27 | ShellStatus::TimedOut => "timeout", |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | pub(super) fn format_shell_job_list(jobs: &[ShellJobSnapshot]) -> String { |
| 32 | if jobs.is_empty() { |
| 33 | return "No live Bash jobs. Bash jobs are process-local; after a restart, inspect durable task artifacts for prior command output.".to_string(); |
| 34 | } |
| 35 | |
| 36 | let mut lines = vec![ |
| 37 | format!("Bash jobs ({})", jobs.len()), |
| 38 | "----------------------------------------".to_string(), |
| 39 | ]; |
| 40 | for job in jobs { |
| 41 | let task = job |
| 42 | .linked_task_id |
| 43 | .as_ref() |
| 44 | .map(|id| format!(" task={id}")) |
| 45 | .unwrap_or_default(); |
| 46 | lines.push(format!( |
| 47 | "{} {:8} {} {}{}", |
| 48 | job.id, |
| 49 | status_label(&job.status, job.stale), |
| 50 | codewhale_command_contract::elapsed::format_elapsed_ms(job.elapsed_ms), |
| 51 | exit_label(job.exit_code, &job.status), |
| 52 | task |
| 53 | )); |
| 54 | lines.push(format!( |
| 55 | " cwd: {}", |
| 56 | codewhale_util::utils::display_path(&job.cwd) |
| 57 | )); |
| 58 | lines.push(format!(" cmd: {}", job.command)); |
| 59 | let tail = if !job.stderr_tail.trim().is_empty() { |
| 60 | job.stderr_tail.trim() |
| 61 | } else { |
| 62 | job.stdout_tail.trim() |
| 63 | }; |
| 64 | let tail_lines: Vec<&str> = tail.lines().collect(); |
| 65 | let shown = tail_lines.len().saturating_sub(3); |
| 66 | for line in &tail_lines[shown..] { |
| 67 | lines.push(format!(" | {line}")); |
| 68 | } |
| 69 | } |
| 70 | lines.push( |
| 71 | "Controls: /jobs show <id>, /jobs poll <id>, /jobs wait <id>, /jobs stdin <id> <input>, /jobs cancel <id|all>." |
| 72 | .to_string(), |
| 73 | ); |
| 74 | lines.join("\n") |
| 75 | } |
| 76 | |
| 77 | fn exit_label(code: Option<i64>, status: &ShellStatus) -> String { |
| 78 | match code { |
| 79 | Some(0) => "exit 0".to_string(), |
| 80 | Some(code) => format!("exit {code}"), |
| 81 | None if *status == ShellStatus::Running => "no exit yet".to_string(), |
| 82 | None => "unavailable".to_string(), |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | pub(super) fn format_shell_poll(result: &ShellResult) -> String { |
| 87 | let mut lines = vec![ |
| 88 | format!( |
| 89 | "Bash job {}: {} {} elapsed={}", |
| 90 | result.task_id.as_deref().unwrap_or("(unknown)"), |
| 91 | status_label(&result.status, false), |
| 92 | exit_label(result.exit_code, &result.status), |
| 93 | codewhale_command_contract::elapsed::format_elapsed_ms(result.duration_ms) |
| 94 | ), |
| 95 | String::new(), |
| 96 | ]; |
| 97 | if result.status == ShellStatus::Killed { |
| 98 | lines.push( |
| 99 | codewhale_engine::tools::shell_output::kill_outcome_note(&format!( |
| 100 | "{}{}", |
| 101 | result.stdout, result.stderr |
| 102 | )) |
| 103 | .to_string(), |
| 104 | ); |
| 105 | lines.push(String::new()); |
| 106 | } |
| 107 | if result.stdout.is_empty() && result.stderr.is_empty() { |
| 108 | lines.push("(no new output)".to_string()); |
| 109 | } else { |
| 110 | if !result.stdout.is_empty() { |
| 111 | lines.push("STDOUT:".to_string()); |
| 112 | lines.push(result.stdout.clone()); |
| 113 | } |
| 114 | if !result.stderr.is_empty() { |
| 115 | lines.push("STDERR:".to_string()); |
| 116 | lines.push(result.stderr.clone()); |
| 117 | } |
| 118 | } |
| 119 | lines.join("\n") |
| 120 | } |
| 121 | |
| 122 | const MAX_INSPECTOR_STREAM_BYTES: usize = 256 * 1024; |
| 123 | |
| 124 | fn bounded_tail(text: &str) -> String { |
| 125 | if text.len() <= MAX_INSPECTOR_STREAM_BYTES { |
| 126 | return text.to_string(); |
| 127 | } |
| 128 | let mut start = text.len() - MAX_INSPECTOR_STREAM_BYTES; |
| 129 | while !text.is_char_boundary(start) { |
| 130 | start += 1; |
| 131 | } |
| 132 | format!("... ({start} earlier bytes omitted)\n{}", &text[start..]) |
| 133 | } |
| 134 | |
| 135 | pub(crate) fn shell_job_for_cell(app: &App, cell_index: usize) -> Option<ShellJobDetail> { |
| 136 | let HistoryCell::Tool(ToolCell::Exec(exec)) = app.cell_at_virtual_index(cell_index)? else { |
| 137 | return None; |
| 138 | }; |
| 139 | let session = app.current_session_id.as_deref()?; |
| 140 | let mut manager = app |
| 141 | .runtime_services |
| 142 | .shell_manager |
| 143 | .as_ref()? |
| 144 | .try_lock() |
| 145 | .ok()?; |
| 146 | let job_id = match exec.shell_task_id.clone() { |
| 147 | Some(id) => id, |
| 148 | None => { |
| 149 | let tool_id = app |
| 150 | .tool_cells |
| 151 | .iter() |
| 152 | .find(|(_, index)| **index == cell_index) |
| 153 | .map(|(tool_id, _)| tool_id.clone())?; |
| 154 | manager |
| 155 | .list_jobs_for_session(session) |
| 156 | .into_iter() |
| 157 | .find(|job| job.origin_tool_call_id.as_deref() == Some(tool_id.as_str()))? |
| 158 | .id |
| 159 | } |
| 160 | }; |
| 161 | manager.inspect_job_for_session(session, &job_id).ok() |
| 162 | } |
| 163 | |
| 164 | pub(crate) fn open_shell_job_pager(app: &mut App, detail: &ShellJobDetail) { |
| 165 | let width = app |
| 166 | .viewport |
| 167 | .last_transcript_area |
| 168 | .map(|area| area.width) |
| 169 | .unwrap_or(100) |
| 170 | .saturating_sub(4); |
| 171 | let live = detail.snapshot.status == ShellStatus::Running && !detail.snapshot.stale; |
| 172 | let body = format_shell_job_detail(detail); |
| 173 | let mut pager = PagerView::from_text( |
| 174 | format!("Bash Job {}", detail.snapshot.id), |
| 175 | &body, |
| 176 | width.max(60), |
| 177 | ) |
| 178 | .with_copy_text(body); |
| 179 | if live { |
| 180 | pager = pager.with_live_shell_job(detail.snapshot.id.clone()); |
| 181 | pager = pager.with_destructive_action( |
| 182 | 's', |
| 183 | app.tr(MessageId::SidebarStopControl), |
| 184 | app.tr(MessageId::WorkSurfaceStopConfirmHint), |
| 185 | ViewEvent::CommandPaletteSelected { |
| 186 | action: CommandPaletteAction::ExecuteCommand { |
| 187 | command: format!("/jobs cancel {}", detail.snapshot.id), |
| 188 | }, |
| 189 | }, |
| 190 | ); |
| 191 | } |
| 192 | app.view_stack.push(pager); |
| 193 | } |
| 194 | |
| 195 | pub(crate) fn refresh_live_shell_job_pager(app: &mut App) -> bool { |
| 196 | let Some(job_id) = app |
| 197 | .view_stack |
| 198 | .top_pager_mut() |
| 199 | .and_then(|pager| pager.live_shell_job().map(str::to_owned)) |
| 200 | else { |
| 201 | return false; |
| 202 | }; |
| 203 | let Some(shell_manager) = app.runtime_services.shell_manager.clone() else { |
| 204 | return false; |
| 205 | }; |
| 206 | let session = app.current_session_id.clone().unwrap_or_default(); |
| 207 | let detail = { |
| 208 | let Ok(mut manager) = shell_manager.try_lock() else { |
| 209 | return false; |
| 210 | }; |
| 211 | manager.inspect_job_for_session(&session, &job_id).ok() |
| 212 | }; |
| 213 | let Some(pager) = app.view_stack.top_pager_mut() else { |
| 214 | return false; |
| 215 | }; |
| 216 | let Some(detail) = detail else { |
| 217 | pager.end_live_shell_job(); |
| 218 | return true; |
| 219 | }; |
| 220 | let changed = pager.replace_live_text(&format_shell_job_detail(&detail)); |
| 221 | if detail.snapshot.status != ShellStatus::Running { |
| 222 | pager.end_live_shell_job(); |
| 223 | return true; |
| 224 | } |
| 225 | changed |
| 226 | } |
| 227 | |
| 228 | fn detail_status_label(job: &ShellJobSnapshot) -> String { |
| 229 | let quiet = u64::try_from(codewhale_engine::tools::shell::QUIET_NO_OUTPUT_AFTER.as_millis()) |
| 230 | .unwrap_or(u64::MAX); |
| 231 | match job.elapsed_since_output_ms { |
| 232 | Some(ms) if job.status == ShellStatus::Running && !job.stale && ms >= quiet => { |
| 233 | crate::tui::history::stale_shell_status_label(ms, codewhale_localization::Locale::En) |
| 234 | } |
| 235 | _ => status_label(&job.status, job.stale).to_string(), |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | pub(crate) fn format_shell_job_detail(detail: &ShellJobDetail) -> String { |
| 240 | let job = &detail.snapshot; |
| 241 | let mut lines = vec![ |
| 242 | format!("Job: {}", job.id), |
| 243 | format!("Status: {}", detail_status_label(job)), |
| 244 | format!("Command: {}", job.command), |
| 245 | format!("Cwd: {}", codewhale_util::utils::display_path(&job.cwd)), |
| 246 | ]; |
| 247 | if let Some(owner) = job |
| 248 | .owner_agent_name |
| 249 | .as_ref() |
| 250 | .or(job.owner_agent_id.as_ref()) |
| 251 | { |
| 252 | lines.push(format!("Owner: {owner}")); |
| 253 | } |
| 254 | lines.push(format!( |
| 255 | "Elapsed: {}", |
| 256 | codewhale_command_contract::elapsed::format_elapsed_ms(job.elapsed_ms) |
| 257 | )); |
| 258 | lines.push(format!( |
| 259 | "Exit Code: {}", |
| 260 | exit_label(job.exit_code, &job.status) |
| 261 | )); |
| 262 | lines.push(format!("Stdin Available: {}", job.stdin_available)); |
| 263 | if let Some(task_id) = job.linked_task_id.as_ref() { |
| 264 | lines.push(format!("Linked Task: {task_id}")); |
| 265 | } |
| 266 | if job.stale { |
| 267 | lines.push( |
| 268 | "Completion state: stale after restart; the process is no longer running.".to_string(), |
| 269 | ); |
| 270 | } else if job.status == ShellStatus::Running { |
| 271 | lines.push("Completion State: still running in this TUI process.".to_string()); |
| 272 | } else { |
| 273 | lines.push("Completion State: finished.".to_string()); |
| 274 | } |
| 275 | lines.push(String::new()); |
| 276 | if detail.stdout.is_empty() |
| 277 | && detail.stderr.is_empty() |
| 278 | && job.status == ShellStatus::Running |
| 279 | && !job.stale |
| 280 | { |
| 281 | lines.push("(no output yet)".to_string()); |
| 282 | return lines.join("\n"); |
| 283 | } |
| 284 | lines.push(format!("STDOUT ({} bytes):", job.stdout_len)); |
| 285 | lines.push(if detail.stdout.is_empty() { |
| 286 | "(empty)".to_string() |
| 287 | } else { |
| 288 | bounded_tail(&detail.stdout) |
| 289 | }); |
| 290 | lines.push(String::new()); |
| 291 | lines.push(format!("STDERR ({} bytes):", job.stderr_len)); |
| 292 | lines.push(if detail.stderr.is_empty() { |
| 293 | "(empty)".to_string() |
| 294 | } else { |
| 295 | bounded_tail(&detail.stderr) |
| 296 | }); |
| 297 | lines.join("\n") |
| 298 | } |
| 299 | |
| 300 | pub(super) fn add_shell_job_message(app: &mut App, content: String) { |
| 301 | app.add_message(HistoryCell::System { content }); |
| 302 | } |
| 303 | |
| 304 | #[cfg(test)] |
| 305 | mod tests { |
| 306 | use super::*; |
| 307 | use codewhale_engine::tools::shell::ShellTerminationCause; |
| 308 | use std::path::PathBuf; |
| 309 | |
| 310 | fn snapshot(status: ShellStatus, stale: bool) -> ShellJobSnapshot { |
| 311 | ShellJobSnapshot { |
| 312 | id: "shell_dead".to_string(), |
| 313 | job_id: "shell_dead".to_string(), |
| 314 | command: "cargo test".to_string(), |
| 315 | description: None, |
| 316 | cwd: PathBuf::from("/tmp/repo"), |
| 317 | status, |
| 318 | started_at: Some(chrono::Utc::now()), |
| 319 | cause: stale.then_some(ShellTerminationCause::Unknown), |
| 320 | producer_reported: false, |
| 321 | exit_code: None, |
| 322 | elapsed_ms: 0, |
| 323 | stdout_tail: String::new(), |
| 324 | stderr_tail: "detached".to_string(), |
| 325 | stdout_len: 0, |
| 326 | stderr_len: 8, |
| 327 | stdin_available: false, |
| 328 | stale, |
| 329 | elapsed_since_output_ms: None, |
| 330 | linked_task_id: Some("task_1".to_string()), |
| 331 | owner_agent_id: None, |
| 332 | owner_agent_name: None, |
| 333 | origin_tool_call_id: None, |
| 334 | origin_turn_id: None, |
| 335 | owner_session_id: "session-test".to_string(), |
| 336 | background: true, |
| 337 | finished_at: Some(chrono::Utc::now()), |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | #[test] |
| 342 | fn silent_running_job_detail_reads_quiet_not_stale() { |
| 343 | let mut job = snapshot(ShellStatus::Running, false); |
| 344 | job.elapsed_since_output_ms = Some(125_000); |
| 345 | let body = format_shell_job_detail(&ShellJobDetail { |
| 346 | snapshot: job, |
| 347 | stdout: String::new(), |
| 348 | stderr: String::new(), |
| 349 | }); |
| 350 | assert!(body.contains("Status: running · no output for"), "{body}"); |
| 351 | assert!(body.contains("(no output yet)"), "{body}"); |
| 352 | assert!(!body.contains("stale"), "{body}"); |
| 353 | } |
| 354 | |
| 355 | #[test] |
| 356 | fn list_shows_controls_and_stale_state() { |
| 357 | let jobs = vec![snapshot(ShellStatus::Killed, true)]; |
| 358 | let formatted = format_shell_job_list(&jobs); |
| 359 | assert!(formatted.contains("Bash jobs (1)")); |
| 360 | assert!(!formatted.contains("Background commands")); |
| 361 | assert!(formatted.contains("shell_dead")); |
| 362 | assert!(formatted.contains("stale")); |
| 363 | assert!(formatted.contains("/jobs poll <id>")); |
| 364 | assert!(formatted.contains("/jobs cancel <id|all>")); |
| 365 | assert!(!formatted.contains("cancel-all")); |
| 366 | assert!(formatted.contains("task=task_1")); |
| 367 | } |
| 368 | } |
| 369 |