返回 CodeWhale
activity_detail.rs
根目录 / crates / tui / src / tui / ui / activity_detail.rs
1 //! Reasoning Detail, Turn Inspector, raw tool-detail, and pager-text helpers
2 //! extracted from `ui.rs` (issue #4103).
3 //!
4 //! Ctrl+O opens the full recorded Reasoning Detail timeline for the selected
5 //! reasoning block or the current/latest turn. The whole-turn Turn Inspector
6 //! moved to a dedicated surface (Ctrl+Alt+O and `/turn inspect`). The `v` raw
7 //! tool-details pager (including #500 spillover folding), copy-cell actions, and
8 //! footer detail labels live here too.
9
10 use crate::tui::app::App;
11 use crate::tui::footer_ui::one_line_summary;
12 use crate::tui::history::text::{history_cell_to_clipboard_text, history_cell_to_text};
13 use crate::tui::history::{HistoryCell, ToolCell, ToolStatus, tool_status_label};
14 use crate::tui::pager::{PagerPage, PagerView};
15 use codewhale_localization::{MessageId, tr};
16 use codewhale_snapshot::SnapshotRepo;
17 use codewhale_tui_kit::ui_text::truncate_line_to_width;
18
19 fn selected_transcript_cell_index(app: &App) -> Option<usize> {
20 if let Some(owner) = app.selection_owner_cell() {
21 return Some(owner);
22 }
23 app.viewport
24 .transcript_selection
25 .ordered_endpoints()
26 .and_then(|(start, _)| {
27 app.viewport
28 .transcript_cache
29 .line_meta()
30 .get(start.line_index)
31 .and_then(|meta| meta.cell_line())
32 .map(|(cell_index, _)| app.original_cell_index_for_rendered(cell_index))
33 })
34 }
35
36 /// Open the full recorded-reasoning detail pager for the selected thinking
37 /// block, or for the current/latest turn when no reasoning block is selected.
38 /// Ctrl+O routes here; only provider-supplied reasoning is shown.
39 pub(super) fn open_reasoning_detail_pager(app: &mut App) -> bool {
40 let width = app
41 .viewport
42 .last_transcript_area
43 .map(|area| area.width)
44 .unwrap_or(80);
45 let Some(text) = reasoning_detail_text(app) else {
46 app.show_input_hint("No reasoning detail available");
47 return true;
48 };
49 app.view_stack.push(PagerView::from_text(
50 "Reasoning Detail",
51 &text,
52 width.saturating_sub(2),
53 ));
54 true
55 }
56
57 /// Resolve the turn range that contains the given virtual cell index.
58 /// The turn starts at the most recent user cell at or before the index and
59 /// ends at the next user cell after the index, or the end of the transcript.
60 fn turn_range_for_index(app: &App, index: usize) -> (usize, usize) {
61 let end = app.virtual_cell_count();
62 let start = (0..index.saturating_add(1))
63 .rev()
64 .find(|&idx| {
65 matches!(
66 app.cell_at_virtual_index(idx),
67 Some(HistoryCell::User { .. })
68 )
69 })
70 .unwrap_or(0);
71 let turn_end = (index..end)
72 .find(|&idx| {
73 idx > index
74 && matches!(
75 app.cell_at_virtual_index(idx),
76 Some(HistoryCell::User { .. })
77 )
78 })
79 .unwrap_or(end);
80 (start, turn_end)
81 }
82
83 /// Assemble the full recorded reasoning for the selected thinking block's
84 /// turn, or for the current/latest turn when nothing is selected. Empty
85 /// chunks are surfaced as "(no reasoning text recorded)" rather than invented.
86 pub(super) fn reasoning_detail_text(app: &App) -> Option<String> {
87 let selected = selected_transcript_cell_index(app).filter(|&idx| {
88 matches!(
89 app.cell_at_virtual_index(idx),
90 Some(HistoryCell::Thinking { .. })
91 )
92 });
93 let (start, end) = selected
94 .map(|idx| turn_range_for_index(app, idx))
95 .unwrap_or_else(|| current_turn_range(app));
96 reasoning_timeline_text(app, selected, start, end)
97 }
98
99 /// Build the full recorded-reasoning text for a turn-scoped set of thinking
100 /// cells. Only provider-supplied reasoning Codewhale actually recorded is
101 /// shown; nothing is fabricated when a chunk is empty.
102 pub(super) fn reasoning_timeline_text(
103 app: &App,
104 selected_cell_index: Option<usize>,
105 start: usize,
106 end: usize,
107 ) -> Option<String> {
108 let thinking_indices: Vec<usize> = (start..end)
109 .filter(|&idx| {
110 matches!(
111 app.cell_at_virtual_index(idx),
112 Some(HistoryCell::Thinking { .. })
113 )
114 })
115 .collect();
116 if thinking_indices.is_empty() {
117 return None;
118 }
119
120 let selected_position = selected_cell_index.and_then(|selected| {
121 thinking_indices
122 .iter()
123 .position(|&idx| idx == selected)
124 .map(|idx| idx + 1)
125 });
126 let total = thinking_indices.len();
127 let running = thinking_indices.iter().any(|&idx| {
128 matches!(
129 app.cell_at_virtual_index(idx),
130 Some(HistoryCell::Thinking {
131 streaming: true,
132 ..
133 })
134 )
135 });
136
137 let mut sections = Vec::new();
138 if let Some(turn_id) = app.runtime_turn_id.as_ref() {
139 let status = humanized_turn_status(app);
140 sections.push(format!("Turn {} \u{00B7} {status}", short_turn_id(turn_id)));
141 }
142 sections.push("Activity: reasoning timeline".to_string());
143 sections.push(format!(
144 "Status: {} · {total} chunk{}",
145 if running { "running" } else { "done" },
146 if total == 1 { "" } else { "s" }
147 ));
148 if let Some(position) = selected_position {
149 sections.push(format!("Selected chunk: {position} of {total}"));
150 if position > 1 {
151 let previous_index = thinking_indices[position - 2];
152 let preview = thinking_chunk_preview(app, previous_index);
153 sections.push(format!(
154 "Previous chunk: {} of {total} - {preview}",
155 position - 1
156 ));
157 }
158 if position < total {
159 let next_index = thinking_indices[position];
160 let preview = thinking_chunk_preview(app, next_index);
161 sections.push(format!(
162 "Next chunk: {} of {total} - {preview}",
163 position + 1
164 ));
165 }
166 }
167 sections.push(String::new());
168
169 for (position, cell_index) in thinking_indices.iter().copied().enumerate() {
170 let Some(HistoryCell::Thinking {
171 content,
172 streaming,
173 duration_secs,
174 }) = app.cell_at_virtual_index(cell_index)
175 else {
176 continue;
177 };
178 let position = position + 1;
179 let marker = if Some(position) == selected_position {
180 " (selected)"
181 } else {
182 ""
183 };
184 let mut status = if *streaming {
185 "running".to_string()
186 } else {
187 "done".to_string()
188 };
189 if let Some(duration_secs) = duration_secs {
190 status.push_str(" · ");
191 status.push_str(&codewhale_command_contract::elapsed::format_elapsed_ms(
192 (duration_secs * 1000.0) as u64,
193 ));
194 }
195 sections.push(format!("Thinking chunk {position} of {total}{marker}"));
196 sections.push(format!("Status: {status}"));
197 let body = content.trim();
198 if body.is_empty() {
199 sections.push("(no reasoning text recorded)".to_string());
200 } else {
201 sections.push(body.to_string());
202 }
203 sections.push(String::new());
204 }
205
206 Some(sections.join("\n"))
207 }
208
209 fn thinking_chunk_preview(app: &App, cell_index: usize) -> String {
210 let Some(HistoryCell::Thinking { content, .. }) = app.cell_at_virtual_index(cell_index) else {
211 return "thinking".to_string();
212 };
213 let preview = one_line_summary(content, 64);
214 if preview.is_empty() {
215 "thinking".to_string()
216 } else {
217 preview
218 }
219 }
220
221 fn activity_cell_label(app: &App, cell_index: usize, cell: &HistoryCell) -> String {
222 match cell {
223 HistoryCell::Thinking { .. } => "thinking".to_string(),
224 HistoryCell::Error { .. } => "error".to_string(),
225 HistoryCell::SubAgent(_) => "sub-agent".to_string(),
226 HistoryCell::Tool(ToolCell::Generic(generic)) => {
227 crate::tui::widgets::tool_card::tool_activity_label_for_name(
228 &generic.name,
229 app.ui_locale,
230 )
231 }
232 HistoryCell::Tool(_) => {
233 detail_target_label(app, cell_index).unwrap_or_else(|| "tool activity".to_string())
234 }
235 _ => "message".to_string(),
236 }
237 }
238
239 fn tool_duration_for_activity(tool: &ToolCell) -> Option<u64> {
240 match tool {
241 ToolCell::Exec(cell) => cell.duration_ms.or_else(|| {
242 (cell.status == ToolStatus::Running)
243 .then_some(cell.started_at)
244 .flatten()
245 .map(|started| u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX))
246 }),
247 _ => None,
248 }
249 }
250
251 /// Empty-state hint shown when the selection has no raw leaf detail to open.
252 /// `v` / `Alt+V` only ever surface the raw detail of the ONE selected
253 /// tool/card/leaf, so when there is nothing leaf-level to show we point the
254 /// user at Ctrl+Alt+O for the whole-turn context instead of failing silently
255 /// (#4105).
256 const NO_RAW_DETAIL_HINT: &str =
257 "No raw detail for this item — press Ctrl+Alt+O for the turn overview.";
258
259 /// Intro line prepended to the raw tool-detail pager body so the surface reads
260 /// as the raw detail of the single selected item — not the whole turn.
261 /// Ctrl+Alt+O is now the whole-turn Turn Inspector (#v092-reasoning-fix).
262 const RAW_DETAIL_PAGER_INTRO: &str =
263 "Raw detail for the selected item — press Ctrl+Alt+O for the whole-turn overview.";
264
265 pub(super) fn open_tool_details_pager(app: &mut App) -> bool {
266 let opened =
267 detail_target_cell_index(app).is_some_and(|index| open_details_pager_for_cell(app, index));
268 if !opened {
269 app.show_input_hint(NO_RAW_DETAIL_HINT);
270 }
271 opened
272 }
273
274 pub(super) fn spillover_pager_reference(app: &App, cell_index: usize) -> Option<(String, String)> {
275 use crate::tui::history::{GenericToolCell, HistoryCell, ToolCell};
276
277 let session_id = app
278 .current_session_id
279 .as_deref()
280 .filter(|id| !id.trim().is_empty())?;
281 let artifact = app
282 .tool_detail_record_for_cell(cell_index)
283 .and_then(|detail| {
284 app.session_artifacts.iter().find(|artifact| {
285 artifact.kind == codewhale_runtime::artifacts::ArtifactKind::ToolOutput
286 && artifact.tool_call_id == detail.tool_id
287 && artifact.session_id == session_id
288 })
289 });
290 let reference = if let Some(artifact) = artifact {
291 artifact.storage_path.to_str()?
292 } else if let Some(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
293 spillover_path: Some(path),
294 ..
295 }))) = app.cell_at_virtual_index(cell_index)
296 {
297 path.to_str()?
298 } else {
299 return None;
300 };
301 if reference.len() > codewhale_engine::tools::tool_result_retrieval::MAX_REFERENCE_BYTES {
302 return None;
303 }
304 Some((session_id.to_string(), reference.to_string()))
305 }
306
307 pub(crate) fn open_details_pager_for_cell(app: &mut App, cell_index: usize) -> bool {
308 if let Some(detail) = crate::tui::shell_job_routing::shell_job_for_cell(app, cell_index) {
309 crate::tui::shell_job_routing::open_shell_job_pager(app, &detail);
310 return true;
311 }
312 if let Some(detail) = app.tool_detail_record_for_cell(cell_index) {
313 let input = serde_json::to_string_pretty(&detail.input)
314 .unwrap_or_else(|_| detail.input.to_string());
315 let output = detail.output.as_deref().map_or(
316 "(not available)".to_string(),
317 std::string::ToString::to_string,
318 );
319
320 let retained = spillover_pager_reference(app, cell_index);
321 let mutation_section = match app.cell_at_virtual_index(cell_index) {
322 Some(HistoryCell::Tool(ToolCell::PatchSummary(cell))) => {
323 cell.receipt.as_ref().map(|receipt| {
324 format!(
325 "── {} ──\n{}",
326 codewhale_localization::tr(
327 app.ui_locale,
328 codewhale_localization::MessageId::FileMutationExactHeading
329 ),
330 receipt.inspect_text(app.ui_locale)
331 )
332 })
333 }
334 _ => None,
335 };
336
337 // Frame the recorded detail at leaf scope; retained bytes use the
338 // owned evidence page rather than being joined into this body.
339 let trailing_sections = [mutation_section]
340 .into_iter()
341 .flatten()
342 .collect::<Vec<_>>()
343 .join("\n\n");
344 let content = if !trailing_sections.is_empty() {
345 format!(
346 "{RAW_DETAIL_PAGER_INTRO}\n\nTool ID: {}\nTool: {}\n\nInput:\n{}\n\nOutput:\n{}\n\n{}",
347 detail.tool_id, detail.tool_name, input, output, trailing_sections
348 )
349 } else {
350 format!(
351 "{RAW_DETAIL_PAGER_INTRO}\n\nTool ID: {}\nTool: {}\n\nInput:\n{}\n\nOutput:\n{}",
352 detail.tool_id, detail.tool_name, input, output
353 )
354 };
355
356 let width = app
357 .viewport
358 .last_transcript_area
359 .map(|area| area.width)
360 .unwrap_or(80);
361 let mut pager = PagerView::from_text(
362 format!("Raw detail — {}", detail.tool_name),
363 &content,
364 width.saturating_sub(2),
365 );
366 if let Some((session, reference)) = retained {
367 pager = pager.with_owned_evidence(app.workspace.clone(), session, reference);
368 }
369 app.view_stack.push(pager);
370 return true;
371 }
372
373 let Some(cell) = app.cell_at_virtual_index(cell_index) else {
374 return false;
375 };
376 let title = match cell {
377 HistoryCell::User { .. } => "You".to_string(),
378 HistoryCell::Assistant { .. } => "Assistant".to_string(),
379 HistoryCell::System { .. } => "Note".to_string(),
380 HistoryCell::Error { .. } => "Error".to_string(),
381 HistoryCell::Thinking { .. } => "Reasoning".to_string(),
382 HistoryCell::Tool(_) => "Message".to_string(),
383 HistoryCell::SubAgent(_) => "Sub-agent".to_string(),
384 HistoryCell::Automation(_) => tr(app.ui_locale, MessageId::AutomationNoun).into_owned(),
385 HistoryCell::ApprovalReceipt(_) => "Approval".to_string(),
386 HistoryCell::ArchivedContext { .. } => "Archived Context".to_string(),
387 };
388 let width = app
389 .viewport
390 .last_transcript_area
391 .map(|area| area.width)
392 .unwrap_or(80);
393 let content = if matches!(cell, HistoryCell::Tool(_)) {
394 history_cell_to_clipboard_text(cell, width)
395 } else {
396 history_cell_to_text(cell, width)
397 };
398 let mut pager = PagerView::from_text(title, &content, width.saturating_sub(2));
399 // A completed assistant cell gets a clean `a` (copy answer) action so
400 // this raw-detail pager can hand over the answer text without the
401 // glyph/label scaffolding that `c`/`y` (rendered body) would include.
402 if let Some(answer) = completed_assistant_answer_text(cell, width) {
403 pager = pager.with_copy_answer(answer);
404 }
405 if let Some((session, reference)) = spillover_pager_reference(app, cell_index) {
406 pager = pager.with_owned_evidence(app.workspace.clone(), session, reference);
407 }
408 app.view_stack.push(pager);
409 true
410 }
411
412 /// Open the focused transcript cell as a full-screen readable pager.
413 pub(crate) fn open_focused_cell_pager(app: &mut App) -> bool {
414 let Some(cell_index) = detail_target_cell_index(app) else {
415 return false;
416 };
417 if let Some(turn) = app.folded_turn_at(cell_index) {
418 let Some(title) = crate::tui::history::turn_fold_changes(&turn, app.ui_locale) else {
419 return false;
420 };
421 let diff = crate::tui::history::turn_fold_diff(&turn, |index| {
422 app.cell_at_virtual_index(index).cloned()
423 });
424 super::overlays::open_diff_pager(app, title, &diff);
425 return true;
426 }
427 let Some(cell) = app.cell_at_virtual_index(cell_index) else {
428 return false;
429 };
430 let title = match cell {
431 HistoryCell::User { .. } => "You".to_string(),
432 HistoryCell::Assistant { .. } => "Assistant".to_string(),
433 HistoryCell::System { .. } => "Note".to_string(),
434 HistoryCell::Error { .. } => "Error".to_string(),
435 HistoryCell::Thinking { .. } => "Reasoning".to_string(),
436 HistoryCell::Tool(_) => "Tool".to_string(),
437 HistoryCell::SubAgent(_) => "Sub-agent".to_string(),
438 HistoryCell::Automation(_) => tr(app.ui_locale, MessageId::AutomationNoun).into_owned(),
439 HistoryCell::ApprovalReceipt(_) => "Approval".to_string(),
440 HistoryCell::ArchivedContext { .. } => "Archived Context".to_string(),
441 };
442 let width = app
443 .viewport
444 .last_transcript_area
445 .map(|area| area.width)
446 .unwrap_or(80);
447 let content = if matches!(cell, HistoryCell::Tool(_)) {
448 history_cell_to_clipboard_text(cell, width)
449 } else {
450 history_cell_to_text(cell, width)
451 };
452 let mut pager = PagerView::from_text(title, &content, width.saturating_sub(2));
453 if let Some(answer) = completed_assistant_answer_text(cell, width) {
454 pager = pager.with_copy_answer(answer);
455 }
456 app.view_stack.push(pager);
457 true
458 }
459
460 /// Copy the "focused" transcript cell to the system clipboard.
461 /// The focused cell is determined by the detail-target heuristic
462 /// (viewport centre or most recent cell). Returns true when text
463 /// was actually copied.
464 pub(super) fn copy_focused_cell(app: &mut App) -> bool {
465 let cell_index = detail_target_cell_index(app);
466 let Some(index) = cell_index else {
467 app.show_copy_notice(
468 "No transcript cell to copy",
469 crate::tui::app::StatusToastLevel::Info,
470 4_000,
471 );
472 return false;
473 };
474 copy_cell_to_clipboard(app, index)
475 }
476
477 pub(crate) fn copy_cell_to_clipboard(app: &mut App, cell_index: usize) -> bool {
478 let Some(cell) = app.cell_at_virtual_index(cell_index) else {
479 app.show_copy_notice(
480 "No message at that line",
481 crate::tui::app::StatusToastLevel::Info,
482 4_000,
483 );
484 return false;
485 };
486 let width = app
487 .viewport
488 .last_transcript_area
489 .map(|area| area.width)
490 .unwrap_or(80);
491 let text = history_cell_to_clipboard_text(cell, width);
492 if text.trim().is_empty() {
493 app.show_copy_notice(
494 "Message is empty",
495 crate::tui::app::StatusToastLevel::Info,
496 4_000,
497 );
498 return false;
499 }
500 let result = app.clipboard.write_text_status(&text);
501 crate::tui::mouse_ui::report_copy_result(app, result, "Message copied", "Copy failed")
502 }
503
504 /// Clean clipboard payload for a completed assistant answer cell.
505 ///
506 /// Selection reuses the typed `HistoryCell::is_completed_assistant_answer`
507 /// projection so reasoning/thinking blocks, tool calls and results, runtime
508 /// status, and still-streaming partials never qualify; serialization reuses
509 /// `history_cell_to_clipboard_text`, the canonical clean-copy path that
510 /// returns the authored assistant Markdown with no glyph/label scaffolding.
511 pub(crate) fn completed_assistant_answer_text(cell: &HistoryCell, width: u16) -> Option<String> {
512 cell.is_completed_assistant_answer()
513 .then(|| history_cell_to_clipboard_text(cell, width))
514 }
515
516 /// Latest completed assistant answer inside the virtual-cell range
517 /// `[start, end)` — the payload behind the Turn Inspector's `a` (copy
518 /// answer) action. Scanning backwards keeps each inspector page scoped to
519 /// its own turn, so the latest page carries the latest completed answer.
520 fn turn_answer_payload(app: &App, start: usize, end: usize, width: u16) -> Option<String> {
521 (start..end).rev().find_map(|idx| {
522 app.cell_at_virtual_index(idx)
523 .and_then(|cell| completed_assistant_answer_text(cell, width))
524 })
525 }
526
527 pub(super) fn detail_target_cell_index(app: &App) -> Option<usize> {
528 if let Some(owner) = app.selection_owner_cell() {
529 return Some(owner);
530 }
531 if let Some((start, _)) = app.viewport.transcript_selection.ordered_endpoints() {
532 return app
533 .viewport
534 .transcript_cache
535 .line_meta()
536 .get(start.line_index)
537 .and_then(|meta| meta.cell_line())
538 .map(|(cell_index, _)| app.original_cell_index_for_rendered(cell_index));
539 }
540 app.detail_cell_index_for_viewport(
541 app.viewport.last_transcript_top,
542 app.viewport.last_transcript_visible.max(1),
543 app.viewport.transcript_cache.line_meta(),
544 )
545 .or_else(|| app.virtual_cell_count().checked_sub(1))
546 }
547
548 pub(crate) fn detail_target_label(app: &App, cell_index: usize) -> Option<String> {
549 if let Some(detail) = app.tool_detail_record_for_cell(cell_index) {
550 return Some(detail.tool_name.clone());
551 }
552 let cell = app.cell_at_virtual_index(cell_index)?;
553 match cell {
554 HistoryCell::Tool(ToolCell::Exec(exec)) => {
555 Some(format!("run {}", one_line_summary(&exec.command, 80)))
556 }
557 HistoryCell::Tool(ToolCell::Exploring(explore)) => Some(format!(
558 "workspace {} item{}",
559 explore.entries.len(),
560 if explore.entries.len() == 1 { "" } else { "s" }
561 )),
562 HistoryCell::Tool(ToolCell::PlanUpdate(_)) => Some("legacy plan update".to_string()),
563 HistoryCell::Tool(ToolCell::PatchSummary(patch)) => Some(format!("patch {}", patch.path)),
564 HistoryCell::Tool(ToolCell::Review(review)) => {
565 let target = one_line_summary(&review.target, 80);
566 Some(if target.is_empty() {
567 "review".to_string()
568 } else {
569 format!("review {target}")
570 })
571 }
572 HistoryCell::Tool(ToolCell::Mcp(mcp)) => Some(format!("tool {}", mcp.tool)),
573 HistoryCell::Tool(ToolCell::ViewImage(image)) => {
574 Some(format!("image {}", image.path.display()))
575 }
576 HistoryCell::Tool(ToolCell::WebSearch(search)) => Some(format!("search {}", search.query)),
577 HistoryCell::Tool(ToolCell::DataDisplay(data)) => Some(match &data.display {
578 Ok(display) => format!(
579 "show_data {}",
580 codewhale_ratatui::text::display_safe(display.label())
581 ),
582 Err(_) => "show_data".to_string(),
583 }),
584 HistoryCell::Tool(ToolCell::Generic(generic)) => Some(
585 crate::tui::widgets::tool_card::tool_activity_label_for_name(
586 &generic.name,
587 app.ui_locale,
588 ),
589 ),
590 HistoryCell::SubAgent(_) => Some("sub-agent".to_string()),
591 HistoryCell::Error { .. } => Some("full error message".to_string()),
592 _ => None,
593 }
594 }
595
596 pub(super) fn extract_reasoning_header(text: &str) -> Option<String> {
597 let start = text.find("**")?;
598 let rest = &text[start + 2..];
599 let end = rest.find("**")?;
600 let header = rest[..end].trim().trim_end_matches(':');
601 if header.is_empty() {
602 None
603 } else {
604 Some(header.to_string())
605 }
606 }
607
608 // ============================================================================
609 // Turn Inspector (issue #4104)
610 //
611 // Ctrl+O opens a *turn-level* overview of the current in-flight turn — or the
612 // latest completed turn when idle — rather than the single-cell Activity
613 // Detail. `v` / `Alt+V` remain the raw leaf-detail command for the selected
614 // item; this surface never dumps a single tool's raw output.
615 //
616 // Each of the nine overview sections renders from whatever turn/cell/app state
617 // is cleanly reachable and DEGRADES the rest gracefully to a short "none"/"—"
618 // line — never a mysterious blank. The thinner sections (diagnostics loop,
619 // tests/verifier) are intentionally heuristic in this first pass; the leaf
620 // issues #4106/#4107/#4108 flesh them out with structured data later.
621 // ============================================================================
622
623 /// Open the whole-turn Turn Inspector pager (Ctrl+O).
624 ///
625 /// Reuses the same `PagerView` text-section machinery as the Activity Detail
626 /// pager — no new modal system. Always succeeds: an empty transcript still
627 /// yields a coherent (degraded) overview rather than a dead keypress.
628 pub(super) fn open_turn_inspector_pager(app: &mut App) -> bool {
629 let width = app
630 .viewport
631 .last_transcript_area
632 .map(|area| area.width)
633 .unwrap_or(80);
634 let ranges = turn_ranges(app);
635 let page_count = ranges.len();
636 let pages = ranges
637 .into_iter()
638 .enumerate()
639 .map(|(page_index, (start, end))| {
640 let latest = page_index + 1 == page_count;
641 let text =
642 turn_inspector_text_for_range(app, start, end, page_index, page_count, latest);
643 let page = PagerPage::from_text("Turn Inspector", &text, width.saturating_sub(2))
644 .with_copy_text(text);
645 // `a` copies only this turn's final assistant answer — the clean
646 // counterpart to `e` (whole-turn handoff markdown).
647 let page = match turn_answer_payload(app, start, end, width) {
648 Some(answer) => page.with_copy_answer(answer),
649 None => page,
650 };
651 if latest {
652 // The existing handoff remains attached only to the
653 // current/latest turn it actually describes.
654 page.with_export_markdown(turn_handoff_markdown(app))
655 } else {
656 page
657 }
658 })
659 .collect();
660 app.view_stack
661 .push(PagerView::from_pages(pages, page_count.saturating_sub(1)));
662 true
663 }
664
665 /// Chronological virtual-cell ranges for every recorded turn. A transcript
666 /// without a user prompt still gets one coherent page, matching the previous
667 /// Turn Inspector empty/degraded behavior.
668 fn turn_ranges(app: &App) -> Vec<(usize, usize)> {
669 let end = app.virtual_cell_count();
670 let starts: Vec<usize> = (0..end)
671 .filter(|&idx| {
672 matches!(
673 app.cell_at_virtual_index(idx),
674 Some(HistoryCell::User { .. })
675 )
676 })
677 .collect();
678 if starts.is_empty() {
679 return vec![(0, end)];
680 }
681 starts
682 .iter()
683 .copied()
684 .enumerate()
685 .map(|(idx, start)| (start, starts.get(idx + 1).copied().unwrap_or(end)))
686 .collect()
687 }
688
689 /// Virtual-cell range `[start, end)` of the turn under inspection.
690 ///
691 /// The turn is the run of cells from the last user prompt through the end of
692 /// the transcript. Because `virtual_cell_count()` includes still-in-flight
693 /// `active_cell` entries, this scopes to the current in-flight turn during a
694 /// turn, and to the latest completed turn once the active cell has flushed to
695 /// history. When no user prompt exists yet the whole transcript is used.
696 fn current_turn_range(app: &App) -> (usize, usize) {
697 let end = app.virtual_cell_count();
698 let start = (0..end)
699 .rev()
700 .find(|&idx| {
701 matches!(
702 app.cell_at_virtual_index(idx),
703 Some(HistoryCell::User { .. })
704 )
705 })
706 .unwrap_or(0);
707 (start, end)
708 }
709
710 /// Human form of the runtime turn status — raw enum-ish values like
711 /// "in_progress" must never reach the inspector (dogfood A6, #4102).
712 fn humanized_turn_status(app: &App) -> &str {
713 match app.runtime_turn_status.as_deref() {
714 Some("in_progress") | None => "in progress",
715 Some(other) => other,
716 }
717 }
718
719 /// Short display form of a runtime turn id. The full UUID reads as internal
720 /// state in the inspector header (dogfood A6); twelve characters is plenty
721 /// to correlate with logs.
722 fn short_turn_id(turn_id: &str) -> &str {
723 turn_id.get(..12).unwrap_or(turn_id)
724 }
725
726 /// Assemble the Turn Inspector overview text from all available turn data.
727 #[cfg(test)]
728 pub(super) fn turn_inspector_text(app: &App) -> String {
729 let (start, end) = current_turn_range(app);
730 turn_inspector_text_for_range(app, start, end, 0, 1, true)
731 }
732
733 fn turn_inspector_text_for_range(
734 app: &App,
735 start: usize,
736 end: usize,
737 page_index: usize,
738 page_count: usize,
739 latest: bool,
740 ) -> String {
741 let mut out: Vec<String> = Vec::new();
742
743 // Turn identity header. Lead with the human turn number and status; the
744 // id is a short correlation suffix, never a raw UUID dump (dogfood A6).
745 let status = if latest {
746 std::borrow::Cow::Borrowed(humanized_turn_status(app))
747 } else {
748 tr(app.ui_locale, MessageId::AutomationRunStatusCompleted)
749 };
750 if !latest {
751 let historical_offset = page_count.saturating_sub(page_index + 1) as u64;
752 let number = app
753 .turn_counter
754 .checked_sub(historical_offset)
755 .filter(|number| *number > 0)
756 .unwrap_or(page_index as u64 + 1);
757 out.push(format!("Turn #{number} \u{00B7} {status}"));
758 } else if app.turn_counter > 0 {
759 let mut line = format!("Turn #{} \u{00B7} {status}", app.turn_counter);
760 if let Some(turn_id) = app.runtime_turn_id.as_ref() {
761 line.push_str(&format!(" \u{00B7} id {}", short_turn_id(turn_id)));
762 }
763 out.push(line);
764 } else if let Some(turn_id) = app.runtime_turn_id.as_ref() {
765 out.push(format!("Turn {} \u{00B7} {status}", short_turn_id(turn_id)));
766 } else {
767 out.push("Turn: \u{2014} (no turn recorded yet)".to_string());
768 }
769 // Restate the Ctrl+O (overview) vs. Alt+V/⌥V (raw leaf detail) contract so
770 // the two surfaces never get confused. Bare `v` is never a details shortcut.
771 let details = crate::tui::shell_key_routing::display_chord(
772 crate::tui::shell_key_routing::binding(
773 crate::tui::shell_key_routing::ShellBindingId::ToolDetails,
774 )
775 .footer_chord,
776 );
777 if latest {
778 out.push(format!(
779 "Overview of the current/latest turn · press {details} for the selected item's raw detail"
780 ));
781 }
782
783 push_section(&mut out, "Intent", vec![turn_intent_line(app, start)]);
784
785 if latest && let Some(line) = selected_item_context_line(app) {
786 push_section(&mut out, "Selected item", vec![line]);
787 }
788
789 push_section(
790 &mut out,
791 "To-do",
792 if latest {
793 turn_todo_lines(app)
794 } else {
795 Vec::new()
796 },
797 );
798 let mut timeline = turn_full_conversation_lines(app, start, end);
799 if !timeline.is_empty() {
800 timeline.push(String::new());
801 }
802 timeline.extend(turn_timeline_lines(app, start, end));
803 push_section(&mut out, "Turn timeline", timeline);
804 push_section(
805 &mut out,
806 "Files changed",
807 turn_files_changed(app, start, end),
808 );
809 push_section(
810 &mut out,
811 "Diagnostics loop",
812 if latest {
813 turn_diagnostics_lines(app)
814 } else {
815 Vec::new()
816 },
817 );
818 push_section(
819 &mut out,
820 "Tests / verifier",
821 turn_verifier_lines(app, start, end),
822 );
823 push_section(
824 &mut out,
825 "Approvals / denials",
826 if latest {
827 turn_approvals_lines(app)
828 } else {
829 Vec::new()
830 },
831 );
832 push_section(
833 &mut out,
834 "Model route + tokens/cost",
835 if latest {
836 turn_route_lines(app)
837 } else {
838 Vec::new()
839 },
840 );
841 push_section(
842 &mut out,
843 "Final result / status",
844 turn_result_lines(app, start, end, ResultDetail::Full),
845 );
846
847 out.join("\n")
848 }
849
850 /// Source-faithful, turn-scoped transcript for the inspector page. The normal
851 /// transcript can stay compact/folded; this explicit detail surface preserves
852 /// complete recorded input, reasoning, tool results, and assistant output.
853 fn turn_full_conversation_lines(app: &App, start: usize, end: usize) -> Vec<String> {
854 let thinking_total = (start..end)
855 .filter(|&idx| {
856 matches!(
857 app.cell_at_virtual_index(idx),
858 Some(HistoryCell::Thinking { .. })
859 )
860 })
861 .count();
862 let mut thinking_position = 0usize;
863 let mut out = Vec::new();
864
865 for idx in start..end {
866 let Some(cell) = app.cell_at_virtual_index(idx) else {
867 continue;
868 };
869 let tag = match cell {
870 HistoryCell::User { .. } => "[›]".to_string(),
871 HistoryCell::Thinking { streaming, .. } => {
872 thinking_position += 1;
873 format!(
874 "[∿ {} {thinking_position}/{thinking_total} · {}]",
875 tr(app.ui_locale, MessageId::PhaseReasoning),
876 tr(
877 app.ui_locale,
878 if *streaming {
879 MessageId::AutomationRunStatusRunning
880 } else {
881 MessageId::PhaseDone
882 }
883 )
884 )
885 }
886 HistoryCell::Tool(_) => format!("[⚙ {}]", tr(app.ui_locale, MessageId::PhaseUsingTool)),
887 HistoryCell::SubAgent(_) => "[↗]".to_string(),
888 HistoryCell::Assistant { streaming, .. } => format!(
889 "[◆ · {}]",
890 tr(
891 app.ui_locale,
892 if *streaming {
893 MessageId::AutomationRunStatusRunning
894 } else {
895 MessageId::PhaseDone
896 }
897 )
898 ),
899 HistoryCell::Error { .. } => "[!]".to_string(),
900 HistoryCell::Automation(_) => "[⏱]".to_string(),
901 HistoryCell::ApprovalReceipt(_) => "[✓]".to_string(),
902 HistoryCell::System { .. } | HistoryCell::ArchivedContext { .. } => "[i]".to_string(),
903 };
904 if !out.is_empty() {
905 out.push(String::new());
906 }
907 out.push(tag);
908 let body = history_cell_to_clipboard_text(cell, 120);
909 if body.trim().is_empty() {
910 out.push("—".to_string());
911 } else {
912 out.push(body);
913 }
914 }
915
916 out
917 }
918
919 /// Build a compact, pasteable Markdown handoff of the current/latest turn
920 /// (issue #4108).
921 ///
922 /// Reuses the exact same turn scope (`current_turn_range`) and the same
923 /// per-section data helpers as the Turn Inspector (#4104), so the handoff can
924 /// never drift from what Ctrl+O shows — it only re-renders that data as
925 /// Markdown headings + bullets instead of the inspector's box-drawn rules.
926 /// Unavailable sections degrade to a short `—` (and the optional Plan section
927 /// is dropped entirely when empty) so the artifact stays paste-ready without
928 /// leaving a heading over a blank void — the same graceful-degrade contract the
929 /// inspector already follows.
930 pub(crate) fn turn_handoff_markdown(app: &App) -> String {
931 let (start, end) = current_turn_range(app);
932 let mut out: Vec<String> = Vec::new();
933
934 // Title + identity — turn id when known, else the turn counter, else a
935 // bare heading so an empty transcript still yields a coherent artifact.
936 let heading = if app.turn_counter > 0 {
937 format!("# Turn handoff — Turn #{}", app.turn_counter)
938 } else if let Some(turn_id) = app.runtime_turn_id.as_ref() {
939 format!("# Turn handoff — {}", short_turn_id(turn_id))
940 } else {
941 "# Turn handoff".to_string()
942 };
943 out.push(heading);
944
945 let status = match app.runtime_turn_status.as_deref() {
946 Some("in_progress") => "in progress",
947 Some(other) => other,
948 None => "idle",
949 };
950 out.push(format!(
951 "_Status: {status} · generated {}_",
952 chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
953 ));
954
955 push_md_section(&mut out, "Intent", vec![turn_intent_line(app, start)]);
956
957 // To-do is optional context: include it only when the canonical list has
958 // items, keeping the handoff compact without recreating a second plan.
959 let todos = turn_todo_lines(app);
960 if !todos.is_empty() {
961 push_md_section(&mut out, "To-do", md_bullets(todos));
962 }
963
964 push_md_section(
965 &mut out,
966 "Files changed",
967 md_bullets(turn_files_changed(app, start, end)),
968 );
969 push_md_section(
970 &mut out,
971 "Turn timeline",
972 md_bullets(turn_timeline_lines(app, start, end)),
973 );
974 push_md_section(
975 &mut out,
976 "Tests / verifier",
977 md_bullets(turn_verifier_lines(app, start, end)),
978 );
979 push_md_section(
980 &mut out,
981 "Model route + tokens/cost",
982 md_bullets(turn_route_lines(app)),
983 );
984 push_md_section(
985 &mut out,
986 "Result / status",
987 md_bullets(turn_result_lines(app, start, end, ResultDetail::Compact)),
988 );
989
990 // Trailing newline keeps the artifact clean when pasted into a PR body.
991 out.push(String::new());
992 out.join("\n")
993 }
994
995 /// Append a `## Title` Markdown section. An empty body degrades to a single
996 /// `—` line so a heading is never followed by a void — the Markdown analogue
997 /// of [`push_section`]'s `none` degrade.
998 fn push_md_section(out: &mut Vec<String>, title: &str, body: Vec<String>) {
999 out.push(String::new());
1000 out.push(format!("## {title}"));
1001 if body.is_empty() {
1002 out.push("—".to_string());
1003 } else {
1004 out.extend(body);
1005 }
1006 }
1007
1008 /// Convert Turn Inspector section lines into Markdown bullet rows. Inspector
1009 /// list helpers prefix rows with `• `; swap that for `- `, and bullet the
1010 /// key/value rows (route, tokens, status) too so the whole section is valid
1011 /// Markdown.
1012 fn md_bullets(lines: Vec<String>) -> Vec<String> {
1013 lines
1014 .into_iter()
1015 .map(|line| {
1016 let body = line.strip_prefix("• ").unwrap_or(line.as_str());
1017 format!("- {body}")
1018 })
1019 .collect()
1020 }
1021
1022 /// Append a `── Title ──` section. An empty body degrades to a single
1023 /// `none` line so the section header is never followed by a blank void.
1024 fn push_section(out: &mut Vec<String>, title: &str, body: Vec<String>) {
1025 out.push(String::new());
1026 out.push(format!("── {title} ──"));
1027 if body.is_empty() {
1028 out.push("none".to_string());
1029 } else {
1030 out.extend(body);
1031 }
1032 }
1033
1034 /// Section 1 — intent / user-prompt summary for the turn.
1035 fn turn_intent_line(app: &App, start: usize) -> String {
1036 if let Some(HistoryCell::User { content }) = app.cell_at_virtual_index(start) {
1037 let summary = one_line_summary(content, 240);
1038 if !summary.is_empty() {
1039 return summary;
1040 }
1041 }
1042 if let Some(prompt) = app.last_submitted_prompt.as_deref() {
1043 let summary = one_line_summary(prompt, 240);
1044 if !summary.is_empty() {
1045 return summary;
1046 }
1047 }
1048 "—".to_string()
1049 }
1050
1051 /// Optional selected-item context. The first view is the turn overview, but
1052 /// when the user has an activity cell selected we surface it plus the Alt+V
1053 /// affordance so the Ctrl+O / Alt+V split stays discoverable.
1054 fn selected_item_context_line(app: &App) -> Option<String> {
1055 let idx = selected_transcript_cell_index(app)?;
1056 let cell = app.cell_at_virtual_index(idx)?;
1057 let label = truncate_line_to_width(&activity_cell_label(app, idx, cell), 48);
1058 let hint = if app.cell_has_detail_target(idx) {
1059 let details = crate::tui::shell_key_routing::display_chord(
1060 crate::tui::shell_key_routing::binding(
1061 crate::tui::shell_key_routing::ShellBindingId::ToolDetails,
1062 )
1063 .footer_chord,
1064 );
1065 if matches!(cell, HistoryCell::Error { .. }) {
1066 format!(" · {details} opens the full error")
1067 } else {
1068 format!(" · {details} opens its raw detail")
1069 }
1070 } else {
1071 String::new()
1072 };
1073 Some(format!("{label}{hint}"))
1074 }
1075
1076 /// Section 2 — canonical To-do state.
1077 fn turn_todo_lines(app: &App) -> Vec<String> {
1078 let mut lines = Vec::new();
1079
1080 if let Ok(todos) = app.todos.try_lock() {
1081 let snapshot = todos.snapshot();
1082 if !snapshot.items.is_empty() {
1083 lines.push(format!("To-do: {}% settled", snapshot.completion_pct));
1084 for item in &snapshot.items {
1085 lines.push(format!(
1086 "{} {}",
1087 todo_status_glyph(&item.status),
1088 truncate_line_to_width(&item.content, 72)
1089 ));
1090 }
1091 }
1092 }
1093
1094 lines
1095 }
1096
1097 fn todo_status_glyph(status: &codewhale_engine::tools::todo::TodoStatus) -> &'static str {
1098 match status {
1099 codewhale_engine::tools::todo::TodoStatus::Completed => "[x]",
1100 codewhale_engine::tools::todo::TodoStatus::InProgress => "[~]",
1101 codewhale_engine::tools::todo::TodoStatus::Pending => "[ ]",
1102 codewhale_engine::tools::todo::TodoStatus::Cancelled => "[-]",
1103 }
1104 }
1105
1106 /// Section 3 — chronological turn timeline with compact action affordances.
1107 fn turn_timeline_lines(app: &App, start: usize, end: usize) -> Vec<String> {
1108 let mut rows = Vec::new();
1109 for idx in start..end {
1110 let Some(cell) = app.cell_at_virtual_index(idx) else {
1111 continue;
1112 };
1113 match cell {
1114 HistoryCell::User { content } => {
1115 let summary = one_line_summary(content, 96);
1116 rows.push(timeline_row("user prompt", &summary, None, None, &[]));
1117 }
1118 HistoryCell::Thinking {
1119 content,
1120 streaming,
1121 duration_secs,
1122 } => {
1123 let summary = one_line_summary(content, 88);
1124 let status = streaming.then_some("running").unwrap_or("done");
1125 let duration = duration_secs.map(|secs| {
1126 codewhale_command_contract::elapsed::format_elapsed_ms((secs * 1000.0) as u64)
1127 });
1128 let actions = timeline_cell_actions(app, idx, cell);
1129 rows.push(timeline_row(
1130 "reasoning",
1131 &summary,
1132 Some(status),
1133 duration.as_deref(),
1134 &actions,
1135 ));
1136 }
1137 HistoryCell::Tool(tool) => {
1138 let (kind, summary) = timeline_tool_summary(app, idx, tool);
1139 let duration = tool_duration_for_activity(tool)
1140 .map(codewhale_command_contract::elapsed::format_elapsed_ms);
1141 let status = tool
1142 .status()
1143 .map(|status| tool_status_label(status, app.ui_locale));
1144 let actions = timeline_cell_actions(app, idx, cell);
1145 rows.push(timeline_row(
1146 kind,
1147 &summary,
1148 status.as_deref(),
1149 duration.as_deref(),
1150 &actions,
1151 ));
1152 }
1153 HistoryCell::SubAgent(_) => {
1154 let summary = detail_target_label(app, idx).unwrap_or_else(|| "sub-agent".into());
1155 let actions = timeline_cell_actions(app, idx, cell);
1156 rows.push(timeline_row("sub-agent", &summary, None, None, &actions));
1157 }
1158 HistoryCell::Assistant { content, streaming } => {
1159 let summary = one_line_summary(content, 96);
1160 let status = streaming.then_some("streaming").unwrap_or("done");
1161 rows.push(timeline_row(
1162 "assistant result",
1163 &summary,
1164 Some(status),
1165 None,
1166 &[],
1167 ));
1168 }
1169 HistoryCell::Error {
1170 message, severity, ..
1171 } => {
1172 let summary = one_line_summary(message, 96);
1173 let status = severity.to_string();
1174 rows.push(timeline_row("error", &summary, Some(&status), None, &[]));
1175 }
1176 HistoryCell::Automation(cell) => {
1177 let summary = one_line_summary(&cell.plain_summary(), 96);
1178 rows.push(timeline_row("automation", &summary, None, None, &[]));
1179 }
1180 HistoryCell::ApprovalReceipt(cell) => {
1181 let summary = one_line_summary(&cell.plain_summary(), 96);
1182 rows.push(timeline_row("approval", &summary, None, None, &[]));
1183 }
1184 HistoryCell::System { content }
1185 | HistoryCell::ArchivedContext {
1186 summary: content, ..
1187 } => {
1188 let summary = one_line_summary(content, 96);
1189 rows.push(timeline_row("system note", &summary, None, None, &[]));
1190 }
1191 }
1192 }
1193 rows.push(turn_checkpoint_timeline_row(app));
1194 rows.into_iter()
1195 .enumerate()
1196 .map(|(idx, row)| format!("{}. {row}", idx + 1))
1197 .collect()
1198 }
1199
1200 fn timeline_tool_summary(app: &App, idx: usize, tool: &ToolCell) -> (&'static str, String) {
1201 match tool {
1202 ToolCell::Exec(exec) if command_looks_like_verifier(&exec.command) => {
1203 ("test/verifier", truncate_line_to_width(&exec.command, 88))
1204 }
1205 ToolCell::Exec(exec) => ("shell command", truncate_line_to_width(&exec.command, 88)),
1206 ToolCell::Exploring(explore) => (
1207 "read/search",
1208 format!(
1209 "{} item{}",
1210 explore.entries.len(),
1211 if explore.entries.len() == 1 { "" } else { "s" }
1212 ),
1213 ),
1214 ToolCell::PlanUpdate(_) => ("legacy plan", "Legacy plan metadata replayed".to_string()),
1215 ToolCell::PatchSummary(patch) => {
1216 let summary = one_line_summary(&patch.summary, 72);
1217 if summary.is_empty() {
1218 ("edit", truncate_line_to_width(&patch.path, 88))
1219 } else {
1220 (
1221 "edit",
1222 truncate_line_to_width(&format!("{} — {summary}", patch.path), 88),
1223 )
1224 }
1225 }
1226 ToolCell::Review(review) => {
1227 let target = one_line_summary(&review.target, 88);
1228 (
1229 "review",
1230 if target.is_empty() {
1231 "code review".to_string()
1232 } else {
1233 target
1234 },
1235 )
1236 }
1237 ToolCell::Mcp(mcp) => ("MCP tool", truncate_line_to_width(&mcp.tool, 88)),
1238 ToolCell::ViewImage(image) => (
1239 "image",
1240 truncate_line_to_width(&image.path.display().to_string(), 88),
1241 ),
1242 ToolCell::WebSearch(search) => ("web search", truncate_line_to_width(&search.query, 88)),
1243 ToolCell::DataDisplay(data) => (
1244 "show_data",
1245 match &data.display {
1246 Ok(display) => truncate_line_to_width(
1247 &codewhale_ratatui::text::display_safe(display.label()),
1248 88,
1249 ),
1250 Err(error) => {
1251 truncate_line_to_width(&codewhale_ratatui::text::display_safe(error), 88)
1252 }
1253 },
1254 ),
1255 ToolCell::Generic(generic) => {
1256 let mut label =
1257 detail_target_label(app, idx).unwrap_or_else(|| generic.name.replace('_', " "));
1258 if let Some(input) = generic.input_summary.as_deref().map(str::trim)
1259 && !input.is_empty()
1260 {
1261 label.push_str(" · ");
1262 label.push_str(input);
1263 }
1264 (
1265 generic_tool_timeline_kind(generic),
1266 truncate_line_to_width(&label, 88),
1267 )
1268 }
1269 }
1270 }
1271
1272 fn generic_tool_timeline_kind(generic: &crate::tui::history::GenericToolCell) -> &'static str {
1273 let name = generic.name.as_str();
1274 if generic.is_diff || name.contains("diff") {
1275 "diff"
1276 } else if matches!(name, "read_file" | "list_files" | "glob" | "grep_files")
1277 || name.contains("read")
1278 || name.contains("search")
1279 || name.contains("grep")
1280 {
1281 "read/search"
1282 } else if matches!(name, "apply_patch" | "edit_file" | "write_file")
1283 || name.contains("patch")
1284 || name.contains("edit")
1285 || name.contains("write")
1286 {
1287 "edit"
1288 } else if name.contains("approval") {
1289 "approval"
1290 } else if name.contains("diagnostic") || name.contains("lsp") {
1291 "diagnostics"
1292 } else {
1293 "tool"
1294 }
1295 }
1296
1297 fn timeline_cell_actions(app: &App, idx: usize, cell: &HistoryCell) -> Vec<String> {
1298 let mut actions = Vec::new();
1299 if app.cell_has_detail_target(idx) {
1300 let details = crate::tui::shell_key_routing::display_chord(
1301 crate::tui::shell_key_routing::binding(
1302 crate::tui::shell_key_routing::ShellBindingId::ToolDetails,
1303 )
1304 .footer_chord,
1305 );
1306 // Diff-bearing cells open their diff through the same details chord;
1307 // bare `v` / `d` always type text (TUI-DOG-002), so no bare-key claim.
1308 let is_diff = matches!(cell, HistoryCell::Tool(ToolCell::PatchSummary(_)))
1309 || matches!(
1310 cell,
1311 HistoryCell::Tool(ToolCell::Generic(generic)) if generic.is_diff
1312 );
1313 if is_diff {
1314 actions.push(format!("{details} diff"));
1315 } else if matches!(cell, HistoryCell::Error { .. }) {
1316 actions.push(format!("{details} full error"));
1317 } else {
1318 actions.push(format!("{details} raw detail"));
1319 }
1320 }
1321 actions
1322 }
1323
1324 fn timeline_row(
1325 kind: &str,
1326 summary: &str,
1327 status: Option<&str>,
1328 duration: Option<&str>,
1329 actions: &[String],
1330 ) -> String {
1331 let mut line = if summary.trim().is_empty() {
1332 kind.to_string()
1333 } else {
1334 format!("{kind}: {}", summary.trim())
1335 };
1336 if let Some(status) = status.filter(|s| !s.trim().is_empty()) {
1337 line.push_str(" — ");
1338 line.push_str(status);
1339 }
1340 if let Some(duration) = duration.filter(|s| !s.trim().is_empty()) {
1341 line.push_str(" · ");
1342 line.push_str(duration);
1343 }
1344 if !actions.is_empty() {
1345 line.push_str(" · actions: ");
1346 line.push_str(&actions.join(", "));
1347 }
1348 line
1349 }
1350
1351 fn turn_checkpoint_timeline_row(app: &App) -> String {
1352 if app.turn_counter == 0 {
1353 return "checkpoint: unavailable — no numbered turn snapshot yet · action: e export handoff"
1354 .to_string();
1355 }
1356
1357 let repo = match SnapshotRepo::open_existing(&app.workspace) {
1358 Ok(Some(repo)) => repo,
1359 Ok(None) => {
1360 return "checkpoint: unavailable — no snapshot repo found · action: e export handoff"
1361 .to_string();
1362 }
1363 Err(err) => {
1364 return format!(
1365 "checkpoint: unknown — snapshot repo could not be opened ({}) · action: e export handoff",
1366 truncate_line_to_width(&err.to_string(), 72)
1367 );
1368 }
1369 };
1370 let snapshots = match repo.list(20) {
1371 Ok(snapshots) => snapshots,
1372 Err(err) => {
1373 return format!(
1374 "checkpoint: unknown — snapshot list failed ({}) · action: e export handoff",
1375 truncate_line_to_width(&err.to_string(), 72)
1376 );
1377 }
1378 };
1379 let prefix = format!("pre-turn:{}", app.turn_counter);
1380 let matching = snapshots
1381 .iter()
1382 .find(|snapshot| {
1383 snapshot.label == prefix || snapshot.label.starts_with(&format!("{prefix}:"))
1384 })
1385 .or_else(|| {
1386 snapshots
1387 .iter()
1388 .find(|snapshot| snapshot.label.starts_with("pre-turn:"))
1389 });
1390 if let Some(snapshot) = matching {
1391 let short = &snapshot.id.as_str()[..snapshot.id.as_str().len().min(8)];
1392 format!(
1393 "checkpoint: {} ({short}) available · actions: r restore via /restore (guarded), e export handoff",
1394 truncate_line_to_width(&snapshot.label, 72)
1395 )
1396 } else {
1397 "checkpoint: unavailable — no pre-turn snapshot found · action: e export handoff"
1398 .to_string()
1399 }
1400 }
1401
1402 /// Section 4 — files touched by patch/diff tool cells in the turn.
1403 fn turn_files_changed(app: &App, start: usize, end: usize) -> Vec<String> {
1404 let mut lines = Vec::new();
1405 let mut seen = std::collections::HashSet::new();
1406 for idx in start..end {
1407 let Some(HistoryCell::Tool(tool)) = app.cell_at_virtual_index(idx) else {
1408 continue;
1409 };
1410 match tool {
1411 ToolCell::PatchSummary(patch) if seen.insert(patch.path.clone()) => {
1412 lines.push(format!(
1413 "• {} — {}",
1414 truncate_line_to_width(&patch.path, 60),
1415 tool_status_label(patch.status, app.ui_locale)
1416 ));
1417 }
1418 _ => {}
1419 }
1420 }
1421 lines
1422 }
1423
1424 /// Section 5 — diagnostics / LSP repair loop (#4107).
1425 ///
1426 /// Shows the observable repair loop when LSP produced diagnostics this turn.
1427 /// Stays quiet when LSP is disabled or no diagnostics were found.
1428 fn turn_diagnostics_lines(app: &App) -> Vec<String> {
1429 if !app.lsp_enabled {
1430 return Vec::new();
1431 }
1432 let repair = &app.lsp_repair;
1433 if repair.diagnostics_found == 0 && !repair.injected && !repair.repair_attempted {
1434 return Vec::new();
1435 }
1436 let mut lines = Vec::new();
1437 if repair.diagnostics_found > 0 {
1438 lines.push(format!(
1439 "Found {} diagnostic{} across {} file{}",
1440 repair.diagnostics_found,
1441 if repair.diagnostics_found == 1 {
1442 ""
1443 } else {
1444 "s"
1445 },
1446 repair.files_touched.max(1),
1447 if repair.files_touched == 1 { "" } else { "s" },
1448 ));
1449 }
1450 lines.push(if repair.injected {
1451 "Injected into the next model request".to_string()
1452 } else {
1453 "Queued — not yet injected".to_string()
1454 });
1455 if repair.repair_attempted {
1456 lines.push("Model attempted a repair after injection".to_string());
1457 }
1458 let latest = match repair.latest {
1459 "resolved" => "Latest: resolved",
1460 "still_failing" => "Latest: still failing",
1461 "unavailable" => "Latest: unavailable",
1462 _ => "Latest: unknown",
1463 };
1464 lines.push(latest.to_string());
1465 lines
1466 }
1467
1468 /// Section 6 — tests / verifier results.
1469 ///
1470 /// Heuristic first pass (issue #4107): scans the turn's exec/review tool cells
1471 /// for verifier-shaped commands and reports their status. Degrades to `none`
1472 /// when nothing test-shaped ran.
1473 fn turn_verifier_lines(app: &App, start: usize, end: usize) -> Vec<String> {
1474 let mut lines = Vec::new();
1475 for idx in start..end {
1476 let Some(HistoryCell::Tool(tool)) = app.cell_at_virtual_index(idx) else {
1477 continue;
1478 };
1479 match tool {
1480 ToolCell::Exec(exec) if command_looks_like_verifier(&exec.command) => {
1481 lines.push(format!(
1482 "• {} — {}",
1483 truncate_line_to_width(&exec.command, 56),
1484 tool_status_label(exec.status, app.ui_locale)
1485 ));
1486 }
1487 ToolCell::Review(review) => {
1488 let target = truncate_line_to_width(review.target.trim(), 48);
1489 let target = if target.is_empty() {
1490 "review".to_string()
1491 } else {
1492 format!("review {target}")
1493 };
1494 lines.push(format!(
1495 "• {target} — {}",
1496 tool_status_label(review.status, app.ui_locale)
1497 ));
1498 }
1499 _ => {}
1500 }
1501 }
1502 lines
1503 }
1504
1505 fn command_looks_like_verifier(command: &str) -> bool {
1506 let lower = command.to_lowercase();
1507 [
1508 "test",
1509 "pytest",
1510 "jest",
1511 "cargo check",
1512 "cargo clippy",
1513 "verif",
1514 "lint",
1515 ]
1516 .iter()
1517 .any(|needle| lower.contains(needle))
1518 }
1519
1520 /// Section 7 — approvals / denials.
1521 ///
1522 /// "Approve for session" grants last the conversation; a Deny lasts only
1523 /// the user turn it answered (cleared on `TurnStarted`), so each count names
1524 /// its own scope.
1525 fn turn_approvals_lines(app: &App) -> Vec<String> {
1526 let mut lines = Vec::new();
1527 let approved = app.approval_session_approved.len();
1528 let denied = app.approval_session_denied.len();
1529 if approved > 0 {
1530 lines.push(format!("Approved (session): {approved}"));
1531 }
1532 if denied > 0 {
1533 lines.push(format!("Denied (this turn): {denied}"));
1534 }
1535 lines
1536 }
1537
1538 /// Section 8 — model route plus token/cost accounting.
1539 fn turn_route_lines(app: &App) -> Vec<String> {
1540 let mut lines = Vec::new();
1541
1542 let (provider, model) = if let Some(route) = app
1543 .active_turn
1544 .as_ref()
1545 .and_then(|turn| turn.route.as_ref())
1546 {
1547 let provider = if route.provider == codewhale_config::ProviderKind::Custom {
1548 route.provider_identity.clone()
1549 } else {
1550 route.provider.provider().display_name().to_string()
1551 };
1552 (provider, route.model.clone())
1553 } else {
1554 // Pending and last Auto routes use the same billing-authoritative
1555 // display contract as the header; do not fall back to `auto` after the
1556 // concrete turn route has resolved.
1557 app.effective_route_identity_display()
1558 };
1559 lines.push(format!("Route: {provider} · {model}"));
1560
1561 let auto_receipt = app
1562 .active_turn
1563 .as_ref()
1564 .filter(|turn| turn.route.as_ref().is_some_and(|route| route.auto_model))
1565 .and_then(|turn| turn.auto_route_receipt.as_ref())
1566 .or_else(|| {
1567 app.pending_turn_route
1568 .as_ref()
1569 .filter(|(_, _, auto_model)| *auto_model)
1570 .and(app.pending_auto_route_receipt.as_ref())
1571 })
1572 .or_else(|| {
1573 app.auto_model
1574 .then_some(app.last_auto_route_receipt.as_ref())
1575 .flatten()
1576 });
1577 if let Some(receipt) = auto_receipt {
1578 lines.push(format!(
1579 "Auto decision: {} · {}",
1580 receipt.tier.label(),
1581 receipt.reason.label()
1582 ));
1583 let pair = receipt.pair.fast.as_deref().map_or_else(
1584 || format!("{} (no runnable fast sibling)", receipt.pair.strong),
1585 |fast| format!("{} strong · {fast} fast", receipt.pair.strong),
1586 );
1587 lines.push(format!("Auto pair: {pair}"));
1588 lines.push(format!("Auto scope: {}", receipt.scope.label()));
1589 lines.push(format!("Auto data: {}", receipt.data_path.label()));
1590 lines.extend(auto_router_receipt_lines(receipt));
1591 }
1592
1593 let session = &app.session;
1594 match (session.last_prompt_tokens, session.last_completion_tokens) {
1595 (Some(prompt), Some(completion)) => {
1596 lines.push(format!(
1597 "Tokens (last turn): {prompt} in · {completion} out"
1598 ));
1599 }
1600 (Some(prompt), None) => lines.push(format!("Tokens (last turn): {prompt} in")),
1601 (None, Some(completion)) => lines.push(format!("Tokens (last turn): {completion} out")),
1602 (None, None) => {
1603 if session.total_tokens > 0 {
1604 lines.push(format!("Tokens (session): {}", session.total_tokens));
1605 }
1606 }
1607 }
1608
1609 let chip = app.cumulative_usage_chip();
1610 match &chip {
1611 codewhale_engine::route_billing::UsageChip::Money(amount) => {
1612 lines.push(format!("Cost (session): {amount}"));
1613 }
1614 codewhale_engine::route_billing::UsageChip::PricedSubtotal { .. } => {
1615 lines.push(format!(
1616 "Cost (session): {}",
1617 codewhale_engine::route_billing::format_usage_chip(&chip, app.ui_locale)
1618 .unwrap_or_default()
1619 ));
1620 }
1621 codewhale_engine::route_billing::UsageChip::Allowance { label, used_pct } => {
1622 lines.push(match used_pct {
1623 Some(pct) => format!("Usage plan: {label} ({pct:.0}% used)"),
1624 None => format!("Usage plan: {label}"),
1625 });
1626 }
1627 codewhale_engine::route_billing::UsageChip::Local => {
1628 lines.push("Cost: local".to_string());
1629 }
1630 codewhale_engine::route_billing::UsageChip::Unknown(_) => {
1631 lines.push("Cost (session): not priced yet".to_string());
1632 }
1633 codewhale_engine::route_billing::UsageChip::Hidden => {}
1634 }
1635
1636 lines
1637 }
1638
1639 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1640 enum ResultDetail {
1641 /// Pager content is the review surface and must retain the complete final
1642 /// response. Width wrapping belongs to `PagerView`, not data assembly.
1643 Full,
1644 /// The exported handoff is intentionally a compact overview.
1645 Compact,
1646 }
1647
1648 /// `/status` lines for the router behind an Auto receipt (#6525): the
1649 /// decision-model answer, its cost and latency, and a failing router.
1650 fn auto_router_receipt_lines(
1651 receipt: &codewhale_engine::model_routing::AutoRouteReceipt,
1652 ) -> Vec<String> {
1653 let percent = |bp: u16| format!("{}%", (u32::from(bp) + 50) / 100);
1654 let mut lines = Vec::new();
1655 if let Some(decision) = receipt.decision.as_ref() {
1656 let cost = decision.provider_reported_cost_usd.as_deref().map_or_else(
1657 || "cost not reported".to_string(),
1658 |cost| format!("${cost} (provider-reported)"),
1659 );
1660 let model = decision
1661 .response_model
1662 .as_deref()
1663 .map(|model| format!(" · {model}"))
1664 .unwrap_or_default();
1665 lines.push(format!(
1666 "Auto router: decision model{model} · {} ms · {cost}",
1667 decision.latency_ms
1668 ));
1669 let mut probabilities: Vec<(&String, &u16)> = decision.probabilities_bp.iter().collect();
1670 probabilities.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
1671 let probabilities = probabilities
1672 .into_iter()
1673 .map(|(option, bp)| format!("{option} {}", percent(*bp)))
1674 .collect::<Vec<_>>()
1675 .join(" · ");
1676 let mut choice = format!(
1677 "Auto choice: {} ({probabilities}) · confidence {} (min {})",
1678 decision.choice,
1679 percent(decision.confidence_bp),
1680 percent(decision.min_confidence_bp)
1681 );
1682 if decision.cost_saving_kept_fast {
1683 choice.push_str(" · cost-saving kept fast");
1684 }
1685 if let Some(thinking) = decision.thinking.as_deref() {
1686 choice.push_str(&format!(" · thinking {thinking}"));
1687 }
1688 lines.push(choice);
1689 }
1690 if let Some(failure) = receipt.router_failure {
1691 lines.push(format!(
1692 "Auto router: failing — {} (used the local fallback)",
1693 failure.label()
1694 ));
1695 }
1696 lines
1697 }
1698
1699 fn cleaned_turn_text(text: &str, detail: ResultDetail, max_width: usize) -> String {
1700 if detail == ResultDetail::Compact {
1701 return one_line_summary(text, max_width);
1702 }
1703
1704 let mut cleaned = String::with_capacity(text.len());
1705 codewhale_sanitize::sanitize::strip_ansi_into(text, &mut cleaned);
1706 cleaned.trim().to_string()
1707 }
1708
1709 /// Section 9 — final result / current status.
1710 fn turn_result_lines(app: &App, start: usize, end: usize, detail: ResultDetail) -> Vec<String> {
1711 let mut lines = Vec::new();
1712
1713 let status = match app.runtime_turn_status.as_deref() {
1714 Some("in_progress") => "in progress",
1715 Some(other) => other,
1716 None => "idle",
1717 };
1718 lines.push(format!("Status: {status}"));
1719
1720 let final_text = (start..end)
1721 .rev()
1722 .find_map(|idx| match app.cell_at_virtual_index(idx) {
1723 Some(HistoryCell::Assistant { content, .. }) => {
1724 let text = cleaned_turn_text(content, detail, 200);
1725 (!text.is_empty()).then_some(text)
1726 }
1727 _ => None,
1728 });
1729 if let Some(text) = final_text {
1730 lines.push(format!("Result: {text}"));
1731 } else if status == "in progress" {
1732 lines.push("Result: turn still running".to_string());
1733 } else {
1734 lines.push("Result: —".to_string());
1735 }
1736
1737 let error_text = (start..end)
1738 .rev()
1739 .find_map(|idx| match app.cell_at_virtual_index(idx) {
1740 Some(HistoryCell::Error { message, .. }) => {
1741 let text = cleaned_turn_text(message, detail, 160);
1742 (!text.is_empty()).then_some(text)
1743 }
1744 _ => None,
1745 });
1746 if let Some(err) = error_text {
1747 lines.push(format!("Error: {err}"));
1748 }
1749
1750 lines
1751 }
1752
1753 #[cfg(test)]
1754 mod tests {
1755 use super::*;
1756 use crate::tui::app::{App, LspRepairState, StatusToastLevel, TuiOptions};
1757 use codewhale_runtime::config::Config;
1758 use std::path::PathBuf;
1759
1760 fn test_app() -> App {
1761 let options = TuiOptions {
1762 model: "deepseek-v4-flash".to_string(),
1763 start_in_agent_mode: true,
1764 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
1765 };
1766 App::new(options, &Config::default())
1767 }
1768
1769 #[test]
1770 fn turn_diagnostics_lines_quiet_when_no_activity() {
1771 let mut app = test_app();
1772 app.lsp_enabled = true;
1773 assert!(turn_diagnostics_lines(&app).is_empty());
1774 app.lsp_enabled = false;
1775 assert!(turn_diagnostics_lines(&app).is_empty());
1776 }
1777
1778 #[test]
1779 fn turn_diagnostics_lines_summarize_repair_loop() {
1780 let mut app = test_app();
1781 app.lsp_enabled = true;
1782 app.lsp_repair = LspRepairState {
1783 diagnostics_found: 2,
1784 files_touched: 1,
1785 injected: true,
1786 repair_attempted: true,
1787 latest: "still_failing",
1788 };
1789 let joined = turn_diagnostics_lines(&app).join("\n");
1790 assert!(joined.contains("Found 2 diagnostics"), "{joined}");
1791 assert!(
1792 joined.contains("Injected into the next model request"),
1793 "{joined}"
1794 );
1795 assert!(joined.contains("Model attempted a repair"), "{joined}");
1796 assert!(joined.contains("still failing"), "{joined}");
1797 }
1798
1799 #[test]
1800 fn turn_route_lines_show_decision_evidence_and_a_failing_router() {
1801 let mut app = test_app();
1802 app.auto_model = true;
1803 app.last_effective_provider = Some(codewhale_config::ProviderKind::Deepseek);
1804 app.last_effective_model = Some("deepseek-v4-pro".to_string());
1805 let decision = codewhale_models::auto_route_evidence::AutoRouteDecisionEvidence {
1806 choice: "strong".to_string(),
1807 probabilities_bp: [("fast".to_string(), 1800), ("strong".to_string(), 8200)]
1808 .into_iter()
1809 .collect(),
1810 confidence_bp: 6400,
1811 min_confidence_bp: 5000,
1812 abstained_questions: Vec::new(),
1813 cost_saving_kept_fast: false,
1814 thinking: Some("max".to_string()),
1815 provider_reported_cost_usd: Some("0.000019992".to_string()),
1816 latency_ms: 180,
1817 response_model: Some("typesafe/jev-1.13-20260917".to_string()),
1818 };
1819 let receipt = codewhale_engine::model_routing::AutoRouteReceipt {
1820 tier: codewhale_engine::model_routing::AutoRouteTier::Strong,
1821 pair: codewhale_engine::model_routing::AutoRoutePair {
1822 strong: "deepseek-v4-pro".to_string(),
1823 fast: Some("deepseek-v4-flash".to_string()),
1824 },
1825 scope: codewhale_engine::model_routing::AutoRouteScope::ActiveProvider,
1826 data_path: codewhale_engine::model_routing::AutoRouteDataPath::Decision {
1827 route: codewhale_engine::client::system_one::DecisionRouterRoute::Openrouter,
1828 model: "typesafe/jev-1.13".to_string(),
1829 },
1830 reason: codewhale_engine::model_routing::AutoRouteReason::ClassifierRecommendation,
1831 decision: Some(decision),
1832 router_failure: None,
1833 };
1834 app.last_auto_route_receipt = Some(receipt.clone());
1835 let joined = turn_route_lines(&app).join("\n");
1836 assert!(joined.contains("-> OpenRouter / typesafe/jev-1.13 (decision model)"));
1837 assert!(joined.contains(
1838 "Auto router: decision model · typesafe/jev-1.13-20260917 · 180 ms · $0.000019992 (provider-reported)"
1839 ));
1840 assert!(joined.contains(
1841 "Auto choice: strong (strong 82% · fast 18%) · confidence 64% (min 50%) · thinking max"
1842 ));
1843 assert!(!joined.contains("failing"));
1844
1845 app.last_auto_route_receipt = Some(codewhale_engine::model_routing::AutoRouteReceipt {
1846 reason: codewhale_engine::model_routing::AutoRouteReason::ClassifierFallback(
1847 codewhale_engine::model_routing::AutoRouteHeuristicReason::DeclaredDefault,
1848 ),
1849 decision: None,
1850 router_failure: Some(codewhale_engine::model_routing::AutoRouterFailure::Http {
1851 status: 402,
1852 }),
1853 ..receipt
1854 });
1855 let joined = turn_route_lines(&app).join("\n");
1856 assert!(
1857 joined.contains("Auto router: failing — HTTP 402 (used the local fallback)"),
1858 "{joined}"
1859 );
1860 }
1861
1862 #[test]
1863 fn turn_route_lines_include_truthful_auto_receipt() {
1864 let mut app = test_app();
1865 app.auto_model = true;
1866 app.last_effective_provider = Some(codewhale_config::ProviderKind::Zai);
1867 app.last_effective_model =
1868 Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL.to_string());
1869 app.last_auto_route_receipt = Some(codewhale_engine::model_routing::AutoRouteReceipt {
1870 tier: codewhale_engine::model_routing::AutoRouteTier::Fast,
1871 pair: codewhale_engine::model_routing::AutoRoutePair {
1872 strong: codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
1873 .to_string(),
1874 fast: Some(
1875 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL
1876 .to_string(),
1877 ),
1878 },
1879 scope: codewhale_engine::model_routing::AutoRouteScope::RunnableProviders,
1880 data_path: codewhale_engine::model_routing::AutoRouteDataPath::Classifier {
1881 provider: "deepseek".into(),
1882 provider_kind: codewhale_config::ProviderKind::Deepseek,
1883 model: "deepseek-v4-flash".to_string(),
1884 },
1885 reason: codewhale_engine::model_routing::AutoRouteReason::ClassifierRecommendation,
1886 decision: None,
1887 router_failure: None,
1888 });
1889
1890 let joined = turn_route_lines(&app).join("\n");
1891
1892 assert!(joined.contains("Route: Zhipu AI / Z.ai · GLM-5-Turbo"));
1893 assert!(joined.contains("Auto decision: fast · classifier recommendation"));
1894 assert!(joined.contains("GLM-5.2 strong · GLM-5-Turbo fast"));
1895 assert!(joined.contains("Auto scope: runnable providers"));
1896 assert!(joined.contains(
1897 "Auto data: latest request + bounded recent context -> DeepSeek / deepseek-v4-flash"
1898 ));
1899 assert!(!joined.contains("API_KEY"));
1900 }
1901
1902 #[test]
1903 fn reasoning_detail_text_empty_when_no_thinking() {
1904 let app = test_app();
1905 assert!(reasoning_detail_text(&app).is_none());
1906 }
1907
1908 #[test]
1909 fn reasoning_detail_text_includes_active_cell_reasoning() {
1910 let mut app = test_app();
1911 let mut active = crate::tui::active_cell::ActiveCell::new();
1912 active.push_thinking(HistoryCell::Thinking {
1913 content: "active reasoning one".to_string(),
1914 streaming: true,
1915 duration_secs: None,
1916 });
1917 active.push_thinking(HistoryCell::Thinking {
1918 content: "active reasoning two".to_string(),
1919 streaming: false,
1920 duration_secs: Some(1.0),
1921 });
1922 app.active_cell = Some(active);
1923 app.runtime_turn_id = Some("turn-active-123".to_string());
1924 app.runtime_turn_status = Some("in_progress".to_string());
1925
1926 let body = reasoning_detail_text(&app).expect("active reasoning should produce detail");
1927 assert!(body.contains("Thinking chunk 1 of 2"), "{body}");
1928 assert!(body.contains("Thinking chunk 2 of 2"), "{body}");
1929 assert!(body.contains("active reasoning one"), "{body}");
1930 assert!(body.contains("active reasoning two"), "{body}");
1931 assert!(body.contains("running"), "{body}");
1932 }
1933
1934 #[test]
1935 fn reasoning_detail_text_scopes_to_latest_turn_without_selection() {
1936 let mut app = test_app();
1937 app.history = vec![
1938 HistoryCell::User {
1939 content: "first prompt".to_string(),
1940 },
1941 HistoryCell::Thinking {
1942 content: "first turn reasoning".to_string(),
1943 streaming: false,
1944 duration_secs: Some(1.0),
1945 },
1946 HistoryCell::Assistant {
1947 content: "first reply".to_string(),
1948 streaming: false,
1949 },
1950 HistoryCell::User {
1951 content: "second prompt".to_string(),
1952 },
1953 HistoryCell::Thinking {
1954 content: "second turn reasoning".to_string(),
1955 streaming: false,
1956 duration_secs: Some(1.0),
1957 },
1958 HistoryCell::Assistant {
1959 content: "second reply".to_string(),
1960 streaming: false,
1961 },
1962 ];
1963 app.resync_history_revisions();
1964
1965 let body =
1966 reasoning_detail_text(&app).expect("latest turn reasoning should produce detail");
1967 assert!(body.contains("second turn reasoning"), "{body}");
1968 assert!(
1969 !body.contains("first turn reasoning"),
1970 "reasoning detail without selection must scope to the latest turn: {body}"
1971 );
1972 }
1973
1974 #[test]
1975 fn turn_range_for_index_scopes_to_containing_turn() {
1976 let mut app = test_app();
1977 app.history = vec![
1978 HistoryCell::User {
1979 content: "first prompt".to_string(),
1980 },
1981 HistoryCell::Thinking {
1982 content: "first turn reasoning".to_string(),
1983 streaming: false,
1984 duration_secs: Some(1.0),
1985 },
1986 HistoryCell::Assistant {
1987 content: "first reply".to_string(),
1988 streaming: false,
1989 },
1990 HistoryCell::User {
1991 content: "second prompt".to_string(),
1992 },
1993 HistoryCell::Thinking {
1994 content: "second turn reasoning".to_string(),
1995 streaming: false,
1996 duration_secs: Some(1.0),
1997 },
1998 HistoryCell::Assistant {
1999 content: "second reply".to_string(),
2000 streaming: false,
2001 },
2002 ];
2003 app.resync_history_revisions();
2004
2005 let (start, end) = turn_range_for_index(&app, 1);
2006 assert_eq!(start, 0, "first turn should start at user cell 0");
2007 assert_eq!(end, 3, "first turn should end before second user cell");
2008
2009 let (start, end) = turn_range_for_index(&app, 4);
2010 assert_eq!(start, 3, "second turn should start at user cell 3");
2011 assert_eq!(end, 6, "second turn should run to end of transcript");
2012 }
2013
2014 #[test]
2015 fn open_reasoning_detail_pager_pushes_reasoning_detail_pager() {
2016 let mut app = test_app();
2017 app.history = vec![HistoryCell::Thinking {
2018 content: "recorded reasoning".to_string(),
2019 streaming: false,
2020 duration_secs: Some(1.0),
2021 }];
2022 app.resync_history_revisions();
2023 let revisions = app.history_revisions.clone();
2024 app.viewport.transcript_cache.ensure(
2025 &app.history,
2026 &revisions,
2027 100,
2028 app.transcript_render_options(),
2029 );
2030 app.viewport.last_transcript_area = Some(ratatui::layout::Rect {
2031 x: 0,
2032 y: 0,
2033 width: 80,
2034 height: 24,
2035 });
2036
2037 assert!(open_reasoning_detail_pager(&mut app));
2038 let top = app.view_stack.top_kind();
2039 assert_eq!(top, Some(crate::tui::views::ModalKind::Pager));
2040 }
2041
2042 #[test]
2043 fn copy_cell_to_clipboard_uses_canonical_assistant_source() {
2044 let mut app = test_app();
2045 let content = "A long response with literal ● and ▏ glyphs that wraps visually.";
2046 app.history = vec![HistoryCell::Assistant {
2047 content: content.to_string(),
2048 streaming: false,
2049 }];
2050 app.resync_history_revisions();
2051 app.viewport.last_transcript_area = Some(ratatui::layout::Rect {
2052 x: 0,
2053 y: 0,
2054 width: 12,
2055 height: 24,
2056 });
2057
2058 assert!(copy_cell_to_clipboard(&mut app, 0));
2059 assert_eq!(app.clipboard.last_written_text(), Some(content));
2060 let toast = app
2061 .active_status_toast(crate::tui::underwater::ShellPhase::Done)
2062 .unwrap();
2063 assert_eq!(toast.kind, crate::tui::app::StatusToastKind::CopyReceipt);
2064 assert_eq!(toast.ttl_ms, Some(4_000));
2065 assert_eq!(app.visible_notice_text(), Some(toast.text));
2066 app.clipboard = crate::tui::clipboard::ClipboardHandler::unavailable_for_test(false);
2067 assert!(!copy_cell_to_clipboard(&mut app, 0));
2068 let failure = app
2069 .active_status_toast(crate::tui::underwater::ShellPhase::Done)
2070 .unwrap();
2071 assert_eq!(failure.level, StatusToastLevel::Error);
2072 assert_eq!(failure.ttl_ms, Some(App::STICKY_ERROR_TTL_MS));
2073 let done = crate::tui::underwater::ShellPhase::Done;
2074 app.push_status_toast_record(crate::tui::app::StatusToast::standing(
2075 "Save failed",
2076 StatusToastLevel::Error,
2077 "session-save",
2078 ));
2079 assert_eq!(app.active_status_toast(done).unwrap().text, "Save failed");
2080 app.retire_event_notices("session-save");
2081 app.acknowledge_sticky_on_composer_activity();
2082 assert!(app.active_status_toast(done).is_none());
2083 assert!(!copy_cell_to_clipboard(&mut app, 0));
2084 app.clipboard = crate::tui::clipboard::ClipboardHandler::for_test(false, false);
2085 assert!(copy_cell_to_clipboard(&mut app, 0));
2086 assert_eq!(
2087 app.active_status_toast(done).unwrap().text,
2088 "Message copied"
2089 );
2090 app.history[0] = HistoryCell::User {
2091 content: String::new(),
2092 };
2093 assert!(!copy_cell_to_clipboard(&mut app, 0));
2094 assert_eq!(
2095 app.active_status_toast(done).unwrap().text,
2096 "Message is empty"
2097 );
2098 app.set_sticky_status("Unrelated failure", StatusToastLevel::Error, None);
2099 assert!(!copy_cell_to_clipboard(&mut app, 1));
2100 assert_eq!(
2101 app.active_status_toast(done).unwrap().text,
2102 "Unrelated failure"
2103 );
2104 }
2105
2106 #[test]
2107 fn focused_pager_and_copy_use_the_same_cell_target() {
2108 let mut app = test_app();
2109 app.history = vec![HistoryCell::Assistant {
2110 content: "focused markdown **answer**".to_string(),
2111 streaming: false,
2112 }];
2113 app.resync_history_revisions();
2114 app.viewport.last_transcript_area = Some(ratatui::layout::Rect {
2115 x: 0,
2116 y: 0,
2117 width: 80,
2118 height: 24,
2119 });
2120
2121 assert!(open_focused_cell_pager(&mut app));
2122 assert_eq!(
2123 app.view_stack.top_kind(),
2124 Some(crate::tui::views::ModalKind::Pager)
2125 );
2126 app.view_stack.pop();
2127 assert!(copy_focused_cell(&mut app));
2128 assert_eq!(
2129 app.clipboard.last_written_text(),
2130 Some("focused markdown **answer**")
2131 );
2132 }
2133
2134 #[test]
2135 fn turn_inspector_copy_answer_copies_only_the_latest_completed_answer() {
2136 use crate::tui::history::GenericToolCell;
2137 use crate::tui::views::{ModalView, ViewAction, ViewEvent};
2138 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
2139
2140 let mut app = test_app();
2141 app.history = vec![
2142 HistoryCell::User {
2143 content: "please summarize".to_string(),
2144 },
2145 HistoryCell::Thinking {
2146 content: "private reasoning trace".to_string(),
2147 streaming: false,
2148 duration_secs: Some(1.0),
2149 },
2150 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
2151 name: "read_file".to_string(),
2152 status: ToolStatus::Success,
2153 input_summary: Some("src/lib.rs".to_string()),
2154 output: Some("raw tool result body".to_string()),
2155 prompts: None,
2156 spillover_path: None,
2157 output_summary: None,
2158 is_diff: false,
2159 })),
2160 HistoryCell::System {
2161 content: "runtime status note".to_string(),
2162 },
2163 HistoryCell::Assistant {
2164 content: "still streaming partial".to_string(),
2165 streaming: true,
2166 },
2167 HistoryCell::Assistant {
2168 content: "FINAL ANSWER\nauthored markdown".to_string(),
2169 streaming: false,
2170 },
2171 ];
2172
2173 assert!(open_turn_inspector_pager(&mut app));
2174 let mut view = app.view_stack.pop().expect("turn inspector pager");
2175 let pager = view
2176 .as_any_mut()
2177 .downcast_mut::<PagerView>()
2178 .expect("turn inspector should reuse PagerView");
2179 let copied = match pager.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)) {
2180 ViewAction::Emit(ViewEvent::CopyToClipboard { text, label }) => {
2181 assert_eq!(label, "Answer");
2182 text
2183 }
2184 other => panic!("expected answer copy event, got {other:?}"),
2185 };
2186
2187 assert_eq!(copied, "FINAL ANSWER\nauthored markdown");
2188 for excluded in [
2189 "please summarize",
2190 "private reasoning trace",
2191 "raw tool result body",
2192 "runtime status note",
2193 "still streaming partial",
2194 ] {
2195 assert!(
2196 !copied.contains(excluded),
2197 "answer copy leaked {excluded:?}"
2198 );
2199 }
2200 }
2201 struct PrivateArtifactRoot {
2202 sessions: Option<PathBuf>,
2203 spillover: Option<PathBuf>,
2204 _guard: std::sync::MutexGuard<'static, ()>,
2205 }
2206 impl PrivateArtifactRoot {
2207 fn set(path: PathBuf) -> Self {
2208 let guard = codewhale_engine::tools::truncate::TEST_SPILLOVER_GUARD
2209 .lock()
2210 .unwrap_or_else(|error| error.into_inner());
2211 let spillover = codewhale_engine::tools::truncate::set_test_spillover_root(Some(
2212 path.join("legacy"),
2213 ));
2214 Self {
2215 sessions: codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(path)),
2216 spillover,
2217 _guard: guard,
2218 }
2219 }
2220 }
2221 impl Drop for PrivateArtifactRoot {
2222 fn drop(&mut self) {
2223 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.sessions.take());
2224 codewhale_engine::tools::truncate::set_test_spillover_root(self.spillover.take());
2225 }
2226 }
2227 fn owned_artifact_fixture(reference: &str) -> Option<String> {
2228 use crate::tui::views::{ModalView, ViewAction, ViewEvent};
2229 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
2230 tokio::runtime::Builder::new_current_thread()
2231 .enable_all()
2232 .build()
2233 .unwrap()
2234 .block_on(async {
2235 let mut pager = PagerView::from_text("fixture", "", 80).with_owned_evidence(
2236 PathBuf::from("."),
2237 "session-a".to_string(),
2238 reference.to_string(),
2239 );
2240 tokio::time::timeout(std::time::Duration::from_secs(5), async {
2241 while !matches!(pager.tick(), ViewAction::Redraw) {
2242 tokio::time::sleep(std::time::Duration::from_millis(1)).await;
2243 }
2244 })
2245 .await
2246 .expect("owned evidence pager did not finish");
2247 match pager.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)) {
2248 ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) => Some(text),
2249 _ => None,
2250 }
2251 })
2252 }
2253
2254 #[test]
2255 fn owned_artifact_pager_reads_regular_exact_session_output() {
2256 let _guard = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
2257 .lock()
2258 .unwrap_or_else(|err| err.into_inner());
2259 let temp = tempfile::tempdir().unwrap();
2260 let _root = PrivateArtifactRoot::set(temp.path().join("sessions"));
2261 codewhale_runtime::artifacts::write_session_artifact(
2262 "session-a",
2263 "mutable",
2264 "exact pager output",
2265 )
2266 .unwrap();
2267 assert_eq!(
2268 owned_artifact_fixture("artifacts/mutable.txt").as_deref(),
2269 Some("exact pager output")
2270 );
2271 assert!(owned_artifact_fixture("other/mutable.txt").is_none());
2272 }
2273
2274 #[cfg(unix)]
2275 #[test]
2276 fn owned_artifact_pager_refuses_linked_session_parent() {
2277 let _guard = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
2278 .lock()
2279 .unwrap_or_else(|err| err.into_inner());
2280 let temp = tempfile::tempdir().unwrap();
2281 let sessions = temp.path().join("sessions");
2282 let _root = PrivateArtifactRoot::set(sessions.clone());
2283 std::fs::create_dir(&sessions).unwrap();
2284 let outside = temp.path().join("outside");
2285 std::fs::create_dir_all(outside.join("artifacts")).unwrap();
2286 std::fs::write(
2287 outside.join("artifacts/mutable.txt"),
2288 b"outside-pager-synthetic",
2289 )
2290 .unwrap();
2291 std::os::unix::fs::symlink(&outside, sessions.join("session-a")).unwrap();
2292 assert!(
2293 owned_artifact_fixture("artifacts/mutable.txt").is_none(),
2294 "pager accepted output from a linked outside session"
2295 );
2296 }
2297
2298 #[cfg(unix)]
2299 #[test]
2300 fn owned_artifact_pager_refuses_hardlinked_outside_bytes() {
2301 let _guard = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
2302 .lock()
2303 .unwrap_or_else(|err| err.into_inner());
2304 let temp = tempfile::tempdir().unwrap();
2305 let sessions = temp.path().join("sessions");
2306 let _root = PrivateArtifactRoot::set(sessions.clone());
2307 std::fs::create_dir_all(sessions.join("session-a/artifacts")).unwrap();
2308 let outside = temp.path().join("outside.txt");
2309 std::fs::write(&outside, b"outside-hardlink-synthetic").unwrap();
2310 std::fs::hard_link(&outside, sessions.join("session-a/artifacts/mutable.txt")).unwrap();
2311 assert!(
2312 owned_artifact_fixture("artifacts/mutable.txt").is_none(),
2313 "pager exposed outside hardlinked bytes"
2314 );
2315 }
2316
2317 #[test]
2318 fn owned_artifact_pager_refuses_oversized_output_without_deleting_it() {
2319 let _guard = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
2320 .lock()
2321 .unwrap_or_else(|err| err.into_inner());
2322 let temp = tempfile::tempdir().unwrap();
2323 let sessions = temp.path().join("sessions");
2324 let _root = PrivateArtifactRoot::set(sessions.clone());
2325 let directory = sessions.join("session-a/artifacts");
2326 std::fs::create_dir_all(&directory).unwrap();
2327 let path = directory.join("mutable.txt");
2328 let file = std::fs::File::create(&path).unwrap();
2329 file.set_len(512 * 1024 * 1024 + 1).unwrap();
2330 assert!(
2331 owned_artifact_fixture("artifacts/mutable.txt").is_none(),
2332 "pager allocated oversized session output"
2333 );
2334 assert_eq!(
2335 std::fs::metadata(path).unwrap().len(),
2336 512 * 1024 * 1024 + 1
2337 );
2338 }
2339 }
2340
2340 lines RUST