返回 CodeWhale
pet_mode.rs
1 //! The full pet work surface. Replaces host-specific full-screen tank layout;
2 //! the host still owns sessions, roster receipts, responses and every action.
3
4 use crate::{
5 DotWhale, MotionMode, Paint, PetStyle, Role, StatusMark, Subagent, SubagentIntent,
6 SubagentView, SubagentViewState, SubagentViewWords, Theme, WhalePet, text,
7 whale_motion::{Inputs, Presence, Stage, Tier},
8 };
9 use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind};
10 use ratatui::{
11 buffer::Buffer,
12 layout::{Alignment, Rect},
13 style::Modifier,
14 text::{Line, Span},
15 widgets::{Paragraph, StatefulWidget, Widget, Wrap},
16 };
17 use std::{
18 borrow::Cow,
19 time::{Duration, Instant},
20 };
21
22 /// Geometry shared by paint, response wrapping and host pointer routing.
23 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24 pub struct PetModeAreas {
25 pub header: Rect,
26 pub pet: Rect,
27 pub agents: Rect,
28 pub output: Rect,
29 pub footer: Rect,
30 }
31
32 impl PetModeAreas {
33 #[must_use]
34 pub fn new(area: Rect, agents: bool, output: bool, focus_agents: bool) -> Self {
35 let header = Rect {
36 height: area.height.min(2),
37 ..area
38 };
39 let footer_height = area.height.saturating_sub(header.height).min(2);
40 let footer = Rect::new(
41 area.x,
42 area.bottom().saturating_sub(footer_height),
43 area.width,
44 footer_height,
45 );
46 let body = Rect::new(
47 area.x,
48 header.bottom(),
49 area.width,
50 area.height.saturating_sub(header.height + footer_height),
51 );
52 let mut plan = Self {
53 header,
54 footer,
55 ..Self::default()
56 };
57 let wide = agents && body.width >= 100 && body.height >= 12;
58 let main = if wide {
59 let width = (body.width / 3).clamp(32, 44);
60 plan.agents = Rect::new(body.right() - width, body.y, width, body.height);
61 Rect {
62 width: body.width.saturating_sub(width + 2),
63 ..body
64 }
65 } else if agents && focus_agents {
66 plan.agents = body;
67 return plan;
68 } else {
69 body
70 };
71 if output && main.height >= 27 && main.width >= 16 {
72 // Reading has priority over scenery, including at 80x24.
73 let height = (u32::from(main.height) * 2 / 3).max(6) as u16;
74 plan.output = Rect::new(main.x, main.bottom() - height, main.width, height);
75 plan.pet = Rect {
76 height: main.height - height,
77 ..main
78 };
79 } else if output {
80 plan.output = main;
81 } else {
82 plan.pet = main;
83 }
84 plan
85 }
86 }
87
88 /// One canonical parent performance plus local selection/scroll. Never Clone.
89 #[derive(Default)]
90 pub struct PetModeState {
91 stage: Stage,
92 agents: SubagentViewState,
93 pub output_scroll: usize,
94 pub focus_agents: bool,
95 output_detached: bool,
96 output_end: usize,
97 areas: PetModeAreas,
98 session: Option<String>,
99 visible: bool,
100 motion: MotionMode,
101 stage_animates: bool,
102 style: PetStyle,
103 }
104
105 impl PetModeState {
106 /// The owner supplies current facts and one clock before painting.
107 pub fn update(
108 &mut self,
109 session: Option<&str>,
110 inputs: Inputs,
111 agents: &[Subagent<'_>],
112 now: Instant,
113 motion: MotionMode,
114 ) {
115 if self.session.as_deref() != session {
116 self.agents = SubagentViewState::default();
117 self.agents.set_visible(self.visible);
118 self.reset_output();
119 self.focus_agents = false;
120 self.session = session.map(str::to_owned);
121 } else if self.stage.director().context.turn_id != inputs.context.turn_id {
122 self.reset_output();
123 }
124 let settled = inputs.presence == Presence::Done
125 || (matches!(
126 inputs.presence,
127 Presence::Idle | Presence::Listening | Presence::Offline
128 ) && matches!(
129 inputs.context.status.as_deref(),
130 Some("completed" | "failed" | "error" | "cancelled" | "canceled" | "interrupted")
131 ));
132 self.motion = motion;
133 self.stage.set_visible(self.visible);
134 self.agents.set_visible(self.visible);
135 self.stage
136 .observe(session, inputs.clone(), !motion.animates());
137 self.stage.advance(now);
138 self.stage_animates = !settled || self.stage.director().completing();
139 if !self.stage_animates {
140 self.stage.observe(session, inputs, true);
141 }
142 self.agents.update(agents, now, motion);
143 if agents.is_empty() {
144 self.focus_agents = false;
145 }
146 }
147
148 pub fn set_visible(&mut self, visible: bool) {
149 self.visible = visible;
150 self.stage.set_visible(visible);
151 self.agents.set_visible(visible);
152 }
153
154 #[must_use]
155 pub fn next_frame_in(&self, agents: &[Subagent<'_>], theme: &Theme) -> Option<Duration> {
156 if !self.visible || !self.motion.animates() {
157 return None;
158 }
159 let art = WhalePet::art_area(self.areas.pet);
160 let pet = (!theme.ascii() && art.width >= 16 && art.height >= 8 && self.stage_animates)
161 .then(|| {
162 self.stage
163 .cadence(if theme.paints_grounds() && self.style == PetStyle::Color {
164 Tier::Hero
165 } else {
166 Tier::Terminal
167 })
168 })
169 .flatten();
170 [pet, self.agents.next_frame_in(agents, theme)]
171 .into_iter()
172 .flatten()
173 .min()
174 }
175
176 /// Painted selection only; hosts validate the ID again before opening.
177 #[must_use]
178 pub fn selected_agent_id(&self) -> Option<&str> {
179 (self.visible && self.focus_agents)
180 .then(|| self.agents.selected_id())
181 .flatten()
182 }
183
184 pub fn toggle_agents(&mut self, agents: &[Subagent<'_>]) {
185 if !agents.is_empty() {
186 self.focus_agents = !self.focus_agents;
187 }
188 }
189
190 /// Follow the next response from the host's authoritative turn boundary.
191 pub fn reset_output(&mut self) {
192 self.output_scroll = 0;
193 self.output_end = 0;
194 self.output_detached = false;
195 }
196
197 fn scroll_output(&mut self, lines: i16) {
198 self.output_scroll = self
199 .output_scroll
200 .saturating_add_signed(isize::from(lines))
201 .min(self.output_end);
202 self.output_detached = self.output_scroll < self.output_end;
203 }
204
205 /// Result scrolling or roster navigation, depending on the visible focus.
206 pub fn scroll(&mut self, agents: &[Subagent<'_>], lines: i16) {
207 if lines == 0 {
208 return;
209 }
210 if self.focus_agents {
211 let index = self
212 .agents
213 .selected_id()
214 .and_then(|id| agents.iter().position(|agent| agent.id == id))
215 .unwrap_or(0);
216 let target = index
217 .saturating_add_signed(isize::from(lines))
218 .min(agents.len().saturating_sub(1));
219 if let Some(agent) = agents.get(target) {
220 self.agents.select(agents, &agent.id);
221 }
222 } else {
223 self.scroll_output(lines);
224 }
225 }
226
227 /// Home/End route to the focused roster or the complete response.
228 pub fn scroll_end(&mut self, agents: &[Subagent<'_>], end: bool) {
229 if self.focus_agents {
230 self.agents.handle_key(
231 agents,
232 KeyEvent::from(if end { KeyCode::End } else { KeyCode::Home }),
233 );
234 } else {
235 self.output_scroll = if end { usize::MAX } else { 0 };
236 self.output_detached = !end;
237 }
238 }
239
240 pub fn open_agent(&mut self, agents: &[Subagent<'_>]) -> Option<SubagentIntent> {
241 if !self.focus_agents {
242 return None;
243 }
244 self.agents
245 .handle_key(agents, KeyEvent::from(KeyCode::Enter))
246 }
247
248 /// Tab switches the composed pane. Focused roster keys return the same
249 /// capability-gated intents as SubagentView; the host owns every action.
250 pub fn handle_key(&mut self, agents: &[Subagent<'_>], key: KeyEvent) -> Option<SubagentIntent> {
251 if !self.visible
252 || key.kind == KeyEventKind::Release
253 || !key.modifiers.difference(KeyModifiers::SHIFT).is_empty()
254 {
255 return None;
256 }
257 if key.code == KeyCode::Tab && key.modifiers.is_empty() {
258 self.toggle_agents(agents);
259 return None;
260 }
261 if self.focus_agents {
262 return self.agents.handle_key(agents, key);
263 }
264 match key.code {
265 KeyCode::Up => self.scroll(agents, -1),
266 KeyCode::Down => self.scroll(agents, 1),
267 KeyCode::PageUp => self.scroll(agents, -10),
268 KeyCode::PageDown => self.scroll(agents, 10),
269 KeyCode::Home => self.scroll_end(agents, false),
270 KeyCode::End => self.scroll_end(agents, true),
271 _ => {}
272 }
273 None
274 }
275
276 /// A click/wheel on the roster uses its recorded IDs; a wheel on the
277 /// response scrolls it. No pointer input executes a worker action.
278 pub fn handle_mouse(&mut self, agents: &[Subagent<'_>], mouse: MouseEvent) -> bool {
279 if !self.visible {
280 return false;
281 }
282 let point = (mouse.column, mouse.row).into();
283 let cove_point = WhalePet::point(self.areas.pet, mouse.column, mouse.row);
284 if cove_point.is_none() {
285 self.stage.cove_leave();
286 }
287 if self.areas.agents.contains(point) && self.agents.handle_mouse(agents, mouse) {
288 self.focus_agents = true;
289 return true;
290 }
291 if self.areas.output.contains(point) {
292 match mouse.kind {
293 MouseEventKind::ScrollUp => self.scroll_output(-3),
294 MouseEventKind::ScrollDown => self.scroll_output(3),
295 MouseEventKind::Down(crossterm::event::MouseButton::Left) => {}
296 _ => return false,
297 }
298 self.focus_agents = false;
299 return true;
300 }
301 if let Some((x, y)) = cove_point {
302 self.stage.cove_observe(x, y);
303 if matches!(
304 mouse.kind,
305 MouseEventKind::Down(crossterm::event::MouseButton::Left)
306 ) {
307 self.stage.cove_tap(x, y);
308 }
309 return true;
310 }
311 false
312 }
313 }
314
315 /// Full pet-mode composition. Response lines are already wrapped by the host's
316 /// existing Markdown/transcript renderer at [`PetModeAreas::output`] width.
317 /// Pass only actual roster facts and localized words. Paint never advances time.
318 pub struct PetMode<'a> {
319 pub theme: &'a Theme,
320 pub title: Cow<'a, str>,
321 pub status: StatusMark,
322 pub dot_whale: Option<DotWhale<'a>>,
323 pub style: PetStyle,
324 pub cove: bool,
325 /// The host's existing notice, using its semantic severity ink.
326 pub notice: Option<Line<'a>>,
327 pub agents: &'a [Subagent<'a>],
328 pub agent_words: SubagentViewWords<'a>,
329 pub output: &'a [Line<'a>],
330 pub output_title: Cow<'a, str>,
331 /// Optional second footer row for the focused pane's controls.
332 pub pane_hints: Cow<'a, str>,
333 pub hints: Cow<'a, str>,
334 }
335
336 impl<'a> PetMode<'a> {
337 #[must_use]
338 pub fn new(theme: &'a Theme, status: StatusMark) -> Self {
339 Self {
340 theme,
341 title: "Codewhale".into(),
342 status,
343 dot_whale: None,
344 style: PetStyle::Color,
345 cove: true,
346 notice: None,
347 agents: &[],
348 agent_words: SubagentViewWords::default(),
349 output: &[],
350 output_title: "Response".into(),
351 pane_hints: "".into(),
352 hints: "Esc back".into(),
353 }
354 }
355 }
356
357 impl StatefulWidget for PetMode<'_> {
358 type State = PetModeState;
359 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
360 let area = area.intersection(buf.area);
361 state.areas = PetModeAreas::default();
362 state.style = self.style;
363 if !state.visible || area.is_empty() {
364 return;
365 }
366 buf.set_style(
367 area,
368 self.theme
369 .bg(Role::Background)
370 .patch(self.theme.fg(Role::Foreground)),
371 );
372 let plan = PetModeAreas::new(
373 area,
374 !self.agents.is_empty(),
375 !self.output.is_empty(),
376 state.focus_agents,
377 );
378 state.areas = plan;
379 if !plan.header.is_empty() {
380 let status = self.status.spans(self.theme);
381 let status_width: usize = status.iter().map(|span| text::width(&span.content)).sum();
382 let title = text::display_safe(&self.title);
383 let mut spans = Vec::new();
384 // Shed identity before phase; narrow/ASCII views still name the
385 // activity even when a caller supplies a long title.
386 if text::width(&title)
387 .saturating_add(3)
388 .saturating_add(status_width)
389 <= usize::from(plan.header.width)
390 {
391 spans.push(Span::styled(
392 title.into_owned(),
393 self.theme.fg(Role::Accent),
394 ));
395 spans.push(Span::raw(" "));
396 }
397 spans.extend(status);
398 Paragraph::new(Line::from(spans)).render(
399 Rect {
400 height: 1,
401 ..plan.header
402 },
403 buf,
404 );
405 }
406 if plan.header.height > 1
407 && let Some(line) = self.notice
408 {
409 let safe = Line::from(
410 line.spans
411 .iter()
412 .map(|span| {
413 Span::styled(text::display_safe(&span.content).into_owned(), span.style)
414 })
415 .collect::<Vec<_>>(),
416 )
417 .style(line.style);
418 Paragraph::new(safe).render(
419 Rect::new(plan.header.x, plan.header.y + 1, plan.header.width, 1),
420 buf,
421 );
422 }
423 if !plan.pet.is_empty() {
424 if let Some(whale) = self.dot_whale {
425 whale.paint(plan.pet, buf, self.theme);
426 } else {
427 WhalePet::new(self.theme)
428 .words("")
429 .style(self.style)
430 .cove(self.cove)
431 .paint(plan.pet, buf, &mut state.stage);
432 }
433 }
434 let marker = if self.theme.ascii() { "> " } else { "› " };
435 let mut agent_words = self.agent_words;
436 if state.focus_agents {
437 agent_words.title = format!("{marker}{}", agent_words.title).into();
438 }
439 if !plan.agents.is_empty() && plan.agents.x > area.x {
440 // The shared layout already reserves this gap; no reading space
441 // or pointer geometry is consumed by the divider.
442 for y in plan.agents.y..plan.agents.bottom() {
443 buf[(plan.agents.x - 1, y)]
444 .set_symbol(if self.theme.ascii() { "|" } else { "│" })
445 .set_style(self.theme.fg(Role::Muted));
446 }
447 }
448 // Render even the hidden roster's empty area to clear stale hitboxes.
449 SubagentView::new(self.agents, self.theme)
450 .words(agent_words)
451 .render(plan.agents, buf, &mut state.agents);
452 if !plan.output.is_empty() {
453 let body = Rect::new(
454 plan.output.x,
455 plan.output.y + 1,
456 plan.output.width,
457 plan.output.height.saturating_sub(1),
458 );
459 state.output_end = self.output.len().saturating_sub(usize::from(body.height));
460 state.output_scroll = if state.output_detached {
461 state.output_scroll.min(state.output_end)
462 } else {
463 state.output_end
464 };
465 let heading = Rect {
466 height: 1,
467 ..plan.output
468 };
469 let mut title_area = heading;
470 if body.height > 0 && state.output_end > 0 {
471 let range = format!(
472 "{}-{} / {}",
473 state.output_scroll + 1,
474 (state.output_scroll + usize::from(body.height)).min(self.output.len()),
475 self.output.len()
476 );
477 let width = text::width(&range) as u16;
478 if heading.width >= width.saturating_add(8) {
479 title_area.width -= width + 1;
480 Paragraph::new(range)
481 .alignment(Alignment::Right)
482 .style(self.theme.fg(Role::Muted))
483 .render(heading, buf);
484 }
485 }
486 let title = if state.focus_agents {
487 self.output_title.into_owned()
488 } else {
489 format!("{marker}{}", self.output_title)
490 };
491 Paragraph::new(text::display_safe(&title).into_owned())
492 .style(if state.focus_agents {
493 self.theme.fg(Role::Muted)
494 } else {
495 self.theme.fg(Role::Accent).add_modifier(Modifier::BOLD)
496 })
497 .render(title_area, buf);
498 // usize selection preserves arbitrarily long already-wrapped output.
499 for (y, line) in self
500 .output
501 .iter()
502 .skip(state.output_scroll)
503 .take(usize::from(body.height))
504 .enumerate()
505 {
506 let safe = Line::from(
507 line.spans
508 .iter()
509 .map(|span| {
510 Span::styled(text::display_safe(&span.content).into_owned(), span.style)
511 })
512 .collect::<Vec<_>>(),
513 )
514 .style(line.style);
515 Paragraph::new(safe)
516 .render(Rect::new(body.x, body.y + y as u16, body.width, 1), buf);
517 }
518 }
519 if !plan.footer.is_empty() {
520 let split = plan.footer.height > 1 && !self.pane_hints.is_empty();
521 let hints = text::display_safe(&self.hints);
522 let hints = if split {
523 text::truncate(&hints, usize::from(plan.footer.width), self.theme.ascii())
524 .into_owned()
525 } else {
526 hints.into_owned()
527 };
528 Paragraph::new(hints)
529 .wrap(Wrap { trim: true })
530 .style(self.theme.fg(Role::Muted))
531 .render(
532 Rect {
533 height: if split { 1 } else { plan.footer.height },
534 ..plan.footer
535 },
536 buf,
537 );
538 if split {
539 Paragraph::new(
540 text::truncate(
541 &text::display_safe(&self.pane_hints),
542 usize::from(plan.footer.width),
543 self.theme.ascii(),
544 )
545 .into_owned(),
546 )
547 .style(self.theme.fg(Role::Muted))
548 .render(
549 Rect::new(plan.footer.x, plan.footer.y + 1, plan.footer.width, 1),
550 buf,
551 );
552 }
553 }
554 }
555 }
556
557 #[cfg(test)]
558 mod visibility_tests {
559 use super::*;
560 #[test]
561 fn default_hidden_updates_do_not_advance_the_parent_clock() {
562 let mut state = PetModeState::default();
563 let now = Instant::now();
564 let inputs = Inputs {
565 presence: Presence::Working,
566 activity: None,
567 context: Default::default(),
568 };
569 state.update(Some("session"), inputs.clone(), &[], now, MotionMode::Full);
570 state.update(
571 Some("session"),
572 inputs.clone(),
573 &[],
574 now + Duration::from_secs(30),
575 MotionMode::Full,
576 );
577 assert!(!state.stage.is_visible());
578 assert_eq!(state.stage.director().f, 0.);
579 state.set_visible(true);
580 state.update(
581 Some("session"),
582 inputs,
583 &[],
584 now + Duration::from_secs(30),
585 MotionMode::Full,
586 );
587 assert_eq!(state.stage.director().f, 0.);
588 }
589 }
590
590 lines RUST