| 1 | //! A live roster and focused agent, over facts supplied by the host. |
| 2 | //! Selection and scroll are local; execution, history and permissions are not. |
| 3 | |
| 4 | use std::{ |
| 5 | borrow::Cow, |
| 6 | collections::{HashMap, HashSet}, |
| 7 | time::{Duration, Instant}, |
| 8 | }; |
| 9 | |
| 10 | use crossterm::event::{ |
| 11 | KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, |
| 12 | }; |
| 13 | use ratatui::{ |
| 14 | buffer::Buffer, |
| 15 | layout::Rect, |
| 16 | style::Modifier, |
| 17 | text::{Line, Span}, |
| 18 | widgets::{Paragraph, StatefulWidget, Widget, Wrap}, |
| 19 | }; |
| 20 | |
| 21 | use super::workbench::row; |
| 22 | use crate::{ |
| 23 | AgentCard, CountBar, MotionMode, Paint, Role, State, Theme, VerificationSpinner, WhalePet, |
| 24 | duration, glyphs, spin, text, |
| 25 | whale_motion::{Inputs, Stage, Tier}, |
| 26 | }; |
| 27 | use unicode_segmentation::UnicodeSegmentation; |
| 28 | |
| 29 | /// A reported event. Keep these in chronological order; the view follows the |
| 30 | /// newest event until the person scrolls back. Text is sanitized before paint. |
| 31 | #[derive(Clone, Debug)] |
| 32 | pub struct SubagentEvent<'a> { |
| 33 | pub when: Cow<'a, str>, |
| 34 | pub state: State, |
| 35 | pub message: Cow<'a, str>, |
| 36 | } |
| 37 | |
| 38 | impl<'a> SubagentEvent<'a> { |
| 39 | #[must_use] |
| 40 | pub fn new( |
| 41 | when: impl Into<Cow<'a, str>>, |
| 42 | state: State, |
| 43 | message: impl Into<Cow<'a, str>>, |
| 44 | ) -> Self { |
| 45 | Self { |
| 46 | when: when.into(), |
| 47 | state, |
| 48 | message: message.into(), |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// Capabilities the owner currently allows. An intent still needs the host's |
| 54 | /// normal validation and permission path; a component never executes it. |
| 55 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 56 | pub struct SubagentControls { |
| 57 | pub open: bool, |
| 58 | pub message: bool, |
| 59 | pub stop: bool, |
| 60 | } |
| 61 | |
| 62 | /// Exact provider receipts. A missing field stays missing, including when |
| 63 | /// another field is explicitly zero. Costs are microdollars, never estimated. |
| 64 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 65 | pub struct SubagentUsage { |
| 66 | pub input_tokens: Option<u64>, |
| 67 | pub output_tokens: Option<u64>, |
| 68 | pub cost_microusd: Option<u64>, |
| 69 | } |
| 70 | |
| 71 | impl SubagentUsage { |
| 72 | fn text(self, ascii: bool) -> String { |
| 73 | let missing = if ascii { "-" } else { "—" }; |
| 74 | let number = |n: Option<u64>| n.map_or_else(|| missing.to_owned(), |n| n.to_string()); |
| 75 | let cost = self |
| 76 | .cost_microusd |
| 77 | .map_or_else(|| format!("${missing}"), |n| crate::format_cost(n, "$")); |
| 78 | format!( |
| 79 | "{} {} / {} {} / {cost}", |
| 80 | if ascii { "in" } else { "↓" }, |
| 81 | number(self.input_tokens), |
| 82 | if ascii { "out" } else { "↑" }, |
| 83 | number(self.output_tokens), |
| 84 | ) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// One retained roster entry. IDs must be nonempty and unique in this roster. |
| 89 | /// The view never expires a worker or infers success from its counts. |
| 90 | #[derive(Clone, Debug)] |
| 91 | pub struct Subagent<'a> { |
| 92 | pub id: Cow<'a, str>, |
| 93 | pub card: AgentCard<'a>, |
| 94 | pub elapsed: Option<Duration>, |
| 95 | pub tokens: Option<Cow<'a, str>>, |
| 96 | /// Structured receipts take precedence over legacy token display text. |
| 97 | pub usage: Option<SubagentUsage>, |
| 98 | pub steps: Option<u32>, |
| 99 | /// Full owner-reported result or error; never shortened into the task line. |
| 100 | pub outcome: Option<Cow<'a, str>>, |
| 101 | pub progress: Option<CountBar>, |
| 102 | pub events: Vec<SubagentEvent<'a>>, |
| 103 | pub performance: Option<Inputs>, |
| 104 | pub checking: bool, |
| 105 | pub controls: SubagentControls, |
| 106 | } |
| 107 | |
| 108 | impl<'a> Subagent<'a> { |
| 109 | #[must_use] |
| 110 | pub fn new(id: impl Into<Cow<'a, str>>, card: AgentCard<'a>) -> Self { |
| 111 | Self { |
| 112 | id: id.into(), |
| 113 | card, |
| 114 | elapsed: None, |
| 115 | tokens: None, |
| 116 | usage: None, |
| 117 | steps: None, |
| 118 | outcome: None, |
| 119 | progress: None, |
| 120 | events: Vec::new(), |
| 121 | performance: None, |
| 122 | checking: false, |
| 123 | controls: SubagentControls::default(), |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn usage_text(&self, ascii: bool, steps_label: Option<&str>) -> String { |
| 128 | [ |
| 129 | self.elapsed |
| 130 | .map(duration) |
| 131 | .or_else(|| self.card.elapsed.as_deref().map(str::to_owned)), |
| 132 | self.usage |
| 133 | .map(|usage| usage.text(ascii)) |
| 134 | .or_else(|| self.tokens.as_deref().map(str::to_owned)), |
| 135 | self.steps.map(|n| { |
| 136 | steps_label.map_or_else( |
| 137 | || format!("{n} {}", if n == 1 { "step" } else { "steps" }), |
| 138 | |label| format!("{label}: {n}"), |
| 139 | ) |
| 140 | }), |
| 141 | ] |
| 142 | .into_iter() |
| 143 | .flatten() |
| 144 | .collect::<Vec<_>>() |
| 145 | .join(" / ") |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// Returned to the host only. In particular, Stop is a request, not a state |
| 150 | /// transition: the reported worker stays Working until its owner says otherwise. |
| 151 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 152 | pub enum SubagentIntent { |
| 153 | Open(String), |
| 154 | Message(String), |
| 155 | Stop(String), |
| 156 | } |
| 157 | |
| 158 | #[derive(Default)] |
| 159 | struct OutputWindow { |
| 160 | source: String, |
| 161 | geometry: Option<(u16, u16, usize)>, |
| 162 | total: usize, |
| 163 | rows: Vec<String>, |
| 164 | } |
| 165 | impl OutputWindow { |
| 166 | fn prepare(&mut self, source: &str, width: u16, height: u16, top: usize) { |
| 167 | if self.source == source && self.geometry == Some((width, height, top)) { |
| 168 | return; |
| 169 | } |
| 170 | self.source.clear(); |
| 171 | self.source.push_str(source); |
| 172 | self.geometry = Some((width, height, top)); |
| 173 | self.rows.clear(); |
| 174 | self.total = 0; |
| 175 | for logical in source.split('\n') { |
| 176 | let safe = text::display_safe(logical); |
| 177 | let mut rest = safe.as_ref(); |
| 178 | if rest.is_empty() { |
| 179 | self.push("", top, height); |
| 180 | } |
| 181 | while !rest.is_empty() { |
| 182 | let mut end = 0; |
| 183 | let mut cells = 0; |
| 184 | let mut space = None; |
| 185 | for (byte, grapheme) in rest.grapheme_indices(true) { |
| 186 | let count = text::width(grapheme); |
| 187 | if cells + count > usize::from(width.max(1)) && cells != 0 { |
| 188 | break; |
| 189 | } |
| 190 | end = byte + grapheme.len(); |
| 191 | cells += count; |
| 192 | if grapheme == " " && !rest[..end].trim_start().is_empty() { |
| 193 | space = Some(end); |
| 194 | } |
| 195 | if cells >= usize::from(width.max(1)) { |
| 196 | break; |
| 197 | } |
| 198 | } |
| 199 | if end < rest.len() { |
| 200 | end = space.unwrap_or(end); |
| 201 | } |
| 202 | self.push(&rest[..end], top, height); |
| 203 | rest = &rest[end..]; |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | fn push(&mut self, row: &str, top: usize, height: u16) { |
| 208 | if self.total >= top && self.rows.len() < usize::from(height) { |
| 209 | self.rows.push(row.to_owned()); |
| 210 | } |
| 211 | self.total += 1; |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /// Local presentation state for one roster. Feed a new roster when the session |
| 216 | /// changes (or replace this state), retaining completed entries in owner data. |
| 217 | /// Deliberately not Clone: the canonical Stage owns a unique performance clock. |
| 218 | /// Keep one state per surface instead of copying an in-flight Director. |
| 219 | pub struct SubagentViewState { |
| 220 | selected: Option<String>, |
| 221 | index: usize, |
| 222 | offset: usize, |
| 223 | event_top: Option<usize>, |
| 224 | event_end: usize, |
| 225 | output: bool, |
| 226 | output_top: usize, |
| 227 | output_end: usize, |
| 228 | had_outcome: bool, |
| 229 | output_window: OutputWindow, |
| 230 | detail: bool, |
| 231 | visible: bool, |
| 232 | now: Option<Instant>, |
| 233 | working: HashMap<String, (bool, Instant)>, |
| 234 | motion: MotionMode, |
| 235 | stage: Stage, |
| 236 | observed: Option<(String, State)>, |
| 237 | flourish_until: Option<Instant>, |
| 238 | shown: usize, |
| 239 | pet_visible: bool, |
| 240 | rows: Vec<(Rect, String)>, |
| 241 | detail_area: Rect, |
| 242 | } |
| 243 | |
| 244 | impl Default for SubagentViewState { |
| 245 | fn default() -> Self { |
| 246 | Self { |
| 247 | selected: None, |
| 248 | index: 0, |
| 249 | offset: 0, |
| 250 | event_top: None, |
| 251 | event_end: 0, |
| 252 | output: false, |
| 253 | output_top: 0, |
| 254 | output_end: 0, |
| 255 | had_outcome: false, |
| 256 | output_window: OutputWindow::default(), |
| 257 | detail: false, |
| 258 | visible: true, |
| 259 | now: None, |
| 260 | working: HashMap::new(), |
| 261 | motion: MotionMode::Full, |
| 262 | stage: Stage::new(), |
| 263 | observed: None, |
| 264 | flourish_until: None, |
| 265 | shown: 0, |
| 266 | pet_visible: false, |
| 267 | rows: Vec::new(), |
| 268 | detail_area: Rect::default(), |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | impl SubagentViewState { |
| 274 | #[must_use] |
| 275 | pub fn selected_id(&self) -> Option<&str> { |
| 276 | self.selected.as_deref() |
| 277 | } |
| 278 | |
| 279 | #[must_use] |
| 280 | pub fn selected_index(&self) -> Option<usize> { |
| 281 | self.selected.as_ref().map(|_| self.index) |
| 282 | } |
| 283 | |
| 284 | /// Select by identity, preserving focus across owner reordering. Returns |
| 285 | /// false for an absent, empty or ambiguous ID rather than choosing a worker. |
| 286 | pub fn select(&mut self, agents: &[Subagent<'_>], id: &str) -> bool { |
| 287 | if id.is_empty() || agents.iter().filter(|a| a.id == id).count() != 1 { |
| 288 | return false; |
| 289 | } |
| 290 | let index = agents.iter().position(|a| a.id == id).unwrap_or(0); |
| 291 | if self.selected.as_deref() != Some(id) { |
| 292 | self.event_top = None; |
| 293 | self.event_end = 0; |
| 294 | self.output = agents[index].outcome.is_some(); |
| 295 | self.had_outcome = self.output; |
| 296 | self.output_window = OutputWindow::default(); |
| 297 | self.output_top = 0; |
| 298 | self.output_end = 0; |
| 299 | } |
| 300 | self.selected = Some(id.to_owned()); |
| 301 | self.index = index; |
| 302 | true |
| 303 | } |
| 304 | |
| 305 | /// Observe explicit owner inputs and advance the existing whale clock once. |
| 306 | /// Paint never reads or advances time. Reduced/Still and terminal states |
| 307 | /// settle; an observed Working -> Done earns one brief native flourish. |
| 308 | pub fn update(&mut self, agents: &[Subagent<'_>], now: Instant, motion: MotionMode) { |
| 309 | self.now = Some(now); |
| 310 | self.motion = motion; |
| 311 | // Presentation onsets only: no worker lifecycle or elapsed-time claims |
| 312 | // are derived from this cache. Drop entries as soon as work stops. |
| 313 | let active: HashSet<_> = agents |
| 314 | .iter() |
| 315 | .filter(|a| a.card.status.state == State::Working) |
| 316 | .map(|a| a.id.as_ref()) |
| 317 | .collect(); |
| 318 | self.working |
| 319 | .retain(|id, _| self.visible && active.contains(id.as_str())); |
| 320 | if self.visible { |
| 321 | for agent in agents |
| 322 | .iter() |
| 323 | .filter(|a| a.card.status.state == State::Working) |
| 324 | { |
| 325 | let phase = self |
| 326 | .working |
| 327 | .entry(agent.id.to_string()) |
| 328 | .or_insert((agent.checking, now)); |
| 329 | if phase.0 != agent.checking { |
| 330 | *phase = (agent.checking, now); |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | let retained = self |
| 335 | .selected |
| 336 | .clone() |
| 337 | .is_some_and(|id| self.select(agents, &id)); |
| 338 | if !retained { |
| 339 | self.selected = None; |
| 340 | if let Some(agent) = agents.get(self.index.min(agents.len().saturating_sub(1))) { |
| 341 | self.select(agents, &agent.id); |
| 342 | } |
| 343 | } |
| 344 | let Some(agent) = self.agent(agents) else { |
| 345 | self.stage.set_visible(false); |
| 346 | self.observed = None; |
| 347 | self.flourish_until = None; |
| 348 | return; |
| 349 | }; |
| 350 | if agent.outcome.is_some() && !self.had_outcome { |
| 351 | self.output = true; |
| 352 | self.output_top = 0; |
| 353 | } else if agent.outcome.is_none() { |
| 354 | self.output = false; |
| 355 | } |
| 356 | self.had_outcome = agent.outcome.is_some(); |
| 357 | let identity = (agent.id.to_string(), agent.card.status.state); |
| 358 | if self.observed.as_ref() != Some(&identity) { |
| 359 | self.flourish_until = self |
| 360 | .observed |
| 361 | .as_ref() |
| 362 | .filter(|(id, status)| { |
| 363 | id == &identity.0 && *status == State::Working && identity.1 == State::Done |
| 364 | }) |
| 365 | .and_then(|_| now.checked_add(Duration::from_millis(1400))); |
| 366 | self.observed = Some(identity); |
| 367 | } |
| 368 | let active = agent.card.status.state == State::Working |
| 369 | || self.flourish_until.is_some_and(|end| now < end); |
| 370 | self.stage |
| 371 | .set_visible(self.visible && agent.performance.is_some()); |
| 372 | if let Some(inputs) = &agent.performance { |
| 373 | self.stage.observe( |
| 374 | Some(&agent.id), |
| 375 | inputs.clone(), |
| 376 | !motion.animates() || !active, |
| 377 | ); |
| 378 | self.stage.advance(now); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | fn agent<'a, 'b>(&self, agents: &'a [Subagent<'b>]) -> Option<&'a Subagent<'b>> { |
| 383 | let agent = agents.get(self.index)?; |
| 384 | let id = self.selected.as_deref()?; |
| 385 | (agent.id == id && !id.is_empty() && agents.iter().filter(|a| a.id == id).count() == 1) |
| 386 | .then_some(agent) |
| 387 | } |
| 388 | |
| 389 | /// Hiding stops animation; resuming discards the hidden interval. |
| 390 | pub fn set_visible(&mut self, visible: bool) { |
| 391 | if self.visible == visible { |
| 392 | return; |
| 393 | } |
| 394 | self.visible = visible; |
| 395 | self.stage.set_visible(visible); |
| 396 | self.working.clear(); |
| 397 | self.rows.clear(); |
| 398 | self.detail_area = Rect::default(); |
| 399 | } |
| 400 | |
| 401 | fn mark_elapsed(&self, agent: &Subagent<'_>) -> Duration { |
| 402 | self.now |
| 403 | .zip(self.working.get(agent.id.as_ref()).map(|(_, start)| *start)) |
| 404 | .map_or(Duration::ZERO, |(now, start)| { |
| 405 | now.saturating_duration_since(start) |
| 406 | }) |
| 407 | } |
| 408 | |
| 409 | /// The host waits for this duration or input, whichever arrives first. |
| 410 | /// Only visible active rows/the focused pet ask for frames. Settled, |
| 411 | /// hidden, empty and Reduced/Still views ask for no timed redraws. |
| 412 | #[must_use] |
| 413 | pub fn next_frame_in(&self, agents: &[Subagent<'_>], theme: &Theme) -> Option<Duration> { |
| 414 | if !self.visible || !self.motion.animates() { |
| 415 | return None; |
| 416 | } |
| 417 | let marks = agents |
| 418 | .iter() |
| 419 | .skip(self.offset) |
| 420 | .take(self.shown) |
| 421 | .filter(|a| a.card.status.state == State::Working) |
| 422 | .filter_map(|agent| spin::next_frame_in(self.mark_elapsed(agent), self.motion)) |
| 423 | .min(); |
| 424 | let pet = self |
| 425 | .pet_visible |
| 426 | .then(|| { |
| 427 | self.stage.cadence(if theme.paints_grounds() { |
| 428 | Tier::Hero |
| 429 | } else { |
| 430 | Tier::Terminal |
| 431 | }) |
| 432 | }) |
| 433 | .flatten(); |
| 434 | [marks, pet].into_iter().flatten().min() |
| 435 | } |
| 436 | |
| 437 | /// Arrow/Home/End navigation, Tab to the next NeedsYou/Failed worker, |
| 438 | /// Left/Right for narrow details, O for output/activity, PageUp/PageDown |
| 439 | /// for the visible content. Full output opens at its beginning. |
| 440 | /// Enter/M/X return capability-gated Open/Message/Stop intents. |
| 441 | pub fn handle_key(&mut self, agents: &[Subagent<'_>], key: KeyEvent) -> Option<SubagentIntent> { |
| 442 | if !self.visible |
| 443 | || key.kind == KeyEventKind::Release |
| 444 | || !key.modifiers.difference(KeyModifiers::SHIFT).is_empty() |
| 445 | { |
| 446 | return None; |
| 447 | } |
| 448 | let index = self |
| 449 | .selected |
| 450 | .as_deref() |
| 451 | .and_then(|id| agents.iter().position(|a| a.id == id)) |
| 452 | .unwrap_or(0); |
| 453 | if let Some(id) = self.selected.clone() { |
| 454 | self.select(agents, &id); |
| 455 | } |
| 456 | let target = match key.code { |
| 457 | KeyCode::Up | KeyCode::Char('k') => Some(index.saturating_sub(1)), |
| 458 | KeyCode::Down | KeyCode::Char('j') => { |
| 459 | Some((index + 1).min(agents.len().saturating_sub(1))) |
| 460 | } |
| 461 | KeyCode::Home => Some(0), |
| 462 | KeyCode::End => Some(agents.len().saturating_sub(1)), |
| 463 | KeyCode::Tab | KeyCode::BackTab => (1..=agents.len()) |
| 464 | .map(|step| { |
| 465 | if key.code == KeyCode::BackTab || key.modifiers.contains(KeyModifiers::SHIFT) { |
| 466 | (index + agents.len() - step) % agents.len() |
| 467 | } else { |
| 468 | (index + step) % agents.len() |
| 469 | } |
| 470 | }) |
| 471 | .find(|i| { |
| 472 | matches!( |
| 473 | agents[*i].card.status.state, |
| 474 | State::NeedsYou | State::Failed |
| 475 | ) |
| 476 | }), |
| 477 | KeyCode::Right => { |
| 478 | self.detail = true; |
| 479 | None |
| 480 | } |
| 481 | KeyCode::Char(' ') => { |
| 482 | self.detail = !self.detail; |
| 483 | None |
| 484 | } |
| 485 | KeyCode::Left => { |
| 486 | self.detail = false; |
| 487 | None |
| 488 | } |
| 489 | KeyCode::Char('o') if self.agent(agents).is_some_and(|a| a.outcome.is_some()) => { |
| 490 | self.output = !self.output; |
| 491 | self.detail = true; |
| 492 | None |
| 493 | } |
| 494 | KeyCode::PageUp => { |
| 495 | self.scroll_content(-5); |
| 496 | None |
| 497 | } |
| 498 | KeyCode::PageDown => { |
| 499 | self.scroll_content(5); |
| 500 | None |
| 501 | } |
| 502 | _ => None, |
| 503 | }; |
| 504 | if let Some(agent) = target.and_then(|i| agents.get(i)) { |
| 505 | self.select(agents, &agent.id); |
| 506 | } |
| 507 | let agent = self.agent(agents)?; |
| 508 | // Holding an action key must not repeat a stop/message request. |
| 509 | if key.kind != KeyEventKind::Press { |
| 510 | return None; |
| 511 | } |
| 512 | match key.code { |
| 513 | KeyCode::Enter if agent.controls.open => { |
| 514 | Some(SubagentIntent::Open(agent.id.to_string())) |
| 515 | } |
| 516 | KeyCode::Char('m') if agent.controls.message => { |
| 517 | Some(SubagentIntent::Message(agent.id.to_string())) |
| 518 | } |
| 519 | KeyCode::Char('x') if agent.controls.stop => { |
| 520 | Some(SubagentIntent::Stop(agent.id.to_string())) |
| 521 | } |
| 522 | _ => None, |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | fn scroll_content(&mut self, lines: isize) { |
| 527 | if self.output { |
| 528 | self.output_top = self |
| 529 | .output_top |
| 530 | .saturating_add_signed(lines) |
| 531 | .min(self.output_end); |
| 532 | } else { |
| 533 | let top = self |
| 534 | .event_top |
| 535 | .unwrap_or(self.event_end) |
| 536 | .saturating_add_signed(lines); |
| 537 | self.event_top = (top < self.event_end).then_some(top); |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | /// Click selects the painted ID, even if the owner reordered its roster |
| 542 | /// after paint. Wheel scrolls the pane under the pointer. No mouse action |
| 543 | /// executes an intent; the host owns opening, messaging and stopping. |
| 544 | pub fn handle_mouse(&mut self, agents: &[Subagent<'_>], mouse: MouseEvent) -> bool { |
| 545 | if !self.visible || !mouse.modifiers.is_empty() { |
| 546 | return false; |
| 547 | } |
| 548 | let point = (mouse.column, mouse.row).into(); |
| 549 | match mouse.kind { |
| 550 | MouseEventKind::Down(MouseButton::Left) => { |
| 551 | let id = self |
| 552 | .rows |
| 553 | .iter() |
| 554 | .find(|(area, _)| area.contains(point)) |
| 555 | .map(|(_, id)| id.clone()); |
| 556 | id.is_some_and(|id| self.select(agents, &id)) |
| 557 | } |
| 558 | MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => { |
| 559 | let up = mouse.kind == MouseEventKind::ScrollUp; |
| 560 | if self.detail_area.contains(point) { |
| 561 | self.scroll_content(if up { -3 } else { 3 }); |
| 562 | true |
| 563 | } else if self.rows.iter().any(|(area, _)| area.contains(point)) { |
| 564 | self.handle_key( |
| 565 | agents, |
| 566 | KeyEvent::new( |
| 567 | if up { KeyCode::Up } else { KeyCode::Down }, |
| 568 | KeyModifiers::NONE, |
| 569 | ), |
| 570 | ); |
| 571 | true |
| 572 | } else { |
| 573 | false |
| 574 | } |
| 575 | } |
| 576 | _ => false, |
| 577 | } |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | /// Caller-owned labels and hints, including localization. State labels remain |
| 582 | /// those on each existing AgentCard; count wording can be supplied separately. |
| 583 | #[derive(Clone, Debug)] |
| 584 | pub struct SubagentViewWords<'a> { |
| 585 | pub title: Cow<'a, str>, |
| 586 | pub empty: Cow<'a, str>, |
| 587 | pub activity: Cow<'a, str>, |
| 588 | pub output: Cow<'a, str>, |
| 589 | pub toggle_output: Cow<'a, str>, |
| 590 | pub no_events: Cow<'a, str>, |
| 591 | pub hints: Cow<'a, str>, |
| 592 | pub open: Cow<'a, str>, |
| 593 | pub message: Cow<'a, str>, |
| 594 | pub stop: Cow<'a, str>, |
| 595 | /// Optional localized receipt label, painted as `label: count`. |
| 596 | pub steps_label: Option<Cow<'a, str>>, |
| 597 | /// Override the default English summary with the owner's localized counts. |
| 598 | pub summary: Option<Cow<'a, str>>, |
| 599 | } |
| 600 | |
| 601 | impl Default for SubagentViewWords<'_> { |
| 602 | fn default() -> Self { |
| 603 | Self { |
| 604 | title: "Subagents".into(), |
| 605 | empty: "No agents reported".into(), |
| 606 | activity: "Activity".into(), |
| 607 | output: "Output".into(), |
| 608 | toggle_output: "O output/activity".into(), |
| 609 | no_events: "No events reported".into(), |
| 610 | hints: "Up/Down select Tab attention Space details PgUp/PgDn scroll".into(), |
| 611 | open: "Enter open".into(), |
| 612 | message: "M message".into(), |
| 613 | stop: "X stop".into(), |
| 614 | steps_label: None, |
| 615 | summary: None, |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | impl SubagentViewWords<'static> { |
| 621 | /// Unified wording for rosters that group subagents and background tasks |
| 622 | /// together. |
| 623 | #[must_use] |
| 624 | pub fn unified() -> Self { |
| 625 | Self { |
| 626 | title: "Agents & Tasks".into(), |
| 627 | empty: "No agents or tasks reported".into(), |
| 628 | ..Self::default() |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | /// Unified roster wording with a formatted `N agents / M tasks` summary. |
| 633 | #[must_use] |
| 634 | pub fn unified_summary(agents: usize, tasks: usize) -> Self { |
| 635 | let agent_word = if agents == 1 { "agent" } else { "agents" }; |
| 636 | let task_word = if tasks == 1 { "task" } else { "tasks" }; |
| 637 | Self { |
| 638 | summary: Some(format!("{agents} {agent_word} / {tasks} {task_word}").into()), |
| 639 | ..Self::unified() |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | /// Group header for a partitioned roster (`In Progress (N)` / `Idle (N)`), |
| 645 | /// with an optional right-aligned attention jump cue. |
| 646 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 647 | pub struct SessionGroupHeader<'a> { |
| 648 | /// Group label (for example `"In Progress"` or `"Idle"`). |
| 649 | pub label: Cow<'a, str>, |
| 650 | /// Number of items in this group. |
| 651 | pub count: usize, |
| 652 | /// Whether this group holds active work. |
| 653 | pub active: bool, |
| 654 | /// Optional attention jump cue painted right-aligned when width permits. |
| 655 | pub attention_cue: Option<Cow<'a, str>>, |
| 656 | } |
| 657 | |
| 658 | impl<'a> SessionGroupHeader<'a> { |
| 659 | /// Create a group header with a custom `label` and item `count`. |
| 660 | #[must_use] |
| 661 | pub fn new(label: impl Into<Cow<'a, str>>, count: usize) -> Self { |
| 662 | Self { |
| 663 | label: label.into(), |
| 664 | count, |
| 665 | active: false, |
| 666 | attention_cue: None, |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | /// Preset header for active work: `In Progress (count)`. |
| 671 | #[must_use] |
| 672 | pub fn in_progress(count: usize) -> Self { |
| 673 | Self::new("In Progress", count).active(true) |
| 674 | } |
| 675 | |
| 676 | /// Preset header for settled or waiting sessions: `Idle (count)`. |
| 677 | #[must_use] |
| 678 | pub fn idle(count: usize) -> Self { |
| 679 | Self::new("Idle", count) |
| 680 | } |
| 681 | |
| 682 | /// Mark whether this group holds active work (emphasized glyph and label). |
| 683 | #[must_use] |
| 684 | pub const fn active(mut self, active: bool) -> Self { |
| 685 | self.active = active; |
| 686 | self |
| 687 | } |
| 688 | |
| 689 | /// Attach a right-aligned attention jump cue (for example `"Tab · 2 need you"`). |
| 690 | #[must_use] |
| 691 | pub fn attention_cue(mut self, cue: impl Into<Cow<'a, str>>) -> Self { |
| 692 | let cue = cue.into(); |
| 693 | self.attention_cue = (!cue.is_empty()).then_some(cue); |
| 694 | self |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | impl Paint for SessionGroupHeader<'_> { |
| 699 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 700 | let area = area.intersection(buf.area); |
| 701 | if area.is_empty() { |
| 702 | return; |
| 703 | } |
| 704 | let ascii = theme.ascii(); |
| 705 | let width = usize::from(area.width); |
| 706 | let glyph = if self.active { |
| 707 | glyphs::pick(glyphs::CURRENT, ascii) |
| 708 | } else { |
| 709 | glyphs::pick(glyphs::AVAILABLE, ascii) |
| 710 | }; |
| 711 | let safe_label = text::display_safe(&self.label); |
| 712 | let title = format!("{safe_label} ({})", self.count); |
| 713 | let cue = self |
| 714 | .attention_cue |
| 715 | .as_deref() |
| 716 | .map(|c| text::display_safe(c).into_owned()) |
| 717 | .filter(|c| !c.is_empty()); |
| 718 | |
| 719 | let glyph_w = text::width(glyph); |
| 720 | let prefix_w = glyph_w.saturating_add(1); |
| 721 | let show_cue = cue.as_deref().filter(|c| { |
| 722 | let cw = text::width(c); |
| 723 | cw + 2 + prefix_w + 4 <= width |
| 724 | }); |
| 725 | let left_budget = match show_cue { |
| 726 | Some(c) => width.saturating_sub(text::width(c) + 2), |
| 727 | None => width, |
| 728 | }; |
| 729 | let title_budget = left_budget.saturating_sub(prefix_w); |
| 730 | let label_style = if self.active { |
| 731 | theme.fg(Role::Foreground).add_modifier(Modifier::BOLD) |
| 732 | } else { |
| 733 | theme.fg(Role::Muted) |
| 734 | }; |
| 735 | let glyph_role = if self.active { |
| 736 | Role::Accent |
| 737 | } else { |
| 738 | Role::Muted |
| 739 | }; |
| 740 | |
| 741 | let mut spans = Vec::new(); |
| 742 | if width >= prefix_w { |
| 743 | spans.push(Span::styled(format!("{glyph} "), theme.fg(glyph_role))); |
| 744 | if title_budget > 0 { |
| 745 | spans.push(Span::styled( |
| 746 | text::truncate(&title, title_budget, ascii).into_owned(), |
| 747 | label_style, |
| 748 | )); |
| 749 | } |
| 750 | } else { |
| 751 | spans.push(Span::styled( |
| 752 | text::truncate(&title, width, ascii).into_owned(), |
| 753 | label_style, |
| 754 | )); |
| 755 | } |
| 756 | row(Rect { height: 1, ..area }, buf, &Line::from(spans)); |
| 757 | |
| 758 | if let Some(cue) = show_cue { |
| 759 | let cw = u16::try_from(text::width(cue)).unwrap_or(0); |
| 760 | let x = area.right().saturating_sub(cw); |
| 761 | buf.set_stringn(x, area.y, cue, usize::from(cw), theme.fg(Role::Attention)); |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | fn height(&self, _width: u16, _theme: &Theme) -> u16 { |
| 766 | 1 |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | /// A dynamic extension of the existing Fleet/AgentCard presentation. Wide |
| 771 | /// terminals show roster + detail; narrow terminals switch between them. |
| 772 | /// |
| 773 | /// ```no_run |
| 774 | /// use codewhale_ratatui::{AgentCard, MotionMode, State, Subagent, SubagentView, SubagentViewState, Theme}; |
| 775 | /// let agents = vec![Subagent::new("review", AgentCard::new("Review", State::Working).task("Check the patch"))]; |
| 776 | /// let mut state = SubagentViewState::default(); |
| 777 | /// let theme = Theme::detect(); |
| 778 | /// state.update(&agents, std::time::Instant::now(), MotionMode::Full); |
| 779 | /// # fn draw(frame: &mut ratatui::Frame<'_>, agents: &[Subagent<'_>], theme: &Theme, state: &mut SubagentViewState) { |
| 780 | /// frame.render_stateful_widget(SubagentView::new(agents, theme), frame.area(), state); |
| 781 | /// # } |
| 782 | /// ``` |
| 783 | pub struct SubagentView<'a> { |
| 784 | agents: &'a [Subagent<'a>], |
| 785 | theme: &'a Theme, |
| 786 | words: SubagentViewWords<'a>, |
| 787 | } |
| 788 | |
| 789 | impl<'a> SubagentView<'a> { |
| 790 | #[must_use] |
| 791 | pub fn new(agents: &'a [Subagent<'a>], theme: &'a Theme) -> Self { |
| 792 | Self { |
| 793 | agents, |
| 794 | theme, |
| 795 | words: SubagentViewWords::default(), |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | #[must_use] |
| 800 | pub fn words(mut self, words: SubagentViewWords<'a>) -> Self { |
| 801 | self.words = words; |
| 802 | self |
| 803 | } |
| 804 | |
| 805 | /// Pure layout also used by host mouse routing. Detail replaces the roster |
| 806 | /// on narrow screens; neither is squeezed into an unreadable column. |
| 807 | #[must_use] |
| 808 | pub fn areas(area: Rect, detail: bool) -> (Rect, Rect) { |
| 809 | let body = Rect::new( |
| 810 | area.x, |
| 811 | area.y.saturating_add(area.height.min(3)), |
| 812 | area.width, |
| 813 | area.height.saturating_sub(5), |
| 814 | ); |
| 815 | if body.width >= 88 && body.height >= 9 { |
| 816 | let width = (u32::from(body.width) * 2 / 5).clamp(34, 48) as u16; |
| 817 | ( |
| 818 | Rect { width, ..body }, |
| 819 | Rect::new( |
| 820 | body.x + width + 3, |
| 821 | body.y, |
| 822 | body.width - width - 3, |
| 823 | body.height, |
| 824 | ), |
| 825 | ) |
| 826 | } else if detail && body.height >= 5 { |
| 827 | (Rect::default(), body) |
| 828 | } else { |
| 829 | (body, Rect::default()) |
| 830 | } |
| 831 | } |
| 832 | |
| 833 | fn line(&self, area: Rect, y: u16, value: &str, role: Role, buf: &mut Buffer) { |
| 834 | if y >= area.height { |
| 835 | return; |
| 836 | } |
| 837 | row( |
| 838 | Rect { |
| 839 | y: area.y + y, |
| 840 | height: 1, |
| 841 | ..area |
| 842 | }, |
| 843 | buf, |
| 844 | &Line::styled( |
| 845 | text::truncate( |
| 846 | &text::display_safe(value), |
| 847 | usize::from(area.width), |
| 848 | self.theme.ascii(), |
| 849 | ) |
| 850 | .into_owned(), |
| 851 | self.theme.fg(role), |
| 852 | ), |
| 853 | ); |
| 854 | } |
| 855 | |
| 856 | fn mark(&self, agent: &Subagent<'_>, state: &SubagentViewState) -> &'static str { |
| 857 | if agent.card.status.state != State::Working { |
| 858 | agent.card.status.glyph(self.theme) |
| 859 | } else if agent.checking { |
| 860 | VerificationSpinner::frame(state.mark_elapsed(agent), state.motion, self.theme.ascii()) |
| 861 | } else { |
| 862 | spin::frame(state.mark_elapsed(agent), state.motion, self.theme.ascii()) |
| 863 | } |
| 864 | } |
| 865 | |
| 866 | fn roster(&self, area: Rect, buf: &mut Buffer, state: &mut SubagentViewState) { |
| 867 | if area.is_empty() { |
| 868 | state.shown = 0; |
| 869 | return; |
| 870 | } |
| 871 | let size = if area.height >= 8 { 4 } else { 2 }; |
| 872 | // Reserve a final row for the range whenever entries overflow. |
| 873 | let capacity = usize::from(area.height / size).max(1); |
| 874 | let clipped = self.agents.len() > capacity; |
| 875 | state.shown = usize::from(area.height.saturating_sub(u16::from(clipped)) / size).max(1); |
| 876 | state.offset = state |
| 877 | .offset |
| 878 | .min(self.agents.len().saturating_sub(state.shown)); |
| 879 | if state.index < state.offset { |
| 880 | state.offset = state.index; |
| 881 | } |
| 882 | if state.index >= state.offset + state.shown { |
| 883 | state.offset = state.index + 1 - state.shown; |
| 884 | } |
| 885 | let rows = Rect { |
| 886 | height: area.height.saturating_sub(u16::from(clipped)), |
| 887 | ..area |
| 888 | }; |
| 889 | for (index, agent) in self |
| 890 | .agents |
| 891 | .iter() |
| 892 | .enumerate() |
| 893 | .skip(state.offset) |
| 894 | .take(state.shown) |
| 895 | { |
| 896 | let y = ((index - state.offset) as u16) * size; |
| 897 | if y >= rows.height { |
| 898 | break; |
| 899 | } |
| 900 | let entry = Rect::new(rows.x, rows.y + y, rows.width, size.min(rows.height - y)); |
| 901 | let selected = state.selected_id() == Some(&*agent.id); |
| 902 | state.rows.push((entry, agent.id.to_string())); |
| 903 | if selected { |
| 904 | buf.set_style(entry, self.theme.bg(Role::Selected)); |
| 905 | } |
| 906 | let marker = if selected { |
| 907 | glyphs::pick(glyphs::SELECTION, self.theme.ascii()) |
| 908 | } else { |
| 909 | " " |
| 910 | }; |
| 911 | let status = format!( |
| 912 | "{} {}", |
| 913 | self.mark(agent, state), |
| 914 | text::display_safe(&agent.card.status.word) |
| 915 | ); |
| 916 | let tail = text::width(&status).min(usize::from(entry.width.saturating_sub(4))) as u16; |
| 917 | let name_width = entry.width.saturating_sub(tail + 3); |
| 918 | row( |
| 919 | Rect { |
| 920 | width: name_width, |
| 921 | height: 1, |
| 922 | ..entry |
| 923 | }, |
| 924 | buf, |
| 925 | &Line::styled( |
| 926 | format!( |
| 927 | "{marker} {}", |
| 928 | text::truncate( |
| 929 | &text::display_safe(&agent.card.title), |
| 930 | usize::from(name_width.saturating_sub(2)), |
| 931 | self.theme.ascii() |
| 932 | ) |
| 933 | ), |
| 934 | self.theme |
| 935 | .fg(if selected { |
| 936 | Role::Accent |
| 937 | } else { |
| 938 | Role::Foreground |
| 939 | }) |
| 940 | .add_modifier(Modifier::BOLD), |
| 941 | ), |
| 942 | ); |
| 943 | self.line( |
| 944 | Rect::new(entry.right() - tail, entry.y, tail, 1), |
| 945 | 0, |
| 946 | &status, |
| 947 | agent.card.status.state.role(), |
| 948 | buf, |
| 949 | ); |
| 950 | let body = Rect::new( |
| 951 | entry.x + entry.width.min(2), |
| 952 | entry.y, |
| 953 | entry.width.saturating_sub(2), |
| 954 | entry.height, |
| 955 | ); |
| 956 | self.line(body, 1, &agent.card.task, Role::Foreground, buf); |
| 957 | if size == 4 { |
| 958 | let usage = agent.usage_text(self.theme.ascii(), self.words.steps_label.as_deref()); |
| 959 | let facts: Vec<&str> = [ |
| 960 | agent.card.role.as_deref(), |
| 961 | Some(usage.as_str()).filter(|s| !s.is_empty()), |
| 962 | ] |
| 963 | .into_iter() |
| 964 | .flatten() |
| 965 | .collect(); |
| 966 | self.line(body, 2, &facts.join(" / "), Role::Muted, buf); |
| 967 | } |
| 968 | } |
| 969 | if clipped { |
| 970 | self.line( |
| 971 | area, |
| 972 | area.height - 1, |
| 973 | &format!( |
| 974 | "{}-{} / {}", |
| 975 | state.offset + 1, |
| 976 | (state.offset + state.shown).min(self.agents.len()), |
| 977 | self.agents.len() |
| 978 | ), |
| 979 | Role::Muted, |
| 980 | buf, |
| 981 | ); |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | fn wrapped( |
| 986 | &self, |
| 987 | area: Rect, |
| 988 | y: u16, |
| 989 | value: &str, |
| 990 | max: u16, |
| 991 | role: Role, |
| 992 | buf: &mut Buffer, |
| 993 | ) -> u16 { |
| 994 | let height = max.min(area.height.saturating_sub(y)); |
| 995 | if height == 0 || area.width == 0 || value.is_empty() { |
| 996 | return 0; |
| 997 | } |
| 998 | let paragraph = Paragraph::new(text::display_safe(value).into_owned()) |
| 999 | .style(self.theme.fg(role)) |
| 1000 | .wrap(Wrap { trim: false }); |
| 1001 | let height = paragraph.line_count(area.width).min(usize::from(height)) as u16; |
| 1002 | paragraph.render(Rect::new(area.x, area.y + y, area.width, height), buf); |
| 1003 | height |
| 1004 | } |
| 1005 | |
| 1006 | fn details(&self, area: Rect, buf: &mut Buffer, state: &mut SubagentViewState) { |
| 1007 | state.pet_visible = false; |
| 1008 | state.detail_area = area; |
| 1009 | if area.is_empty() { |
| 1010 | return; |
| 1011 | } |
| 1012 | let Some(agent) = state.agent(self.agents) else { |
| 1013 | return; |
| 1014 | }; |
| 1015 | self.line(area, 0, &agent.card.title, Role::Accent, buf); |
| 1016 | if area.height > 1 { |
| 1017 | row( |
| 1018 | Rect::new(area.x, area.y + 1, area.width, 1), |
| 1019 | buf, |
| 1020 | &Line::from(agent.card.status.spans(self.theme)), |
| 1021 | ); |
| 1022 | } |
| 1023 | let identity: Vec<_> = [agent.card.role.as_deref(), agent.card.route.as_deref()] |
| 1024 | .into_iter() |
| 1025 | .flatten() |
| 1026 | .collect(); |
| 1027 | let mut y = 2; |
| 1028 | y += self.wrapped(area, y, &identity.join(" / "), 2, Role::Muted, buf); |
| 1029 | y += self.wrapped(area, y, &agent.card.task, 3, Role::Foreground, buf); |
| 1030 | y += self.wrapped( |
| 1031 | area, |
| 1032 | y, |
| 1033 | &agent.usage_text(self.theme.ascii(), self.words.steps_label.as_deref()), |
| 1034 | area.height.saturating_sub(y), |
| 1035 | Role::Muted, |
| 1036 | buf, |
| 1037 | ); |
| 1038 | if y < area.height |
| 1039 | && let Some(progress) = &agent.progress |
| 1040 | { |
| 1041 | progress.paint( |
| 1042 | Rect::new(area.x, area.y + y, area.width, 1), |
| 1043 | buf, |
| 1044 | self.theme, |
| 1045 | ); |
| 1046 | y += 1; |
| 1047 | } |
| 1048 | // Keep at least nine lines for content. The pet is a small companion, |
| 1049 | // never the reason a result or error becomes unreadable. |
| 1050 | if area.height.saturating_sub(y) >= 18 |
| 1051 | && area.width >= 26 |
| 1052 | && agent.performance.is_some() |
| 1053 | && !self.theme.ascii() |
| 1054 | { |
| 1055 | let width = area.width.min(32); |
| 1056 | WhalePet::new(self.theme) |
| 1057 | .words(agent.card.status.word.to_string()) |
| 1058 | .paint( |
| 1059 | Rect::new(area.x + (area.width - width) / 2, area.y + y, width, 9), |
| 1060 | buf, |
| 1061 | &mut state.stage, |
| 1062 | ); |
| 1063 | state.pet_visible = true; |
| 1064 | y += 9; |
| 1065 | } else if y < area.height { |
| 1066 | y += 1; |
| 1067 | } |
| 1068 | if y >= area.height { |
| 1069 | return; |
| 1070 | } |
| 1071 | let output = state.output && agent.outcome.is_some(); |
| 1072 | let label = if output { |
| 1073 | &self.words.output |
| 1074 | } else { |
| 1075 | &self.words.activity |
| 1076 | }; |
| 1077 | let title = if agent.outcome.is_some() { |
| 1078 | format!("{label} / {}", self.words.toggle_output) |
| 1079 | } else { |
| 1080 | label.to_string() |
| 1081 | }; |
| 1082 | self.line(area, y, &title, Role::Accent, buf); |
| 1083 | y += 1; |
| 1084 | if y >= area.height { |
| 1085 | return; |
| 1086 | } |
| 1087 | let body = Rect::new(area.x, area.y + y, area.width, area.height - y); |
| 1088 | // Cache only the visible window, never a String per physical row. |
| 1089 | // Long results keep bounded paint memory, including newline-heavy data. |
| 1090 | if output |
| 1091 | && (state.output_window.source != agent.outcome.as_deref().unwrap_or("") |
| 1092 | || state |
| 1093 | .output_window |
| 1094 | .geometry |
| 1095 | .is_none_or(|g| g.0 != body.width)) |
| 1096 | { |
| 1097 | state.output_window.prepare( |
| 1098 | agent.outcome.as_deref().unwrap_or(""), |
| 1099 | body.width, |
| 1100 | body.height, |
| 1101 | state.output_top, |
| 1102 | ); |
| 1103 | } |
| 1104 | let paragraph = if output { |
| 1105 | None |
| 1106 | } else { |
| 1107 | if agent.events.is_empty() { |
| 1108 | self.line(body, 0, &self.words.no_events, Role::Muted, buf); |
| 1109 | state.event_end = 0; |
| 1110 | state.event_top = None; |
| 1111 | return; |
| 1112 | } |
| 1113 | let lines: Vec<_> = agent |
| 1114 | .events |
| 1115 | .iter() |
| 1116 | .map(|event| { |
| 1117 | Line::from(vec![ |
| 1118 | Span::styled( |
| 1119 | format!("{} ", text::display_safe(&event.when)), |
| 1120 | self.theme.fg(Role::Muted), |
| 1121 | ), |
| 1122 | Span::styled( |
| 1123 | format!("{} ", glyphs::pick(event.state.glyph(), self.theme.ascii())), |
| 1124 | self.theme.fg(event.state.role()), |
| 1125 | ), |
| 1126 | Span::styled( |
| 1127 | text::display_safe(&event.message).into_owned(), |
| 1128 | self.theme.fg(Role::Foreground), |
| 1129 | ), |
| 1130 | ]) |
| 1131 | }) |
| 1132 | .collect(); |
| 1133 | Some(Paragraph::new(lines).wrap(Wrap { trim: false })) |
| 1134 | }; |
| 1135 | let total = if output { |
| 1136 | state.output_window.total |
| 1137 | } else { |
| 1138 | paragraph.as_ref().map_or(0, |p| p.line_count(body.width)) |
| 1139 | }; |
| 1140 | // Reserve a range indicator only when there is content to scroll. |
| 1141 | let clipped = total > usize::from(body.height) && body.height > 1; |
| 1142 | let content = Rect { |
| 1143 | height: body.height.saturating_sub(u16::from(clipped)), |
| 1144 | ..body |
| 1145 | }; |
| 1146 | let end = total.saturating_sub(usize::from(content.height)); |
| 1147 | let top = if output { |
| 1148 | state.output_end = end; |
| 1149 | state.output_top = state.output_top.min(end); |
| 1150 | state.output_top |
| 1151 | } else { |
| 1152 | state.event_end = end; |
| 1153 | state.event_top = state.event_top.map(|top| top.min(end)); |
| 1154 | state.event_top.unwrap_or(end) |
| 1155 | }; |
| 1156 | if output { |
| 1157 | state.output_window.prepare( |
| 1158 | agent.outcome.as_deref().unwrap_or(""), |
| 1159 | body.width, |
| 1160 | content.height, |
| 1161 | top, |
| 1162 | ); |
| 1163 | for (y, line) in state |
| 1164 | .output_window |
| 1165 | .rows |
| 1166 | .iter() |
| 1167 | .take(usize::from(content.height)) |
| 1168 | .enumerate() |
| 1169 | { |
| 1170 | self.line(content, y as u16, line, Role::Foreground, buf); |
| 1171 | } |
| 1172 | } else if let Some(paragraph) = paragraph { |
| 1173 | paragraph |
| 1174 | .scroll((top.min(usize::from(u16::MAX)) as u16, 0)) |
| 1175 | .render(content, buf); |
| 1176 | } |
| 1177 | if clipped { |
| 1178 | self.line( |
| 1179 | body, |
| 1180 | body.height - 1, |
| 1181 | &format!( |
| 1182 | "{}-{} / {}", |
| 1183 | top + 1, |
| 1184 | (top + usize::from(content.height)).min(total), |
| 1185 | total |
| 1186 | ), |
| 1187 | Role::Muted, |
| 1188 | buf, |
| 1189 | ); |
| 1190 | } |
| 1191 | } |
| 1192 | } |
| 1193 | |
| 1194 | impl StatefulWidget for SubagentView<'_> { |
| 1195 | type State = SubagentViewState; |
| 1196 | fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { |
| 1197 | let area = area.intersection(buf.area); |
| 1198 | state.shown = 0; |
| 1199 | state.pet_visible = false; |
| 1200 | state.rows.clear(); |
| 1201 | state.detail_area = Rect::default(); |
| 1202 | if area.is_empty() || !state.visible { |
| 1203 | return; |
| 1204 | } |
| 1205 | buf.set_style( |
| 1206 | area, |
| 1207 | self.theme |
| 1208 | .bg(Role::Background) |
| 1209 | .patch(self.theme.fg(Role::Foreground)), |
| 1210 | ); |
| 1211 | self.line(area, 0, &self.words.title, Role::Accent, buf); |
| 1212 | let count = |status| { |
| 1213 | self.agents |
| 1214 | .iter() |
| 1215 | .filter(|a| a.card.status.state == status) |
| 1216 | .count() |
| 1217 | }; |
| 1218 | let summary = self |
| 1219 | .words |
| 1220 | .summary |
| 1221 | .as_deref() |
| 1222 | .map(str::to_owned) |
| 1223 | .unwrap_or_else(|| { |
| 1224 | let mut counts: Vec<_> = State::ALL |
| 1225 | .into_iter() |
| 1226 | .filter_map(|status| { |
| 1227 | let n = count(status); |
| 1228 | (n > 0).then(|| format!("{n} {}", status.word().to_lowercase())) |
| 1229 | }) |
| 1230 | .collect(); |
| 1231 | counts.push(format!("{} total", self.agents.len())); |
| 1232 | counts.join(" / ") |
| 1233 | }); |
| 1234 | self.line(area, 1, &summary, Role::Muted, buf); |
| 1235 | let (roster, detail) = Self::areas(area, state.detail); |
| 1236 | if self.agents.is_empty() { |
| 1237 | self.line( |
| 1238 | if roster.is_empty() { detail } else { roster }, |
| 1239 | 0, |
| 1240 | &self.words.empty, |
| 1241 | Role::Muted, |
| 1242 | buf, |
| 1243 | ); |
| 1244 | } else { |
| 1245 | self.roster(roster, buf, state); |
| 1246 | self.details(detail, buf, state); |
| 1247 | } |
| 1248 | if area.height >= 3 { |
| 1249 | self.line(area, area.height - 1, &self.words.hints, Role::Muted, buf); |
| 1250 | let mut actions = Vec::new(); |
| 1251 | if let Some(agent) = state.agent(self.agents) { |
| 1252 | if agent.controls.open { |
| 1253 | actions.push(self.words.open.as_ref()); |
| 1254 | } |
| 1255 | if agent.controls.message { |
| 1256 | actions.push(self.words.message.as_ref()); |
| 1257 | } |
| 1258 | if agent.controls.stop { |
| 1259 | actions.push(self.words.stop.as_ref()); |
| 1260 | } |
| 1261 | } |
| 1262 | self.line( |
| 1263 | area, |
| 1264 | area.height - 2, |
| 1265 | &actions.join(" "), |
| 1266 | Role::Accent, |
| 1267 | buf, |
| 1268 | ); |
| 1269 | } |
| 1270 | } |
| 1271 | } |
| 1272 | |
| 1273 | #[cfg(test)] |
| 1274 | mod output_window_tests { |
| 1275 | use super::OutputWindow; |
| 1276 | #[test] |
| 1277 | fn newline_heavy_output_retains_only_the_viewport_and_reuses_it() { |
| 1278 | let source = "\n".repeat(8 * 1024 * 1024); |
| 1279 | let mut window = OutputWindow::default(); |
| 1280 | window.prepare(&source, 30, 12, 0); |
| 1281 | assert_eq!(window.total, source.len() + 1); |
| 1282 | assert_eq!(window.rows.len(), 12); |
| 1283 | let allocation = window.rows.as_ptr(); |
| 1284 | window.prepare(&source, 30, 12, 0); |
| 1285 | assert_eq!(window.rows.as_ptr(), allocation); |
| 1286 | } |
| 1287 | #[test] |
| 1288 | fn exact_width_output_preserves_only_source_blank_lines() { |
| 1289 | let mut window = OutputWindow::default(); |
| 1290 | window.prepare("12345\ndone\n\n", 5, 10, 0); |
| 1291 | assert_eq!(window.rows, ["12345", "done", "", ""]); |
| 1292 | } |
| 1293 | } |
| 1294 |