Skip to content

Commit d06dc76

Browse files
committed
ui: compact failed background tasks with connected diagnostics
1 parent 0369ba4 commit d06dc76

4 files changed

Lines changed: 140 additions & 0 deletions

File tree

‎crates/jcode-base/src/message/notifications.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,17 @@ pub fn format_background_task_notification_markdown(task: &BackgroundTaskComplet
254254
exit_code,
255255
);
256256

257+
if matches!(task.status, BackgroundTaskStatus::Failed) {
258+
// Completion events are formatted on delivery. Preserve the inferred call
259+
// time so the UI can show age rather than confusing runtime with age.
260+
if let Ok(elapsed) = std::time::Duration::try_from_secs_f64(task.duration_secs)
261+
&& let Ok(elapsed) = chrono::Duration::from_std(elapsed)
262+
&& let Some(called_at) = chrono::Utc::now().checked_sub_signed(elapsed)
263+
{
264+
message.push_str(&format!("\n\n_Called at:_ `{}`", called_at.to_rfc3339()));
265+
}
266+
}
267+
257268
if matches!(task.status, BackgroundTaskStatus::Failed)
258269
&& let Some(summary) = background_task_failure_summary(&task.output_preview)
259270
{

‎crates/jcode-tui/src/tui/ui_messages.rs‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2793,6 +2793,85 @@ pub(crate) fn render_background_task_message(
27932793
if is_swarm {
27942794
return render_compact_swarm_background_completion(&parsed, width);
27952795
}
2796+
if parsed.status.starts_with('✗') {
2797+
let muted = Style::default().fg(dim_color());
2798+
let failure = Style::default().fg(rgb(220, 100, 100));
2799+
let timing = msg
2800+
.content
2801+
.lines()
2802+
.find_map(|line| {
2803+
let timestamp = line.strip_prefix("_Called at:_ `")?.strip_suffix('`')?;
2804+
let called = chrono::DateTime::parse_from_rfc3339(timestamp).ok()?;
2805+
let seconds = (chrono::Utc::now() - called.with_timezone(&chrono::Utc))
2806+
.num_seconds()
2807+
.max(0);
2808+
Some(if seconds < 60 {
2809+
format!("{seconds}s ago")
2810+
} else if seconds < 3600 {
2811+
format!("{}m ago", seconds / 60)
2812+
} else {
2813+
format!("{}h ago", seconds / 3600)
2814+
})
2815+
})
2816+
.unwrap_or_else(|| format!("took {}", parsed.duration));
2817+
let summary = parsed.failure_summary.clone().or_else(|| {
2818+
let preview = strip_ansi_escape_sequences(parsed.preview.as_deref()?);
2819+
preview
2820+
.lines()
2821+
.map(str::trim)
2822+
.map(|line| {
2823+
line.strip_prefix("[stderr] ")
2824+
.or_else(|| line.strip_prefix("[stdout] "))
2825+
.unwrap_or(line)
2826+
})
2827+
.find(|line| {
2828+
line.starts_with("error")
2829+
|| line.starts_with("Error:")
2830+
|| line.starts_with("Failed:")
2831+
|| line.contains("panicked at")
2832+
})
2833+
.map(str::to_owned)
2834+
});
2835+
let detail = summary
2836+
.map(|text| {
2837+
let clean = strip_ansi_escape_sequences(&text);
2838+
format!(
2839+
"{} · {}",
2840+
parsed.exit_label,
2841+
clean.split_whitespace().collect::<Vec<_>>().join(" ")
2842+
)
2843+
})
2844+
.unwrap_or_else(|| format!("{} · no diagnostic captured", parsed.exit_label));
2845+
let mut header = Line::from(vec![
2846+
Span::styled("✗ ", failure),
2847+
Span::styled(
2848+
if task_label == parsed.tool_name {
2849+
parsed.tool_name.clone()
2850+
} else {
2851+
format!("{} {}", parsed.tool_name, task_label)
2852+
},
2853+
Style::default(),
2854+
),
2855+
]);
2856+
let timing = format!(" · {timing}");
2857+
header = super::truncate_line_with_ellipsis_to_width(
2858+
&header,
2859+
(width as usize).saturating_sub(UnicodeWidthStr::width(timing.as_str())),
2860+
);
2861+
header.spans.push(Span::styled(timing, muted));
2862+
let reason = Line::from(vec![
2863+
Span::styled("╰─ ", muted),
2864+
Span::styled(detail, muted),
2865+
]);
2866+
let mut lines = vec![
2867+
super::truncate_line_with_ellipsis_to_width(&header, width as usize),
2868+
super::truncate_line_with_ellipsis_to_width(&reason, width as usize),
2869+
];
2870+
if centered {
2871+
left_pad_lines_for_centered_mode(&mut lines, width);
2872+
}
2873+
return lines;
2874+
}
27962875
let (title, border_color, status_color, preview_color) = if parsed.status.starts_with('✓') {
27972876
(
27982877
if is_swarm {

‎crates/jcode-tui/src/tui/ui_messages/tests.rs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -819,6 +819,52 @@ fn render_system_message_uses_width_stable_titles_on_kitty() {
819819
}
820820
}
821821

822+
#[test]
823+
fn render_background_task_failure_is_compact() {
824+
let called = (chrono::Utc::now() - chrono::Duration::seconds(125)).to_rfc3339();
825+
let msg = DisplayMessage::background_task(format!(
826+
"**Background task** `bg123` · `Comparison trace` (`bash`) · ✗ failed · 11.0s · exit 101\n\n_Called at:_ `{called}`\n\n```text\n[stderr] justrust: remote build\n[stderr] warning: unused variable\n[stderr] error[E0308]: mismatched types\n```\n\n_Full output:_ `bg action=\"output\" task_id=\"bg123\"`"
827+
));
828+
let lines = render_background_task_message(&msg, 100, crate::config::DiffDisplayMode::Off);
829+
assert_eq!(lines.len(), 2);
830+
let plain = lines
831+
.iter()
832+
.map(extract_line_text)
833+
.collect::<Vec<_>>()
834+
.join("\n");
835+
assert!(
836+
plain.contains("✗ bash Comparison trace · 2m ago"),
837+
"{plain}"
838+
);
839+
assert!(
840+
plain.contains("╰─ exit 101 · error[E0308]: mismatched types"),
841+
"{plain}"
842+
);
843+
assert!(!plain.contains("remote build"));
844+
for width in [0, 1, 2, 8, 20, 40] {
845+
let lines =
846+
render_background_task_message(&msg, width, crate::config::DiffDisplayMode::Off);
847+
assert_eq!(lines.len(), 2);
848+
for line in lines {
849+
assert!(UnicodeWidthStr::width(extract_line_text(&line).as_str()) <= width as usize);
850+
}
851+
}
852+
}
853+
854+
#[test]
855+
fn render_background_task_failure_without_diagnostic_is_honest() {
856+
let msg = DisplayMessage::background_task(
857+
"**Background task** `bg123` · `bash` · ✗ failed · 7.1s · exit 1\n\n_No output captured._\n\n_Full output:_ `bg action=\"output\" task_id=\"bg123\"`",
858+
);
859+
let plain = render_background_task_message(&msg, 100, crate::config::DiffDisplayMode::Off)
860+
.iter()
861+
.map(extract_line_text)
862+
.collect::<Vec<_>>()
863+
.join("\n");
864+
assert!(plain.contains("✗ bash · took 7.1s"), "{plain}");
865+
assert!(plain.contains("╰─ exit 1 · no diagnostic captured"));
866+
}
867+
822868
#[test]
823869
fn render_background_task_message_uses_box_and_truncates_preview_lines() {
824870
let msg = DisplayMessage::background_task(

‎crates/jcode-tui/src/tui/ui_messages_cache.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ pub(crate) fn get_cached_message_lines<F>(
1111
where
1212
F: FnOnce(&DisplayMessage, u16, crate::config::DiffDisplayMode) -> Vec<Line<'static>>,
1313
{
14+
// Relative call ages change even when the notification content does not.
15+
if msg.role == "background_task" && msg.content.contains("_Called at:_ `") {
16+
return render(msg, width, diff_mode);
17+
}
1418
jcode_tui_messages::get_cached_message_lines(
1519
msg,
1620
width,

0 commit comments

Comments
 (0)