返回 CodeWhale
fleet_roster.rs
根目录 / crates / tui / src / tui / views / fleet_roster.rs
1 //! `/fleet` roster — the barracks view of the saved agent party.
2 //!
3 //! The roster view is the primary `/fleet` face. The first row is the
4 //! **operator** — the Fleet leader (your live session model). When a user
5 //! picks a session model they are picking the operator, and every member
6 //! below is that leader's team. The header names the selected saved Fleet and
7 //! whether it is user-global or folder-scoped, so scope is never ambiguous.
8 //! Below the operator sits the merged [`FleetRoster`] (built-in <
9 //! `[fleet.profiles]` config < `$CODEWHALE_HOME/agents/*.toml` personal <
10 //! `.codewhale/agents/*.toml` project members)
11 //! as a scrollable list with a detail pane for the selected row. The view
12 //! never writes anything; Enter opens the shared model/thinking picker for
13 //! the selected role, retaining this roster underneath. The existing saved
14 //! team/profile owner validates and persists assignments. Switch named
15 //! saved Fleets with `/fleet fleets` (`/fleet fleets` remains compatible).
16 //!
17 //! #5888: the default lineup folds the built-in `general` alias out of
18 //! presentation — it is the same posture as `worker` and stays dispatchable
19 //! (roster lookup and the identity selector both still resolve it) — so the
20 //! default surface is 11 rows: the live operator plus ten members.
21 //!
22 //! NOTE: like `fleet_setup.rs`, the copy below is intentionally English for
23 //! now (#3167 reworks Fleet UI localization); the command entry
24 //! (`CmdFleetDescription`) is already localized.
25
26 use std::cell::{Cell, RefCell};
27
28 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
29 use ratatui::{
30 buffer::Buffer,
31 layout::{Constraint, Direction, Layout, Rect},
32 style::{Color, Modifier, Style},
33 text::{Line, Span},
34 widgets::{Paragraph, Widget, Wrap},
35 };
36
37 use crate::tui::app::App;
38 use codewhale_agent_contract::role::public_role_label;
39 use codewhale_engine::fleet::profile::AgentProfile;
40 use codewhale_engine::fleet::roster::{
41 FleetRoster, ProfileLayer, ProfileOrigin, layers_from_parts,
42 };
43 use codewhale_engine::fleet::worker_runtime::roster_member_agent_type;
44 use codewhale_runtime::config::Config;
45 use codewhale_tui_kit::menu_style;
46
47 /// Rows one PageUp/PageDown travels. Pages clamp at the ends per the shared
48 /// vocabulary instead of wrapping (#6290).
49 const FLEET_ROSTER_PAGE: usize = 10;
50 use crate::tui::views::{
51 ActionHint, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent,
52 active_modal_accent_color, active_modal_border_color, render_modal_footer, render_modal_rule,
53 render_panel_scroll_rail, render_surface_frame, render_vertical_divider, truncate_view_text,
54 };
55 use crate::tui::whales;
56 use codewhale_agent_contract::worker_profile::{ShellPolicy, WorkerRuntimeProfile};
57 use codewhale_localization::{Locale, MessageId, tr};
58 use codewhale_palette as palette;
59
60 /// The live session route — the operator the roster works for. Read once at
61 /// open, the same way [`super::fleet_setup::FleetSetupSnapshot`] snapshots it.
62 #[derive(Debug, Clone)]
63 struct OperatorInfo {
64 provider: String,
65 /// Exact canonical route key, kept separate from the display label so
66 /// capability lookup can use provider-scoped catalog facts.
67 provider_id: String,
68 model: String,
69 reasoning: String,
70 }
71
72 impl OperatorInfo {
73 fn from_app(app: &App) -> Self {
74 let model = if app.auto_model {
75 app.last_effective_model
76 .as_deref()
77 .map(|effective| format!("auto -> {effective}"))
78 .unwrap_or_else(|| "auto".to_string())
79 } else {
80 app.model.clone()
81 };
82 let route_provider = if app.auto_model {
83 app.last_effective_provider.unwrap_or(app.api_provider)
84 } else {
85 app.api_provider
86 };
87 let provider_id = if app.auto_model {
88 app.last_effective_provider_identity
89 .clone()
90 .unwrap_or_else(|| {
91 if route_provider == codewhale_config::ProviderKind::Custom {
92 app.provider_identity_for_persistence().to_string()
93 } else {
94 route_provider.as_str().to_string()
95 }
96 })
97 } else {
98 app.provider_identity_for_persistence().to_string()
99 };
100 let provider = if route_provider == codewhale_config::ProviderKind::Custom {
101 provider_id.clone()
102 } else {
103 route_provider.provider().display_name().to_string()
104 };
105 Self {
106 provider,
107 provider_id,
108 model,
109 reasoning: app.reasoning_effort_display_label(),
110 }
111 }
112 }
113
114 /// Which named Fleet (if any) this session is using, and where that selection
115 /// is pinned — user-global vs this folder only.
116 #[derive(Debug, Clone)]
117 struct SelectedFleetSummary {
118 name: String,
119 scope: codewhale_engine::fleet::store::FleetScope,
120 }
121
122 /// View-owned action attached to a painted saved-profile row.
123 ///
124 /// This stays deliberately separate from Tideline's live-worker targets,
125 /// which are backed by `SubAgentStatus`, not editable profiles in this roster.
126 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
127 enum FleetRosterRowAction {
128 SelectOrActivate { row: usize },
129 }
130
131 impl FleetRosterRowAction {
132 const fn row(self) -> usize {
133 match self {
134 Self::SelectOrActivate { row } => row,
135 }
136 }
137 }
138
139 pub struct FleetRosterView {
140 operator: OperatorInfo,
141 members: Vec<AgentProfile>,
142 /// Shadow records from the roster load (#5098): which lower-precedence
143 /// files the displayed members are ignoring.
144 shadowed: Vec<codewhale_engine::fleet::roster::ShadowedProfile>,
145 /// Selected named Fleet + scope, when one is active for this session.
146 selected_fleet: Option<SelectedFleetSummary>,
147 /// A selected Fleet existed but could not become the runtime roster.
148 load_error: Option<String>,
149 /// Selected row: 0 is the pinned operator row, members follow at 1..
150 selected: usize,
151 detail_scroll: usize,
152 /// Exact visible row geometry from the latest render. This is a
153 /// frame-scoped projection, not a second roster or navigation owner.
154 row_hitboxes: RefCell<Vec<(Rect, FleetRosterRowAction)>>,
155 /// A first click selects/reveals details; a consecutive click on the same
156 /// row activates the exact same handoff as Enter.
157 last_mouse_selected: Option<usize>,
158 /// Row under the pointer, tinted with the shared hover style. Hover
159 /// never moves the keyboard selection; only painted rows answer.
160 hovered_row: Cell<Option<usize>>,
161 workers_hitbox: Cell<Option<Rect>>,
162 hovered_workers: Cell<bool>,
163 /// Canonical active-theme surface captured from `App`; Terminal owns
164 /// `Color::Reset`, while explicit themes retain their resolved surface.
165 surface_bg: Color,
166 /// UI locale captured from the app at construction (#4057 wave 2).
167 locale: Locale,
168 }
169
170 impl FleetRosterView {
171 #[must_use]
172 pub fn new(app: &App, config: &Config) -> Self {
173 let selected_fleet =
174 codewhale_engine::fleet::store::selected_fleet(&app.workspace).map(|sel| {
175 SelectedFleetSummary {
176 name: sel.name,
177 scope: sel.scope,
178 }
179 });
180 let mut view = Self::from_parts(
181 OperatorInfo::from_app(app),
182 codewhale_engine::fleet::identity::load_effective_roster(
183 &config.fleet_config(),
184 &app.workspace,
185 Some(app.plugin_registry.as_ref()),
186 ),
187 selected_fleet,
188 );
189 view.locale = app.ui_locale;
190 view.surface_bg = app.ui_theme.surface_bg;
191 view
192 }
193
194 fn from_parts(
195 operator: OperatorInfo,
196 roster: FleetRoster,
197 selected_fleet: Option<SelectedFleetSummary>,
198 ) -> Self {
199 let load_error = roster.load_error().map(str::to_string);
200 Self {
201 operator,
202 // The operator is pinned as its own row 0 (the live session route),
203 // so exclude the built-in "operator" profile from the dispatchable
204 // member list to avoid rendering it twice (#dogfood 0.8.67). The
205 // engine's FleetRoster is untouched, so role/dispatch semantics are
206 // unchanged; only this view drops the duplicate.
207 members: roster
208 .members()
209 .iter()
210 .filter(|m| !m.id.trim().eq_ignore_ascii_case("operator"))
211 .cloned()
212 .collect(),
213 shadowed: roster.shadowed().to_vec(),
214 selected_fleet,
215 load_error,
216 selected: 0,
217 detail_scroll: 0,
218 row_hitboxes: RefCell::new(Vec::new()),
219 last_mouse_selected: None,
220 hovered_row: Cell::new(None),
221 workers_hitbox: Cell::new(None),
222 hovered_workers: Cell::new(false),
223 surface_bg: palette::UI_THEME.surface_bg,
224 locale: Locale::En,
225 }
226 }
227
228 /// Rebuild this roster from the current workspace, keeping the cursor.
229 ///
230 /// #5954: the roster now stays parked under the saved-teams list, so a
231 /// team switch or delete has to refresh the parked view in place — the
232 /// user pops back to it, and it must not keep painting the pre-change
233 /// selection. Cursor and detail scroll survive because losing them is
234 /// exactly the disruption the back path exists to avoid.
235 pub fn reload(&mut self, app: &App, config: &Config) {
236 let selected = self.selected;
237 let detail_scroll = self.detail_scroll;
238 *self = Self::new(app, config);
239 self.selected = selected.min(self.row_count().saturating_sub(1));
240 self.detail_scroll = detail_scroll;
241 }
242
243 /// Total selectable rows: the operator plus every roster member.
244 fn row_count(&self) -> usize {
245 1 + self.members.len()
246 }
247
248 fn operator_selected(&self) -> bool {
249 self.selected == 0
250 }
251
252 fn selected_member(&self) -> Option<&AgentProfile> {
253 self.selected.checked_sub(1).and_then(|idx| {
254 self.members
255 .get(idx.min(self.members.len().saturating_sub(1)))
256 })
257 }
258
259 fn move_up(&mut self) {
260 self.selected =
261 codewhale_tui_kit::list_nav::wrap_index(self.selected, self.row_count(), -1);
262 self.detail_scroll = 0;
263 self.last_mouse_selected = None;
264 self.hovered_row.set(None);
265 }
266
267 fn move_down(&mut self) {
268 self.selected = codewhale_tui_kit::list_nav::wrap_index(self.selected, self.row_count(), 1);
269 self.detail_scroll = 0;
270 self.last_mouse_selected = None;
271 self.hovered_row.set(None);
272 }
273
274 /// Apply one [`list_nav`](codewhale_tui_kit::list_nav) motion (#6290), returning
275 /// whether it was consumed. Steps wrap; pages travel [`FLEET_ROSTER_PAGE`]
276 /// rows and clamp. The region axis is declined so Tab keeps opening the
277 /// workers view through the explicit arm below.
278 fn apply_motion(&mut self, motion: codewhale_tui_kit::list_nav::Motion) -> bool {
279 use codewhale_tui_kit::list_nav::Motion;
280 match motion {
281 Motion::Prev => {
282 self.move_up();
283 true
284 }
285 Motion::Next => {
286 self.move_down();
287 true
288 }
289 Motion::RegionPrev | Motion::RegionNext => false,
290 _ => {
291 let count = self.row_count();
292 if count == 0 {
293 return false;
294 }
295 let Some(next) = codewhale_tui_kit::list_nav::apply(
296 self.selected,
297 count,
298 FLEET_ROSTER_PAGE,
299 motion,
300 ) else {
301 return false;
302 };
303 self.selected = next;
304 self.detail_scroll = 0;
305 self.last_mouse_selected = None;
306 self.hovered_row.set(None);
307 true
308 }
309 }
310 }
311
312 fn select_row(&mut self, row: usize) {
313 self.selected = row.min(self.row_count().saturating_sub(1));
314 self.detail_scroll = 0;
315 }
316
317 fn activate_selected(&self) -> ViewAction {
318 if let Some(member) = self.selected_member() {
319 let member_id = member.id.clone();
320 // Carry the exact member the operator already chose. The host
321 // focuses it in the selected v2 Fleet editor, or starts legacy
322 // setup from its member id when no Fleet is selected.
323 ViewAction::Emit(ViewEvent::FleetRosterOpenSetupRequested { member_id })
324 } else {
325 ViewAction::Emit(ViewEvent::FleetRosterOpenCoordinatorRequested)
326 }
327 }
328
329 fn select_or_activate_mouse_row(&mut self, row: usize) -> ViewAction {
330 let activate = self.last_mouse_selected == Some(row) && self.selected == row;
331 self.select_row(row);
332 self.last_mouse_selected = Some(row);
333 if activate {
334 self.activate_selected()
335 } else {
336 ViewAction::None
337 }
338 }
339
340 /// One navigation grammar (grokbuild): arrows move, Enter acts, Tab
341 /// moves across the header tabs, Esc closes. `f` is the one named
342 /// destination this room has that is not a tab. Detail scrolling
343 /// (PgUp/PgDn) works but is not advertised — the pane is short now.
344 fn footer_hints(&self) -> Vec<ActionHint> {
345 let mut hints = vec![
346 ActionHint::new("↑↓", "move"),
347 ActionHint::new("Enter", "model & thinking"),
348 ];
349 hints.extend([
350 ActionHint::new("Tab", tr(self.locale, MessageId::FleetRosterWorkers)),
351 ActionHint::new("f", "saved teams"),
352 ActionHint::new("Esc", "close"),
353 ]);
354 hints
355 }
356 }
357
358 impl ModalView for FleetRosterView {
359 fn kind(&self) -> ModalKind {
360 ModalKind::FleetRoster
361 }
362
363 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
364 self
365 }
366
367 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
368 // A keyboard gesture ends any pending mouse double-click sequence so
369 // a later single click can never activate a stale row.
370 self.last_mouse_selected = None;
371 self.hovered_workers.set(false);
372 self.hovered_row.set(None);
373 // Shift-modified paging scrolls the detail pane; bare keys drive the
374 // row list through the shared vocabulary (#6290, #6014-style split).
375 if key.modifiers.contains(KeyModifiers::SHIFT) {
376 match key.code {
377 KeyCode::PageUp => {
378 self.detail_scroll = self.detail_scroll.saturating_sub(8);
379 return ViewAction::None;
380 }
381 KeyCode::PageDown => {
382 self.detail_scroll = self.detail_scroll.saturating_add(8);
383 return ViewAction::None;
384 }
385 KeyCode::Home => {
386 self.detail_scroll = 0;
387 return ViewAction::None;
388 }
389 _ => {}
390 }
391 }
392 // Movement keys come from the shared vocabulary (#6290), j/k aliases
393 // included — this surface captures no text.
394 if let Some(motion) = codewhale_tui_kit::list_nav::motion(&key)
395 && self.apply_motion(motion)
396 {
397 return ViewAction::None;
398 }
399 match key.code {
400 KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
401 KeyCode::Enter => self.activate_selected(),
402 // #5954: the roster stays on the stack under the view it opens,
403 // so `Esc` in workers / saved teams pops back here instead of
404 // closing the window. `Emit` (not `EmitAndClose`) is what makes
405 // the three Fleet views one stack.
406 KeyCode::Tab | KeyCode::BackTab | KeyCode::Char('w') => {
407 ViewAction::Emit(ViewEvent::FleetRosterOpenWorkersRequested)
408 }
409 KeyCode::Char('f') => ViewAction::Emit(ViewEvent::FleetRosterOpenFleetsRequested),
410 _ => ViewAction::None,
411 }
412 }
413
414 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
415 match mouse.kind {
416 MouseEventKind::Moved => {
417 self.hovered_workers.set(
418 self.workers_hitbox
419 .get()
420 .is_some_and(|rect| rect.contains((mouse.column, mouse.row).into())),
421 );
422 let hovered = self
423 .row_hitboxes
424 .borrow()
425 .iter()
426 .find_map(|(rect, action)| {
427 rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
428 .then_some(action.row())
429 });
430 self.hovered_row.set(hovered);
431 ViewAction::None
432 }
433 MouseEventKind::ScrollUp => {
434 self.move_up();
435 ViewAction::None
436 }
437 MouseEventKind::ScrollDown => {
438 self.move_down();
439 ViewAction::None
440 }
441 MouseEventKind::Down(MouseButton::Left) => {
442 if self
443 .workers_hitbox
444 .get()
445 .is_some_and(|rect| rect.contains((mouse.column, mouse.row).into()))
446 {
447 self.last_mouse_selected = None;
448 return ViewAction::Emit(ViewEvent::FleetRosterOpenWorkersRequested);
449 }
450 let action = self
451 .row_hitboxes
452 .borrow()
453 .iter()
454 .find_map(|(rect, action)| {
455 rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
456 .then_some(*action)
457 });
458 action.map_or(ViewAction::None, |action| {
459 self.select_or_activate_mouse_row(action.row())
460 })
461 }
462 _ => ViewAction::None,
463 }
464 }
465
466 fn render(&self, area: Rect, buf: &mut Buffer) {
467 let title = format!(
468 "{} · {}",
469 tr(self.locale, MessageId::FleetRosterHeaderLabel),
470 tr(self.locale, MessageId::FleetRosterTabRoster)
471 );
472 let workers_label = tr(self.locale, MessageId::FleetRosterWorkers).into_owned();
473 let workers_style = if self.hovered_workers.get() {
474 menu_style::hovered_row_style().fg(active_modal_accent_color())
475 } else {
476 Style::default()
477 .fg(active_modal_accent_color())
478 .add_modifier(Modifier::BOLD)
479 };
480 let mut frame = SurfaceFrame::new(title).right_pill(workers_label, workers_style);
481 if self.surface_bg == Color::Reset {
482 let mut theme = palette::TERMINAL_UI_THEME;
483 theme.surface_bg = Color::Reset;
484 theme.composer_bg = Color::Reset;
485 frame = frame.theme(theme);
486 }
487 let (inner, pill_hitbox) = render_surface_frame(area, buf, frame);
488 self.workers_hitbox.set(pill_hitbox);
489
490 let hints = self.footer_hints();
491 let content = render_modal_footer(inner, buf, &hints);
492
493 let show_rule = content.height >= 4;
494 let header_height = if show_rule {
495 2
496 } else {
497 u16::from(content.height >= 2)
498 };
499 let chunks = Layout::default()
500 .direction(Direction::Vertical)
501 .constraints([Constraint::Length(header_height), Constraint::Min(1)])
502 .split(content);
503 if chunks[0].height > 0 {
504 let summary = format!(
505 "{} · {}",
506 self.selected_fleet_line(),
507 tr(self.locale, MessageId::FleetRosterMembersCount)
508 .replace("{count}", &(self.members.len() + 1).to_string())
509 );
510 Paragraph::new(Line::from(Span::styled(
511 truncate_view_text(&summary, usize::from(chunks[0].width)),
512 Style::default().fg(palette::TEXT_MUTED),
513 )))
514 .render(Rect::new(chunks[0].x, chunks[0].y, chunks[0].width, 1), buf);
515 }
516 if show_rule && chunks[0].height > 1 {
517 render_modal_rule(
518 Rect::new(chunks[0].x, chunks[0].y + 1, chunks[0].width, 1),
519 buf,
520 );
521 }
522
523 self.render_body(chunks[1], buf);
524 }
525 }
526
527 impl FleetRosterView {
528 /// Scope-explicit selected Fleet line. Paths stay out — receipts name them.
529 fn selected_fleet_line(&self) -> String {
530 if let Some(error) = &self.load_error {
531 return format!("Team selection error — {error}");
532 }
533 match &self.selected_fleet {
534 Some(sel) => format!("Team `{}` · {}", sel.name, sel.scope.long_label()),
535 None => "No team selected — built-in team".to_string(),
536 }
537 }
538
539 fn render_body(&self, area: Rect, buf: &mut Buffer) {
540 self.row_hitboxes.borrow_mut().clear();
541 if area.width == 0 || area.height == 0 {
542 return;
543 }
544
545 // Two columns when there is room, stacked otherwise — same responsive
546 // shape as the setup wizard's choice step so nothing truncates at
547 // 80x24.
548 let (list_area, detail_area) = if area.width >= 56 {
549 let cols = Layout::default()
550 .direction(Direction::Horizontal)
551 .constraints([
552 Constraint::Percentage(45),
553 Constraint::Length(2),
554 Constraint::Min(20),
555 ])
556 .split(area);
557 render_vertical_divider(cols[1], buf, active_modal_border_color());
558 (cols[0], cols[2])
559 } else {
560 let list_height =
561 (self.row_count() as u16 + 1).min(area.height.saturating_sub(1).max(1));
562 let rows = Layout::default()
563 .direction(Direction::Vertical)
564 .constraints([Constraint::Length(list_height), Constraint::Min(1)])
565 .split(area);
566 (rows[0], rows[1])
567 };
568
569 let visible_rows = usize::from(list_area.height).max(1);
570 let first = self
571 .selected
572 .saturating_sub(visible_rows.saturating_sub(1))
573 .min(
574 self.row_count()
575 .saturating_sub(visible_rows.min(self.row_count())),
576 );
577 let list_area =
578 render_panel_scroll_rail(list_area, buf, self.row_count(), first, visible_rows, true);
579 let list_width = usize::from(list_area.width);
580 let mut list_lines: Vec<Line> = Vec::with_capacity(visible_rows);
581 for (line_offset, idx) in (first..(first + visible_rows).min(self.row_count())).enumerate()
582 {
583 self.row_hitboxes.borrow_mut().push((
584 Rect::new(
585 list_area.x,
586 list_area
587 .y
588 .saturating_add(u16::try_from(line_offset).unwrap_or(u16::MAX)),
589 list_area.width,
590 1,
591 ),
592 FleetRosterRowAction::SelectOrActivate { row: idx },
593 ));
594 let is_selected = idx == self.selected;
595 // Hover tints but never steals the keyboard selection.
596 let hovered = !is_selected && self.hovered_row.get() == Some(idx);
597 let hover_tint = || menu_style::hovered_row_style();
598 let pointer = format!(
599 "{} ",
600 codewhale_tui_kit::glyphs::selection_marker(is_selected)
601 );
602 let shadow_badge = idx.checked_sub(1).and_then(|index| {
603 member_shadow_badge(self.locale, &self.members[index], &self.shadowed)
604 });
605 let (text, base_style) = if idx == 0 {
606 (
607 format!(
608 "{pointer}@ {}",
609 tr(self.locale, MessageId::FleetRosterOperatorRow)
610 ),
611 Style::default().fg(palette::TEXT_PRIMARY).bold(),
612 )
613 } else {
614 let member = &self.members[idx - 1];
615 let mark = member_role_mark(member);
616 let member_name = member
617 .display_name
618 .as_deref()
619 .map(str::trim)
620 .filter(|name| !name.is_empty() && !name.eq_ignore_ascii_case(&member.id))
621 .map_or_else(
622 || member.id.clone(),
623 |name| format!("{name} ({})", member.id),
624 );
625 (
626 format!(
627 "{pointer}{mark} {member_name}{}",
628 shadow_badge.as_deref().unwrap_or("")
629 ),
630 Style::default().fg(palette::TEXT_PRIMARY),
631 )
632 };
633 let text = if list_width >= 28 && shadow_badge.is_none() {
634 let route = if idx == 0 {
635 self.operator.model.as_str()
636 } else {
637 let profile = &self.members[idx - 1].profile;
638 profile
639 .model
640 .as_deref()
641 .filter(|model| !model.trim().is_empty())
642 .unwrap_or_else(|| {
643 if profile.loadout.as_str() == "inherit" {
644 "follow Coordinator"
645 } else {
646 profile.loadout.as_str()
647 }
648 })
649 };
650 let role_width = (list_width / 2).clamp(14, 24);
651 let label = truncate_view_text(&text, role_width);
652 let pad = role_width
653 .saturating_sub(unicode_width::UnicodeWidthStr::width(label.as_str()));
654 format!(
655 "{label}{} {}",
656 " ".repeat(pad),
657 truncate_view_text(route, list_width.saturating_sub(role_width + 2))
658 )
659 } else {
660 text
661 };
662 let style = if is_selected {
663 menu_style::selected_row_style()
664 } else if hovered {
665 base_style.patch(hover_tint())
666 } else {
667 base_style
668 };
669 if is_selected || hovered {
670 buf.set_style(
671 Rect::new(
672 list_area.x,
673 list_area.y + line_offset as u16,
674 list_area.width,
675 1,
676 ),
677 style,
678 );
679 }
680 list_lines.push(Line::from(Span::styled(
681 truncate_view_text(&text, list_width),
682 style,
683 )));
684 }
685 Paragraph::new(list_lines).render(list_area, buf);
686
687 // Detail pane for the selected row.
688 let lines = if self.operator_selected() {
689 operator_detail_lines(&self.operator)
690 } else if let Some(member) = self.selected_member() {
691 // Whale Teams identity first: the species badge plus species and
692 // job. Rendered without a state — a roster member is a profile,
693 // not a runtime, so this claims nothing about whether anyone is
694 // working. (The hand-drawn portrait that used to open this pane
695 // was deleted per the 2026-08-29 founder directive.)
696 let mut lines = whale_identity_lines(member, self.locale);
697 // Session model is the operator route so "fast" loadouts resolve
698 // to the fast sibling the runtime will actually launch.
699 lines.extend(member_detail_lines_with_session(
700 member,
701 Some(self.operator.model.as_str()),
702 &self.shadowed,
703 self.locale,
704 ));
705 lines
706 } else {
707 vec![Line::from(Span::styled(
708 "Fleet is empty.",
709 Style::default().fg(palette::TEXT_MUTED),
710 ))]
711 };
712
713 // Same wrapped-row scroll bound as the setup review step: count
714 // visual rows so the tail stays reachable.
715 let wrap_width = usize::from(detail_area.width).max(1);
716 let visual_rows: usize = lines
717 .iter()
718 .map(|line| line.width().div_ceil(wrap_width).max(1))
719 .sum();
720 let max_scroll = visual_rows.saturating_sub(usize::from(detail_area.height).max(1));
721 let scroll = self.detail_scroll.min(max_scroll);
722 Paragraph::new(lines)
723 .wrap(Wrap { trim: true })
724 .scroll((scroll as u16, 0))
725 .render(detail_area, buf);
726 }
727 }
728
729 /// Species for a roster member: the profile id first (built-in ids are role
730 /// names), then the resolved worker agent type. Unknown → the plain whale.
731 fn member_species(member: &AgentProfile) -> whales::WhaleSpecies {
732 match whales::WhaleSpecies::for_role_id(&member.id) {
733 whales::WhaleSpecies::Plain => {
734 whales::WhaleSpecies::for_fleet_role(&roster_member_agent_type(member))
735 }
736 species => species,
737 }
738 }
739
740 /// Identity block for the detail pane: the species badge, then
741 /// `Name · species · job`. No state is drawn or claimed — a roster member is
742 /// a profile, not a runtime.
743 fn whale_identity_lines(member: &AgentProfile, locale: Locale) -> Vec<Line<'static>> {
744 let species = member_species(member);
745 let theme = &palette::UI_THEME;
746 let mut lines: Vec<Line> = Vec::new();
747 let mut caption = whales::badge(species, theme);
748 caption.push(Span::styled(
749 format!(
750 " {} · {} · {}",
751 species.name(),
752 species.animal(locale),
753 species.job(locale)
754 ),
755 Style::default().fg(palette::TEXT_PRIMARY),
756 ));
757 lines.push(Line::from(caption));
758 lines.push(Line::from(""));
759 lines
760 }
761
762 fn member_role_mark(member: &AgentProfile) -> &'static str {
763 let role = public_role_label(&member.id);
764 match role.as_str() {
765 "manager" | "explore" => codewhale_tui_kit::glyphs::ROLE_MANAGER,
766 "implement" => codewhale_tui_kit::glyphs::ROLE_BUILDER,
767 "reviewer" => codewhale_tui_kit::glyphs::ROLE_REVIEWER,
768 "test" => codewhale_tui_kit::glyphs::ROLE_VERIFIER,
769 "synthesizer" => codewhale_tui_kit::glyphs::ROLE_SYNTHESIZER,
770 _ => match roster_member_agent_type(member).as_str() {
771 "explore" | "manager" => codewhale_tui_kit::glyphs::ROLE_MANAGER,
772 "implement" => codewhale_tui_kit::glyphs::ROLE_BUILDER,
773 "reviewer" => codewhale_tui_kit::glyphs::ROLE_REVIEWER,
774 "test" => codewhale_tui_kit::glyphs::ROLE_VERIFIER,
775 "synthesizer" => codewhale_tui_kit::glyphs::ROLE_SYNTHESIZER,
776 _ => codewhale_tui_kit::glyphs::NEUTRAL,
777 },
778 }
779 }
780
781 /// Shared field renderer for the detail pane.
782 fn detail_field(lines: &mut Vec<Line<'static>>, label: &str, body: String) {
783 lines.push(Line::from(vec![
784 Span::styled(
785 format!("{label} "),
786 Style::default().fg(palette::TEXT_MUTED).bold(),
787 ),
788 Span::styled(body, Style::default().fg(palette::TEXT_PRIMARY)),
789 ]));
790 lines.push(Line::from(""));
791 }
792
793 /// Detail pane for the pinned operator row: the live session route, plus the
794 /// product truth that the operator is this Fleet's leader.
795 fn operator_detail_lines(operator: &OperatorInfo) -> Vec<Line<'static>> {
796 let mut lines: Vec<Line> = Vec::new();
797 detail_field(
798 &mut lines,
799 "Role",
800 "Coordinator — this session's model leads the Fleet".to_string(),
801 );
802 // Model, provider, and reasoning are one route: one line, same shape
803 // as a member's.
804 let mut route = format!("{} · {}", operator.model, operator.provider);
805 if !operator.reasoning.trim().is_empty() {
806 route.push_str(" · ");
807 route.push_str(&operator.reasoning);
808 }
809 detail_field(&mut lines, "Model", route);
810 detail_field(&mut lines, "Access", "full session access".to_string());
811 // Session-route capability badges (#5038). Use the exact route key rather
812 // than the display label so built-in routes get provider-scoped catalog
813 // facts; custom routes still fall back conservatively to registry facts.
814 if let Some(badges) =
815 codewhale_engine::fleet::capability_badges::resolve_route_capability_badges(
816 Some(&operator.provider_id),
817 &operator.model,
818 )
819 {
820 detail_field(&mut lines, "Capabilities", badges.summary());
821 }
822 detail_field(
823 &mut lines,
824 "Description",
825 "The Coordinator leads this session. Press Enter to change its model and thinking. \
826 Roles set to follow the Coordinator use this route; pinned roles keep their own models."
827 .to_string(),
828 );
829 lines.push(Line::from(Span::styled(
830 "saved for this session only",
831 Style::default().fg(palette::TEXT_MUTED),
832 )));
833 lines
834 }
835
836 /// The resolved worker posture for a roster member: what the runtime would
837 /// actually grant when this member is dispatched (role posture, not the
838 /// profile's requested permissions).
839 /// Plain-Access summary for a roster member: what it may do, derived from the
840 /// same runtime profile dispatch would grant. No internal role/posture words.
841 fn member_access_summary(member: &AgentProfile) -> String {
842 let agent_type = roster_member_agent_type(member);
843 let runtime = WorkerRuntimeProfile::for_role(agent_type.clone());
844 let write = if runtime.permissions.write {
845 "can edit files"
846 } else {
847 "read-only files"
848 };
849 let shell = match runtime.shell {
850 ShellPolicy::None => "cannot run commands",
851 ShellPolicy::ReadOnly => "read-only commands",
852 ShellPolicy::Full => "can run commands",
853 };
854 let network = if runtime.permissions.network {
855 "network"
856 } else {
857 "no network"
858 };
859 format!("{write} · {shell} · {network}")
860 }
861
862 /// The model truth for a member: explicit model choice, else saved model set,
863 /// else the session's model. `[subagents]` overrides still win at dispatch.
864 ///
865 /// When the loadout is `fast`, show that the runtime picks the **fast sibling
866 /// of the active session model** — not a stale on-disk profile name — so the
867 /// roster matches what Fleet will actually launch.
868 fn member_routing_with_session(member: &AgentProfile, session_model: Option<&str>) -> String {
869 if let Some(model) = member
870 .profile
871 .model
872 .as_deref()
873 .map(str::trim)
874 .filter(|model| !model.is_empty())
875 {
876 if let Some(provider) = member
877 .profile
878 .provider
879 .as_deref()
880 .map(str::trim)
881 .filter(|provider| !provider.is_empty())
882 {
883 return format!("model {provider}/{model}");
884 }
885 return format!("model {model}");
886 }
887 match member.profile.loadout.as_str() {
888 "inherit" => "same model as this session".to_string(),
889 "fast" => match session_model.map(str::trim).filter(|m| !m.is_empty()) {
890 Some(session) => format!("fast model for {session}"),
891 None => "fast model, picked at launch".to_string(),
892 },
893 loadout => format!("saved model set {loadout}"),
894 }
895 }
896
897 fn member_shadow_badge(
898 locale: Locale,
899 member: &AgentProfile,
900 shadowed: &[codewhale_engine::fleet::roster::ShadowedProfile],
901 ) -> Option<String> {
902 let layers = layers_from_parts(member, shadowed);
903 if layers.len() < 2 {
904 return None;
905 }
906 let personal_ignored = layers
907 .iter()
908 .any(|layer| !layer.wins && layer.origin == ProfileOrigin::Personal);
909 let id = if personal_ignored {
910 MessageId::FleetRosterShadowBadgePersonalIgnored
911 } else {
912 match member.origin {
913 ProfileOrigin::Workspace => MessageId::FleetRosterShadowBadgeProjectOverride,
914 ProfileOrigin::Personal => MessageId::FleetRosterShadowBadgePersonalOverride,
915 ProfileOrigin::Config => MessageId::FleetRosterShadowBadgeConfigOverride,
916 ProfileOrigin::Plugin | ProfileOrigin::BuiltIn | ProfileOrigin::ClaudeCode => {
917 return None;
918 }
919 }
920 };
921 Some(format!(" {}", tr(locale, id)))
922 }
923
924 fn format_profile_layer(layer: &ProfileLayer, locale: Locale) -> String {
925 let mark = if layer.wins {
926 tr(locale, MessageId::FleetRosterLayerWins)
927 } else {
928 tr(locale, MessageId::FleetRosterLayerIgnored)
929 };
930 format!("{} · {} ({mark})", layer.origin, layer.source.display())
931 }
932
933 fn member_detail_lines_with_session(
934 member: &AgentProfile,
935 session_model: Option<&str>,
936 shadowed: &[codewhale_engine::fleet::roster::ShadowedProfile],
937 locale: Locale,
938 ) -> Vec<Line<'static>> {
939 let mut lines: Vec<Line> = Vec::new();
940
941 // Role is the member's primary identity; the id/display name only
942 // appears when it says something the role does not.
943 let role = member.profile.role.name.trim().to_string();
944 let display_name = member
945 .display_name
946 .as_deref()
947 .map(str::trim)
948 .filter(|name| !name.is_empty() && !name.eq_ignore_ascii_case(&member.id));
949 let role_line = match display_name {
950 Some(name) => format!("{role} — {name} ({})", member.id),
951 None if member.id.trim().eq_ignore_ascii_case(&role) => role.clone(),
952 None => format!("{role} ({})", member.id),
953 };
954 detail_field(&mut lines, "Role", role_line);
955 // #5098: every layer found for this id, with the winner named. The
956 // Origin field still shows the effective copy; this list is the full
957 // stack so a personal/config edit is visible when project wins.
958 let layers = layers_from_parts(member, shadowed);
959 if layers.len() > 1 {
960 let body = layers
961 .iter()
962 .map(|layer| format_profile_layer(layer, locale))
963 .collect::<Vec<_>>()
964 .join("\n");
965 detail_field(
966 &mut lines,
967 &tr(locale, MessageId::FleetRosterLayersLabel),
968 body,
969 );
970 }
971 // Model and provider are attributes of the role: one line, together.
972 let model = match (
973 member.profile.model.as_deref(),
974 codewhale_engine::fleet::identity::friendly_model_name(member),
975 ) {
976 (Some(model), Some(name)) if !name.eq_ignore_ascii_case(model.trim()) => {
977 format!("{name} ({})", model.trim())
978 }
979 _ => member_routing_with_session(member, session_model),
980 };
981 let route = match member
982 .profile
983 .provider
984 .as_deref()
985 .map(str::trim)
986 .filter(|provider| !provider.is_empty())
987 {
988 Some(provider) => format!("{model} · {provider}"),
989 None => model,
990 };
991 detail_field(&mut lines, "Model", route);
992 detail_field(
993 &mut lines,
994 "Thinking",
995 member
996 .profile
997 .reasoning_effort
998 .clone()
999 .unwrap_or_else(|| "Follow Coordinator".to_string()),
1000 );
1001 // Slot is internal dispatch vocabulary and duplicates Role — never shown.
1002 detail_field(&mut lines, "Access", member_access_summary(member));
1003
1004 // Capability badges for a pinned model, from the shared Fleet resolver
1005 // (#5038). Unknown models omit the field rather than fabricating facts.
1006 if let Some(model) = member
1007 .profile
1008 .model
1009 .as_deref()
1010 .map(str::trim)
1011 .filter(|model| !model.is_empty())
1012 && let Some(badges) =
1013 codewhale_engine::fleet::capability_badges::resolve_route_capability_badges(
1014 member.profile.provider.as_deref(),
1015 model,
1016 )
1017 {
1018 detail_field(&mut lines, "Capabilities", badges.summary());
1019 }
1020
1021 let delegation = &member.profile.delegation;
1022 if delegation.max_spawn_depth.is_some() || delegation.max_concurrency.is_some() {
1023 let mut bounds: Vec<String> = Vec::new();
1024 if let Some(depth) = delegation.max_spawn_depth {
1025 bounds.push(format!("spawn depth {depth}"));
1026 }
1027 if let Some(concurrency) = delegation.max_concurrency {
1028 bounds.push(format!("concurrency {concurrency}"));
1029 }
1030 detail_field(&mut lines, "Delegation", bounds.join(" · "));
1031 }
1032
1033 // Only a real overlay earns a field; "none" is the default and says
1034 // nothing.
1035 if member.profile.role.instructions.is_some() {
1036 detail_field(
1037 &mut lines,
1038 "Instructions",
1039 match member.origin {
1040 ProfileOrigin::Workspace => {
1041 format!("custom overlay ({})", member.source.display())
1042 }
1043 ProfileOrigin::Personal => {
1044 format!("personal overlay ({})", member.source.display())
1045 }
1046 _ => "custom overlay".to_string(),
1047 },
1048 );
1049 }
1050
1051 if let Some(description) = member
1052 .description
1053 .as_deref()
1054 .map(str::trim)
1055 .filter(|description| !description.is_empty())
1056 {
1057 detail_field(&mut lines, "Description", description.to_string());
1058 }
1059
1060 // Where the member is saved, last and muted: provenance, not identity.
1061 lines.push(Line::from(Span::styled(
1062 match member.origin {
1063 ProfileOrigin::BuiltIn => "saved for all projects (built-in team)".to_string(),
1064 ProfileOrigin::Workspace => "saved for this project".to_string(),
1065 _ => format!("saved: {} · {}", member.origin, member.source.display()),
1066 },
1067 Style::default().fg(palette::TEXT_MUTED),
1068 )));
1069
1070 lines
1071 }
1072
1073 #[cfg(test)]
1074 mod tests;
1075
1075 lines RUST