返回 CodeWhale
agent_focus.rs
根目录 / crates / tui / src / tui / agent_focus.rs
1 //! Agent focus — one child's full conversation takes over the main
2 //! transcript area and the composer addresses that child's fork.
3 //!
4 //! Selecting a worker anywhere it is listed (the Agents rail panel, the
5 //! sub-agent cards, `/agents`) focuses it: the transcript area shows the
6 //! child's complete chat rendered with the same history cells as the main
7 //! conversation and scrolls the same way, the focused rail row carries a
8 //! left-edge marker, and the composer grows a chip naming the worker so it is
9 //! unmistakable that the next message goes to *that* fork. Esc on an empty
10 //! composer returns to the main conversation.
11 //!
12 //! Follow-ups are real runtime work, never a UI illusion: a running child
13 //! receives the text on its live input channel; an interrupted or completed
14 //! child is continued from its checkpoint on a new fork (the terminal record
15 //! is an immutable receipt), and focus follows the fork. Failed and cancelled
16 //! children answer with the exact reason they cannot continue.
17
18 use crate::tui::app::StatusToastLevel;
19 use std::time::{Duration, Instant};
20
21 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
22 use ratatui::{
23 buffer::Buffer,
24 layout::Rect,
25 style::{Modifier, Style},
26 text::{Line, Span},
27 };
28
29 use crate::tui::app::App;
30 use crate::tui::history::{HistoryCell, history_cells_from_message_with_results};
31 use codewhale_engine::tools::subagent::SubAgentStatus;
32 use codewhale_localization::MessageId;
33 use codewhale_models::Message;
34
35 /// How often the focused transcript re-reads the child's durable artifact.
36 /// The rail's live activity line already ticks per event; the full chat only
37 /// needs to catch up at a human cadence.
38 const REFRESH_INTERVAL: Duration = Duration::from_millis(400);
39
40 /// Focus state for one child.
41 #[derive(Debug, Clone)]
42 pub struct AgentFocus {
43 /// The worker whose fork the composer addresses.
44 pub agent_id: String,
45 /// Stable user-facing name (dispatch name, generated whale, or label).
46 pub label: String,
47 /// The child's transcript rendered as ordinary history cells.
48 pub cells: Vec<HistoryCell>,
49 /// Number of source messages the cells were built from.
50 pub source_message_count: usize,
51 /// Messages omitted from the resident tail (durable artifact absent).
52 pub omitted_messages: usize,
53 /// A settled agent's full result (or the reason it stopped), shown after
54 /// the transcript when the transcript does not already end with it, and
55 /// on its own when there is no transcript at all (#6565).
56 /// The text and whether it is a stop reason rather than a result.
57 pub result: Option<(String, bool)>,
58 /// Local receipts appended after the source transcript: the user's own
59 /// follow-ups echoed immediately and delivery notes.
60 pub local_cells: Vec<HistoryCell>,
61 /// Scroll position from the top in visual lines; `None` follows the tail.
62 pub scroll_top: Option<usize>,
63 /// Last visible-line count, so paging keys move a screen at a time.
64 pub last_visible: usize,
65 /// Last total line count after wrapping (for scrollbar/clamping).
66 pub last_total: usize,
67 /// Number of permission receipts folded into `cells`, so a new receipt
68 /// on an unchanged message count still triggers a rebuild.
69 receipt_count: usize,
70 last_refresh: Instant,
71 settled_refreshed: bool,
72 wrapped: Option<(u16, codewhale_palette::UiTheme, Vec<Line<'static>>)>,
73 }
74
75 impl AgentFocus {
76 pub(crate) fn new(agent_id: String, label: String) -> Self {
77 Self {
78 agent_id,
79 label,
80 cells: Vec::new(),
81 source_message_count: 0,
82 omitted_messages: 0,
83 result: None,
84 local_cells: Vec::new(),
85 scroll_top: None,
86 last_visible: 0,
87 last_total: 0,
88 receipt_count: 0,
89 last_refresh: Instant::now() - REFRESH_INTERVAL,
90 settled_refreshed: false,
91 wrapped: None,
92 }
93 }
94
95 /// Whether the given agent is the focused one.
96 pub fn is(&self, agent_id: &str) -> bool {
97 self.agent_id == agent_id
98 }
99 }
100
101 /// Load a child's transcript messages: the durable on-disk artifact first
102 /// (the whole chat), else the bounded resident handle. Returns the messages and
103 /// how many earlier messages the resident tail omitted.
104 pub(crate) fn resolve_agent_transcript_messages(
105 app: &App,
106 agent_id: &str,
107 ) -> (Vec<Message>, usize) {
108 if let Ok(display) =
109 codewhale_engine::tools::subagent::load_subagent_transcript_display_artifact(
110 &app.workspace,
111 agent_id,
112 )
113 && display.conversation_count > 0
114 {
115 return (display.messages, 0);
116 }
117 use codewhale_engine::tools::handle::{HandleValue, VarHandle};
118 let lookup = VarHandle {
119 kind: "var_handle".to_string(),
120 session_id: format!("agent:{agent_id}"),
121 name: "full_transcript".to_string(),
122 type_name: String::new(),
123 length: 0,
124 repr_preview: String::new(),
125 sha256: String::new(),
126 };
127 let Ok(store) = app.runtime_services.handle_store.try_lock() else {
128 return (Vec::new(), 0);
129 };
130 let Some(record) = store.get(&lookup) else {
131 return (Vec::new(), 0);
132 };
133 let HandleValue::Json(payload) = &record.value else {
134 return (Vec::new(), 0);
135 };
136 let omitted = payload
137 .get("omitted_messages")
138 .and_then(serde_json::Value::as_u64)
139 .and_then(|value| usize::try_from(value).ok())
140 .unwrap_or(0);
141 let messages = payload
142 .get("messages")
143 .and_then(serde_json::Value::as_array)
144 .map(|raw| {
145 raw.iter()
146 .filter_map(|value| serde_json::from_value::<Message>(value.clone()).ok())
147 .collect::<Vec<_>>()
148 })
149 .unwrap_or_default();
150 (messages, omitted)
151 }
152
153 /// The same name the rail shows for a worker: its dispatch/session name when
154 /// it has one, else the generated or labelled display name.
155 pub(crate) fn agent_display_label(app: &App, agent_id: &str) -> String {
156 app.agent_given_name(agent_id)
157 .unwrap_or_else(|| crate::tui::agent_details::safe_agent_display_name(app, agent_id))
158 }
159
160 /// Render a child's messages as history cells, folding in the permission
161 /// receipts recorded for that child: each receipt lands right after the
162 /// message that carries the tool's result (or, while the call is still
163 /// running, after the tool-use block itself), so a decision reads in place.
164 fn cells_for_messages(messages: &[Message], receipts: &[(String, String)]) -> Vec<HistoryCell> {
165 use codewhale_models::ContentBlock;
166 let mut calls = std::collections::HashMap::new();
167 let mut results = std::collections::HashMap::new();
168 let mut raw_ids = std::collections::HashMap::<&str, usize>::new();
169 for block in messages.iter().flat_map(|message| &message.content) {
170 let Some(key) = block
171 .tool_call_key()
172 .filter(|key| !key.as_str().trim().is_empty())
173 else {
174 continue;
175 };
176 match block {
177 ContentBlock::ToolUse { id, .. } => {
178 *raw_ids.entry(key.as_str()).or_default() += 1;
179 calls
180 .entry(key)
181 .and_modify(|entry| *entry = None)
182 .or_insert(Some(id.as_str()));
183 }
184 ContentBlock::ToolResult { tool_use_id, .. } => {
185 results
186 .entry(key)
187 .and_modify(|entry| *entry = None)
188 .or_insert(Some(tool_use_id.as_str()));
189 }
190 _ => {}
191 }
192 }
193 let mut cells = Vec::new();
194 for message in messages {
195 cells.extend(history_cells_from_message_with_results(message, messages));
196 for block in &message.content {
197 let Some(key) = block.tool_call_key() else {
198 continue;
199 };
200 let Some(Some(provider)) = calls.get(&key) else {
201 continue;
202 };
203 if raw_ids.get(key.as_str()) != Some(&1) {
204 continue;
205 }
206 let anchor = match block {
207 ContentBlock::ToolResult { tool_use_id, .. } => {
208 results.get(&key) == Some(&Some(*provider)) && tool_use_id.as_str() == *provider
209 }
210 ContentBlock::ToolUse { .. } => !results.contains_key(&key),
211 _ => false,
212 };
213 if anchor {
214 for (_, text) in receipts.iter().filter(|(id, _)| id == key.as_str()) {
215 cells.push(HistoryCell::System {
216 content: text.clone(),
217 });
218 }
219 }
220 }
221 }
222 cells
223 }
224
225 fn child_receipts<'a>(app: &'a App, agent_id: &str) -> &'a [(String, String)] {
226 app.child_gate_receipts
227 .get(agent_id)
228 .map_or(&[], Vec::as_slice)
229 }
230
231 /// What a settled agent produced, in full, and whether it is a failure
232 /// reason rather than a result. The durable worker record (the roster) holds
233 /// the complete text; the manager snapshot is the fallback. `None` while the
234 /// agent is live or when it left nothing. Not redacted; see [`settled_result`].
235 pub(crate) fn settled_result_raw(app: &App, agent_id: &str) -> Option<(String, bool)> {
236 let from_roster = app
237 .current_agent_roster()
238 .iter()
239 .find(|row| row.worker_id == agent_id)
240 .and_then(|row| {
241 let failed = matches!(
242 row.state,
243 codewhale_engine::agent_roster::RosterState::Failed
244 | codewhale_engine::agent_roster::RosterState::Cancelled
245 );
246 row.outcome.clone().map(|text| (text, failed))
247 });
248 let from_snapshot = || {
249 let agent = app
250 .subagent_cache
251 .iter()
252 .find(|agent| agent.agent_id == agent_id)?;
253 match &agent.status {
254 SubAgentStatus::Running => None,
255 SubAgentStatus::Completed => agent.result.clone().map(|text| (text, false)),
256 SubAgentStatus::Failed(reason) | SubAgentStatus::Interrupted(reason) => {
257 Some((reason.clone(), true))
258 }
259 SubAgentStatus::Cancelled | SubAgentStatus::BudgetExhausted => {
260 agent.result.clone().map(|text| (text, true))
261 }
262 }
263 };
264 from_roster
265 .or_else(from_snapshot)
266 .filter(|(text, _)| !text.trim().is_empty())
267 }
268
269 /// Strip terminal escapes and redact secrets before agent text is shown.
270 fn visible_agent_text(text: &str) -> String {
271 let mut visible = String::with_capacity(text.len());
272 codewhale_sanitize::sanitize::strip_ansi_into(text, &mut visible);
273 codewhale_config::persistence::redact_secrets(&visible)
274 }
275
276 /// [`settled_result_raw`], safe to render.
277 pub(crate) fn settled_result(app: &App, agent_id: &str) -> Option<(String, bool)> {
278 settled_result_raw(app, agent_id)
279 .map(|(text, failed)| (visible_agent_text(&text).trim().to_string(), failed))
280 .filter(|(text, _)| !text.is_empty())
281 }
282
283 /// One line saying what a settled agent produced (its result headline, or
284 /// why it stopped), bounded for a row with a visible `…` when cut. The full
285 /// text is in the agent's focused view.
286 pub(crate) fn settled_headline(app: &App, agent_id: &str) -> Option<String> {
287 let (text, _) = settled_result_raw(app, agent_id)?;
288 codewhale_engine::agent_roster::result_headline(&text)
289 .map(|headline| codewhale_engine::agent_roster::one_line(&visible_agent_text(&headline)))
290 }
291
292 /// The result block for a settled agent, unless the transcript already ends
293 /// with that answer. The completion envelope is machine data and is dropped.
294 fn result_block_for(app: &App, agent_id: &str, messages: &[Message]) -> Option<(String, bool)> {
295 let (text, failed) = settled_result(app, agent_id)?;
296 let text = text
297 .lines()
298 .filter(|line| !line.trim_start().starts_with("<codewhale:"))
299 .collect::<Vec<_>>()
300 .join("\n");
301 let text = text.trim();
302 if text.is_empty() {
303 return None;
304 }
305 let answered = messages
306 .iter()
307 .rev()
308 .find(|message| message.role == "assistant")
309 .map(message_plain_text)
310 .is_some_and(|last| {
311 codewhale_engine::agent_roster::result_headline(text)
312 .is_some_and(|headline| last.contains(headline.as_str()))
313 });
314 (!answered || failed).then(|| (text.to_string(), failed))
315 }
316
317 /// The heading and body cells for a result block.
318 fn result_cells(app: &App, result: Option<&(String, bool)>) -> Vec<HistoryCell> {
319 let Some((text, failed)) = result else {
320 return Vec::new();
321 };
322 let heading = if *failed {
323 MessageId::AgentFocusStopReason
324 } else {
325 MessageId::AgentFocusResult
326 };
327 vec![
328 HistoryCell::System {
329 content: app.tr(heading).into_owned(),
330 },
331 HistoryCell::Assistant {
332 content: text.clone(),
333 streaming: false,
334 },
335 ]
336 }
337
338 /// Focus a child: its full transcript owns the main area and the composer
339 /// addresses its fork. Re-focusing the same child is a no-op that keeps the
340 /// scroll position; focusing another child replaces the focus.
341 pub(crate) fn focus_agent(app: &mut App, agent_id: &str) {
342 if app
343 .agent_focus
344 .as_ref()
345 .is_some_and(|focus| focus.is(agent_id))
346 {
347 app.needs_redraw = true;
348 return;
349 }
350 let label = agent_display_label(app, agent_id);
351 let mut focus = AgentFocus::new(agent_id.to_string(), label.clone());
352 let (messages, omitted) = resolve_agent_transcript_messages(app, agent_id);
353 let receipts = child_receipts(app, agent_id);
354 focus.cells = cells_for_messages(&messages, receipts);
355 focus.receipt_count = receipts.len();
356 focus.source_message_count = messages.len();
357 focus.omitted_messages = omitted;
358 focus.result = result_block_for(app, agent_id, &messages);
359 focus.last_refresh = Instant::now();
360 app.agent_focus = Some(focus);
361 codewhale_engine::extension_host::command::bump_epoch();
362 // The composer is now the natural owner: the next keys address the
363 // worker, and Esc leaves focus rather than the rail.
364 crate::tui::work_surface::release_focus(app);
365 app.scroll_to_bottom();
366 let status = app
367 .tr(MessageId::AgentFocusOpened)
368 .replace("{agent}", &label);
369
370 app.push_status_toast(status, crate::tui::app::StatusToastLevel::Info, Some(4_000));
371 app.needs_redraw = true;
372 }
373
374 /// Return to the main conversation. Returns whether a focus was active.
375 pub(crate) fn exit_focus(app: &mut App) -> bool {
376 codewhale_engine::extension_host::command::bump_epoch();
377 let Some(focus) = app.agent_focus.take() else {
378 return false;
379 };
380 // The rail tracked this worker as its opened row while focused.
381 crate::tui::work_surface::agent_details_closed(app, &focus.agent_id);
382 app.scroll_to_bottom();
383 let status = app.tr(MessageId::AgentFocusClosed).into_owned();
384 app.show_command_result(status, StatusToastLevel::Info);
385 app.needs_redraw = true;
386 true
387 }
388
389 /// Re-read the focused child's transcript at a human cadence so live workers
390 /// stream into the focused view. Local echoes of the user's own follow-ups are
391 /// dropped once the child's own transcript carries them.
392 pub(crate) fn refresh_focus(app: &mut App) {
393 let Some(focus) = app.agent_focus.as_ref() else {
394 return;
395 };
396 if focus.last_refresh.elapsed() < REFRESH_INTERVAL {
397 return;
398 }
399 let agent_id = focus.agent_id.clone();
400 let settled = app
401 .subagent_cache
402 .iter()
403 .find(|agent| agent.agent_id == agent_id)
404 .is_some_and(|agent| !matches!(agent.status, SubAgentStatus::Running));
405 if settled && focus.settled_refreshed {
406 return;
407 }
408 let (messages, omitted) = resolve_agent_transcript_messages(app, &agent_id);
409 let receipts = child_receipts(app, &agent_id).to_vec();
410 // The result lands when the agent settles, often with no new message.
411 let result = result_block_for(app, &agent_id, &messages);
412 let Some(focus) = app.agent_focus.as_mut() else {
413 return;
414 };
415 focus.last_refresh = Instant::now();
416 focus.settled_refreshed = settled;
417 if focus.result != result {
418 focus.result = result;
419 focus.wrapped = None;
420 app.needs_redraw = true;
421 }
422 let Some(focus) = app.agent_focus.as_mut() else {
423 return;
424 };
425 if messages.len() == focus.source_message_count
426 && omitted == focus.omitted_messages
427 && receipts.len() == focus.receipt_count
428 {
429 return;
430 }
431 let previous_count = focus.source_message_count;
432 focus.wrapped = None;
433 focus.cells = cells_for_messages(&messages, &receipts);
434 focus.receipt_count = receipts.len();
435 focus.source_message_count = messages.len();
436 focus.omitted_messages = omitted;
437 // Drop local user echoes that the transcript now carries itself.
438 for message in messages.iter().skip(previous_count) {
439 if message.role != "user" {
440 continue;
441 }
442 let text = message_plain_text(message);
443 if let Some(index) = focus.local_cells.iter().position(
444 |cell| matches!(cell, HistoryCell::User { content } if content.trim() == text.trim()),
445 ) {
446 focus.local_cells.remove(index);
447 }
448 }
449 app.needs_redraw = true;
450 }
451
452 fn message_plain_text(message: &Message) -> String {
453 message
454 .content
455 .iter()
456 .filter_map(|block| match block {
457 codewhale_models::ContentBlock::Text { text, .. } => Some(text.as_str()),
458 _ => None,
459 })
460 .collect::<Vec<_>>()
461 .join("\n")
462 }
463
464 /// Record the user's follow-up in the focused view immediately so the send is
465 /// visible before the child's transcript catches up.
466 pub(crate) fn echo_user_follow_up(app: &mut App, text: &str) {
467 if let Some(focus) = app.agent_focus.as_mut() {
468 focus.local_cells.push(HistoryCell::User {
469 content: text.to_string(),
470 });
471 focus.wrapped = None;
472 focus.scroll_top = None;
473 app.needs_redraw = true;
474 }
475 }
476
477 /// Apply a delivery receipt from the engine. Focus follows the actual successor
478 /// on a new continuation or successful delivery to an existing continuation.
479 pub(crate) fn apply_follow_up_receipt(
480 app: &mut App,
481 agent_id: &str,
482 outcome: &Result<codewhale_engine::tools::subagent::UserFollowUpOutcome, String>,
483 ) {
484 let label = agent_display_label(app, agent_id);
485 let note = match outcome {
486 Ok(receipt)
487 if (receipt.resumed || receipt.delivered) && receipt.target_agent_id != agent_id =>
488 {
489 let target_label = agent_display_label(app, &receipt.target_agent_id);
490 if app
491 .agent_focus
492 .as_ref()
493 .is_some_and(|focus| focus.is(agent_id))
494 {
495 // Carry the local echoes across so the send stays visible on
496 // the fork until its transcript includes it.
497 let carried = app
498 .agent_focus
499 .as_ref()
500 .map(|focus| focus.local_cells.clone())
501 .unwrap_or_default();
502 app.agent_focus = None;
503 codewhale_engine::extension_host::command::bump_epoch();
504 focus_agent(app, &receipt.target_agent_id);
505 if let Some(focus) = app.agent_focus.as_mut() {
506 focus.local_cells = carried;
507 focus.wrapped = None;
508 }
509 }
510 if receipt.resumed {
511 app.tr(MessageId::AgentFocusFollowUpContinued)
512 .replace("{agent}", &label)
513 .replace("{target}", &target_label)
514 } else {
515 app.tr(MessageId::AgentFocusFollowUpDelivered)
516 .replace("{agent}", &target_label)
517 }
518 }
519 Ok(receipt) if receipt.delivered => app
520 .tr(MessageId::AgentFocusFollowUpDelivered)
521 .replace("{agent}", &label),
522 Ok(receipt) => app
523 .tr(MessageId::AgentFocusFollowUpFailed)
524 .replace("{agent}", &label)
525 .replace("{reason}", &receipt.note),
526 Err(reason) => app
527 .tr(MessageId::AgentFocusFollowUpFailed)
528 .replace("{agent}", &label)
529 .replace("{reason}", reason),
530 };
531 let level = if matches!(outcome, Ok(receipt) if receipt.delivered) {
532 crate::tui::app::StatusToastLevel::Info
533 } else {
534 crate::tui::app::StatusToastLevel::Warning
535 };
536 // The receipt belongs to the agent it names (or the fork focus followed
537 // above). A delayed receipt for another agent must not land in whichever
538 // transcript happens to be focused now; the toast still reports it.
539 let receipt_target = outcome
540 .as_ref()
541 .ok()
542 .map(|receipt| receipt.target_agent_id.as_str());
543 if let Some(focus) = app
544 .agent_focus
545 .as_mut()
546 .filter(|focus| focus.is(agent_id) || receipt_target.is_some_and(|id| focus.is(id)))
547 {
548 focus.local_cells.push(HistoryCell::System {
549 content: note.clone(),
550 });
551 focus.wrapped = None;
552 focus.scroll_top = None;
553 }
554
555 app.push_status_toast(note, level, Some(5_000));
556 app.needs_redraw = true;
557 }
558
559 /// Status word for the focused child from the live cache (glyph + word rule:
560 /// the word is always shown; color is secondary).
561 pub(crate) fn focused_status(app: &App) -> Option<(char, String)> {
562 let focus = app.agent_focus.as_ref()?;
563 let agent = app
564 .subagent_cache
565 .iter()
566 .find(|agent| agent.agent_id == focus.agent_id)?;
567 Some(match &agent.status {
568 SubAgentStatus::Running => ('●', "running".to_string()),
569 SubAgentStatus::Completed => ('✓', "done".to_string()),
570 SubAgentStatus::Interrupted(_) => ('⏸', "interrupted".to_string()),
571 SubAgentStatus::Failed(_) => ('✕', "failed".to_string()),
572 SubAgentStatus::Cancelled => ('✕', "cancelled".to_string()),
573 SubAgentStatus::BudgetExhausted => ('◆', "budget exhausted".to_string()),
574 })
575 }
576
577 /// One short line naming the focused worker's effective posture: its role,
578 /// whether it may write the workspace, reach the network, and run shell —
579 /// from the runtime's persisted permission snapshot, never guessed.
580 pub(crate) fn focused_posture(app: &App) -> Option<String> {
581 let focus = app.agent_focus.as_ref()?;
582 let agent = app
583 .subagent_cache
584 .iter()
585 .find(|agent| agent.agent_id == focus.agent_id)?;
586 let permissions = agent.runtime_permissions.as_ref()?;
587 let write = app.tr(if permissions.write {
588 MessageId::AgentFocusPostureWrites
589 } else {
590 MessageId::AgentFocusPostureReadOnly
591 });
592 let network = app.tr(if permissions.network {
593 MessageId::AgentFocusPostureNetwork
594 } else {
595 MessageId::AgentFocusPostureNoNetwork
596 });
597 let shell = app.tr(match permissions.shell.as_str() {
598 "full" => MessageId::AgentFocusPostureShellFull,
599 "read_only" => MessageId::AgentFocusPostureShellReadOnly,
600 _ => MessageId::AgentFocusPostureShellNone,
601 });
602 Some(
603 app.tr(MessageId::AgentFocusPosture)
604 .replace("{role}", agent.agent_type.as_str())
605 .replace("{write}", &write)
606 .replace("{network}", &network)
607 .replace("{shell}", &shell),
608 )
609 }
610
611 /// Whether any worker exists to list, focus, or manage this session.
612 pub(crate) fn agents_exist(app: &App) -> bool {
613 !app.subagent_cache.is_empty() || !app.agent_progress.is_empty()
614 }
615
616 /// Shell action owned by the agent shortcuts advertised above the composer.
617 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
618 pub(crate) enum AgentShellShortcut {
619 FocusAgents,
620 ManageAgents,
621 }
622
623 /// Whether the composer currently owns the two agent shortcuts.
624 ///
625 /// This is deliberately stricter than [`agents_exist`]. A visible worker is
626 /// not enough to advertise a key when a modal, attachment, or focused inline
627 /// surface owns that same arrow. Rendering and dispatch both consume this
628 /// predicate so the footer cannot promise an action that another owner will
629 /// swallow.
630 ///
631 /// A workflow run on the workbar counts as agents to manage: `↓` then opens
632 /// `/workflows` instead of the agent register.
633 pub(crate) fn shell_shortcuts_available(app: &App, completion_menu_open: bool) -> bool {
634 (agents_exist(app) || !app.workflow_runs.is_empty())
635 && !completion_menu_open
636 && app.input.is_empty()
637 && app.view_stack.is_empty()
638 && app.selected_composer_attachment_index().is_none()
639 && !app.work_surface.focused
640 }
641
642 /// Resolve a key only while the agent shortcut contract is actually active.
643 pub(crate) fn shell_shortcut(
644 app: &App,
645 key: &KeyEvent,
646 completion_menu_open: bool,
647 ) -> Option<AgentShellShortcut> {
648 if key.modifiers != KeyModifiers::NONE || !shell_shortcuts_available(app, completion_menu_open)
649 {
650 return None;
651 }
652 match key.code {
653 KeyCode::Left => Some(AgentShellShortcut::FocusAgents),
654 KeyCode::Down => Some(AgentShellShortcut::ManageAgents),
655 _ => None,
656 }
657 }
658
659 /// Footer hint chain fragment `← for agents · ↓ to manage` (ASCII-safe:
660 /// `<- for agents · v to manage`). Words are localized; the glyphs follow the
661 /// shell's ASCII-safe switch.
662 pub(crate) fn footer_agent_hints(app: &App) -> String {
663 let ascii = crate::tui::color_compat::ascii_safe_enabled();
664 let (left, down) = if ascii { ("<-", "v") } else { ("←", "↓") };
665 format!(
666 "{left} {} · {down} {}",
667 app.tr(MessageId::FooterHintForAgents),
668 app.tr(MessageId::FooterHintToManage)
669 )
670 }
671
672 /// `· N queued` suffix for a rail row: follow-ups the running child has not
673 /// yet taken at its next round boundary. `None` when nothing is queued.
674 pub(crate) fn queued_suffix(app: &App, agent_id: &str) -> Option<String> {
675 let count = *app.agent_queued_follow_ups.get(agent_id)?;
676 if count == 0 {
677 return None;
678 }
679 Some(
680 app.tr(MessageId::AgentRailQueuedCount)
681 .replace("{count}", &count.to_string()),
682 )
683 }
684
685 /// The composer chip naming the addressed fork.
686 pub(crate) fn composer_chip_text(app: &App) -> Option<String> {
687 let focus = app.agent_focus.as_ref()?;
688 Some(
689 app.tr(MessageId::AgentFocusComposerChip)
690 .replace("{agent}", &focus.label),
691 )
692 }
693
694 /// Empty-composer hint while focused.
695 pub(crate) fn composer_placeholder(app: &App) -> Option<String> {
696 let focus = app.agent_focus.as_ref()?;
697 Some(
698 app.tr(MessageId::AgentFocusPlaceholder)
699 .replace("{agent}", &focus.label),
700 )
701 }
702
703 /// Render the focused child's transcript into the main conversation area.
704 ///
705 /// Consumes the shared `pending_scroll_delta` so PageUp/PageDown, wheel, and
706 /// the jump-to-latest affordance behave exactly as they do on the main
707 /// transcript.
708 pub(crate) fn render_focus(app: &mut App, area: Rect, buf: &mut Buffer) {
709 let area = area.intersection(buf.area);
710 let Some(focus) = app.agent_focus.as_ref() else {
711 return;
712 };
713 let theme = app.ui_theme;
714 let background = Style::default().bg(theme.surface_bg);
715 buf.set_style(area, background);
716 if area.height == 0 || area.width == 0 {
717 return;
718 }
719 let (status_glyph, status_word) = focused_status(app).unwrap_or(('○', "unknown".to_string()));
720 let banner = app
721 .tr(MessageId::AgentFocusBanner)
722 .replace("{agent}", &focus.label)
723 .replace("{status}", &status_word);
724 let mut banner_spans = vec![
725 Span::styled(
726 format!("{status_glyph} "),
727 Style::default().fg(theme.accent_action),
728 ),
729 Span::styled(
730 banner,
731 Style::default()
732 .fg(theme.accent_action)
733 .add_modifier(Modifier::BOLD),
734 ),
735 ];
736 // The worker's effective posture, in the same dot chain: what it may do
737 // is stated where its conversation is read, not hidden in a role name.
738 if let Some(posture) = focused_posture(app) {
739 banner_spans.push(Span::styled(
740 format!(" · {posture}"),
741 Style::default().fg(theme.text_muted),
742 ));
743 }
744 let banner_line = Line::from(banner_spans);
745 let width = area.width.max(1);
746 let mut lines: Vec<Line<'static>> = Vec::new();
747 if focus.omitted_messages > 0 {
748 lines.push(Line::from(Span::styled(
749 app.tr(MessageId::AgentFocusOmitted)
750 .replace("{count}", &focus.omitted_messages.to_string()),
751 Style::default().fg(theme.text_muted),
752 )));
753 }
754 let result_cells = result_cells(app, focus.result.as_ref());
755 if focus.cells.is_empty() && result_cells.is_empty() && focus.local_cells.is_empty() {
756 lines.push(Line::from(Span::styled(
757 app.tr(MessageId::AgentFocusNoTranscript)
758 .replace("{agent}", &focus.label),
759 Style::default().fg(theme.text_muted),
760 )));
761 }
762 if !focus
763 .wrapped
764 .as_ref()
765 .is_some_and(|(cached_width, cached_theme, _)| {
766 *cached_width == width && *cached_theme == theme
767 })
768 {
769 let mut body = Vec::new();
770 for cell in focus
771 .cells
772 .iter()
773 .chain(result_cells.iter())
774 .chain(focus.local_cells.iter())
775 {
776 body.extend(cell.transcript_lines(width));
777 body.push(Line::default());
778 }
779 if let Some(focus) = app.agent_focus.as_mut() {
780 focus.wrapped = Some((width, theme, body));
781 }
782 }
783 let Some(focus) = app.agent_focus.as_ref() else {
784 return;
785 };
786 if let Some((_, _, body)) = focus.wrapped.as_ref() {
787 lines.extend(body.iter().cloned());
788 }
789 let visible = usize::from(area.height.saturating_sub(1)).max(1);
790 let total = lines.len();
791 let max_top = total.saturating_sub(visible);
792 let delta = app.viewport.pending_scroll_delta;
793 app.viewport.pending_scroll_delta = 0;
794 let Some(focus) = app.agent_focus.as_mut() else {
795 return;
796 };
797 let current = focus.scroll_top.unwrap_or(max_top);
798 let next = if delta < 0 {
799 current.saturating_sub(delta.unsigned_abs() as usize)
800 } else {
801 current.saturating_add(delta as usize)
802 }
803 .min(max_top);
804 focus.scroll_top = if next >= max_top { None } else { Some(next) };
805 focus.last_visible = visible;
806 focus.last_total = total;
807 let top = focus.scroll_top.unwrap_or(max_top);
808
809 lines.insert(0, banner_line);
810 let mut viewport = codewhale_ratatui::TranscriptViewport::new(&lines);
811 viewport.offset = top;
812 viewport.pinned_rows = 1;
813 viewport.style = background;
814 let plan = viewport.render(area, buf);
815 app.viewport.ocean_semantic_surfaces = codewhale_ratatui::ocean::ocean_semantic_surfaces(
816 plan.display_rows(),
817 plan.area,
818 codewhale_tui_kit::ui_text::grapheme_display_width,
819 );
820 // The focused view owns the transcript geometry for paging keys.
821 app.viewport.last_transcript_area = Some(plan.body_area);
822 app.viewport.last_transcript_visible = visible;
823 app.viewport.last_transcript_total = total;
824 app.viewport.last_transcript_top = top;
825 }
826
827 #[cfg(test)]
828 mod tests {
829 use super::*;
830 use crate::tui::app::TuiOptions;
831 use codewhale_runtime::config::Config;
832 use serde_json::json;
833 use std::path::PathBuf;
834 use tempfile::tempdir;
835
836 fn test_app(workspace: PathBuf) -> App {
837 App::new(
838 TuiOptions {
839 model: "test-model".to_string(),
840 use_mouse_capture: true,
841 max_subagents: 4,
842 ..crate::tui::test_support::test_tui_options(workspace)
843 },
844 &Config::default(),
845 )
846 }
847
848 #[test]
849 fn child_receipts_anchor_only_to_unique_execution_pairs() {
850 let messages: Vec<Message> = serde_json::from_value(json!([
851 {"role":"assistant","content":[{"type":"tool_use","id":"wire","execution_id":"first","name":"read_file","input":{}}]},
852 {"role":"user","content":[{"type":"tool_result","tool_use_id":"wire","execution_id":"first","content":"one"}]},
853 {"role":"assistant","content":[{"type":"tool_use","id":"wire","execution_id":"second","name":"read_file","input":{}}]},
854 {"role":"user","content":[{"type":"tool_result","tool_use_id":"wire","execution_id":"second","content":"two"}]}
855 ])).unwrap();
856 let receipts = vec![
857 ("first".into(), "receipt one".into()),
858 ("second".into(), "receipt two".into()),
859 ];
860 let rendered = cells_for_messages(&messages, &receipts);
861 let anchored: Vec<_> = rendered
862 .iter()
863 .filter_map(|cell| match cell {
864 HistoryCell::System { content } if content.starts_with("receipt ") => {
865 Some(content.as_str())
866 }
867 _ => None,
868 })
869 .collect();
870 assert_eq!(anchored, ["receipt one", "receipt two"]);
871
872 for duplicate in [messages[0].clone(), serde_json::from_value(json!({
873 "role":"assistant","content":[{"type":"tool_use","id":"first","name":"read_file","input":{}}]
874 })).unwrap()] {
875 let mut ambiguous = messages.clone();
876 ambiguous.push(duplicate);
877 let rendered = cells_for_messages(&ambiguous, &receipts);
878 assert!(!rendered.iter().any(|cell| matches!(cell, HistoryCell::System { content } if content == "receipt one")));
879 assert_eq!(rendered.iter().filter(|cell| matches!(cell, HistoryCell::System { content } if content == "receipt two")).count(), 1);
880 }
881 }
882
883 #[test]
884 fn agent_shell_shortcuts_only_claim_an_unowned_empty_composer() {
885 let tmp = tempdir().expect("tempdir");
886 let mut app = test_app(tmp.path().to_path_buf());
887 let left = KeyEvent::new(KeyCode::Left, KeyModifiers::NONE);
888 let down = KeyEvent::new(KeyCode::Down, KeyModifiers::NONE);
889
890 assert_eq!(
891 shell_shortcut(&app, &left, false),
892 None,
893 "no agents: cursor owns Left"
894 );
895 assert_eq!(
896 shell_shortcut(&app, &down, false),
897 None,
898 "no agents: cursor owns Down"
899 );
900
901 app.agent_progress
902 .insert("agent_one".to_string(), "working".to_string());
903 assert_eq!(
904 shell_shortcut(&app, &left, false),
905 Some(AgentShellShortcut::FocusAgents)
906 );
907 assert_eq!(
908 shell_shortcut(&app, &down, false),
909 Some(AgentShellShortcut::ManageAgents)
910 );
911
912 app.input = "draft".to_string();
913 assert_eq!(
914 shell_shortcut(&app, &left, false),
915 None,
916 "text cursor keeps Left"
917 );
918 app.input.clear();
919 app.work_surface.focused = true;
920 assert_eq!(
921 shell_shortcut(&app, &down, false),
922 None,
923 "focused work surface keeps Down for row navigation"
924 );
925 }
926
927 #[test]
928 fn open_completion_menu_keeps_agent_shortcuts_out_of_its_arrows() {
929 let tmp = tempdir().expect("tempdir");
930 let mut app = test_app(tmp.path().to_path_buf());
931 app.agent_progress
932 .insert("agent_one".to_string(), "working".to_string());
933
934 assert_eq!(
935 shell_shortcut(
936 &app,
937 &KeyEvent::new(KeyCode::Left, KeyModifiers::NONE),
938 true,
939 ),
940 None
941 );
942 assert_eq!(
943 shell_shortcut(
944 &app,
945 &KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
946 true,
947 ),
948 None
949 );
950 assert!(!shell_shortcuts_available(&app, true));
951 }
952
953 fn seed_resident_transcript(app: &mut App, agent_id: &str, messages: serde_json::Value) {
954 let mut store = app
955 .runtime_services
956 .handle_store
957 .try_lock()
958 .expect("handle store");
959 let count = messages.as_array().map(|m| m.len()).unwrap_or(0);
960 let _ = store.insert_json(
961 format!("agent:{agent_id}"),
962 "full_transcript",
963 json!({ "message_count": count, "messages": messages }),
964 );
965 }
966
967 fn render(app: &mut App, width: u16, height: u16) -> String {
968 let area = Rect::new(0, 0, width, height);
969 let mut buf = Buffer::empty(area);
970 render_focus(app, area, &mut buf);
971 (0..height)
972 .map(|y| {
973 (0..width)
974 .map(|x| buf[(x, y)].symbol().to_string())
975 .collect::<String>()
976 .trim_end()
977 .to_string()
978 })
979 .collect::<Vec<_>>()
980 .join("\n")
981 }
982
983 #[test]
984 fn focus_renders_the_childs_full_transcript_and_the_composer_addresses_it() {
985 let tmp = tempdir().expect("tempdir");
986 let mut app = test_app(tmp.path().to_path_buf());
987 seed_resident_transcript(
988 &mut app,
989 "agent_alpha",
990 json!([
991 {"role": "user", "content": [{"type": "text", "text": "Investigate the flaky test", "cache_control": null}]},
992 {"role": "assistant", "content": [{"type": "text", "text": "Found the race in the pool", "cache_control": null}]}
993 ]),
994 );
995 focus_agent(&mut app, "agent_alpha");
996 let focus = app.agent_focus.as_ref().expect("focused");
997 assert_eq!(focus.source_message_count, 2);
998 assert_eq!(focus.cells.len(), 2);
999 let screen = render(&mut app, 80, 12);
1000 assert!(screen.contains("Investigate the flaky test"), "{screen}");
1001 assert!(screen.contains("Found the race in the pool"), "{screen}");
1002 assert!(
1003 composer_chip_text(&app)
1004 .expect("chip")
1005 .contains(&focus_label(&app)),
1006 "chip names the focused worker"
1007 );
1008 assert!(composer_placeholder(&app).is_some());
1009 assert!(exit_focus(&mut app));
1010 assert!(app.agent_focus.is_none());
1011 assert!(composer_chip_text(&app).is_none());
1012 assert!(!exit_focus(&mut app));
1013 }
1014
1015 #[test]
1016 fn focus_banner_states_the_workers_effective_posture_from_the_runtime_snapshot() {
1017 let tmp = tempdir().expect("tempdir");
1018 let mut app = test_app(tmp.path().to_path_buf());
1019 seed_resident_transcript(
1020 &mut app,
1021 "agent_scout",
1022 json!([{"role": "user", "content": [{"type": "text", "text": "look around", "cache_control": null}]}]),
1023 );
1024 app.subagent_cache
1025 .push(codewhale_engine::tools::subagent::SubAgentResult {
1026 usage: None,
1027 name: "agent_scout".to_string(),
1028 agent_id: "agent_scout".to_string(),
1029 context_mode: "fresh".to_string(),
1030 fork_context: false,
1031 workspace: None,
1032 git_branch: None,
1033 agent_type: codewhale_agent_contract::role::FleetRole::Scout,
1034 assignment: codewhale_engine::tools::subagent::SubAgentAssignment {
1035 native_preset: None,
1036 objective: "look around".to_string(),
1037 role: Some("explore".to_string()),
1038 },
1039 model: "deepseek-v4-flash".to_string(),
1040 nickname: None,
1041 status: SubAgentStatus::Running,
1042 worker_status: None,
1043 runtime_permissions: Some(codewhale_protocol::fleet::FleetEffectivePermissions {
1044 write: false,
1045 network: true,
1046 shell: "read_only".to_string(),
1047 tool_scope: "inherit".to_string(),
1048 tools: Vec::new(),
1049 background: true,
1050 max_spawn_depth: 1,
1051 profile_id: None,
1052 profile_origin: None,
1053 source: "built_in".to_string(),
1054 }),
1055 parent_run_id: None,
1056 spawn_depth: 1,
1057 child_route: None,
1058 result: None,
1059 steps_taken: 0,
1060 checkpoint: None,
1061 needs_input: None,
1062 duration_ms: 0,
1063 started_at: None,
1064 from_prior_session: false,
1065 idle_ms: None,
1066 heartbeat_timeout_ms: None,
1067 });
1068 focus_agent(&mut app, "agent_scout");
1069 let posture = focused_posture(&app).expect("posture line from the snapshot");
1070 assert_eq!(posture, "explore · read-only · network · read-only shell");
1071 let screen = render(&mut app, 100, 8);
1072 assert!(
1073 screen.contains("read-only · network · read-only shell"),
1074 "{screen}"
1075 );
1076 // No snapshot, no guess.
1077 app.subagent_cache[0].runtime_permissions = None;
1078 assert!(focused_posture(&app).is_none());
1079 }
1080
1081 fn focus_label(app: &App) -> String {
1082 app.agent_focus.as_ref().map(|f| f.label.clone()).unwrap()
1083 }
1084
1085 #[test]
1086 fn empty_transcript_explains_instead_of_dead_ending() {
1087 let tmp = tempdir().expect("tempdir");
1088 let mut app = test_app(tmp.path().to_path_buf());
1089 focus_agent(&mut app, "agent_quiet");
1090 let screen = render(&mut app, 120, 8);
1091 let expected = app
1092 .tr(MessageId::AgentFocusNoTranscript)
1093 .replace("{agent}", &focus_label(&app));
1094 let head: String = expected.chars().take(24).collect();
1095 assert!(screen.contains(head.trim_end()), "{screen}");
1096 }
1097
1098 fn settled_agent(
1099 agent_id: &str,
1100 status: SubAgentStatus,
1101 result: Option<&str>,
1102 ) -> codewhale_engine::tools::subagent::SubAgentResult {
1103 codewhale_engine::tools::subagent::SubAgentResult {
1104 usage: None,
1105 name: agent_id.to_string(),
1106 agent_id: agent_id.to_string(),
1107 context_mode: "fresh".to_string(),
1108 fork_context: false,
1109 workspace: None,
1110 git_branch: None,
1111 agent_type: codewhale_agent_contract::role::FleetRole::Scout,
1112 assignment: codewhale_engine::tools::subagent::SubAgentAssignment {
1113 native_preset: None,
1114 objective: "audit the docs".to_string(),
1115 role: Some("explore".to_string()),
1116 },
1117 model: "deepseek-v4-flash".to_string(),
1118 nickname: None,
1119 status,
1120 worker_status: None,
1121 runtime_permissions: None,
1122 parent_run_id: None,
1123 spawn_depth: 1,
1124 child_route: None,
1125 result: result.map(str::to_string),
1126 steps_taken: 3,
1127 checkpoint: None,
1128 needs_input: None,
1129 duration_ms: 1_000,
1130 started_at: None,
1131 from_prior_session: false,
1132 idle_ms: None,
1133 heartbeat_timeout_ms: None,
1134 }
1135 }
1136
1137 #[test]
1138 fn a_finished_agent_without_a_transcript_shows_its_full_result() {
1139 // #6565: with no live capture the focused view explained the missing
1140 // capture instead of showing the answer the engine had kept.
1141 let tmp = tempdir().expect("tempdir");
1142 let mut app = test_app(tmp.path().to_path_buf());
1143 let body = (0..80)
1144 .map(|n| format!("Finding {n} is documented in section {n}."))
1145 .collect::<Vec<_>>()
1146 .join(" ");
1147 assert!(body.len() > 2_500);
1148 let result = format!("## Summary\n\n{body}\n\nEND-OF-RESULT");
1149 app.subagent_cache.push(settled_agent(
1150 "agent_done",
1151 SubAgentStatus::Completed,
1152 Some(&result),
1153 ));
1154 focus_agent(&mut app, "agent_done");
1155 let (text, failed) = app
1156 .agent_focus
1157 .as_ref()
1158 .and_then(|focus| focus.result.clone())
1159 .expect("the stored result is the focused view");
1160 assert!(!failed);
1161 assert_eq!(text, result);
1162 let screen = render(&mut app, 100, 200);
1163 assert!(screen.contains("Finding 0 is documented"), "{screen}");
1164 assert!(screen.contains("Finding 79 is documented"), "{screen}");
1165 assert!(screen.contains("END-OF-RESULT"), "{screen}");
1166 let heading = app.tr(MessageId::AgentFocusResult).into_owned();
1167 assert!(screen.contains(&heading), "{screen}");
1168 let missing = app
1169 .tr(MessageId::AgentFocusNoTranscript)
1170 .replace("{agent}", &focus_label(&app));
1171 let head: String = missing.chars().take(12).collect();
1172 assert!(!screen.contains(head.trim_end()), "{screen}");
1173 }
1174
1175 #[test]
1176 fn a_failed_agent_shows_why_it_stopped_in_full() {
1177 let tmp = tempdir().expect("tempdir");
1178 let mut app = test_app(tmp.path().to_path_buf());
1179 let reason = format!(
1180 "provider returned 429 after 5 retries; {} last-line",
1181 "context ".repeat(80)
1182 );
1183 app.subagent_cache.push(settled_agent(
1184 "agent_failed",
1185 SubAgentStatus::Failed(reason.clone()),
1186 None,
1187 ));
1188 focus_agent(&mut app, "agent_failed");
1189 assert_eq!(
1190 app.agent_focus
1191 .as_ref()
1192 .and_then(|focus| focus.result.clone()),
1193 Some((reason.trim().to_string(), true))
1194 );
1195 let screen = render(&mut app, 100, 60);
1196 assert!(screen.contains("last-line"), "{screen}");
1197 let heading = app.tr(MessageId::AgentFocusStopReason).into_owned();
1198 assert!(screen.contains(&heading), "{screen}");
1199 }
1200
1201 #[test]
1202 fn a_transcript_that_already_ends_with_the_answer_gets_no_result_block() {
1203 let tmp = tempdir().expect("tempdir");
1204 let mut app = test_app(tmp.path().to_path_buf());
1205 seed_resident_transcript(
1206 &mut app,
1207 "agent_told",
1208 json!([
1209 {"role": "user", "content": [{"type": "text", "text": "audit", "cache_control": null}]},
1210 {"role": "assistant", "content": [{"type": "text", "text": "## Summary\n\nThree links are stale. Details follow.", "cache_control": null}]}
1211 ]),
1212 );
1213 app.subagent_cache.push(settled_agent(
1214 "agent_told",
1215 SubAgentStatus::Completed,
1216 Some("## Summary\n\nThree links are stale. Details follow."),
1217 ));
1218 focus_agent(&mut app, "agent_told");
1219 assert_eq!(app.agent_focus.as_ref().unwrap().result, None);
1220
1221 // A capture that stops before the answer gets the answer appended,
1222 // and the refresh picks it up when the agent settles later.
1223 seed_resident_transcript(
1224 &mut app,
1225 "agent_partial",
1226 json!([{"role": "user", "content": [{"type": "text", "text": "audit", "cache_control": null}]}]),
1227 );
1228 app.subagent_cache.push(settled_agent(
1229 "agent_partial",
1230 SubAgentStatus::Running,
1231 None,
1232 ));
1233 focus_agent(&mut app, "agent_partial");
1234 assert_eq!(app.agent_focus.as_ref().unwrap().result, None);
1235 let agent = app
1236 .subagent_cache
1237 .iter_mut()
1238 .find(|agent| agent.agent_id == "agent_partial")
1239 .unwrap();
1240 agent.status = SubAgentStatus::Completed;
1241 agent.result = Some("Two links are stale.".to_string());
1242 app.agent_focus.as_mut().unwrap().last_refresh = Instant::now() - REFRESH_INTERVAL;
1243 refresh_focus(&mut app);
1244 assert_eq!(
1245 app.agent_focus.as_ref().unwrap().result,
1246 Some(("Two links are stale.".to_string(), false))
1247 );
1248 }
1249
1250 #[test]
1251 fn user_echo_is_replaced_once_the_child_transcript_carries_it() {
1252 let tmp = tempdir().expect("tempdir");
1253 let mut app = test_app(tmp.path().to_path_buf());
1254 seed_resident_transcript(
1255 &mut app,
1256 "agent_echo",
1257 json!([{"role": "assistant", "content": [{"type": "text", "text": "ready", "cache_control": null}]}]),
1258 );
1259 focus_agent(&mut app, "agent_echo");
1260 echo_user_follow_up(&mut app, "please continue");
1261 assert_eq!(app.agent_focus.as_ref().unwrap().local_cells.len(), 1);
1262 seed_resident_transcript(
1263 &mut app,
1264 "agent_echo",
1265 json!([
1266 {"role": "assistant", "content": [{"type": "text", "text": "ready", "cache_control": null}]},
1267 {"role": "user", "content": [{"type": "text", "text": "please continue", "cache_control": null}]}
1268 ]),
1269 );
1270 // Force the cadence gate open.
1271 app.agent_focus.as_mut().unwrap().last_refresh = Instant::now() - REFRESH_INTERVAL;
1272 refresh_focus(&mut app);
1273 let focus = app.agent_focus.as_ref().unwrap();
1274 assert_eq!(focus.source_message_count, 2);
1275 assert!(focus.local_cells.is_empty(), "echo dropped once carried");
1276 }
1277
1278 #[test]
1279 fn scrolling_pages_through_the_focused_transcript_and_returns_to_tail() {
1280 let tmp = tempdir().expect("tempdir");
1281 let mut app = test_app(tmp.path().to_path_buf());
1282 let messages: Vec<serde_json::Value> = (0..40)
1283 .map(|i| json!({"role": "assistant", "content": [{"type": "text", "text": format!("line {i}"), "cache_control": null}]}))
1284 .collect();
1285 seed_resident_transcript(&mut app, "agent_long", json!(messages));
1286 focus_agent(&mut app, "agent_long");
1287 let tail = render(&mut app, 60, 10);
1288 assert!(tail.contains("line 39"), "{tail}");
1289 app.scroll_up(1000);
1290 let head = render(&mut app, 60, 10);
1291 assert!(head.contains("line 0"), "{head}");
1292 assert!(app.agent_focus.as_ref().unwrap().scroll_top.is_some());
1293 app.scroll_down(100_000);
1294 let back = render(&mut app, 60, 10);
1295 assert!(back.contains("line 39"), "{back}");
1296 assert!(app.agent_focus.as_ref().unwrap().scroll_top.is_none());
1297 }
1298
1299 #[test]
1300 fn continued_fork_moves_focus_to_the_new_agent_and_reports_it() {
1301 let tmp = tempdir().expect("tempdir");
1302 let mut app = test_app(tmp.path().to_path_buf());
1303 focus_agent(&mut app, "agent_done");
1304 echo_user_follow_up(&mut app, "one more thing");
1305 let outcome = Ok(codewhale_engine::tools::subagent::UserFollowUpOutcome {
1306 agent_id: "agent_done".to_string(),
1307 target_agent_id: "agent_fork".to_string(),
1308 delivered: true,
1309 resumed: true,
1310 note: "continued".to_string(),
1311 });
1312 apply_follow_up_receipt(&mut app, "agent_done", &outcome);
1313 let focus = app.agent_focus.as_ref().expect("focus follows the fork");
1314 assert_eq!(focus.agent_id, "agent_fork");
1315 assert!(
1316 focus.local_cells.iter().any(
1317 |cell| matches!(cell, HistoryCell::User { content } if content == "one more thing")
1318 ),
1319 "echo carried across the fork"
1320 );
1321 assert!(
1322 focus
1323 .local_cells
1324 .iter()
1325 .any(|cell| matches!(cell, HistoryCell::System { .. })),
1326 "receipt shown in the focused view"
1327 );
1328 let failed: Result<codewhale_engine::tools::subagent::UserFollowUpOutcome, String> =
1329 Err("status is cancelled".to_string());
1330 apply_follow_up_receipt(&mut app, "agent_fork", &failed);
1331 assert!(
1332 app.visible_notice_text()
1333 .as_deref()
1334 .is_some_and(|status| status.contains("status is cancelled"))
1335 );
1336 }
1337
1338 /// U05-05: a delayed follow-up receipt for another agent must not be
1339 /// appended to whichever transcript happens to be focused when it lands.
1340 #[test]
1341 fn delayed_follow_up_receipt_stays_out_of_another_agents_focus() {
1342 let tmp = tempdir().expect("tempdir");
1343 let mut app = test_app(tmp.path().to_path_buf());
1344 focus_agent(&mut app, "agent_b");
1345 let outcome = Ok(codewhale_engine::tools::subagent::UserFollowUpOutcome {
1346 agent_id: "agent_a".to_string(),
1347 target_agent_id: "agent_a".to_string(),
1348 delivered: true,
1349 resumed: false,
1350 note: "delivered".to_string(),
1351 });
1352 apply_follow_up_receipt(&mut app, "agent_a", &outcome);
1353 let focus = app.agent_focus.as_ref().expect("focus kept");
1354 assert_eq!(focus.agent_id, "agent_b");
1355 assert!(
1356 focus.local_cells.is_empty(),
1357 "another agent's receipt leaked into this transcript: {:?}",
1358 focus.local_cells
1359 );
1360 assert!(
1361 app.visible_notice_text().is_some(),
1362 "the toast still reports it"
1363 );
1364 }
1365
1366 #[test]
1367 fn delivered_existing_successor_moves_focus_and_names_the_actual_recipient() {
1368 let tmp = tempdir().expect("tempdir");
1369 let mut app = test_app(tmp.path().to_path_buf());
1370 focus_agent(&mut app, "agent_original");
1371 echo_user_follow_up(&mut app, "message for the existing successor");
1372 let outcome = Ok(codewhale_engine::tools::subagent::UserFollowUpOutcome {
1373 agent_id: "agent_original".into(),
1374 target_agent_id: "agent_existing".into(),
1375 delivered: true,
1376 resumed: false,
1377 note: "delivered to existing successor".into(),
1378 });
1379 apply_follow_up_receipt(&mut app, "agent_original", &outcome);
1380 let focus = app.agent_focus.as_ref().unwrap();
1381 assert_eq!(focus.agent_id, "agent_existing");
1382 assert!(focus.local_cells.iter().any(
1383 |cell| matches!(cell, HistoryCell::User { content } if content == "message for the existing successor")
1384 ));
1385 let expected = app
1386 .tr(MessageId::AgentFocusFollowUpDelivered)
1387 .replace("{agent}", &agent_display_label(&app, "agent_existing"));
1388 assert_eq!(
1389 app.visible_notice_text().as_deref(),
1390 Some(expected.as_str())
1391 );
1392 }
1393
1394 #[test]
1395 fn undelivered_existing_successor_keeps_focus_and_shows_the_failure_note() {
1396 let tmp = tempdir().expect("tempdir");
1397 let mut app = test_app(tmp.path().to_path_buf());
1398 focus_agent(&mut app, "agent_original");
1399 let outcome = Ok(codewhale_engine::tools::subagent::UserFollowUpOutcome {
1400 agent_id: "agent_original".into(),
1401 target_agent_id: "agent_existing".into(),
1402 delivered: false,
1403 resumed: false,
1404 note: "queued; live input channel closed".into(),
1405 });
1406 apply_follow_up_receipt(&mut app, "agent_original", &outcome);
1407 assert_eq!(app.agent_focus.as_ref().unwrap().agent_id, "agent_original");
1408 assert!(
1409 app.visible_notice_text()
1410 .as_deref()
1411 .unwrap()
1412 .contains("queued; live input channel closed")
1413 );
1414 }
1415
1416 #[test]
1417 fn scroll_to_bottom_returns_the_focused_transcript_to_its_tail() {
1418 let tmp = tempdir().expect("tempdir");
1419 let mut app = test_app(tmp.path().to_path_buf());
1420 let messages: Vec<serde_json::Value> = (0..40)
1421 .map(|i| json!({"role": "assistant", "content": [{"type": "text", "text": format!("line {i}"), "cache_control": null}]}))
1422 .collect();
1423 seed_resident_transcript(&mut app, "agent_tail", json!(messages));
1424 focus_agent(&mut app, "agent_tail");
1425 let _ = render(&mut app, 60, 10);
1426 app.scroll_up(5);
1427 let _ = render(&mut app, 60, 10);
1428 assert!(app.agent_focus.as_ref().unwrap().scroll_top.is_some());
1429
1430 // The main transcript's jump-to-bottom affordances (Ctrl+End, the
1431 // jump-to-latest button) route through `App::scroll_to_bottom`; the
1432 // focused pane shares those keys, so it must return to its own tail.
1433 app.scroll_to_bottom();
1434 let screen = render(&mut app, 60, 10);
1435 assert!(
1436 app.agent_focus.as_ref().unwrap().scroll_top.is_none(),
1437 "jump-to-bottom must release the focused pane's pin"
1438 );
1439 assert!(screen.contains("line 39"), "{screen}");
1440 }
1441
1442 #[test]
1443 fn main_conversation_activity_keeps_a_pinned_focused_transcript_pinned() {
1444 let tmp = tempdir().expect("tempdir");
1445 let mut app = test_app(tmp.path().to_path_buf());
1446 let messages: Vec<serde_json::Value> = (0..40)
1447 .map(|i| json!({"role": "assistant", "content": [{"type": "text", "text": format!("line {i}"), "cache_control": null}]}))
1448 .collect();
1449 seed_resident_transcript(&mut app, "agent_pin", json!(messages));
1450 focus_agent(&mut app, "agent_pin");
1451 let _ = render(&mut app, 60, 10);
1452 app.scroll_up(10);
1453 let _ = render(&mut app, 60, 10);
1454 assert!(app.agent_focus.as_ref().unwrap().scroll_top.is_some());
1455
1456 // Turn completion clears the per-turn scroll lock while the focused
1457 // pane keeps its pin — the state the auto-follow guard must respect.
1458 app.user_scrolled_during_stream = false;
1459 app.add_message(HistoryCell::System {
1460 content: "worker finished".to_string(),
1461 });
1462
1463 assert!(
1464 app.agent_focus.as_ref().unwrap().scroll_top.is_some(),
1465 "main-conversation activity must not yank the pinned focused pane to its tail"
1466 );
1467 }
1468
1469 #[test]
1470 fn focused_transcript_follows_new_child_activity_while_at_tail() {
1471 let tmp = tempdir().expect("tempdir");
1472 let mut app = test_app(tmp.path().to_path_buf());
1473 let seed = |count: usize| {
1474 let messages: Vec<serde_json::Value> = (0..count)
1475 .map(|i| json!({"role": "assistant", "content": [{"type": "text", "text": format!("line {i}"), "cache_control": null}]}))
1476 .collect();
1477 json!(messages)
1478 };
1479 seed_resident_transcript(&mut app, "agent_live", seed(40));
1480 focus_agent(&mut app, "agent_live");
1481 let first = render(&mut app, 60, 10);
1482 assert!(first.contains("line 39"), "{first}");
1483 assert!(app.agent_focus.as_ref().unwrap().scroll_top.is_none());
1484
1485 // The child streams on; while the pane sits at its tail the new
1486 // activity must pull the viewport down with it.
1487 seed_resident_transcript(&mut app, "agent_live", seed(60));
1488 app.agent_focus.as_mut().unwrap().last_refresh = Instant::now() - REFRESH_INTERVAL;
1489 refresh_focus(&mut app);
1490 let second = render(&mut app, 60, 10);
1491 assert!(second.contains("line 59"), "{second}");
1492 assert!(
1493 app.agent_focus.as_ref().unwrap().scroll_top.is_none(),
1494 "following the tail must not flip into a pinned offset"
1495 );
1496 }
1497 }
1498
1498 lines RUST