返回 CodeWhale
agent_details.rs
根目录 / crates / tui / src / tui / agent_details.rs
1 //! Safe, bounded Agent Details projection (#2889).
2 //!
3 //! Since the v0.9.7 "one agent, one destination" inversion, activating an
4 //! agent row opens the agent's transcript surface directly
5 //! (`crate::tui::agent_transcript`); this bounded projection is the secondary
6 //! action, reached from the transcript via the same Alt+V chord that opens
7 //! the transcript from here.
8
9 use std::path::{Component, Path};
10
11 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent};
12 use ratatui::{buffer::Buffer, layout::Rect};
13
14 use crate::tui::app::{
15 AgentCurrentActivityStatus, AgentProgressMeta, App, bound_agent_activity_text,
16 };
17 use crate::tui::pager::PagerView;
18 use crate::tui::views::{ModalKind, ModalView, ViewAction, ViewEvent};
19 use codewhale_engine::tools::subagent::{
20 SubAgentResult, SubAgentStatus, localized_whale_display_names,
21 };
22
23 pub(crate) struct AgentDetailsProjection {
24 pub(crate) title: String,
25 pub(crate) body: String,
26 pub(crate) transcript_available: bool,
27 }
28
29 /// Pager-backed details view with a distinct close receipt and an explicit
30 /// exact-transcript action.
31 pub(crate) struct AgentDetailsView {
32 pager: PagerView,
33 agent_id: String,
34 transcript_available: bool,
35 }
36
37 impl AgentDetailsView {
38 fn new(projection: AgentDetailsProjection, agent_id: impl Into<String>, width: u16) -> Self {
39 let agent_id = agent_id.into();
40 let pager =
41 PagerView::from_text(projection.title, &projection.body, width.saturating_sub(2))
42 .with_copy_text(projection.body);
43 Self {
44 pager,
45 agent_id,
46 transcript_available: projection.transcript_available,
47 }
48 }
49
50 #[cfg(test)]
51 fn body_text(&self) -> String {
52 self.pager.body_text()
53 }
54
55 #[cfg(test)]
56 fn title(&self) -> &str {
57 self.pager.title()
58 }
59 }
60
61 impl ModalView for AgentDetailsView {
62 fn kind(&self) -> ModalKind {
63 ModalKind::Pager
64 }
65
66 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
67 if matches!(key.code, KeyCode::Char('v' | 'V'))
68 && key.modifiers.contains(KeyModifiers::ALT)
69 && self.transcript_available
70 {
71 return ViewAction::Emit(ViewEvent::OpenAgentTranscript {
72 agent_id: self.agent_id.clone(),
73 });
74 }
75 if matches!(key.code, KeyCode::Esc | KeyCode::Left)
76 || (key.code == KeyCode::Char('q') && key.modifiers.is_empty())
77 {
78 return ViewAction::EmitAndClose(ViewEvent::AgentDetailsClosed {
79 agent_id: self.agent_id.clone(),
80 });
81 }
82 self.pager.handle_key(key)
83 }
84
85 fn handle_paste(&mut self, text: &str) -> bool {
86 self.pager.handle_paste(text)
87 }
88
89 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
90 self.pager.handle_mouse(mouse)
91 }
92
93 fn render(&self, area: Rect, buf: &mut Buffer) {
94 self.pager.render(area, buf);
95 }
96
97 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
98 self
99 }
100 }
101
102 pub(crate) fn open_agent_details(app: &mut App, agent_id: &str) -> bool {
103 let Some(projection) = project_agent_details(app, agent_id) else {
104 return false;
105 };
106 let width = app
107 .viewport
108 .last_transcript_area
109 .map(|area| area.width)
110 .unwrap_or(80);
111 app.view_stack
112 .push(AgentDetailsView::new(projection, agent_id, width));
113 true
114 }
115
116 pub(crate) fn safe_agent_display_name(app: &App, agent_id: &str) -> String {
117 let generated = localized_whale_display_names(
118 app.subagent_cache
119 .iter()
120 .map(|agent| (agent.agent_id.as_str(), agent.nickname.as_deref())),
121 app.ui_locale.tag(),
122 );
123 app.agent_given_name(agent_id)
124 .or_else(|| generated.get(agent_id).cloned())
125 .or_else(|| app.agent_label_map.get(agent_id).cloned())
126 .and_then(|name| safe_child_value(app, &name))
127 .unwrap_or_else(|| "Agent".to_string())
128 }
129
130 pub(crate) fn project_agent_details(app: &App, agent_id: &str) -> Option<AgentDetailsProjection> {
131 // The Agents sidebar is the primary worker surface. Consume its exact row
132 // projection so status precedence, model, elapsed time, and steps cannot
133 // diverge between the row and the popup opened from it.
134 let surface_row = crate::tui::sidebar::sidebar_agent_rows(app)
135 .into_iter()
136 .find(|row| row.id == agent_id)?;
137 let agent = app
138 .subagent_cache
139 .iter()
140 .find(|agent| agent.agent_id == agent_id);
141 let meta = app.agent_progress_meta.get(agent_id);
142
143 let display_name = safe_child_value(app, &surface_row.name).unwrap_or_else(|| "Agent".into());
144 let mut lines = Vec::new();
145
146 if let Some(agent) = agent {
147 push_safe_line(app, &mut lines, "Assignment", &agent.assignment.objective);
148
149 // The child's own route receipt is the authoritative resolved truth
150 // for a fleet-dispatched child; `assignment.role` is only the caller's
151 // advisory token and may be absent on a `type`-only dispatch.
152 let route = agent.child_route.as_ref();
153 let role = route
154 .map(|route| route.canonical_role.trim())
155 .filter(|role| !role.is_empty())
156 .or(agent.assignment.role.as_deref())
157 .map(str::trim)
158 .filter(|role| !role.is_empty());
159 if let Some(role) = role {
160 push_safe_line(app, &mut lines, "Role", role);
161 }
162 // Profile is the member that actually resolved. A caller alias/model
163 // label is useful evidence but must not be presented as who ran.
164 let profile = route
165 .and_then(|route| route.resolved_profile_id.as_deref())
166 .map(str::trim)
167 .filter(|profile| !profile.is_empty())
168 .or_else(|| {
169 route
170 .and_then(|route| route.requested_profile.as_deref())
171 .map(str::trim)
172 .filter(|profile| !profile.is_empty())
173 })
174 .unwrap_or_else(|| agent.agent_type.as_str());
175 push_safe_line(app, &mut lines, "Profile", profile);
176 if let Some(requested) = route
177 .and_then(|route| route.requested_profile.as_deref())
178 .map(str::trim)
179 .filter(|requested| !requested.is_empty() && !requested.eq_ignore_ascii_case(profile))
180 {
181 push_safe_line(app, &mut lines, "Requested as", requested);
182 }
183 push_safe_line(app, &mut lines, "Type", agent.agent_type.as_str());
184 lines.push(format!("Parent: {}", safe_parent_name(app, agent)));
185 } else {
186 lines.push(format!("Parent: {}", safe_parent_from_meta(app, meta)));
187 }
188
189 let mut state = vec![surface_row.status.clone()];
190 if let Some(duration_ms) = surface_row.duration_ms {
191 state.push(format!(
192 "elapsed {}",
193 codewhale_command_contract::elapsed::format_elapsed_ms(duration_ms)
194 ));
195 }
196 state.push(format!(
197 "{} {}",
198 surface_row.steps_taken,
199 if surface_row.steps_taken == 1 {
200 "step"
201 } else {
202 "steps"
203 }
204 ));
205 lines.push(format!("State: {}", state.join(" · ")));
206
207 if let Some(meta) = meta
208 && let Some(provider) = meta.resolved_provider.as_deref()
209 {
210 push_safe_line(app, &mut lines, "Provider", provider);
211 } else if let Some(route) = agent.and_then(|agent| agent.child_route.as_ref())
212 && !route.provider_id.trim().is_empty()
213 {
214 push_safe_line(app, &mut lines, "Provider", &route.provider_id);
215 }
216 // Model truth: the resolved route model wins, then the Work-row receipt
217 // (which itself carries `agent.model` or usage-envelope route evidence),
218 // then the child's spawn model.
219 let model = agent
220 .and_then(|agent| agent.child_route.as_ref())
221 .map(|route| route.model_id.clone())
222 .filter(|model| !model.trim().is_empty())
223 .or_else(|| surface_row.model.clone())
224 .or_else(|| {
225 agent
226 .map(|agent| agent.model.clone())
227 .filter(|model| !model.trim().is_empty())
228 })
229 .or_else(|| meta.and_then(|meta| meta.resolved_model.clone()));
230 if let Some(model) = model {
231 push_safe_line(app, &mut lines, "Model", &model);
232 }
233
234 if let Some(agent) = agent {
235 if let Some(workspace) = agent.workspace.as_deref()
236 && let Some(workspace) = safe_workspace(app, workspace)
237 {
238 lines.push(format!("Workspace: {workspace}"));
239 }
240 if let Some(branch) = agent.git_branch.as_deref() {
241 push_safe_line(app, &mut lines, "Branch", branch);
242 }
243 }
244
245 if let Some(activity) = meta.and_then(|meta| meta.current_activity.as_ref())
246 && !matches!(
247 activity.status,
248 AgentCurrentActivityStatus::Done
249 | AgentCurrentActivityStatus::Failed
250 | AgentCurrentActivityStatus::Canceled
251 | AgentCurrentActivityStatus::Interrupted
252 | AgentCurrentActivityStatus::Waiting
253 )
254 {
255 let mut current = vec![activity_status_label(activity.status, app.ui_locale).into_owned()];
256 if let Some(tool) = activity
257 .current_tool
258 .as_deref()
259 .and_then(|tool| safe_child_value(app, tool))
260 {
261 current.push(tool);
262 }
263 if let Some(step) = activity.step {
264 current.push(format!("step {step}"));
265 }
266 if let Some(detail) = activity
267 .detail
268 .as_deref()
269 .and_then(|detail| safe_child_value(app, detail))
270 && !detail.starts_with("started ")
271 && !current.iter().any(|part| part == &detail)
272 {
273 current.push(detail);
274 }
275 lines.push(format!("Current: {}", current.join(" · ")));
276 }
277
278 if let Some(meta) = meta {
279 for action in meta.recent_actions.iter().rev().take(3).rev() {
280 if let Some(tool) = safe_child_value(app, &action.tool) {
281 lines.push(format!(
282 "Recent: {} {tool} · step {}",
283 if action.ok { "✓" } else { "!" },
284 action.step
285 ));
286 }
287 }
288 }
289
290 if let Some(question) = pending_question(agent, meta)
291 && let Some(question) = safe_child_value(app, question)
292 {
293 lines.push(format!("Pending question: {question}"));
294 }
295 if let Some(blocker) = blocker(agent, meta)
296 && let Some(blocker) = safe_child_value(app, blocker)
297 {
298 lines.push(format!("Blocker: {blocker}"));
299 }
300 if let Some(summary) = terminal_summary(agent, meta)
301 && let Some(summary) = safe_child_value(app, summary)
302 {
303 lines.push(format!("Summary: {summary}"));
304 }
305
306 let transcript_available =
307 crate::tui::mouse_ui::agent_transcript_evidence_available(app, agent_id);
308 if transcript_available {
309 // Platform glyph via display_chord (⌥V on macOS, Alt+V elsewhere) —
310 // never the dual "Alt/⌥V" spelling, and cap:verb not a sentence.
311 let chord = crate::tui::shell_key_routing::tool_details_chord();
312 lines.push(format!("Exact evidence: available · {chord}:transcript"));
313 } else {
314 lines.push("Exact evidence: unavailable".to_string());
315 }
316
317 Some(AgentDetailsProjection {
318 title: format!("Agent Details — {display_name}"),
319 body: lines.join("\n"),
320 transcript_available,
321 })
322 }
323
324 fn push_safe_line(app: &App, lines: &mut Vec<String>, label: &str, value: &str) {
325 if let Some(value) = safe_child_value(app, value) {
326 lines.push(format!("{label}: {value}"));
327 }
328 }
329
330 fn safe_child_value(app: &App, value: &str) -> Option<String> {
331 let bounded = bound_agent_activity_text(value);
332 let scrubbed = scrub_raw_agent_ids(app, &bounded);
333 let trimmed = scrubbed.trim();
334 if trimmed.is_empty()
335 || matches!(
336 trimmed.to_ascii_lowercase().as_str(),
337 "none" | "(none)" | "n/a" | "unknown" | "not set" | "not available" | "-"
338 )
339 {
340 None
341 } else {
342 Some(trimmed.to_string())
343 }
344 }
345
346 fn scrub_raw_agent_ids(app: &App, value: &str) -> String {
347 let mut scrubbed = value.to_string();
348 let mut ids: Vec<&str> = app
349 .subagent_cache
350 .iter()
351 .map(|agent| agent.agent_id.as_str())
352 .chain(
353 app.subagent_cache
354 .iter()
355 .filter_map(|agent| agent.parent_run_id.as_deref()),
356 )
357 .chain(app.agent_progress_meta.keys().map(String::as_str))
358 .chain(
359 app.agent_progress_meta
360 .values()
361 .filter_map(|meta| meta.parent_run_id.as_deref()),
362 )
363 .chain(app.agent_progress.keys().map(String::as_str))
364 .chain(app.agent_label_map.keys().map(String::as_str))
365 .collect();
366 ids.sort_unstable_by_key(|id| std::cmp::Reverse(id.len()));
367 ids.dedup();
368 for id in ids {
369 if !id.is_empty() {
370 scrubbed = scrubbed.replace(id, "agent");
371 }
372 }
373
374 let mut output = String::with_capacity(scrubbed.len());
375 let mut token = String::new();
376 let flush = |token: &mut String, output: &mut String| {
377 if token.starts_with("agent_")
378 || token.starts_with("agent-")
379 || token.starts_with("worker:agent_")
380 || token.starts_with("worker:agent-")
381 {
382 output.push_str("agent");
383 } else {
384 output.push_str(token);
385 }
386 token.clear();
387 };
388 for ch in scrubbed.chars() {
389 if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | ':') {
390 token.push(ch);
391 } else {
392 flush(&mut token, &mut output);
393 output.push(ch);
394 }
395 }
396 flush(&mut token, &mut output);
397 output
398 }
399
400 fn safe_parent_name(app: &App, agent: &SubAgentResult) -> String {
401 match agent.parent_run_id.as_deref() {
402 Some(parent_id)
403 if app
404 .subagent_cache
405 .iter()
406 .any(|candidate| candidate.agent_id == parent_id) =>
407 {
408 safe_agent_display_name(app, parent_id)
409 }
410 Some(_) if agent.spawn_depth > 1 => "parent agent".to_string(),
411 _ => "primary session".to_string(),
412 }
413 }
414
415 fn safe_parent_from_meta(app: &App, meta: Option<&AgentProgressMeta>) -> String {
416 match meta.and_then(|meta| meta.parent_run_id.as_deref()) {
417 Some(parent_id)
418 if app
419 .subagent_cache
420 .iter()
421 .any(|candidate| candidate.agent_id == parent_id) =>
422 {
423 safe_agent_display_name(app, parent_id)
424 }
425 Some(_) => "parent agent".to_string(),
426 None => "primary session".to_string(),
427 }
428 }
429
430 fn activity_status_label(
431 status: AgentCurrentActivityStatus,
432 locale: codewhale_localization::Locale,
433 ) -> std::borrow::Cow<'static, str> {
434 if status == AgentCurrentActivityStatus::Parked {
435 return codewhale_localization::tr(
436 locale,
437 codewhale_localization::MessageId::AgentStatusParked,
438 );
439 }
440 std::borrow::Cow::Borrowed(match status {
441 AgentCurrentActivityStatus::Queued => "queued",
442 AgentCurrentActivityStatus::Starting => "starting",
443 AgentCurrentActivityStatus::Running => "running",
444 AgentCurrentActivityStatus::ModelWait => "waiting for model",
445 AgentCurrentActivityStatus::RunningTool => "running tool",
446 AgentCurrentActivityStatus::Waiting => "waiting for input",
447 AgentCurrentActivityStatus::Done => "completed",
448 AgentCurrentActivityStatus::Failed => "failed",
449 AgentCurrentActivityStatus::Canceled => "canceled",
450 AgentCurrentActivityStatus::Interrupted => "interrupted",
451 AgentCurrentActivityStatus::Parked => unreachable!("handled above"),
452 })
453 }
454
455 fn pending_question<'a>(
456 agent: Option<&'a SubAgentResult>,
457 meta: Option<&'a AgentProgressMeta>,
458 ) -> Option<&'a str> {
459 // A parked child carries a `needs_input` note that is phrased as a
460 // question but asks the *operator* nothing — it is the resume recipe.
461 // Reporting it as a pending question is the #5906 complaint verbatim, so
462 // this surface reports the parked state and its recovery instead.
463 if agent.is_some_and(crate::tui::subagent_routing::subagent_is_parked) {
464 return None;
465 }
466 agent
467 .and_then(|agent| agent.needs_input.as_ref())
468 .map(|needs_input| needs_input.question.as_str())
469 .or_else(|| {
470 meta.and_then(|meta| meta.current_activity.as_ref())
471 .filter(|activity| activity.status == AgentCurrentActivityStatus::Waiting)
472 .and_then(|activity| activity.detail.as_deref())
473 })
474 .or_else(|| match agent.map(|agent| &agent.status) {
475 Some(SubAgentStatus::Interrupted(reason)) => Some(reason.as_str()),
476 _ => None,
477 })
478 }
479
480 fn blocker<'a>(
481 agent: Option<&'a SubAgentResult>,
482 meta: Option<&'a AgentProgressMeta>,
483 ) -> Option<&'a str> {
484 match agent.map(|agent| &agent.status) {
485 Some(SubAgentStatus::Failed(error) | SubAgentStatus::Interrupted(error)) => {
486 Some(error.as_str())
487 }
488 Some(SubAgentStatus::BudgetExhausted) => Some("worker budget exhausted"),
489 _ => meta
490 .and_then(|meta| meta.current_activity.as_ref())
491 .filter(|activity| activity.status == AgentCurrentActivityStatus::Failed)
492 .and_then(|activity| activity.detail.as_deref()),
493 }
494 }
495
496 fn terminal_summary<'a>(
497 agent: Option<&'a SubAgentResult>,
498 meta: Option<&'a AgentProgressMeta>,
499 ) -> Option<&'a str> {
500 let agent = agent?;
501 if !matches!(
502 agent.status,
503 SubAgentStatus::Completed | SubAgentStatus::Cancelled
504 ) {
505 return None;
506 }
507 agent.result.as_deref().or_else(|| {
508 meta.and_then(|meta| meta.current_activity.as_ref())
509 .and_then(|activity| activity.detail.as_deref())
510 })
511 }
512
513 fn safe_workspace(app: &App, workspace: &Path) -> Option<String> {
514 if workspace.as_os_str().is_empty() {
515 return None;
516 }
517 if workspace == app.workspace {
518 return Some(".".to_string());
519 }
520 if let Ok(relative) = workspace.strip_prefix(&app.workspace) {
521 let parts: Vec<String> = relative
522 .components()
523 .filter_map(|component| match component {
524 Component::Normal(part) => part.to_str().map(ToString::to_string),
525 _ => None,
526 })
527 .collect();
528 if !parts.is_empty() {
529 return safe_child_value(app, &parts.join("/"));
530 }
531 }
532 workspace
533 .file_name()
534 .and_then(|name| name.to_str())
535 .and_then(|name| safe_child_value(app, name))
536 }
537
538 #[cfg(test)]
539 mod tests {
540 use super::*;
541 use std::path::PathBuf;
542
543 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
544 use ratatui::{buffer::Buffer, layout::Rect};
545 use serde_json::json;
546 use tempfile::tempdir;
547
548 use crate::tui::app::{
549 AgentCurrentActivity, AgentRecentAction, MAX_AGENT_RECENT_ACTIONS, TuiOptions,
550 };
551 use codewhale_agent_contract::role::FleetRole;
552 use codewhale_engine::tools::subagent::{
553 AgentWorkerStatus, ChildRouteReceipt, SubAgentAssignment, SubAgentNeedsInput,
554 };
555 use codewhale_runtime::config::Config;
556
557 fn test_app(workspace: PathBuf) -> App {
558 App::new(
559 TuiOptions {
560 model: "test-model".to_string(),
561 use_mouse_capture: true,
562 max_subagents: 4,
563 ..crate::tui::test_support::test_tui_options(workspace)
564 },
565 &Config::default(),
566 )
567 }
568
569 fn agent(agent_id: &str, status: SubAgentStatus) -> SubAgentResult {
570 SubAgentResult {
571 usage: None,
572 name: agent_id.to_string(),
573 agent_id: agent_id.to_string(),
574 context_mode: "isolated".to_string(),
575 fork_context: false,
576 workspace: None,
577 git_branch: None,
578 agent_type: FleetRole::Builder,
579 assignment: SubAgentAssignment {
580 native_preset: None,
581 objective: "Implement the bounded details route".to_string(),
582 role: Some("worker".to_string()),
583 },
584 model: "deepseek-v4-pro".to_string(),
585 nickname: Some(
586 codewhale_engine::tools::subagent::whale_name_for_id_in_locale(agent_id, "en"),
587 ),
588 status,
589 worker_status: None,
590 runtime_permissions: None,
591 parent_run_id: None,
592 spawn_depth: 1,
593 child_route: None,
594 result: None,
595 steps_taken: 2,
596 checkpoint: None,
597 needs_input: None,
598 duration_ms: 2_500,
599 started_at: None,
600 from_prior_session: false,
601 idle_ms: None,
602 heartbeat_timeout_ms: None,
603 }
604 }
605
606 fn body_for(
607 status: SubAgentStatus,
608 worker_status: AgentWorkerStatus,
609 detail: Option<&str>,
610 ) -> String {
611 let tmp = tempdir().expect("tempdir");
612 let mut app = test_app(tmp.path().to_path_buf());
613 let agent_id = "agent_matrix_subject";
614 let mut child = agent(agent_id, status);
615 child.worker_status = Some(worker_status);
616 match worker_status {
617 AgentWorkerStatus::WaitingForUser => {
618 child.needs_input = Some(SubAgentNeedsInput {
619 question: detail.unwrap_or("Which path should I use?").to_string(),
620 });
621 }
622 AgentWorkerStatus::Completed => child.result = detail.map(str::to_string),
623 _ => {}
624 }
625 app.subagent_cache.push(child);
626 app.agent_progress_meta.insert(
627 agent_id.to_string(),
628 AgentProgressMeta {
629 current_activity: Some(AgentCurrentActivity::bounded(
630 worker_status.into(),
631 detail.map(str::to_string),
632 (worker_status == AgentWorkerStatus::RunningTool)
633 .then(|| "read_file".to_string()),
634 Some(2),
635 )),
636 ..AgentProgressMeta::default()
637 },
638 );
639 project_agent_details(&app, agent_id)
640 .expect("projection")
641 .body
642 }
643
644 #[test]
645 fn provider_free_status_matrix_is_typed_and_bounded() {
646 let running = body_for(
647 SubAgentStatus::Running,
648 AgentWorkerStatus::RunningTool,
649 None,
650 );
651 assert!(running.contains("State: tool · elapsed 2s · 2 steps"));
652 assert!(running.contains("Current: running tool · read_file · step 2"));
653 assert!(!running.contains("Provider:"));
654
655 let waiting = body_for(
656 SubAgentStatus::Running,
657 AgentWorkerStatus::WaitingForUser,
658 Some("Which path should I use?"),
659 );
660 assert!(waiting.contains("State: waiting"));
661 assert!(waiting.contains("Pending question: Which path should I use?"));
662
663 let failed = body_for(
664 SubAgentStatus::Failed("verification failed".to_string()),
665 AgentWorkerStatus::Failed,
666 Some("verification failed"),
667 );
668 assert!(failed.contains("State: failed"));
669 assert!(failed.contains("Blocker: verification failed"));
670
671 let completed = body_for(
672 SubAgentStatus::Completed,
673 AgentWorkerStatus::Completed,
674 Some("all checks passed"),
675 );
676 assert!(completed.contains("State: done"));
677 assert!(completed.contains("Summary: all checks passed"));
678 }
679
680 #[test]
681 fn details_projection_matches_primary_agents_row() {
682 let tmp = tempdir().expect("tempdir");
683 let mut app = test_app(tmp.path().to_path_buf());
684 let agent_id = "agent_row_agreement";
685 let mut child = agent(
686 agent_id,
687 SubAgentStatus::Failed("stale failure".to_string()),
688 );
689 child.model = "kimi-k3".to_string();
690 child.steps_taken = 7;
691 child.duration_ms = 61_000;
692 app.subagent_cache.push(child);
693 app.agent_progress_meta.insert(
694 agent_id.to_string(),
695 AgentProgressMeta {
696 current_activity: Some(AgentCurrentActivity::bounded(
697 AgentCurrentActivityStatus::RunningTool,
698 Some("checking tests".to_string()),
699 Some("cargo test".to_string()),
700 Some(7),
701 )),
702 resolved_model: Some("stale-meta-model".to_string()),
703 ..AgentProgressMeta::default()
704 },
705 );
706
707 let row = crate::tui::sidebar::sidebar_agent_rows(&app)
708 .into_iter()
709 .find(|row| row.id == agent_id)
710 .expect("primary agents row");
711 let details = project_agent_details(&app, agent_id).expect("details projection");
712
713 assert_eq!(row.status, "tool");
714 assert_eq!(row.steps_taken, 7);
715 assert_eq!(row.model.as_deref(), Some("kimi-k3"));
716 assert_eq!(row.duration_ms, Some(61_000));
717 assert!(details.body.contains(&format!(
718 "State: {} · elapsed {} · {} steps",
719 row.status,
720 codewhale_command_contract::elapsed::format_elapsed_ms(
721 row.duration_ms.expect("duration")
722 ),
723 row.steps_taken
724 )));
725 assert!(details.body.contains("Model: kimi-k3"));
726 assert!(!details.body.contains("stale-meta-model"));
727 }
728
729 #[test]
730 fn details_projection_shows_resolved_route_truth_for_fleet_child() {
731 let tmp = tempdir().expect("tempdir");
732 let mut app = test_app(tmp.path().to_path_buf());
733 let agent_id = "agent_fleet_child";
734 let mut child = agent(agent_id, SubAgentStatus::Running);
735 // A `type`-only fleet dispatch leaves the advisory role empty and the
736 // spawn model is a requested placeholder; the child's own route receipt
737 // is the authoritative resolved truth.
738 child.assignment.role = None;
739 child.model = "stale-requested-model".to_string();
740 child.child_route = Some(ChildRouteReceipt {
741 requested_type: "custom".to_string(),
742 requested_profile: Some("release-lead".to_string()),
743 resolved_profile_id: Some("roster-release-lead".to_string()),
744 profile_origin: Some("roster".to_string()),
745 canonical_role: "release-lead".to_string(),
746 provider_id: "deepseek".to_string(),
747 model_id: "deepseek-v4-pro".to_string(),
748 route_source: "roster".to_string(),
749 fallback_note: None,
750 requested_reasoning: "inherit".to_string(),
751 effective_reasoning: Some("high".to_string()),
752 runtime_version: "test".to_string(),
753 runtime_build_sha: "unknown".to_string(),
754 });
755 app.subagent_cache.push(child);
756
757 let body = project_agent_details(&app, agent_id)
758 .expect("projection")
759 .body;
760 assert!(body.contains("Role: release-lead"), "{body}");
761 assert!(body.contains("Profile: roster-release-lead"), "{body}");
762 assert!(body.contains("Requested as: release-lead"), "{body}");
763 assert!(body.contains("Type: implement"), "{body}");
764 assert!(body.contains("Model: deepseek-v4-pro"), "{body}");
765 assert!(body.contains("Provider: deepseek"), "{body}");
766 assert!(!body.contains("stale-requested-model"), "{body}");
767 }
768
769 #[test]
770 fn display_name_prefers_the_dispatch_name_over_the_whale() {
771 // #5287: the lane was dispatched as `branch-triage`; that is the
772 // identity the operator glances for. An unnamed sibling keeps its
773 // generated whale rather than showing a bare id.
774 let tmp = tempdir().expect("tempdir");
775 let mut app = test_app(tmp.path().to_path_buf());
776 let mut named = agent("agent_named_lane", SubAgentStatus::Running);
777 named.name = "branch-triage".to_string();
778 app.subagent_cache.push(named);
779 let mut unnamed = agent("agent_plain_lane", SubAgentStatus::Running);
780 unnamed.nickname = None;
781 app.subagent_cache.push(unnamed);
782
783 assert_eq!(
784 safe_agent_display_name(&app, "agent_named_lane"),
785 "branch-triage"
786 );
787 assert_eq!(
788 safe_agent_display_name(&app, "agent_plain_lane"),
789 codewhale_engine::tools::subagent::whale_name_for_id_in_locale(
790 "agent_plain_lane",
791 app.ui_locale.tag()
792 )
793 );
794 }
795
796 #[test]
797 fn projection_redacts_child_strings_and_never_exposes_raw_ids_or_none() {
798 let tmp = tempdir().expect("tempdir");
799 let mut app = test_app(tmp.path().to_path_buf());
800 let agent_id = "agent_secret_child";
801 let parent_id = "agent_raw_parent";
802 let mut parent = agent(parent_id, SubAgentStatus::Running);
803 parent.nickname = Some("Parent Whale".to_string());
804 let mut child = agent(agent_id, SubAgentStatus::Running);
805 child.parent_run_id = Some(parent_id.to_string());
806 child.spawn_depth = 2;
807 child.assignment.objective = format!(
808 "\u{1b}[31minspect {agent_id}\u{1b}[0m with api_key=sk-agent-details-secret-1234567890"
809 );
810 child.git_branch = Some(format!("work/{parent_id}"));
811 child.model.clear();
812 child.nickname = Some(format!("\u{1b}[35m{agent_id}\u{1b}[0m"));
813 app.subagent_cache.extend([parent, child]);
814
815 let projection = project_agent_details(&app, agent_id).expect("projection");
816 let all = format!("{}\n{}", projection.title, projection.body);
817 assert!(!all.contains(agent_id), "{all}");
818 assert!(!all.contains(parent_id), "{all}");
819 assert!(!all.contains("sk-agent-details-secret"), "{all}");
820 assert!(!all.contains('\u{1b}'), "{all:?}");
821 assert!(!all.contains("None"), "{all}");
822 assert!(all.contains("[redacted]"), "{all}");
823 }
824
825 #[test]
826 fn external_workspace_is_basename_safe_and_branch_is_bounded() {
827 let mut app = test_app(PathBuf::from("/repo/main"));
828 let agent_id = "agent_external_workspace";
829 let mut child = agent(agent_id, SubAgentStatus::Running);
830 child.workspace = Some(PathBuf::from("/private/customer/secret/repo-child"));
831 child.git_branch = Some("codex/details".to_string());
832 app.subagent_cache.push(child);
833
834 let body = project_agent_details(&app, agent_id)
835 .expect("projection")
836 .body;
837 assert!(body.contains("Workspace: repo-child"), "{body}");
838 assert!(!body.contains("/private/customer/secret"), "{body}");
839 assert!(body.contains("Branch: codex/details"), "{body}");
840 }
841
842 #[test]
843 fn recent_actions_are_bounded_and_render_only_structured_outcomes() {
844 let tmp = tempdir().expect("tempdir");
845 let mut app = test_app(tmp.path().to_path_buf());
846 let agent_id = "agent_recent_actions";
847 app.subagent_cache
848 .push(agent(agent_id, SubAgentStatus::Running));
849 let mut meta = AgentProgressMeta::default();
850 for step in 1..=MAX_AGENT_RECENT_ACTIONS as u32 {
851 meta.recent_actions.push_back(AgentRecentAction::bounded(
852 if step == 2 {
853 "apply_patch"
854 } else {
855 "read_file"
856 },
857 step,
858 step != 2,
859 ));
860 }
861 app.agent_progress_meta.insert(agent_id.to_string(), meta);
862
863 let body = project_agent_details(&app, agent_id)
864 .expect("projection")
865 .body;
866 assert_eq!(body.matches("Recent:").count(), 3, "{body}");
867 assert!(body.contains("Recent: ! apply_patch · step 2"), "{body}");
868 }
869
870 #[test]
871 fn alt_v_is_truthful_for_present_and_absent_evidence() {
872 let tmp = tempdir().expect("tempdir");
873 let agent_id = "agent_evidence";
874 let mut app = test_app(tmp.path().to_path_buf());
875 app.subagent_cache
876 .push(agent(agent_id, SubAgentStatus::Running));
877 let absent = project_agent_details(&app, agent_id).expect("projection");
878 assert!(!absent.transcript_available);
879 let details_chord = crate::tui::shell_key_routing::tool_details_chord();
880 let transcript_hint = format!("{details_chord}:transcript");
881 assert!(!absent.body.contains(&transcript_hint));
882 let mut absent_view = AgentDetailsView::new(absent, agent_id, 80);
883 assert!(matches!(
884 absent_view.handle_key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT)),
885 ViewAction::None
886 ));
887
888 {
889 let mut store = app
890 .runtime_services
891 .handle_store
892 .try_lock()
893 .expect("handle store");
894 let _ = store.insert_json(
895 format!("agent:{agent_id}"),
896 "full_transcript",
897 json!({
898 "message_count": 1,
899 "messages": [{
900 "role": "assistant",
901 "content": [{
902 "type": "text",
903 "text": "exact evidence",
904 "cache_control": null
905 }]
906 }]
907 }),
908 );
909 }
910 let present = project_agent_details(&app, agent_id).expect("projection");
911 assert!(present.transcript_available);
912 assert!(
913 present.body.contains(&transcript_hint),
914 "expected {transcript_hint:?} in {}",
915 present.body
916 );
917 assert!(
918 !present.body.contains("Alt/⌥V"),
919 "dual Alt/⌥ spelling must not appear: {}",
920 present.body
921 );
922 let mut present_view = AgentDetailsView::new(present, agent_id, 80);
923 assert!(matches!(
924 present_view.handle_key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT)),
925 ViewAction::Emit(ViewEvent::OpenAgentTranscript { agent_id: ref id }) if id == agent_id
926 ));
927
928 assert!(open_agent_details(&mut app, agent_id));
929 let events = app
930 .view_stack
931 .handle_key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT));
932 assert!(matches!(
933 events.as_slice(),
934 [ViewEvent::OpenAgentTranscript { agent_id: id }] if id == agent_id
935 ));
936 // The transcript destination is the in-place focus; the details view
937 // survives underneath and its chord still points at the transcript.
938 crate::tui::agent_focus::focus_agent(&mut app, agent_id);
939 assert!(
940 app.agent_focus
941 .as_ref()
942 .is_some_and(|focus| focus.is(agent_id))
943 );
944 assert!(matches!(
945 app.view_stack
946 .handle_key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT))
947 .as_slice(),
948 [ViewEvent::OpenAgentTranscript { agent_id: id }] if id == agent_id
949 ));
950 }
951
952 #[test]
953 fn close_keys_emit_receipt_and_80x24_render_stays_safe() {
954 let tmp = tempdir().expect("tempdir");
955 let agent_id = "agent_render_80x24";
956 let mut app = test_app(tmp.path().to_path_buf());
957 app.subagent_cache
958 .push(agent(agent_id, SubAgentStatus::Running));
959 let projection = project_agent_details(&app, agent_id).expect("projection");
960 let mut view = AgentDetailsView::new(projection, agent_id, 80);
961 assert!(view.title().starts_with("Agent Details — "));
962 assert!(view.body_text().contains("Exact evidence: unavailable"));
963
964 let area = Rect::new(0, 0, 80, 24);
965 let mut buffer = Buffer::empty(area);
966 view.render(area, &mut buffer);
967 let rendered = (0..area.height)
968 .flat_map(|y| (0..area.width).map(move |x| (x, y)))
969 .map(|point| buffer[point].symbol())
970 .collect::<String>();
971 assert!(rendered.contains("Agent Details"), "{rendered}");
972 assert!(rendered.contains("Assignment"), "{rendered}");
973 assert!(!rendered.contains(agent_id), "{rendered}");
974
975 for code in [KeyCode::Esc, KeyCode::Left] {
976 assert!(matches!(
977 view.handle_key(KeyEvent::new(code, KeyModifiers::NONE)),
978 ViewAction::EmitAndClose(ViewEvent::AgentDetailsClosed { agent_id: ref id })
979 if id == agent_id
980 ));
981 }
982 }
983 // === #5906: a parked husk is not a pending question ==================
984
985 /// The runtime hands a parked child a `needs_input` note that reads like a
986 /// question, so Agent Details used to print `Pending question: Resume this
987 /// parked child with ...` — a question no operator ever asked and none can
988 /// answer. Build one exactly as the runtime does and assert the view names
989 /// the state and both ways out instead.
990 fn parked_child(agent_id: &str) -> SubAgentResult {
991 let mut child = agent(
992 agent_id,
993 SubAgentStatus::Interrupted(
994 "Parent turn ended before this turn-owned child settled.".to_string(),
995 ),
996 );
997 child.worker_status = Some(AgentWorkerStatus::WaitingForUser);
998 child.needs_input = Some(SubAgentNeedsInput {
999 question: format!(
1000 "Resume this parked child with agent(action=\"start\", resume_from=\"{agent_id}\")."
1001 ),
1002 });
1003 child.checkpoint = Some(codewhale_engine::tools::subagent::SubAgentCheckpoint {
1004 limit_kind: None,
1005 checkpoint_id: format!("{agent_id}:step:2"),
1006 agent_id: agent_id.to_string(),
1007 continuation_handle: format!("agent:{agent_id}:checkpoint"),
1008 reason: "Parent turn ended before this turn-owned child settled.".to_string(),
1009 continuable: true,
1010 steps_taken: 2,
1011 message_count: 4,
1012 created_at_ms: 1_000,
1013 messages: Vec::new(),
1014 omitted_messages: 0,
1015 parked_at_turn_end: true,
1016 });
1017 child
1018 }
1019
1020 #[test]
1021 fn parked_details_name_the_state_and_the_recovery_not_a_pending_question() {
1022 let tmp = tempdir().expect("tempdir");
1023 let mut app = test_app(tmp.path().to_path_buf());
1024 let agent_id = "agent_parked_details";
1025 app.subagent_cache.push(parked_child(agent_id));
1026 crate::tui::subagent_routing::reconcile_subagent_activity_state(&mut app);
1027
1028 let body = project_agent_details(&app, agent_id)
1029 .expect("projection")
1030 .body;
1031
1032 assert!(body.contains("State: parked"), "{body}");
1033 assert!(
1034 !body.contains("waiting for input") && !body.contains("State: waiting"),
1035 "a parked husk must not wear the answerable label: {body}"
1036 );
1037 assert!(
1038 !body.contains("Pending question"),
1039 "nothing asked the operator anything: {body}"
1040 );
1041 // The recovery is quoted with the verbs the runtime actually exposes.
1042 assert!(body.contains("resume_from"), "{body}");
1043 assert!(body.contains("cancel"), "{body}");
1044 }
1045
1046 #[test]
1047 fn a_child_that_really_asked_still_reports_waiting_for_input() {
1048 let tmp = tempdir().expect("tempdir");
1049 let mut app = test_app(tmp.path().to_path_buf());
1050 let agent_id = "agent_really_asked";
1051 let mut child = agent(agent_id, SubAgentStatus::Running);
1052 child.worker_status = Some(AgentWorkerStatus::WaitingForUser);
1053 child.needs_input = Some(SubAgentNeedsInput {
1054 question: "Which path should I use?".to_string(),
1055 });
1056 app.subagent_cache.push(child);
1057 crate::tui::subagent_routing::reconcile_subagent_activity_state(&mut app);
1058
1059 let body = project_agent_details(&app, agent_id)
1060 .expect("projection")
1061 .body;
1062 assert!(body.contains("State: waiting"), "{body}");
1063 assert!(
1064 body.contains("Pending question: Which path should I use?"),
1065 "{body}"
1066 );
1067 assert!(!body.contains("parked"), "{body}");
1068 }
1069 }
1070
1070 lines RUST